branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>rgeber/xkb-layout-us-intl-de<file_sep>/README.md
# XKB Layout US - German Umlauts
Custom US based keyboard layout adding Umlauts via the right <ALT> key. Use this with `xkb` on Linux/Unix Systems and X11. Once installed the layout will show up as `English (US, intl., German) in your layout selector.
Tested with Arch Linux only.
## Installation
**IMPORTANT:** You're about to mess around with system files controlling the way your keyboard works. If things go south you may end up with a very strange state. Whatever you do, **create a backup** of any file you touch.
```
# Create a backup (Example)
sudo cp /usr/share/X11/xkb/symbols/us /usr/share/X11/xkb/rules/evdev.xml /root/
```
Append the contents of `intlde` to `/usr/share/X11/xkb/symbols/us`:
```
sudo cat intlde >> /usr/share/X11/xkb/symbols/us
```
Next, make the layout available to the various keyboard managers (e.g. KDE, Gnome, etc.) by adding the following block to the variants section of the US Layout. This is a bit tricky as you need to find the right spot in the XMl file first.
Variants are defined under `layoutList -> layout`. If you can't find that run a search for `US, intl.`. This should put you in the right spot. Just append the variant block below that:
```
<variant>
<configItem>
<name>intlde</name>
<description>English (US, intl., German)</description>
</configItem>
</variant>
```
Last but not least, activate the layout using your Desktop's layout manager.
### X.org config
You may choose to set the layout though the cofiguration of X.org directly. The file `10-keyboard.conf` offers an example configuration. This way works regardless of the window managers capabilities.
## Usage
Once active, you'll be able to type `äÄ`, `öÖ`, `üÜ` and `ß` holding down your **right alt key** and optionally the shift key. No compose key nonesense but smooth on the fly typing.
| Combination | Result |
|-------------------|--------|
| RAlt + a | ä |
| RAlt + o | ö |
| RAlt + u | ü |
| RAlt + Shift + a | Ä |
| RAlt + Shift + o | Ö |
| RAlt + Shift + u | Ü |
| RAlt + s | ß |
Have fun!
## Troubleshooting
So far this is a "works form me" repository. Feel free to open issues if things don't work fo you. Make sure to mention your exact OS versions and I'll see what I can do for you.
### The keyboard layout doesn't show up in my Keyboard manager
You may have some cache files that need to be deleted first. Try:
```
sudo rm /var/lib/xkb/*.xkm
```
<file_sep>/arch-linux-auto-install.py
import xml.etree.ElementTree as ET
import os
import sys
PATH_EVDEV = '/usr/share/X11/xkb/rules/evdev.xml'
PATH_SYMBOLS = '/usr/share/X11/xkb/symbols/us'
dir_path = os.path.dirname(os.path.realpath(__file__))
# Append the symbols file
with open(os.path.join(dir_path, 'intlde'), 'r') as intde_file:
with open(PATH_SYMBOLS, 'a') as system_symbols_file:
system_symbols_file.write(intde_file.read())
# Fix evdev.xml
# root = ET.parse(path.join(getenv('HOME'), 'evdev.xml')).getroot()
root = ET.parse(PATH_EVDEV).getroot()
for layout in root.find('layoutList').findall('layout'):
if layout.find('configItem').find('name').text != 'us':
continue
variantList = layout.find('variantList')
newET = ET.Element('variant')
newETCI = ET.SubElement(newET, 'configItem')
newETName = ET.SubElement(newETCI, 'name')
newETName.text = 'intlde'
newETDesc = ET.SubElement(newETCI, 'description')
newETDesc.text = 'English (US, intl., German)'
variantList.append(newET)
tree = ET.ElementTree(root)
tree.write(PATH_EVDEV)
print ('Done')
sys.exit(0)
| 3b1514e4ada8d5c797710a4056e32e6dd44a4c89 | [
"Markdown",
"Python"
] | 2 | Markdown | rgeber/xkb-layout-us-intl-de | f3c24c3d8a3c06d96f95ee263884269969001da2 | a74f7477b2bde735dfffa3e552e0570511d60a9b |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ClassesDAO;
namespace Back_End.Controllers
{
public class PRATOSController : Controller
{
private DADOS_MODEL db = new DADOS_MODEL();
// GET: PRATOS
public async Task<ActionResult> Index()
{
var pRATOS = db.PRATOS.Include(p => p.RESTAURANTE);
return View(await pRATOS.ToListAsync());
}
// GET: PRATOS/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PRATO pRATO = await db.PRATOS.FindAsync(id);
if (pRATO == null)
{
return HttpNotFound();
}
return View(pRATO);
}
// GET: PRATOS/Create
public ActionResult Create()
{
ViewBag.CODIGO_RESTAURANTE = new SelectList(db.RESTAURANTES, "CODIGO", "NOME");
return View();
}
// POST: PRATOS/Create
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "CODIGO,CODIGO_RESTAURANTE,DESCRICAO,VALOR,IMAGENS")] PRATO pRATO)
{
if (ModelState.IsValid)
{
db.PRATOS.Add(pRATO);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.CODIGO_RESTAURANTE = new SelectList(db.RESTAURANTES, "CODIGO", "NOME", pRATO.CODIGO_RESTAURANTE);
return View(pRATO);
}
// GET: PRATOS/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PRATO pRATO = await db.PRATOS.FindAsync(id);
if (pRATO == null)
{
return HttpNotFound();
}
ViewBag.CODIGO_RESTAURANTE = new SelectList(db.RESTAURANTES, "CODIGO", "NOME", pRATO.CODIGO_RESTAURANTE);
return View(pRATO);
}
// POST: PRATOS/Edit/5
// Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para
// obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "CODIGO,CODIGO_RESTAURANTE,DESCRICAO,VALOR,IMAGENS")] PRATO pRATO)
{
if (ModelState.IsValid)
{
db.Entry(pRATO).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.CODIGO_RESTAURANTE = new SelectList(db.RESTAURANTES, "CODIGO", "NOME", pRATO.CODIGO_RESTAURANTE);
return View(pRATO);
}
// GET: PRATOS/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PRATO pRATO = await db.PRATOS.FindAsync(id);
if (pRATO == null)
{
return HttpNotFound();
}
return View(pRATO);
}
// POST: PRATOS/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
PRATO pRATO = await db.PRATOS.FindAsync(id);
db.PRATOS.Remove(pRATO);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.OData;
using System.Web.Http.Description;
using ClassesDAO;
namespace Back_End.Controllers
{
public class PRATOController : ApiController
{
private DADOS_MODEL db = new DADOS_MODEL();
// GET: api/PRATO
[EnableQuery]
public IQueryable<PRATO> GetPRATOS()
{
return db.PRATOS;
}
// GET: api/PRATO/5
[ResponseType(typeof(PRATO))]
public async Task<IHttpActionResult> GetPRATO(int id)
{
PRATO pRATO = await db.PRATOS.FindAsync(id);
if (pRATO == null)
{
return NotFound();
}
return Ok(pRATO);
}
// PUT: api/PRATO/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutPRATO(int id, PRATO pRATO)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != pRATO.CODIGO)
{
return BadRequest();
}
db.Entry(pRATO).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PRATOExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/PRATO
[ResponseType(typeof(PRATO))]
public async Task<IHttpActionResult> PostPRATO(PRATO pRATO)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.PRATOS.Add(pRATO);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = pRATO.CODIGO }, pRATO);
}
// DELETE: api/PRATO/5
[ResponseType(typeof(PRATO))]
public async Task<IHttpActionResult> DeletePRATO(int id)
{
PRATO pRATO = await db.PRATOS.FindAsync(id);
if (pRATO == null)
{
return NotFound();
}
db.PRATOS.Remove(pRATO);
await db.SaveChangesAsync();
return Ok(pRATO);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool PRATOExists(int id)
{
return db.PRATOS.Count(e => e.CODIGO == id) > 0;
}
}
} | dd18fe45f40eeb5f5fd26521d4b58b09614fcb25 | [
"C#"
] | 2 | C# | rodrigovalentini/Back-End | 217a8191f5a974b1fdc2f5ba1c7cf5b6f0877e90 | d85531164d79b5ed66d127471ec2b5fa7484e734 |
refs/heads/main | <file_sep>During Advantage Data Structure class.
This is a group project (3 team members) to research different types of sorting algorithms.
We developed an algorithm for a new sorting method called SA Sorting using Python programming language.
-------------------------------------------------------
SA sorting is introduced as a new approach to operate on both sorted and unsorted lists and shows better execution time on the sorted list.
Algorithm:
1. Establish leftmost element in array as target.
2. The target is compared with all the other elements until the smaller element is found.
3. Swap the target with the smaller element and continuously compared till the right end of the list.
4. Go back to the target position, a new target element is taken at that position and continuously the process. NOTE: The target’s position is not changed until the targeted element is found as is already operated.
5. When the targeted element is found to be already operated, the target’s position is changed to next by 1. Repeat the process.
-------------------------------------------------------
Given an array of integers: 5 6 3 9 4 8 1
Target is the most left element: (Round 1)
5 6 3 9 4 8 1 (target is 5)
Compare target to its right elements and swap if a smaller element is found:
3 6 5 9 4 8 1 (swap 5 and 3)
Continue compare target to its right elements and swap:
3 6 4 9 5 8 1 (swap 5 and 4)
3 6 4 9 1 8 5 (swap 5 and 1)
Go back to the target position, a new target element is taken at that position and continuously the process:
3 6 4 9 1 8 5 (target now is 3)
Compare target and swap:
1 6 4 9 3 8 5 (swap 3 and 1)
Go back to the target position, a new target element is taken at that position and continuously the process:
1 6 4 9 3 8 5 (target now is 1)
The targeted element is found to be already operated, the target’s position is changed to next by 1: (Round 2)
1 6 4 9 3 8 5 (target now is 6)
.....…...
Repeat the process and we get a sorted array at the end: 1 3 4 5 6 8 9. Done!
<file_sep># Group project 325 - SA sorting
def recursion(arr, target):
countOfComparison = 0
tempIndex = target
for j in range(target+1, len(arr)):
if (arr[tempIndex] > arr[j]):
arr[j], arr[tempIndex] = arr[tempIndex], arr[j]
tempIndex = j
print(arr)
countOfComparison += 1
if (countOfComparison > 0):
recursion(arr, target)
else:
return(arr)
def sort(arr):
target = 0
#for i in range(len(arr)):
for target in range(len(arr)):
print("Target = {}".format(target))
print(arr)
recursion(arr, target)
print("Done round....")
#target += 1
arr = [5,6,3,9,4,8,1]
sort(arr)
print(arr)
| 2d6e3d07f1ca5bfc0b62a9e4c0998b98e3665303 | [
"Markdown",
"Python"
] | 2 | Markdown | trinhvo20/SASorting | 371ccd9ed78189a6c9ee39c49db18c44b756b4a4 | 9434d04e7397bff1536bdbed93694361f10dd688 |
refs/heads/master | <repo_name>algirdasubaviciuspi/Paskaita11uzduotis1<file_sep>/Program.cs
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace Paskaita11uzduotis1
{
class Program
{
const string CFd = "..\\..\\..\\Duomenys1.txt";
const string CFr = "..\\..\\..\\Rezultatai1.txt";
static void Main(string[] args)
{
List<string> lines = new List<string>();
ReadData(CFd, ref lines);
Dictionary<char, int> letters = new Dictionary<char, int>();
LetterCounting(lines, ref letters);
if (File.Exists(CFr))
File.Delete(CFr);
PrintLinesAndLetters(CFr, lines, letters);
}
static void ReadData(string file, ref List<string> lines)
{ // nuskaito visus duomenis iš failo į string List masyvą
if (File.Exists(file))
using (StreamReader reader = new StreamReader(file))
lines = File.ReadAllLines(file).ToList();
}
static void LetterCounting(List<string> lines, ref Dictionary<char, int> letters)
{ // iš string List masyvo išrenka raides į char Dictionary masyvą
for (int i = 0; i < lines.Count; i++)
{
for (int j = 0; j < lines[i].Length; j++)
{
char symb = lines[i][j];
if (Char.IsLetter(symb))
symb = Char.ToLower(symb);
else
continue;
if (letters.ContainsKey(symb))
letters[symb]++;
else letters.Add(symb, 1);
}
}
}
static void PrintLinesAndLetters(string file, List<string> lines, Dictionary<char, int> letters)
{ // į failą išveda rez.lentelę
using (var fr = File.AppendText(file))
{
foreach (string line in lines)
fr.WriteLine(line);
if (letters.Count > 0)
{
string tableHead = new string('-', 18) + '\n' +
String.Format("{0,6} {1,9}", "Raidė", "Skaičius") + '\n' +
new string('-', 18);
fr.WriteLine(tableHead);
foreach (var pair in letters)
fr.WriteLine("{0,6} {1,9}", pair.Key, pair.Value);
fr.WriteLine(new string('-', 18));
}
else
{
fr.WriteLine("Raidžių nerasta");
}
}
}
}
}
| 65e2cc6399595d1ae04bd3ed19df3d68a9ed8d63 | [
"C#"
] | 1 | C# | algirdasubaviciuspi/Paskaita11uzduotis1 | 9443baeb15b4429295aadf193302b969b7c0673f | d8c7c9c44d4c04ed5e36b82fcfcab5211be6779c |
refs/heads/master | <repo_name>YuxinPan/ATmega328-Morse-Code-Decoder<file_sep>/decoder.c
// <NAME>
#include <avr/io.h>
#include "util/delay.h"
#include "uart.h"
#include <avr/interrupt.h>
#include <stdio.h>
volatile uint8_t tot_overflow,pressed,P1=0;
volatile int releaseTime1;
void timer2_delay(){
PORTB |= (1<<PB5); // turn on LED
OCR1A=TCNT1+23333; // for indication purpose on LED
TIMSK1 |= 0x02; // enable output compare A interrupt
}
void timer1_init() {
TCCR1B |= (1 << CS12); // set up timer with prescaler = 256
TCNT1 = 0;
TIMSK1 |= (1 << TOIE1); // enable overflow interrupt
TIMSK1 |= (1 << ICIE1); // enable Input Capture Interrupt
TCCR1A = 0x40; // toggle on an output compare
}
// 200ms=12500
// pressed: 0:not pressed 1:pressed
// code: 2:dot 3:dash 4:space
int main(void) {
int i,sum;
uint8_t received=0,num=0;
uart_init(); // for serial output
DDRB|=(1<<PB5); // set LED as output, PB5 just means bit number 5 (LED internally connects to PB5)
// 7 segment LEDs
DDRB|=(1<<PB4); // set 4 (pin12) as output
DDRB|=(1<<PB3); // set 3 (pin11) as output
DDRB|=(1<<PB2); // set 3 (pin11) as output
PORTB |= (1<<PB2); // this is voltage high input for 7 segment LEDs
PORTB |= (1<<PB3); // turn off dash on 7 segment
PORTB |= (1<<PB4); // turn off dot on 7 segment
// end 7 segment LEDs
timer1_init();
//timer2_init();
sei(); // enable global interrupts
releaseTime1=0;
tot_overflow = 0;
pressed=0;
sum=0;
while(1) {
received=0;
// dot
if ((releaseTime1>1875)&(releaseTime1<12500)&(!(tot_overflow))){
PORTB &= ~(1 << PB4);
num++;
sum+=7*num;
P1=0;
printf(". " );
releaseTime1=0;
timer2_delay();
}
// dash
if ((TCNT1>=12500)&(pressed)&(!(P1))){
PORTB &= ~(1 << PB3);
num++;
sum+=10*num;
printf("- " );
P1=1;
timer2_delay();
}
// space
if ((TCNT1>=25000)&(!(pressed))){
received=1;
P1=0;
}
if ((received)&(sum!=0)){
printf("\n" );
//printf("\nSUM = %d\n",sum );
if (num>5) printf("Invalid Code\n" );
else
switch(sum) {
case 27 :
printf("A\n" );
break;
case 73 :
printf("B\n" );
break;
case 82 :
printf("C\n" );
break;
case 45 :
printf("D\n" );
break;
case 42 :
printf("S\n" );
break;
case 7 :
printf("E\n" );
break;
case 24 :
printf("N\n" );
break;
case 10 :
printf("T\n" );
break;
case 147 :
printf("1\n" );
break;
case 141 :
printf("2\n" );
break;
case 132 :
printf("3\n" );
break;
case 120 :
printf("4\n" );
break;
case 105 :
printf("5\n" );
break;
default :
printf("Invalid Code\n" );
}
num=0;
sum=0;
}
}
}
// TIMER0 overflow interrupt service routine, called whenever TCNT0 overflows
ISR(TIMER1_OVF_vect) {
tot_overflow=1;
}
ISR (TIMER1_COMPA_vect){
TIMSK1 &= ~(1 << OCIE1A);
PORTB |= (1<<PB3); // turn off dash on 7 segment
PORTB |= (1<<PB4); // turn off dot on 7 segment
PORTB &= ~(1 << PB5); // turn off LED
}
ISR(TIMER1_CAPT_vect) {
if (pressed) {
pressed=0;
releaseTime1=TCNT1;
}
else {
pressed=1;
releaseTime1=0;
}
TCCR1B ^= (1 << ICES1); // toggle ICES1 to capture next event either rise or fall)
TCNT1=0;
tot_overflow=0;
P1=0;
}
| 9283ef41e736eac6a5c2b390133914e6684d1b33 | [
"C"
] | 1 | C | YuxinPan/ATmega328-Morse-Code-Decoder | 1e75d9fdcad7dd9cc2a3ed6e6d1447a5317b0889 | 82b33acf4fbf38dc4a56b73290efd4c4b394cb3f |
refs/heads/master | <file_sep>package edu.groupawesome.quotetracker;
import org.junit.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by JL5372 on 6/8/2016.
*
* will add better doc later
*/
public class TestDatabaseManagement {
// public void addition_isCorrect() throws Exception {
// assertEquals(4, 2 + 2);
// }
// @Test
// public void testaddQouteToDB() throws Exception {
// DatabaseManagement a = new DatabaseManagement();
// Quote quote = new Quote();
// boolean returnValue = a.addQuoteToDB(quote);
// System.out.println(returnValue);
// assertTrue(returnValue);
// }
//
// @Test
// public void testretrieveQuoteFromDB(){
// DatabaseManagement a = new DatabaseManagement();
// Quote dbQuote = a.retrieveQuoteFromDB(1);
// System.out.println(dbQuote.getAuthor() + " : " + dbQuote.getID());
// assertEquals(0, (int)dbQuote.getID());
// }
@Test
public void miscDriverTest(){
DatabaseManagement t = new DatabaseManagement();
Quote a = t.retrieveQuoteFromDB(1);
System.out.println(a.getAuthor());
System.out.println(a.getID());
System.out.println(a.getTitle());
System.out.println(a.getFullText());
System.out.println(a.getTags());
Tag tag1 = new Tag("Testing Tag1");
Set<Tag> sTag1 = new HashSet<>();
sTag1.add(tag1);
List<Quote> quoteList = t.retrieveQuotesWithTag(tag1);
List<Quote> quoteListAll = t.retrieveAllQuotesFromDB();
Tag tag2 = t.retrieveTagFromDB(1);
List<Tag> tagList = t.retrieveTagsWithKeyword("testkeyword");
List<Tag> tagListAll = t.retrieveAllTagsFromDB();
System.out.println(tag2.getTagName());
}
} | 8d0663fd59db51b623b8a50777389e6cb99742a6 | [
"Java"
] | 1 | Java | thexwts/cs246-quotes-app | 80e5a9b5d9f60a1fa2ff444603a2ee745076f730 | 543dece32b1c70718b4fc3d58dc7b1c92c4b8c19 |
refs/heads/master | <repo_name>algoke/Candlesticks<file_sep>/CandlesticksCommon/EventReceiver.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Text;
namespace Candlesticks
{
class EventReceiver : IDisposable {
public static EventReceiver Instance = new EventReceiver();
private TcpClient tcpClient = null;
public event Action<OrderBookUpdated> OrderBookUpdatedEvent = delegate { };
public void Execute() {
try {
Console.WriteLine("receive start");
tcpClient = new TcpClient("localhost", 4444);
var reader = new BinaryReader(tcpClient.GetStream());
while (true) {
int length = reader.ReadInt32();
byte[] body = reader.ReadBytes(length);
using (var memStream = new MemoryStream(body)) {
DataContractSerializer ser = new DataContractSerializer(typeof(ServerEvent), new Type[] { typeof(OrderBookUpdated) });
var receivedObject = ((ServerEvent)ser.ReadObject(memStream)).Body;
Console.WriteLine("received: " + receivedObject);
if (receivedObject is OrderBookUpdated) {
OrderBookUpdatedEvent((OrderBookUpdated)receivedObject);
}
}
}
} catch (Exception e) {
Console.WriteLine(e);
}
}
#region IDisposable Support
private bool disposedValue = false; // 重複する呼び出しを検出するには
protected virtual void Dispose(bool disposing) {
if (!disposedValue) {
if (disposing) {
if(tcpClient != null) {
tcpClient.Close();
tcpClient = null;
OrderBookUpdatedEvent = null;
}
}
disposedValue = true;
}
}
public void Dispose() {
Dispose(true);
}
#endregion
}
}
<file_sep>/CandlesticksServer/OrderBookCollector.cs
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;
namespace Candlesticks {
class OrderBookCollector {
private static int INTERVAL_MINUTE = 20;
private static string[] INSTRUMENTS = new string[] { "USD_JPY", "EUR_USD", "EUR_JPY"};
private EventServer eventServer;
private OandaAPI oandaApi;
private NpgsqlConnection connection;
public OrderBookCollector(EventServer eventServer) {
this.eventServer = eventServer;
oandaApi = new OandaAPI();
this.connection = DBUtils.OpenConnection();
foreach(var instrument in INSTRUMENTS) {
var orderbook = oandaApi.GetOrderbookData(instrument, 3600);
SaveOrderbook(orderbook, instrument);
}
var now = DateTime.Now;
var millisecond = (now.Minute * 60 + now.Second) * 1000 + now.Millisecond;
var remainMillisecond = INTERVAL_MINUTE * 60 * 1000 - millisecond % (INTERVAL_MINUTE * 60 * 1000) + 60 * 1000;
Trace.WriteLine("now:" + now);
Trace.WriteLine("remain:" + remainMillisecond);
Trace.Flush();
var timer = new System.Timers.Timer() {
Interval = (double)remainMillisecond,
AutoReset = false,
};
timer.Elapsed += Timer_FirstElapsed;
timer.Start();
}
private void Timer_FirstElapsed(object sender, ElapsedEventArgs e) {
try {
Trace.WriteLine("Timer_FirstElapsed");
var timer = new System.Timers.Timer() {
Interval = (double)INTERVAL_MINUTE * 60 * 1000,
AutoReset = true,
};
timer.Elapsed += Timer_Elapsed;
timer.Start();
foreach(var instrument in INSTRUMENTS) {
for (int i = 0; SaveOrderbook(oandaApi.GetOrderbookData(instrument,3600), instrument) == false && i < 3; i++) {
Thread.Sleep(1000);
}
}
Trace.WriteLine("Timer_FirstElapsed end");
} catch(Exception ex) {
Trace.WriteLine(ex);
}
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e) {
try {
Trace.WriteLine("Timer_Elapsed");
foreach (var instrument in INSTRUMENTS) {
for (int i = 0; SaveOrderbook(oandaApi.GetOrderbookData(instrument,3600),instrument) == false && i < 3; i++) {
Thread.Sleep(1000);
}
}
Trace.WriteLine("Timer_Elapsed end");
} catch (Exception ex) {
Trace.WriteLine(ex);
}
}
private bool SaveOrderbook(Dictionary<DateTime,PricePoints> orderbook, string instrument) {
DateTime? lastUpdated = null;
Trace.WriteLine("order book count:"+orderbook.Keys.Count());
foreach (var time in orderbook.Keys.OrderBy(k => k)) {
if ( new OrderBookDao(connection).GetCountByDateTime(instrument,time) == 0) {
Trace.WriteLine(time+" is not exists");
Trace.Flush();
SavePricePoints(instrument, time, orderbook[time]);
lastUpdated = time;
} else {
Trace.WriteLine(time + " is exists");
}
}
if (lastUpdated != null) {
eventServer.Send(new OrderBookUpdated() { Instrument = instrument, DateTime = lastUpdated.Value });
return true;
} else {
return false;
}
}
private void SavePricePoints(string instrument, DateTime time, PricePoints pricePoints) {
using (var transaction = connection.BeginTransaction()) {
Int64 id = 0;
using (var cmd = new NpgsqlCommand()) {
cmd.Connection = connection;
cmd.CommandText = "insert into order_book(instrument,date_time,rate) values(:instrument,:date_time,:rate) returning id";
cmd.Parameters.Add(new NpgsqlParameter("instrument", DbType.String));
cmd.Parameters.Add(new NpgsqlParameter("date_time", DbType.DateTime));
cmd.Parameters.Add(new NpgsqlParameter("rate", DbType.Single));
cmd.Parameters["instrument"].Value = instrument;
cmd.Parameters["date_time"].Value = time;
cmd.Parameters["rate"].Value = pricePoints.rate;
id = (Int64)cmd.ExecuteScalar();
}
using (var cmd = new NpgsqlCommand()) {
cmd.Connection = connection;
cmd.CommandText = "insert into order_book_price_point(order_book_id,price,os,ps,ol,pl) values(:order_book_id,:price,:os,:ps,:ol,:pl)";
cmd.Parameters.Add(new NpgsqlParameter("order_book_id", DbType.Int64));
cmd.Parameters.Add(new NpgsqlParameter("price", DbType.Single));
cmd.Parameters.Add(new NpgsqlParameter("os", DbType.Single));
cmd.Parameters.Add(new NpgsqlParameter("ps", DbType.Single));
cmd.Parameters.Add(new NpgsqlParameter("ol", DbType.Single));
cmd.Parameters.Add(new NpgsqlParameter("pl", DbType.Single));
foreach(var price in pricePoints.price_points.Keys.OrderBy(k=>k)) {
var price_point = pricePoints.price_points[price];
cmd.Parameters["order_book_id"].Value = id;
cmd.Parameters["price"].Value = price;
cmd.Parameters["os"].Value = price_point.os;
cmd.Parameters["ps"].Value = price_point.ps;
cmd.Parameters["ol"].Value = price_point.ol;
cmd.Parameters["pl"].Value = price_point.pl;
cmd.ExecuteNonQuery();
}
}
transaction.Commit();
}
}
}
}
<file_sep>/CandlesticksServer/TextLineTraceListener.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Candlesticks {
class TextLineTraceListener : TraceListener {
private FileStream fs;
private StreamWriter writer;
private bool isNewLine = true;
public TextLineTraceListener(string fileName) {
fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
writer = new StreamWriter(fs);
}
private string GetHeader() {
DateTime now = DateTime.Now;
return "[" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:") + String.Format("{0:D3}",now.Millisecond) + "] ";
}
public override void Write(string message) {
lock (fs) {
if (isNewLine) {
writer.Write(GetHeader());
isNewLine = false;
}
writer.Write(message);
writer.Flush();
}
}
public override void WriteLine(string message) {
lock(fs) {
if (isNewLine) {
writer.Write(GetHeader());
}
writer.WriteLine(message);
writer.Flush();
isNewLine = true;
}
}
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
writer.Dispose();
}
}
}
<file_sep>/CandlesticksServer/schema.sql
create table order_book (
id bigserial primary key,
instrument text,
date_time timestamp with time zone,
rate numeric(12,5)
);
create index order_book_date_time_idx on order_book(instrument,date_time desc);
alter table order_book add column instrument text;
update order_book set instrument='USD_JPY';
drop index order_book_date_time_idx;
alter table order_book alter column rate type numeric(12,5);
create table order_book_price_point (
id bigserial primary key,
order_book_id bigint,
price numeric(12,5),
os numeric(6,4),
ps numeric(6,4),
ol numeric(6,4),
pl numeric(6,4)
);
create index order_book_price_point_order_book_idx on order_book_price_point(order_book_id);
alter table order_book_price_point alter column price type numeric(12,5);
create table candlestick (
id bigserial primary key,
instrument text,
granularity text,
date_time timestamp with time zone,
open numeric(12,5),
high numeric(12,5),
low numeric(12,5),
close numeric(12,5),
volume integer,
unique(instrument,granularity,date_time)
);
alter table candlestick alter column open type numeric(12,5);
alter table candlestick alter column high type numeric(12,5);
alter table candlestick alter column low type numeric(12,5);
alter table candlestick alter column close type numeric(12,5);
create table time_of_day_pattern (
id bigserial primary key,
check_start_time time,
check_end_time time,
is_check_up boolean,
trade_start_time time,
trade_end_time time,
trade_type text,
total_verification integer,
match_verification integer
);
<file_sep>/CandlesticksCommon/CandlesticksGetter.cs
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Candlesticks {
class CandlesticksGetter {
public string Instrument = "USD_JPY";
/*
1分の初めにアライン
“S5” - 5 秒
“S10” - 10 秒
“S15” - 15 秒
“S30” - 30 秒
“M1” - 1 分
1時間の初めにアライン
“M2” - 2 分
“M3” - 3 分
“M5” - 5 分
“M10” - 10 分
“M15” - 15 分
“M30” - 30 分
“H1” - 1 時間
1日の初めにアライン(17:00, 米国東部標準時)
“H2” - 2 時間
“H3” - 3 時間
“H4” - 4 時間
“H6” - 6 時間
“H8” - 8 時間
“H12” - 12 時間
“D” - 1 日
1週間の初めにアライン (土曜日)
“W” - 1 週
1か月の初めにアライン (その月の最初の日)
“M” - 1 か月
*/
public string Granularity = "M10";
public DateTime Start;
public DateTime End {
set {
end = value;
if(end > DateTime.Now) {
end = DateTime.Now;
}
}
get {
return end;
}
}
private DateTime end;
public int Count = -1;
private OandaAPI oandaAPI = null;
public OandaAPI OandaAPI {
get {
if(oandaAPI == null) {
oandaAPI = OandaAPI.Instance;
}
return oandaAPI;
}
set {
oandaAPI = value;
}
}
private void SaveOandaCandle(CandlestickDao dao, OandaCandle oandaCandle) {
var entity = dao.CreateNewEntity();
entity.Instrument = this.Instrument;
entity.Granularity = this.Granularity;
entity.DateTime = oandaCandle.DateTime;
entity.Open = oandaCandle.openMid;
entity.High = oandaCandle.highMid;
entity.Low = oandaCandle.lowMid;
entity.Close = oandaCandle.closeMid;
entity.Volume = oandaCandle.volume;
try {
entity.Save();
} catch(NpgsqlException e) {
if(e.Code == "23505") {
Console.WriteLine(e.Message);
throw new RetryException();
} else {
throw e;
}
}
}
private class RetryException : Exception { }
private void SaveNullCandle(CandlestickDao dao, DateTime t) {
var entity = dao.CreateNewEntity();
entity.Instrument = this.Instrument;
entity.Granularity = this.Granularity;
entity.DateTime = t;
entity.Open = 0;
entity.High = 0;
entity.Low = 0;
entity.Close = 0;
entity.Volume = 0;
try {
entity.Save();
} catch (NpgsqlException e) {
if (e.Code == "23505") {
Console.WriteLine(e.Message);
throw new RetryException();
} else {
throw e;
}
}
}
public IEnumerable<Candlestick> Execute() {
List<Candlestick> result = new List<Candlestick>();
TimeSpan granularitySpan = GetGranularitySpan();
if (Count != -1) {
End = Start.AddTicks(granularitySpan.Ticks * Count);
}
var dao = new CandlestickDao();
while (true) {
try {
using (var transaction = DBUtils.GetConnection().BeginTransaction()) {
DateTime t = GetAlignTime(Start);
foreach (var entity in dao.GetBy(Instrument, Granularity, t, End).ToList()) {
if (entity.DateTime != t) {
foreach (var oandaCandle in GetCandles(t, entity.DateTime.AddSeconds(-1))) {
t = SaveAndAdd(result, granularitySpan, dao, t, oandaCandle);
}
FillNullCandles(result, granularitySpan, dao, t, entity.DateTime);
t = entity.DateTime;
}
result.Add(entity.Candlestick);
t = t.Add(granularitySpan);
}
if (t < End) {
foreach (var oandaCandle in GetCandles(t, End)) {
t = SaveAndAdd(result, granularitySpan, dao, t, oandaCandle);
}
FillNullCandles(result, granularitySpan, dao, t, End);
}
transaction.Commit();
}
break;
} catch (RetryException) {
continue;
}
}
return result;
}
public async Task<List<Candlestick>> ExecuteAsync() {
return await Task.Run(() => {
Console.WriteLine("ExecuteAsync Start");
try {
lock (this.GetType()) { // このメソッドが大量に同時実行されるとOpenThreadConnectionがタイムアウトする
using (DBUtils.OpenThreadConnection()) {
return Execute().ToList();
}
}
} finally {
Console.WriteLine("ExecuteAsync End");
}
});
}
private void FillNullCandles(List<Candlestick> result, TimeSpan granularitySpan, CandlestickDao dao, DateTime t, DateTime endTime) {
while (t < endTime) {
SaveNullCandle(dao, t);
result.Add(new Candlestick() { DateTime = t, Open = 0 });
t = t.Add(granularitySpan);
}
}
private DateTime SaveAndAdd(List<Candlestick> result, TimeSpan granularitySpan, CandlestickDao dao, DateTime t, OandaCandle oandaCandle) {
while (t < oandaCandle.DateTime) {
SaveNullCandle(dao, t);
result.Add(new Candlestick() { DateTime = t, Open = 0 });
t = t.Add(granularitySpan);
}
SaveOandaCandle(dao, oandaCandle);
result.Add(oandaCandle.Candlestick);
t = t.Add(granularitySpan);
return t;
}
private IEnumerable<OandaCandle> GetCandles(DateTime start, DateTime end) {
TimeSpan granularitySpan = GetGranularitySpan();
long count;
do {
count = (end - start).Ticks / granularitySpan.Ticks;
DateTime e = start.AddTicks(granularitySpan.Ticks * Math.Min(count, 5000));
foreach (var c in this.OandaAPI.GetCandles(start, e, Instrument, Granularity)) {
if(c.DateTime < start) {
continue;
}
yield return c;
}
start = e;
} while (count > 5000);
}
public DateTime GetAlignTime(DateTime time) {
if (Granularity[0] == 'S') {
int s = int.Parse(Granularity.Substring(1));
int aligned = (int)Math.Floor((double)time.Second / s) * s;
return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, aligned, 0, time.Kind);
// return time.AddMilliseconds(-time.Millisecond).AddSeconds(-time.Second + aligned);
} else if (Granularity[0] == 'M') {
int s = int.Parse(Granularity.Substring(1));
int aligned = (int)Math.Floor((double)time.Minute / s) * s;
return new DateTime(time.Year, time.Month, time.Day, time.Hour, aligned, 0, 0, time.Kind);
// return time.AddMilliseconds(-time.Millisecond).AddSeconds(-time.Second).AddMinutes(-time.Minute + aligned);
} else if (Granularity[0] == 'H' || Granularity == "D") {
int s = Granularity == "D" ? 24 : int.Parse(Granularity.Substring(1));
int aligned = (int)Math.Floor((double)time.Hour / s) * s;
Console.WriteLine("align:" + aligned + " s:" + s + " hour:" + time.Hour);
return new DateTime(time.Year, time.Month, time.Day, aligned, 0, 0, 0, time.Kind);
// return time.AddMilliseconds(-time.Millisecond).AddSeconds(-time.Second).AddMinutes(-time.Minute).AddHours(-time.Hour + aligned);
}
throw new Exception("not supported granularity:" + Granularity);
}
public TimeSpan GetGranularitySpan() {
if (Granularity[0] == 'S') {
return new TimeSpan(0, 0, int.Parse(Granularity.Substring(1)));
}
if (Granularity[0] == 'M') {
return new TimeSpan(0, int.Parse(Granularity.Substring(1)), 0);
}
if (Granularity[0] == 'H') {
return new TimeSpan(int.Parse(Granularity.Substring(1)), 0, 0);
}
if (Granularity == "D") {
return new TimeSpan(24, 0, 0);
}
throw new Exception("not supported granularity:" + Granularity);
}
}
}
<file_sep>/CandlesticksCommon/Candlestick.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Candlesticks {
struct Candlestick {
public DateTime DateTime;
private float _open;
private float _close;
private float _high;
private float _low;
private int _volume;
public float Open {
get {
if(IsNull) {
throw new Exception("Null candlestick");
}
return _open;
}
set {
_open = value;
}
}
public float Close {
get {
if (IsNull) {
throw new Exception("Null candlestick");
}
return _close;
}
set {
_close = value;
}
}
public float High {
get {
if (IsNull) {
throw new Exception("Null candlestick");
}
return _high;
}
set {
_high = value;
}
}
public float Low {
get {
if (IsNull) {
throw new Exception("Null candlestick");
}
return _low;
}
set {
_low = value;
}
}
public int Volume {
get {
if (IsNull) {
throw new Exception("Null candlestick");
}
return _volume;
}
set {
_volume = value;
}
}
public bool IsNull {
get {
return _open == 0f;
}
}
public float PriceRange {
get {
return High - Low;
}
}
public float BarRange {
get {
return Math.Abs(Open - Close);
}
}
public bool IsUp(float d=0) {
return Close > Open + d;
}
public bool IsPinbar(bool isUp, float minPositivePinRatio, float maxNegativePinRatio) {
float bar = Math.Abs(this.Open - this.Close);
float upPin = this.High - this.BarTop;
float downPin = this.BarBottom - this.Low;
if(isUp) {
return upPin >= bar * minPositivePinRatio && downPin <= bar * maxNegativePinRatio;
} else {
return downPin >= bar * minPositivePinRatio && upPin <= bar * maxNegativePinRatio;
}
}
public float BarTop {
get {
return Math.Max(this.Open, this.Close);
}
}
public float BarBottom {
get {
return Math.Min(this.Open, this.Close);
}
}
static public Candlestick Aggregate(IEnumerable<Candlestick> l) {
Candlestick result = new Candlestick();
result.High = float.MinValue;
result.Low = float.MaxValue;
bool isOpen = true;
foreach(var c in l) {
if(isOpen) {
result.DateTime = c.DateTime;
if(c.IsNull) {
result.Open = 0;
} else {
result.Open = c.Open;
}
isOpen = false;
}
if (c.IsNull) {
continue;
}
result.Close = c.Close;
if(result.IsNull == false) {
result.High = Math.Max(result.High, c.High);
result.Low = Math.Min(result.Low, c.Low);
}
}
if(isOpen) {
throw new Exception();
}
return result;
}
static public IEnumerable<Candlestick> Aggregate(IEnumerable<Candlestick> l, int n) {
for (int s = 0; s < l.Count(); s += n) {
yield return Aggregate(l.Skip(s).Take(n));
}
}
public Candlestick Add(Candlestick candle) {
return Candlestick.Aggregate(new Candlestick[] { this, candle });
}
}
}
<file_sep>/CandlesticksCommon/ThreadConnectionManager.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Candlesticks
{
class ThreadConnectionManager
{
}
}
<file_sep>/Candlesticks/SignalForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Candlesticks {
public partial class SignalForm : Form {
private static int randomSecond = new Random().Next() % 10;
[DllImport("USER32.dll", CallingConvention = CallingConvention.StdCall)]
static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
private const int MOUSEEVENTF_LEFTDOWN = 0x2;
private const int MOUSEEVENTF_LEFTUP = 0x4;
private List<TradePattern> patterns = new List<TradePattern>();
private HashSet<TimeTradeOrder> havePositionSet = new HashSet<TimeTradeOrder>();
public SignalForm() {
InitializeComponent();
}
private void SignalForm_Load(object sender, EventArgs e) {
using (DBUtils.OpenThreadConnection()) {
// 81.56%
patterns.Add(
new TradePattern() {
TradeCondition = new TradeConditionAnd() {
TradeConditions = new TradeCondition[] {
new TimeOfDayPattern() {
Instrument = "USD_JPY",
CheckStartTime = new TimeSpan(0, 30, 0),
CheckEndTime = new TimeSpan(4, 50, 0),
IsCheckUp = false,
},
new TimeOfDayPattern() {
Instrument = "USD_JPY",
CheckStartTime = new TimeSpan(3, 20, 0),
CheckEndTime = new TimeSpan(3, 30, 0),
IsCheckUp = false,
},
},
},
TradeOrders = new TradeOrders(
new TimeTradeOrder() {
Instrument = "USD_JPY",
TradeType = TradeType.Ask,
Time = new TimeSpan(4, 50, 0),
},
new TimeTradeOrder() {
Instrument = "USD_JPY",
TradeType = TradeType.Settle,
Time = new TimeSpan(7, 10, 0),
}
)
}
);
// 83.08%
patterns.Add(
new TradePattern() {
TradeCondition = new TradeConditionAnd() {
TradeConditions = new TradeCondition[] {
new TimeOfDayPattern() {
Instrument = "USD_JPY",
CheckStartTime = new TimeSpan(1, 00, 0),
CheckEndTime = new TimeSpan(3, 40, 0),
IsCheckUp = false,
},
new TimeOfDayPattern() {
Instrument = "USD_JPY",
CheckStartTime = new TimeSpan(3, 50, 0),
CheckEndTime = new TimeSpan(4, 20, 0),
IsCheckUp = false,
},
},
},
TradeOrders = new TradeOrders(
new TimeTradeOrder() {
Instrument = "USD_JPY",
TradeType = TradeType.Ask,
Time = new TimeSpan(4, 50, 0),
},
new TimeTradeOrder() {
Instrument = "USD_JPY",
TradeType = TradeType.Settle,
Time = new TimeSpan(7, 10, 0),
}
)
}
);
//73.78%
patterns.Add(
new TradePattern() {
TradeCondition = new TimeOfDayPattern() {
Instrument = "USD_JPY",
CheckStartTime = new TimeSpan(0, 20, 0),
CheckEndTime = new TimeSpan(5, 40, 0),
IsCheckUp = false,
},
TradeOrders = new TradeOrders(
new TimeTradeOrder() {
Instrument = "USD_JPY",
TradeType = TradeType.Ask,
Time = new TimeSpan(5, 49, 0),
},
new TimeTradeOrder() {
Instrument = "USD_JPY",
TradeType = TradeType.Settle,
Time = new TimeSpan(7, 10, 0),
}
)
}
);
/*
patterns.Add(new TimeOfDayPattern() {
Instrument = "USD_JPY",
CheckStartTime = new TimeOfDayPattern.Time(5, 50),
CheckEndTime = new TimeOfDayPattern.Time(6, 00),
IsCheckUp = false,
TradeStartTime = new TimeOfDayPattern.Time(6, 00),
TradeEndTime = new TimeOfDayPattern.Time(6, 10),
TradeType = TradeType.Ask
});*/
// 64.19%
patterns.Add(
new TradePattern() {
TradeCondition = new TimeOfDayPattern() {
Instrument = "USD_JPY",
CheckStartTime = new TimeSpan(7, 50, 0),
CheckEndTime = new TimeSpan(8, 40, 0),
IsCheckUp = true,
},
TradeOrders = new TradeOrders(
new TimeTradeOrder() {
Instrument = "USD_JPY",
TradeType = TradeType.Bid,
Time = new TimeSpan(8, 50, 0),
},
new TimeTradeOrder() {
Instrument = "USD_JPY",
TradeType = TradeType.Settle,
Time = new TimeSpan(11, 30, 0),
}
)
}
);
// 62.87%
patterns.Add(
new TradePattern() {
TradeCondition = new TimeOfDayPattern() {
Instrument = "USD_JPY",
CheckStartTime = new TimeSpan(1, 30, 0),
CheckEndTime = new TimeSpan(4, 20, 0),
IsCheckUp = false,
},
TradeOrders = new TradeOrders(
new TimeTradeOrder() {
Instrument = "USD_JPY",
TradeType = TradeType.Bid,
Time = new TimeSpan(9, 50, 0),
},
new TimeTradeOrder() {
Instrument = "USD_JPY",
TradeType = TradeType.Settle,
Time = new TimeSpan(13, 10, 0),
}
)
}
);
// 64.54% ... A
patterns.Add(
new TradePattern() {
TradeCondition = new TimeOfDayPattern() {
Instrument = "EUR_USD",
CheckStartTime = new TimeSpan(8, 50, 0),
CheckEndTime = new TimeSpan(11, 00, 0),
IsCheckUp = false,
},
TradeOrders = new TradeOrders(
new TimeTradeOrder() {
Instrument = "EUR_USD",
TradeType = TradeType.Ask,
Time = new TimeSpan(11, 01, 0),
},
new TimeTradeOrder() {
Instrument = "EUR_USD",
TradeType = TradeType.Settle,
Time = new TimeSpan(11, 40, 0),
}
)
}
);
/*
//62.9% ... B
patterns.Add(
new TradePattern() {
TradeCondition = new TimeOfDayPattern() {
Instrument = "EUR_USD",
CheckStartTime = new TimeSpan(6, 50, 0),
CheckEndTime = new TimeSpan(7, 50, 0),
IsCheckUp = true,
},
TradeOrders = new TradeOrders(
new TimeTradeOrder() {
Instrument = "EUR_USD",
TradeType = TradeType.Ask,
Time = new TimeSpan(11, 00, 0),
},
new TimeTradeOrder() {
Instrument = "EUR_USD",
TradeType = TradeType.Settle,
Time = new TimeSpan(11, 30, 0),
}
)
}
);
*/
// 11:00-11:40の上昇確率
// !A && !B => 42.86%
// A && !B => 57.76%
// !A && B => 53.82%
// A && B => 68.81%
patterns.Add(
new TradePattern() {
TradeCondition = new TradeConditionAnd() {
TradeConditions = new TradeCondition[] {
new TimeOfDayPattern() {
Instrument = "EUR_USD",
CheckStartTime = new TimeSpan(6, 50, 0),
CheckEndTime = new TimeSpan(7, 50, 0),
IsCheckUp = true,
},
new TimeOfDayPattern() {
Instrument = "EUR_USD",
CheckStartTime = new TimeSpan(8, 50, 0),
CheckEndTime = new TimeSpan(11, 00, 0),
IsCheckUp = false,
},
},
},
TradeOrders = new TradeOrders(
new TimeTradeOrder() {
Instrument = "EUR_USD",
TradeType = TradeType.Ask,
Time = new TimeSpan(11, 00, 0),
},
new TimeTradeOrder() {
Instrument = "EUR_USD",
TradeType = TradeType.Settle,
Time = new TimeSpan(11, 40, 0),
}
)
}
);
//63.98%
patterns.Add(
new TradePattern() {
TradeCondition = new TimeOfDayPattern() {
Instrument = "EUR_USD",
CheckStartTime = new TimeSpan(0, 50, 0),
CheckEndTime = new TimeSpan(4, 00, 0),
IsCheckUp = true,
},
TradeOrders = new TradeOrders(
new TimeTradeOrder() {
Instrument = "EUR_USD",
TradeType = TradeType.Bid,
Time = new TimeSpan(6, 20, 0),
},
new TimeTradeOrder() {
Instrument = "EUR_USD",
TradeType = TradeType.Settle,
Time = new TimeSpan(7, 40, 0),
}
)
}
);
this.signalDataGrid.Columns.Add("pattern", "パターン");
this.signalDataGrid.Columns.Add("match", "マッチ状況");
this.signalDataGrid.Columns.Add("trade", "トレード");
this.signalDataGrid.Columns.Add(new DataGridViewCheckBoxColumn() {
Name = "autoTrade",
HeaderText = "自動取引"
});
foreach (var pattern in patterns) {
this.signalDataGrid.Rows.Add();
}
}
}
private void SignalForm_Shown(object sender, EventArgs e) {
this.signalDataGrid.CurrentCell = null;
}
private void timer1_Tick(object sender, EventArgs e) {
// this.signalDataGrid.CurrentCell = null;
using (DBUtils.OpenThreadConnection()) {
int index = 0;
this.signalDataGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
foreach (var pattern in patterns) {
var cells = this.signalDataGrid.Rows[index].Cells;
cells["pattern"].Value = pattern.TradeCondition.GetCheckDescription();
Signal signal;
bool isMatch = false;
TradeContext tradeContext = new TradeContext() {
Instrument = pattern.TradeOrders[0].Instrument,
Date = DateTime.Today
};
cells["trade"].Value = pattern.TradeOrders.GetTradeDescription(tradeContext);
if (pattern.TradeCondition.IsMatch(out signal, tradeContext)) {
pattern.TradeOrders.DoTrade(tradeContext);
if (tradeContext.Profit > 0f) {
cells["trade"].Style.BackColor = Color.LightPink;
} else {
cells["trade"].Style.BackColor = pattern.TradeOrders.IsInTradeTime ? Color.Red : Color.Yellow;
}
isMatch = true;
} else {
cells["trade"].Style.BackColor = Color.White;
isMatch = false;
}
if (signal != null) {
if (isMatch) {
cells["match"].Value = "Matched!" + signal.GetCheckResultDescription();
cells["match"].Style.BackColor = Color.Yellow;
var isAutoTrade = cells["autoTrade"].Value;
if (isAutoTrade != null && (bool)isAutoTrade) {
DoTrade(pattern.TradeOrders);
}
} else {
if (signal.IsCheckFinished) {
cells["match"].Style.BackColor = Color.LightGray;
}
cells["match"].Value = "Not Match " + signal.GetCheckResultDescription();
}
} else {
cells["match"].Value = "Not Match";
}
index++;
}
this.signalDataGrid.AutoResizeColumn(0);
this.signalDataGrid.AutoResizeColumn(1);
this.signalDataGrid.AutoResizeColumn(2);
}
}
private void DoTrade(TradeOrders orders) {
DateTime now = DateTime.Now;
DateTime nowMinutes = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0, now.Kind);
foreach (var order in orders) {
var mouseClickPosition = GetMouseClickPosition(order.Instrument);
if (order.TradeType == TradeType.Settle) {
if (DateTime.Today.Add(order.Time) == nowMinutes && now.Second % 10 == randomSecond) {
Cursor.Position = mouseClickPosition.Settle;
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
} else {
if (DateTime.Today.Add(order.Time) == nowMinutes && !havePositionSet.Contains(order)) {
Cursor.Position = order.TradeType == TradeType.Ask ? mouseClickPosition.Ask : mouseClickPosition.Bid;
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
havePositionSet.Add(order);
}
}
}
}
private Setting.MouseClikPositoin GetMouseClickPosition(string instrument) {
switch (instrument) {
case "USD_JPY":
return Setting.Instance.MouseClickPositionUSD_JPY;
case "EUR_USD":
return Setting.Instance.MouseClickPositionEUR_USD;
default:
throw new Exception("Unknown Instrument:" + instrument);
}
}
}
}
<file_sep>/CandlesticksServer/Setting.cs
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace Candlesticks {
[DataContract]
class Setting {
public static Setting Instance;
public static void LoadInstance(string filePath) {
var settings = new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
var serializer = new DataContractJsonSerializer(typeof(Setting), settings);
using (var stream = new FileStream(filePath, FileMode.Open)) {
Instance = (Setting)serializer.ReadObject(stream);
}
}
[DataMember]
public string LogFilePath = null;
[DataMember]
public int ListenPort = -1;
[DataMember]
public string OandaAccountId = null;
[DataMember]
public string OandaBearerToken = null;
[DataMember]
public DBConnectionSetting DBConnection = null;
[DataContract]
public class DBConnectionSetting {
[DataMember]
public string Host = "localhost";
[DataMember]
public int Port = 5432;
[DataMember]
public string UserName = "candlesticks";
[DataMember]
public string Password = <PASSWORD>;
[DataMember]
public string Database = "candlesticks";
}
}
}
<file_sep>/CandlesticksCommon/OrderBookUpdated.cs
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace Candlesticks
{
[DataContract]
[KnownType(typeof(OrderBookUpdated))]
public class ServerEvent {
[DataMember]
public object Body;
}
[DataContract]
public class OrderBookUpdated : ServerEvent {
[DataMember]
public DateTime DateTime;
[DataMember]
public string Instrument;
}
}
<file_sep>/Candlesticks/Setting.cs
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Candlesticks {
class Setting {
public static Setting Instance = new Setting();
private Setting() {
var registryKey = Registry.CurrentUser.CreateSubKey(@"Software\CandleSticks\Setting");
this.OandaAccountId = (string)registryKey.GetValue("oandaAccountId");
this.OandaBearerToken = (string)registryKey.GetValue("oandaBearerToken");
this.DataFilePath = (string)registryKey.GetValue("dataFilePath");
this.DBConnection = new DBConnectionSetting() {
Host = (string)registryKey.GetValue("dbHost","localhost"),
Port = (int)registryKey.GetValue("dbUserName",5432),
Password = (string)registryKey.GetValue("dbPassword"),
};
string s = (string)registryKey.GetValue("orderBookScrollPositions");
if(s != null) {
foreach (var instrumentPos in s.Split(',').Select(kv => kv.Split('='))) {
OrderBookScrollPositions[instrumentPos[0]] = int.Parse(instrumentPos[1]);
}
}
registryKey.Close();
this.MouseClickPositionUSD_JPY = LoadMouseClickPos("MousePosUsdJpy");
this.MouseClickPositionEUR_USD = LoadMouseClickPos("MousePosEurUsd");
}
private MouseClikPositoin LoadMouseClickPos(string subKeyName) {
var registryKey = Registry.CurrentUser.CreateSubKey(@"Software\CandleSticks\Setting\"+ subKeyName);
var result = new MouseClikPositoin() {
Bid = new Point((int)registryKey.GetValue("bidPosX", 0), (int)registryKey.GetValue("bidPosY", 0)),
Ask = new Point((int)registryKey.GetValue("askPosX", 0), (int)registryKey.GetValue("askPosY", 0)),
Settle = new Point((int)registryKey.GetValue("settlePosX", 0), (int)registryKey.GetValue("settlePosY", 0)),
};
registryKey.Close();
return result;
}
public void Save() {
var registryKey = Registry.CurrentUser.CreateSubKey(@"Software\CandleSticks\Setting");
registryKey.SetValue("oandaAccountId", this.OandaAccountId);
registryKey.SetValue("oandaBearerToken", this.OandaBearerToken);
registryKey.SetValue("dataFilePath", this.DataFilePath);
registryKey.SetValue("dbHost", this.DBConnection.Host);
registryKey.SetValue("dbPort", this.DBConnection.Port);
registryKey.SetValue("dbPassword", this.DBConnection.Password);
registryKey.SetValue("orderBookScrollPositions", string.Join(",",OrderBookScrollPositions.Select(kv=>kv.Key+"="+kv.Value)));
registryKey.Close();
SaveMouseClickPos(this.MouseClickPositionUSD_JPY, "MousePosUsdJpy");
SaveMouseClickPos(this.MouseClickPositionEUR_USD, "MousePosEurUsd");
}
private void SaveMouseClickPos(MouseClikPositoin mouseClickPos, string subKeyName) {
var registryKeyMousePos = Registry.CurrentUser.CreateSubKey(@"Software\CandleSticks\Setting\"+subKeyName);
registryKeyMousePos.SetValue("bidPosX", mouseClickPos.Bid.X);
registryKeyMousePos.SetValue("bidPosY", mouseClickPos.Bid.Y);
registryKeyMousePos.SetValue("askPosX", mouseClickPos.Ask.X);
registryKeyMousePos.SetValue("askPosY", mouseClickPos.Ask.Y);
registryKeyMousePos.SetValue("settlePosX", mouseClickPos.Settle.X);
registryKeyMousePos.SetValue("settlePosY", mouseClickPos.Settle.Y);
registryKeyMousePos.Close();
}
public string OandaAccountId {
get;
set;
}
public string OandaBearerToken {
get;
set;
}
public string DataFilePath {
get;
set;
}
public DBConnectionSetting DBConnection {
get;
set;
}
public class DBConnectionSetting {
public string Host = "localhost";
public int Port = 5432;
public string UserName = "candlesticks";
public string Password = <PASSWORD>;
public string Database = "candlesticks";
}
public MouseClikPositoin MouseClickPositionUSD_JPY {
get;
set;
}
public MouseClikPositoin MouseClickPositionEUR_USD {
get;
set;
}
public class MouseClikPositoin {
public Point Bid;
public Point Ask;
public Point Settle;
}
public Dictionary<string, int> OrderBookScrollPositions = new Dictionary<string, int>();
}
}<file_sep>/Candlesticks/CandlesticksReader.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Candlesticks {
class CandlesticksReader {
public IEnumerable<Candlestick> Read(string filePath) {
var file = new StreamReader(filePath);
string line;
while(true) {
line = file.ReadLine();
if(line == null) {
break;
}
var e = line.Split(',');
Candlestick c = new Candlestick();
c.DateTime = DateTime.Parse(e[0]+" "+e[1]);
c.Open = float.Parse(e[2]);
c.High = float.Parse(e[3]);
c.Low = float.Parse(e[4]);
c.Close = float.Parse(e[5]);
yield return c;
}
file.Close();
}
}
}
<file_sep>/Candlesticks/SettingDialog.cs
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Candlesticks {
public partial class SettingDialog : Form {
public SettingDialog() {
InitializeComponent();
}
private void SettingDialog_Load(object sender, EventArgs e) {
var setting = Setting.Instance;
oandaAccountId.Text = setting.OandaAccountId;
oandaBearerToken.Text = setting.OandaBearerToken;
dataFilePath.Text = setting.DataFilePath;
dbHost.Text = setting.DBConnection.Host;
dbPort.Text = setting.DBConnection.Port.ToString();
dbPassword.Text = setting.DBConnection.Password;
}
private void button1_Click(object sender, EventArgs e) {
var setting = Setting.Instance;
setting.DataFilePath = dataFilePath.Text;
setting.OandaAccountId = oandaAccountId.Text;
setting.OandaBearerToken = oandaBearerToken.Text;
setting.DBConnection.Host = dbHost.Text;
setting.DBConnection.Port = int.Parse(dbPort.Text);
setting.DBConnection.Password = <PASSWORD>;
setting.Save();
this.Close();
}
}
}
<file_sep>/CandlesticksCommon/OrderBookPricePointDao.cs
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace Candlesticks
{
class OrderBookPricePointDao
{
private NpgsqlConnection connection;
public OrderBookPricePointDao(NpgsqlConnection connection) {
this.connection = connection;
}
public IEnumerable<Tuple<DateTime, float, float>> GetPositionSummaryGroupByOrderBookDateTime(DateTime start, DateTime end) {
using (var cmd = new NpgsqlCommand()) {
cmd.Connection = connection;
cmd.CommandText = "select ob.date_time, sum(pp.ps), sum(pp.pl) from order_book_price_point as pp, order_book as ob where pp.order_book_id = ob.id and :start <= ob.date_time and ob.date_time < :end group by ob.date_time order by ob.date_time";
cmd.Parameters.Add(new NpgsqlParameter("start", DbType.DateTime));
cmd.Parameters.Add(new NpgsqlParameter("end", DbType.DateTime));
cmd.Parameters["start"].Value = start;
cmd.Parameters["end"].Value = end;
using (var dr = cmd.ExecuteReader()) {
while (dr.Read()) {
yield return new Tuple<DateTime, float, float>((DateTime)dr[0], (float)((decimal)dr[1]), (float)((decimal)dr[2]));
}
}
}
}
public IEnumerable<Entity> GetByOrderBookOrderByPrice(Int64 orderBookId) {
using (var cmd = new NpgsqlCommand()) {
cmd.Connection = connection;
cmd.CommandText = "select id, price, os, ps, ol, pl from order_book_price_point where order_book_id = :order_book_id order by price";
cmd.Parameters.Add(new NpgsqlParameter("order_book_id", DbType.Int64));
cmd.Parameters["order_book_id"].Value = orderBookId;
using (var dr = cmd.ExecuteReader()) {
while (dr.Read()) {
var entity = new Entity();
entity.Connection = connection;
entity.Id = (Int64)dr[0];
entity.OrderBookId = orderBookId;
entity.Price = (float)((decimal)dr[1]);
entity.Os = (float)((decimal)dr[2]);
entity.Ps = (float)((decimal)dr[3]);
entity.Ol = (float)((decimal)dr[4]);
entity.Pl = (float)((decimal)dr[5]);
yield return entity;
}
}
}
}
public class Entity {
public NpgsqlConnection Connection;
public Int64 Id;
public Int64 OrderBookId;
public float Price;
public float Os;
public float Ps;
public float Ol;
public float Pl;
}
}
}
<file_sep>/Candlesticks/OrderBookLabForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Candlesticks {
public partial class OrderBookLabForm : Form {
private static float ORDERBOOK_GRANULARITY = 0.05f;
public OrderBookLabForm() {
InitializeComponent();
}
private void RunTask(object sender, Action<Report> action) {
Report.RunTask(sender, action, dataGridView1, label1);
}
private IEnumerable<OrderBookDao.Entity> GetOrderBooks() {
foreach(var orderBook in new OrderBookDao(DBUtils.GetConnection()).GetByInstrumentOrderByDateTimeDescendant("USD_JPY").Reverse().ToList()) {
if(!new CandlesticksGetter() {
Granularity = "M10",
Start = orderBook.NormalizedDateTime.AddMinutes(-10),
Count = 1
}.Execute().First().IsNull) {
yield return orderBook;
}
}
}
private void 近傍ポジション変化_Click(object sender, EventArgs e) {
RunTask(sender, report => {
report.Version = 3;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("date_time","pre_pl", "cur_pl", "pre_ps", "cur_ps", "low","high","close");
using (DBUtils.OpenThreadConnection()) {
OrderBookDao.Entity preOrderBook = null;
foreach (var orderBook in GetOrderBooks()) {
if(preOrderBook != null) {
var candle = Candlestick.Aggregate(new CandlesticksGetter() {
Granularity = "M10",
Start = orderBook.NormalizedDateTime.AddMinutes(-20),
Count = 2
}.Execute());
if (orderBook.NormalizedDateTime == new DateTime(2016, 2, 22, 10, 40, 0, DateTimeKind.Local)) {
int a = 1;
}
float prePl = 0, prePs = 0;
float curPl = 0, curPs = 0;
foreach(var pp in GetRangePricePoint(orderBook, candle.Low, candle.High)) {
curPl += pp.Pl;
curPs += pp.Ps;
}
foreach (var pp in GetRangePricePoint(preOrderBook, candle.Low, candle.High)) {
prePl += pp.Pl;
prePs += pp.Ps;
}
report.WriteLine(orderBook.DateTime, prePl, curPl, prePs, curPs, candle.Low, candle.High, candle.Close);
}
preOrderBook = orderBook;
}
}
});
}
private static OrderBookPricePointDao.Entity GetRatePricePoint(OrderBookDao.Entity orderBook, float rate) {
float min = float.MaxValue;
OrderBookPricePointDao.Entity closedPricePoint = null;
foreach (var pricePoint in orderBook.GetPricePointsOrderByPrice()) {
float d = Math.Abs(rate - pricePoint.Price);
if (d < min) {
min = d;
closedPricePoint = pricePoint;
}
}
return closedPricePoint;
}
private static IEnumerable<OrderBookPricePointDao.Entity> GetRangePricePoint(OrderBookDao.Entity orderBook, float min, float max) {
float start = GetRoundPrice(min);
float end = GetRoundPrice(max);
foreach (var pricePoint in orderBook.GetPricePointsOrderByPrice()) {
if(start - 0.001f <= pricePoint.Price && pricePoint.Price <= end + 0.001f) {
yield return pricePoint;
}
}
}
private static float GetRoundPrice(float price) {
int n = (int)((price + ORDERBOOK_GRANULARITY / 2) / ORDERBOOK_GRANULARITY);
return ORDERBOOK_GRANULARITY * n;
}
}
}
<file_sep>/CandlesticksCommon/PriceObserver.cs
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
namespace Candlesticks
{
delegate void PriceListener(string instrument, DateTime dateTime, float bid, float ask);
class PriceObserver
{
private static Dictionary<string, PriceObserver> instances = new Dictionary<string, PriceObserver>();
public static PriceObserver Get(string instrument = "USD_JPY,EUR_JPY,EUR_USD") {
lock(typeof(PriceObserver)) {
if(!instances.ContainsKey(instrument)) {
instances[instrument] = new PriceObserver(instrument);
}
return instances[instrument];
}
}
private PriceListener listeners = null;
private OandaAPI oandaApi;
private HttpClient client;
private string instrument;
public PriceObserver(string instrument) {
this.instrument = instrument;
}
public void Observe(PriceListener listener) {
lock(this) {
if (listeners == null) {
oandaApi = new OandaAPI();
listeners = delegate { };
client = oandaApi.GetPrices(ReceivePrice, instrument);
}
listeners += listener;
}
}
private void ReceivePrice(string instrument, DateTime dateTime, float bid, float ask) {
lock(this) {
listeners.Invoke(instrument, dateTime, bid, ask);
}
}
public void UnOnserve(PriceListener listener) {
lock (this) {
listeners -= listener;
if (listeners.GetInvocationList().Length == 1) {
client.Dispose();
oandaApi.Dispose();
listeners = null;
}
}
}
}
}
<file_sep>/Candlesticks/OrderBookForm.cs
using Npgsql;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Candlesticks {
public partial class OrderBookForm : Form {
class InstrumentInfo {
public string Name;
public float GraphMinPrice;
public float GraphMaxPrice;
public float GraphInterval;
public string AxisLabelFormat;
public float VolumePriceGranularity;
public float Bid;
public float Ask;
public DateTime LastPriceTime;
public override string ToString() {
return Name;
}
}
private InstrumentInfo[] instruments = new InstrumentInfo[] {
new InstrumentInfo() {
Name = "USD_JPY",
GraphMinPrice = 105f,
GraphMaxPrice = 120f,
GraphInterval = 0.05f,
AxisLabelFormat = "f2",
VolumePriceGranularity = 0.01f,
},
new InstrumentInfo() {
Name = "EUR_JPY",
GraphMinPrice = 120f,
GraphMaxPrice = 135f,
GraphInterval = 0.05f,
AxisLabelFormat = "f2",
VolumePriceGranularity = 0.01f,
},
new InstrumentInfo() {
Name = "EUR_USD",
GraphMinPrice = 1.05f,
GraphMaxPrice = 1.2f,
GraphInterval = 0.0005f,
AxisLabelFormat = "f4",
VolumePriceGranularity = 0.0001f,
},
};
private NpgsqlConnection connection = null;
private TcpClient tcpClient = null;
private Dictionary<string, List<OrderBookDao.Entity>> orderBooks = new Dictionary<string, List<OrderBookDao.Entity>>();
private Series streamPriceSeries = null;
private float latestPrice;
private Series latestVolumeSeries = null;
private List<Candlestick> latestS5Candles;
private Thread retriveVolumesThread = null;
private InstrumentInfo selectedInstrument = null;
private Dictionary<string, Dictionary<OrderBookDao.Entity, PricePoints>> pricePointsCache = null;
private BlockingCollection<Action> retriveVolumeQueue = new BlockingCollection<Action>();
public OrderBookForm() {
InitializeComponent();
foreach (var instrument in instruments) {
comboBox1.Items.Add(instrument);
}
}
private void OrderBookForm_Load(object sender, EventArgs ev) {
connection = DBUtils.OpenConnection();
comboBox1.SelectedIndex = 0;
// LoadOrderBookList(INSTRUMENTS[0]);
/* splitContainer1.Panel2.HorizontalScroll.Value = splitContainer1.Panel1.HorizontalScroll.Value
= (splitContainer1.Panel1.HorizontalScroll.Maximum + splitContainer1.Panel1.HorizontalScroll.Minimum - splitContainer1.Panel1.ClientSize.Width) / 2;*/
EventReceiver.Instance.OrderBookUpdatedEvent += OnOrderBookUpdated;
retriveVolumesThread = new Thread(new ThreadStart(RetriveVolumes));
retriveVolumesThread.Start();
PriceObserver.Get().Observe(ReceivePrice);
}
private void RetriveVolumes() {
while (true) {
var action = retriveVolumeQueue.Take();
if(action == null) {
break;
}
action();
}
}
private List<Candlestick> RetrieveS5Candles(OrderBookDao.Entity orderBook) {
using(DBUtils.OpenThreadConnection()) {
DateTime firstDateTime = orderBook.DateTime;
DateTime startDateTime = new DateTime(
firstDateTime.Year, firstDateTime.Month, firstDateTime.Day, firstDateTime.Hour, firstDateTime.Minute, 0, DateTimeKind.Local);
return new CandlesticksGetter() {
Start = startDateTime,
End = startDateTime.AddMinutes(20),
Granularity = "S5",
Instrument = selectedInstrument.Name
}.Execute().ToList();
}
}
private void LoadVolumeSeries(Series series, List<Candlestick> s5candles) {
Dictionary<float, float> priceVolumes = new Dictionary<float, float>();
foreach (var candle in s5candles) {
if(candle.IsNull) {
continue;
}
float min = GetRoundPrice(candle.Low);
float max = GetRoundPrice(candle.High);
float average = (float)candle.Volume / (int)((max - min + 1) / selectedInstrument.VolumePriceGranularity);
for (float i = min; i <= max; i += selectedInstrument.VolumePriceGranularity) {
if (priceVolumes.ContainsKey(i)) {
priceVolumes[i] += average;
} else {
priceVolumes[i] = average;
}
}
}
series.Points.Clear();
foreach (var price in priceVolumes.Keys.OrderBy(k => k)) {
series.Points.Add(new DataPoint(price, priceVolumes[price] / (100 * selectedInstrument.VolumePriceGranularity)));
}
}
private void RetriveVolumeLatest() {
var candle = OandaAPI.Instance.GetCandles(1,selectedInstrument.Name, "S5").First();
Invoke(new Action(() => {
if(latestS5Candles == null) {
return;
}
if (latestS5Candles.Where(c => c.DateTime.Equals(candle.DateTime)).Count() >= 1) {
return;
}
latestS5Candles.Add(candle.Candlestick);
if (orderBookList.SelectedIndex == 0) {
volumeLabel.Text = candle.volume.ToString();
volumeLabel.ForeColor = candle.volume >= 10 ? Color.Red : (candle.volume >= 5 ? Color.Orange : (candle.volume >= 2 ? Color.Blue : Color.Gray));
float min = GetRoundPrice(candle.lowMid);
float max = GetRoundPrice(candle.highMid);
float average = (float)candle.volume / (int)((max - min + 1) / selectedInstrument.VolumePriceGranularity);
Console.WriteLine("candle lowMid:" + min + "(" + candle.lowMid+") highMid:" +max + "(" + candle.highMid+") volume:"+candle.volume+" avg:"+ average);
for (float i = min; i <= max; i += selectedInstrument.VolumePriceGranularity) {
DataPoint dp = latestVolumeSeries.Points.Where(p => p.XValue == i).FirstOrDefault();
if(dp == null) {
dp = new DataPoint(i, 0);
latestVolumeSeries.Points.Add(dp);
}
dp.YValues[0] += average / (100 * selectedInstrument.VolumePriceGranularity);
}
}
}));
}
private float GetRoundPrice(float price) {
int n = (int)((price + selectedInstrument.VolumePriceGranularity / 2) / selectedInstrument.VolumePriceGranularity);
return n * selectedInstrument.VolumePriceGranularity;
}
private InstrumentInfo GetInstrumentInfo(string instrument) {
return instruments.Where(i => i.Name == instrument).First();
}
private void ReceivePrice(string instrument, DateTime dateTime,float bid, float ask) {
var info = GetInstrumentInfo(instrument);
info.Bid = bid;
info.Ask = ask;
info.LastPriceTime = dateTime;
if (selectedInstrument.Name == instrument) {
Invoke(new Action(() => {
UpdatePrice();
}));
}
}
private void UpdatePrice() {
timeLabel.Text = selectedInstrument.LastPriceTime.ToString("M/d HH:mm:ss");
bidLabel.Text = selectedInstrument.Bid.ToString("f3");
askLabel.Text = selectedInstrument.Ask.ToString("f3");
if (streamPriceSeries != null) {
latestPrice = (selectedInstrument.Bid + selectedInstrument.Ask) / 2;
streamPriceSeries.Points[0].XValue = latestPrice;
streamPriceSeries.Points[1].XValue = latestPrice;
}
}
private void OnOrderBookUpdated(OrderBookUpdated orderBookUpdated) {
if (orderBookUpdated.Instrument == selectedInstrument.Name) {
Invoke(new Action(() => {
int selectedIndex = orderBookList.SelectedIndex;
latestS5Candles = null;
LoadOrderBookList(orderBookUpdated.Instrument, orderBookUpdated.DateTime);
if (selectedIndex == 0) {
orderBookList.SelectedIndex = 0;
}
}));
}
}
private void LoadOrderBookList(string instrument) {
orderBookList.Items.Clear();
if(orderBooks.ContainsKey(instrument) == false) {
orderBooks[instrument] = new OrderBookDao(connection).GetByInstrumentOrderByDateTimeDescendant(instrument).ToList();
}
foreach (var entity in orderBooks[instrument]) {
orderBookList.Items.Add(entity.DateTime);
}
}
private void LoadOrderBookList(string instrument, DateTime dateTime) {
if (orderBooks.ContainsKey(instrument) == false) {
return;
}
var list = orderBooks[instrument];
if (list.Count(e=>e.DateTime==dateTime) == 0) {
var entity = new OrderBookDao(connection).GetByInstrumentAndDateTime(instrument, dateTime);
orderBookList.Items.Insert(0,entity.DateTime);
list.Insert(0, entity);
}
}
private void LoadChart(Chart chart, DateTime dateTime, OrderBookDao.Entity orderBook, OrderBookDao.Entity previousOrderBook, bool isLatestChart) {
PricePoints pricePoints = GetPricePoints(orderBook);
PricePoints previousPricePoints = previousOrderBook!=null ? GetPricePoints(previousOrderBook) : null;
chart.Series.Clear();
chart.ChartAreas.Clear();
chart.Titles.Clear();
chart.Size = new Size(6000, 400);
ChartArea chartArea = new ChartArea();
chartArea.AxisX.Interval = selectedInstrument.GraphInterval;
chartArea.AxisX.Minimum = selectedInstrument.GraphMinPrice;
chartArea.AxisX.Maximum = selectedInstrument.GraphMaxPrice;
chartArea.AxisX.LabelStyle.Format = selectedInstrument.AxisLabelFormat;
chartArea.AxisX.MajorGrid.Enabled = true;
chartArea.AxisX.MajorGrid.Interval = selectedInstrument.GraphInterval * 2;
chartArea.AxisX.MinorGrid.Enabled = true;
chartArea.AxisX.MinorGrid.LineColor = Color.LightGray;
chartArea.AxisX.MinorGrid.Interval = selectedInstrument.GraphInterval;
/* chartArea.AxisX2.Enabled = AxisEnabled.True;
chartArea.AxisX2.Minimum = chartArea.AxisX.Minimum;
chartArea.AxisX2.Maximum = chartArea.AxisX.Maximum;*/
// chartArea.AxisX2.Interval = VOLUME_PRICE_GRANURALITY;
chartArea.AxisY.Maximum = 5.0f;
chartArea.AxisY.Minimum = 0f;
chartArea.AxisY.Interval = 1.0f;
chartArea.AxisY.MajorGrid.LineColor = Color.LightGray;
chartArea.AxisY2.Enabled = AxisEnabled.True;
chartArea.AxisY2.Maximum = 2.5f;
chartArea.AxisY2.Minimum = -2.5f;
chartArea.AxisY2.Interval = 1.0f;
chart.ChartAreas.Add(chartArea);
Series volumeSeries = new Series();
volumeSeries.ChartType = SeriesChartType.Column;
// volumeSeries.XAxisType = AxisType.Secondary;
volumeSeries.Color = Color.LightGray;
volumeSeries.SetCustomProperty("PixelPointWidth", "2");
// volumeSeries.SetCustomProperty("PointWidth", "0.5");
chart.Series.Add(volumeSeries);
var UISyncContext = TaskScheduler.FromCurrentSynchronizationContext();
if (isLatestChart) {
if(latestS5Candles == null) {
latestVolumeSeries = volumeSeries;
retriveVolumeQueue.Add(() => {
var candlesticks = RetrieveS5Candles(orderBook);
Invoke(new Action(()=>{
latestS5Candles = candlesticks.ToList();
LoadVolumeSeries(volumeSeries, latestS5Candles);
}));
});
}
// , UISyncContext);
/*
lock (volumeCandlesLock) {
if (latestS5Candles != null) {
LoadVolumeSeries(latestVolumeSeries,latestS5Candles);
}
}*/
} else {
retriveVolumeQueue.Add(() => {
var candlesticks = RetrieveS5Candles(orderBook);
Invoke(new Action(() => {
LoadVolumeSeries(volumeSeries, candlesticks);
}));
});
/*
new TaskFactory().StartNew(() => RetrieveS5Candles(orderBook)).ContinueWith(candlesticks => {
latestS5Candles = candlesticks.Result.ToList();
LoadVolumeSeries(volumeSeries, latestS5Candles);
}, UISyncContext);*/
/*
if (gettingVolumes == false) {
gettingVolumes = true;
RetrieveS5CandlesAsync(orderBook).ContinueWith(candlesticks => {
LoadVolumeSeries(volumeSeries, candlesticks.Result);
gettingVolumes = false;
}, UISyncContext);
}*/
}
Series seriesDeltaPos = new Series();
chart.Series.Add(seriesDeltaPos);
seriesDeltaPos.YAxisType = AxisType.Secondary;
seriesDeltaPos.ChartType = SeriesChartType.StackedColumn;
seriesDeltaPos.LegendText = "buy - sell position";
seriesDeltaPos.SetCustomProperty("PixelPointWidth", "14");
seriesDeltaPos.Color = Color.FromArgb(100, 0, 255, 0);
Series seriesPreviousDeltaPos = new Series();
chart.Series.Add(seriesPreviousDeltaPos);
seriesPreviousDeltaPos.YAxisType = AxisType.Secondary;
seriesPreviousDeltaPos.ChartType = SeriesChartType.StackedColumn;
seriesPreviousDeltaPos.SetCustomProperty("PixelPointWidth", "14");
seriesPreviousDeltaPos.Color = Color.FromArgb(100, 0, 255, 0);
float totalPl = 0;
float totalPs = 0;
foreach (var price in pricePoints.price_points.Keys.OrderBy(k => k)) {
var dprice = (double)price;
var p = pricePoints.price_points[price];
var curD = p.pl - p.ps;
totalPl += p.pl;
totalPs += p.ps;
if(previousPricePoints != null) {
if(previousPricePoints.price_points.ContainsKey(price)) {
var pre = previousPricePoints.price_points[price];
var preD = pre.pl - pre.ps;
if (preD < 0 && curD > 0) {
seriesDeltaPos.Points.Add(new DataPoint(dprice, curD) { Color = Color.FromArgb(100, 255, 0, 0) } );
seriesPreviousDeltaPos.Points.Add(new DataPoint(dprice, preD) { Color = Color.FromArgb(100, 255, 0, 0) });
} else if(preD > 0 && curD < 0) {
seriesDeltaPos.Points.Add(new DataPoint(dprice, curD) { Color = Color.FromArgb(100, 0, 0, 255) });
seriesPreviousDeltaPos.Points.Add(new DataPoint(dprice, preD) { Color = Color.FromArgb(100, 0, 0, 255) });
} else if(preD > 0 && curD > 0) {
seriesDeltaPos.Points.Add(new DataPoint(dprice, Math.Min(curD, preD)) { Color = Color.FromArgb(100, 0, 255, 0) });
seriesPreviousDeltaPos.Points.Add(new DataPoint(dprice, Math.Abs(curD - preD)) { Color = curD > preD ? Color.FromArgb(100, 255, 0, 0) : Color.FromArgb(25,0,0,255) });
} else {
seriesDeltaPos.Points.Add(new DataPoint(dprice, Math.Max(curD, preD)) { Color = Color.FromArgb(100, 0, 255, 0) });
seriesPreviousDeltaPos.Points.Add(new DataPoint(dprice, -Math.Abs(curD - preD)) { Color = curD > preD ? Color.FromArgb(25, 255, 0, 0) : Color.FromArgb(100, 0, 0, 255) });
}
} else {
seriesDeltaPos.Points.Add(new DataPoint(dprice, curD));
seriesPreviousDeltaPos.Points.Add(new DataPoint(dprice,0));
}
} else {
seriesDeltaPos.Points.Add(new DataPoint(dprice, curD));
}
}
Series[] lines = new Series[4];
string[] titles = new string[] { "order_long", "order_short", "pos_long", "pos_short" };
Color[] colors = new Color[] { Color.Pink, Color.LightBlue, Color.Red, Color.Blue};
for (int i=0; i<4; i++) {
Series seriesLine = new Series();
chart.Series.Add(seriesLine);
seriesLine.ChartType = SeriesChartType.Line;
seriesLine.LegendText = titles[i];
seriesLine.BorderWidth = 1;
seriesLine.Color = colors[i];
seriesLine.MarkerStyle = MarkerStyle.Circle;
seriesLine.MarkerSize = 2;
lines[i] = seriesLine;
}
foreach (var price in pricePoints.price_points.Keys.OrderBy(k => k)) {
var dprice = decimal.ToDouble((decimal)price);
var p = pricePoints.price_points[price];
lines[0].Points.Add(new DataPoint(dprice, p.ol));
lines[1].Points.Add(new DataPoint(dprice, p.os));
lines[2].Points.Add(new DataPoint(dprice, p.pl));
lines[3].Points.Add(new DataPoint(dprice, p.ps));
}
Series seriesRate = new Series();
chart.Series.Add(seriesRate);
seriesRate.ChartType = SeriesChartType.Line;
// seriesRate.SetCustomProperty("PointWidth", "0.01");
seriesRate.Points.Add(new DataPoint(pricePoints.rate, 5.0f));
seriesRate.Points.Add(new DataPoint(pricePoints.rate, -1.0f));
seriesRate.Color = Color.Pink;
seriesRate.BorderWidth = 3;
if (isLatestChart) {
streamPriceSeries = new Series();
chart.Series.Add(streamPriceSeries);
streamPriceSeries.ChartType = SeriesChartType.Line;
// streamPriceSeries.SetCustomProperty("PointWidth", "0.01");
streamPriceSeries.Points.Add(new DataPoint(latestPrice, 5.0f));
streamPriceSeries.Points.Add(new DataPoint(latestPrice, -1.0f));
streamPriceSeries.Color = Color.Red;
streamPriceSeries.BorderWidth = 3;
}
float pld = 0;
float psd = 0;
if (previousPricePoints != null) {
float prevTotalPl = 0;
float prevTotalPs = 0;
foreach (var pp in previousPricePoints.price_points) {
prevTotalPl += pp.Value.pl;
prevTotalPs += pp.Value.ps;
}
pld = totalPl - prevTotalPl;
psd = totalPs - prevTotalPs;
}
chart.Titles.Add(String.Format("{0} short position:{1:0.###}({2:+0.###;-0.###;0.###}) long position:{3:0.###}({4:+0.###;-0.###;0.###}) ", dateTime, totalPs, psd, totalPl, pld));
}
private void splitContainer1_Panel1_Scroll(object sender, ScrollEventArgs e) {
splitContainer1.Panel2.HorizontalScroll.Value = splitContainer1.Panel1.HorizontalScroll.Value;
Setting.Instance.OrderBookScrollPositions[selectedInstrument.Name] = splitContainer1.Panel1.HorizontalScroll.Value;
}
private void splitContainer1_Panel2_Scroll(object sender, ScrollEventArgs e) {
splitContainer1.Panel1.HorizontalScroll.Value = splitContainer1.Panel2.HorizontalScroll.Value;
Setting.Instance.OrderBookScrollPositions[selectedInstrument.Name] = splitContainer1.Panel2.HorizontalScroll.Value;
}
protected override Point ScrollToControl(Control activeControl)
{
return splitContainer1.Panel1.AutoScrollPosition;
}
private PricePoints GetPricePoints(OrderBookDao.Entity orderBook) {
if(pricePointsCache == null) {
pricePointsCache = new Dictionary<string, Dictionary<OrderBookDao.Entity, PricePoints>>();
}
if(pricePointsCache.ContainsKey(selectedInstrument.Name) == false) {
pricePointsCache.Add(selectedInstrument.Name, new Dictionary<OrderBookDao.Entity, PricePoints>());
}
var orderBookPricePoints = pricePointsCache[selectedInstrument.Name];
if(orderBookPricePoints.ContainsKey(orderBook)) {
return orderBookPricePoints[orderBook];
}
PricePoints pricePoints = new PricePoints();
pricePoints.rate = orderBook.Rate;
pricePoints.price_points = new Dictionary<float, PricePoint>();
foreach (var pp in orderBook.GetPricePointsOrderByPrice()) {
pricePoints.price_points[pp.Price] = new PricePoint() {
os = pp.Os,
ol = pp.Ol,
ps = pp.Ps,
pl = pp.Pl
};
}
orderBookPricePoints[orderBook] = pricePoints;
return pricePoints;
}
private void LoadChart(Chart chart, int index) {
var list = orderBooks[selectedInstrument.Name];
OrderBookDao.Entity orderBook = list[index];
OrderBookDao.Entity previousOrderBook = (index + 1 < list.Count()) ? list[index + 1] : null;
LoadChart(chart, orderBook.DateTime, orderBook, previousOrderBook, index == 0);
/* splitContainer1.Panel2.HorizontalScroll.Value = splitContainer1.Panel1.HorizontalScroll.Value
= (int) chart.ChartAreas[0].AxisX.ValueToPixelPosition(orderBook.Rate);*/
// Console.WriteLine("ratePixel"+chart.ChartAreas[0].AxisX.ValueToPixelPosition(orderBook.Rate));
// Console.WriteLine("splitContainer1.Panel2.HorizontalScroll.Value" + splitContainer1.Panel2.HorizontalScroll.Value);
}
private void SetHorizonalScrollPosition(int x) {
var p = splitContainer1.Panel2.AutoScrollPosition;
p.X = x;
splitContainer1.Panel1.AutoScrollPosition = p;
p = splitContainer1.Panel2.AutoScrollPosition;
p.X = x;
splitContainer1.Panel2.AutoScrollPosition = p;
}
private void orderBookList_SelectedIndexChanged(object sender, EventArgs ev) {
try {
LoadChart(chart1, orderBookList.SelectedIndex);
if (orderBookList.SelectedIndex + 1 < orderBooks[selectedInstrument.Name].Count()) {
LoadChart(chart2, orderBookList.SelectedIndex + 1);
}
if (orderBookList.SelectedIndex == 0) {
// splitContainer1.Update();
if (!Setting.Instance.OrderBookScrollPositions.ContainsKey(selectedInstrument.Name)) {
double scrollRatio = (orderBooks[selectedInstrument.Name][0].Rate - selectedInstrument.GraphMinPrice) / (selectedInstrument.GraphMaxPrice - selectedInstrument.GraphMinPrice);
int value = (int)((splitContainer1.Panel1.HorizontalScroll.Maximum - splitContainer1.Panel1.HorizontalScroll.Minimum) * scrollRatio + splitContainer1.Panel1.HorizontalScroll.Minimum - splitContainer1.Panel1.ClientSize.Width / 2);
Console.WriteLine("scrollRatio:" + scrollRatio + " value:" + value + " min:" + splitContainer1.Panel1.HorizontalScroll.Minimum + " max:" + splitContainer1.Panel1.HorizontalScroll.Maximum);
Console.WriteLine("scrollRatio:" + scrollRatio + " value:" + value + " min:" + splitContainer1.Panel2.HorizontalScroll.Minimum + " max:" + splitContainer1.Panel2.HorizontalScroll.Maximum);
// splitContainer1.Panel2.HorizontalScroll.Value = splitContainer1.Panel1.HorizontalScroll.Value = value;
SetHorizonalScrollPosition(value);
Setting.Instance.OrderBookScrollPositions.Add(selectedInstrument.Name, value);
} else {
SetHorizonalScrollPosition(Setting.Instance.OrderBookScrollPositions[selectedInstrument.Name]);
}
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
private void OrderBookForm_FormClosing(object sender, FormClosingEventArgs e) {
Console.WriteLine("OrderBookForm_FormClosing");
PriceObserver.Get().UnOnserve(ReceivePrice);
EventReceiver.Instance.OrderBookUpdatedEvent -= OnOrderBookUpdated;
Setting.Instance.Save();
if (connection != null) {
connection.Close();
connection = null;
}
if(tcpClient != null) {
tcpClient.Close();
tcpClient = null;
}
if(retriveVolumeQueue != null) {
retriveVolumeQueue.Add(null);
// retriveVolumeQueue = null;
}
/* if(oandaApi != null) {
oandaApi.Dispose();
oandaApi = null;
}*/
if(retriveVolumesThread != null) {
retriveVolumesThread.Interrupt();
retriveVolumesThread = null;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
selectedInstrument = (InstrumentInfo) comboBox1.SelectedItem;
latestS5Candles = null;
LoadOrderBookList(selectedInstrument.Name);
orderBookList.SelectedIndex = 0;
UpdatePrice();
}
private void timer1_Tick(object sender, EventArgs e) {
retriveVolumeQueue.Add(() => RetriveVolumeLatest());
}
}
}
<file_sep>/CandlesticksServer/EventServer.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Candlesticks {
class EventServer {
private HashSet<EventSession> sessions = new HashSet<EventSession>();
private TcpListener listener;
public EventServer() {
}
public void Execute() {
listener = new TcpListener(IPAddress.Parse("127.0.0.1"), Setting.Instance.ListenPort);
listener.Start();
Trace.WriteLine("EventServer listen start port: "+ Setting.Instance.ListenPort);
while (true) {
try {
EventSession session = new EventSession(this, listener.AcceptTcpClient());
lock (sessions) {
sessions.Add(session);
}
} catch(Exception e) {
Trace.WriteLine("EventServer stopped:"+e.Message);
return;
}
/* new Thread(new ThreadStart(() => {
session.ReceiveLoop();
lock(sessions) {
sessions.Remove(session);
}
}));*/
}
}
public void Send(object packet) {
lock (sessions) {
List<EventSession> removes = new List<EventSession>();
foreach (var session in sessions) {
if(session.Send(packet) == false) {
removes.Add(session);
}
}
sessions.RemoveWhere(item => removes.Contains(item));
}
}
public void Close() {
lock (sessions) {
foreach(var session in sessions) {
session.Close();
}
sessions.Clear();
}
listener.Stop();
}
class EventSession {
private EventServer server;
private TcpClient client;
private BinaryWriter writer;
public EventSession(EventServer server, TcpClient tcpClient) {
this.server = server;
this.client = tcpClient;
this.writer = new BinaryWriter(this.client.GetStream());
Trace.WriteLine("EventServer Session start " + tcpClient.Client.RemoteEndPoint);
}
public bool Send(object packet) {
try {
Trace.WriteLine("send " + packet +" to "+client.Client.RemoteEndPoint);
using (var memStream = new MemoryStream()) {
DataContractSerializer ser = new DataContractSerializer(typeof(ServerEvent));
ser.WriteObject(memStream, new ServerEvent() { Body = packet });
byte [] bytes = memStream.ToArray();
writer.Write(bytes.Count());
writer.Write(bytes);
writer.Flush();
}
} catch(Exception e) {
Trace.WriteLine("EventServer Session closed: " + e.Message);
client.Close();
return false;
}
return true;
}
/*
public void ReceiveLoop() {
try {
while (true) {
BinaryFormatter f = new BinaryFormatter();
var request = f.Deserialize(stream);
}
} catch(Exception e) {
Trace.WriteLine("EventServer Session closed: " + e.Message);
client.Close();
}
}
*/
public void Close() {
client.Close();
}
}
}
}
<file_sep>/Candlesticks/ChartLabForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Candlesticks {
public partial class ChartLabForm : Form {
public ChartLabForm() {
InitializeComponent();
}
private void RunTask(object sender, Action<Report> action) {
Report.RunTask(sender, action, dataGridView1, label1);
}
private void 急変戻り戻り_Click(object sender, EventArgs e) {
RunTask(sender, (report) => {
using(DBUtils.OpenThreadConnection()) {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("t", "upc1", "upc2", "uptotal", "downc1", "downc2", "downtotal");
var candles = new CandlesticksGetter() {
Granularity = "M1",
Start = DateTime.Today.AddYears(-5),
End = DateTime.Today
}.Execute().ToList();
List<int> indexList = GetOverMoveCandles(candles).ToList();
foreach (var t in Fibs().Take(20)) {
int upc1 = 0;
int upc2 = 0;
int uptotal = 0;
int downc1 = 0;
int downc2 = 0;
int downtotal = 0;
foreach (var i in indexList) {
if (i + t + 15 >= candles.Count()) {
break;
}
var candleOrg = candles[i];
var candleArter15 = candles[i + t];
var candleArter30 = candles[i + t + 15];
if(candleOrg.IsNull || candleArter15.IsNull || candleArter30.IsNull) {
continue;
}
if (candleOrg.IsUp()) {
if (candleOrg.Close > candleArter15.Close) {
upc1++;
if (candleArter15.Close < candleArter30.Close) {
upc2++;
}
}
uptotal++;
} else {
if (candleOrg.Close < candleArter15.Close) {
downc1++;
if (candleArter15.Close > candleArter30.Close) {
downc2++;
}
}
downtotal++;
}
}
report.WriteLine(t, upc1, upc2, uptotal, downc1, downc2, downtotal);
}
}
});
}
private IEnumerable<int> GetOverMoveCandles(List<Candlestick> candles) {
int index = 0;
while (true) {
index++;
index = Find(index, candles, c => c.PriceRange > 0.20);
if (index == -1) {
break;
}
if (candles.Skip(index - 5).Take(5).Where(c => c.BarRange > 0.10).Count() >= 1) {
continue;
}
yield return index;
}
}
private IEnumerable<int> Fibs() {
int x = 0;
int y = 1;
while(true) {
int next = x + y;
yield return next;
x = y;
y = next;
}
}
private int Find(int start, List<Candlestick> candles, Func<Candlestick,bool> eval) {
for(int i= start; i<candles.Count(); i++) {
if(eval(candles[i])) {
return i;
}
}
return -1;
}
private void 急変日時_Click(object sender, EventArgs e) {
RunTask(sender, (report) => {
using (DBUtils.OpenThreadConnection()) {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("datetime","isUp","price", "2584date","2584price");
var candles = new CandlesticksGetter() {
Granularity = "M1",
Start = DateTime.Today.AddYears(-5),
End = DateTime.Today
}.Execute().ToList();
foreach(int i in GetOverMoveCandles(candles)) {
if(i+2584>=candles.Count()) {
break;
}
report.WriteLine(
candles[i].DateTime.ToString("yyyy年MM月dd日(dddd) h:mm"),
candles[i].IsUp(),
candles[i].Close,
candles[i+2584].DateTime.ToString("yyyy年MM月dd日(dddd) h:mm"),
candles[i+2584].Close);
}
}
});
}
}
}
<file_sep>/CandlesticksServer/Service.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace Candlesticks {
class Service : ServiceBase {
private StartingTask task = null;
public Service() {
this.ServiceName = "Cnadlesticks Server";
this.CanStop = true;
this.CanPauseAndContinue = true;
this.AutoLog = true;
}
protected override void OnStart(string[] args) {
task = new StartingTask();
task.Execute();
}
protected override void OnStop() {
task.Stop();
}
}
}
<file_sep>/Candlesticks/BestTradeTime.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Candlesticks {
class BestTradeTime {
private IEnumerable<Candlestick> candlesticks;
public BestTradeTime(IEnumerable<Candlestick> candlesticks) {
this.candlesticks = candlesticks;
this.ShiftHour = 0;
this.Comparator = f => (int)(Math.Max((double)f[1]/(f[0] + f[1]), (double)f[2]/(f[2] + f[3]))*10000);
this.IsSummerTime = null;
this.Granularity = new TimeSpan(0, 30, 0);
}
public int NumOfCandlesInDay {
get {
return (int)(new TimeSpan(1,0,0,0).Ticks / this.Granularity.Ticks);
}
}
public TimeSpan Granularity {
get;
set;
}
public int ShiftHour {
get;
set;
}
public Func<int[], int> Comparator {
get;
set;
}
public bool? IsSummerTime {
get;
set;
}
public List<Candlestick[]> GetCandlesticksEachDate() {
DateTime oldDate = new DateTime();
Candlestick[] hmList = null;
List<Candlestick[]> result = new List<Candlestick[]>();
TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
foreach (var c in candlesticks) {
if (IsSummerTime!=null && IsSummerTime.Value ==false && est.IsDaylightSavingTime(c.DateTime)) {
continue;
}
DateTime shiftedTime = c.DateTime.AddHours(this.ShiftHour);
if (!oldDate.Equals(shiftedTime.Date)) {
hmList = new Candlestick[NumOfCandlesInDay];
result.Add(hmList);
oldDate = shiftedTime.Date;
}
hmList[GetArrayIndex(new TimeSpan(shiftedTime.Hour, shiftedTime.Minute, 0))]= c;
// hmList[shiftedTime.Hour * 2 + (shiftedTime.Minute == 30 ? 1 : 0)] = c;
}
return result;
}
public int GetArrayIndex(TimeSpan span) {
return (int)(span.Ticks / Granularity.Ticks);
}
public string HMString(int index) {
long t = Granularity.Ticks * index - new TimeSpan(this.ShiftHour, 0, 0).Ticks;
if(t < 0) {
t += new TimeSpan(1, 0, 0, 0).Ticks;
}
return new TimeSpan(t).ToString("h\\:mm");
}
/* public string HMString(int t) {
t -= this.ShiftHour * 2;
if(t < 0) {
t += 48;
}
return (t / 2 < 10 ? "0" : "") + t / 2 + ":" + (t % 2 == 0 ? "00" : "30");
}*/
public IEnumerable<Tuple<int[], int[]>> Calculate( int limit = 0) {
List<Candlestick[]> candlesticksEachDate = GetCandlesticksEachDate();
List<Tuple<int[], int[]>> summary = new List<Tuple<int[], int[]>>();
int dayLength = GetArrayIndex(new TimeSpan(1, 0, 0, 0));
int searchLength = GetArrayIndex(new TimeSpan(0, 6, 0, 0));
for (int s1 = 0; s1 < dayLength; s1++) {
int e1Max = Math.Min(s1 + searchLength, dayLength);
for (int e1 = s1 + 1; e1 < e1Max; e1++) {
for (int s2 = e1; s2 < dayLength; s2++) {
int e2Max = Math.Min(s2 + searchLength, dayLength);
for (int e2 = s2 + 1; e2 < e2Max ; e2++) {
int[] dayResult = new int[4];
summary.Add(new Tuple<int[], int[]>(new int[] { s1, e1, s2, e2 }, dayResult));
foreach (var hml in candlesticksEachDate) {
if (hml[e1].IsNull || hml[s1].IsNull || hml[s2].IsNull || hml[e2].IsNull) {
continue;
}
float d1 = hml[e1].Open - hml[s1].Open;
float d2 = hml[e2].Open - hml[s2].Open;
if(d1 == 0 || d2 == 0) {
continue;
}
dayResult[(d1 >= 0 ? 0 : 2) + (d2 >= 0 ? 0 : 1)]++;
}
}
}
}
}
if(limit == 0) {
return summary;
} else {
return summary.OrderByDescending(t => this.Comparator(t.Item2)).Take(limit);
}
}
public IEnumerable<Tuple<int[], int[]>> CalculateDoubleCheckRange(TimeSpan tradeStart, TimeSpan tradeEnd) {
List<Candlestick[]> candlesticksEachDate = GetCandlesticksEachDate();
int dayLength = GetArrayIndex(new TimeSpan(1, 0, 0, 0));
int searchLength = GetArrayIndex(new TimeSpan(0, 6, 0, 0));
int s3 = GetArrayIndex(tradeStart);
int e3 = GetArrayIndex(tradeEnd);
int progress = 0;
for (int s1 = 0; s1 < s3; s1++) {
int newProg = s1 * 100 / s3;
if(progress < newProg) {
Console.WriteLine(newProg+"%");
progress = newProg;
}
int e1Max = Math.Min(s1 + searchLength, s3);
for (int e1 = s1 + 1; e1 <= e1Max; e1++) {
for (int s2 = s1 + 1; s2 < s3; s2++) {
int e2Max = Math.Min(s2 + searchLength, s3);
for (int e2 = s2 + 1; e2 <= e2Max; e2++) {
if(s1 == s2 || e1 == e2) {
continue;
}
int[] dayResult = new int[8];
foreach (var hml in candlesticksEachDate) {
if (hml[e1].IsNull || hml[s1].IsNull || hml[s2].IsNull || hml[e2].IsNull || hml[s3].IsNull || hml[e3].IsNull) {
continue;
}
float d1 = hml[e1].Open - hml[s1].Open;
float d2 = hml[e2].Open - hml[s2].Open;
float d3 = hml[e3].Open - hml[s3].Open;
if (d1 == 0 || d2 == 0 || d3 == 0) {
continue;
}
dayResult[(d1 > 0 ? 0 : 4) + (d2 > 0 ? 0 : 2) + (d3 > 0 ? 0 : 1)]++;
}
yield return new Tuple<int[], int[]>(new int[] { s1, e1, s2, e2 }, dayResult);
}
}
}
}
}
}
}
<file_sep>/CandlesticksServer/Program.cs
using Npgsql;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
namespace Candlesticks {
class Program {
static void Main(string[] args) {
Setting.LoadInstance(args[1]);
Trace.Listeners.Add(new TextLineTraceListener(Setting.Instance.LogFilePath));
if (args[0] == "--service") {
ServiceBase.Run(new Service());
} else {
new StartingTask().Execute();
Thread.Sleep(int.MaxValue);
}
}
}
}
<file_sep>/CandlesticksCommon/TradePattern.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace Candlesticks
{
public class TradePattern {
public TradeCondition TradeCondition;
public TradeOrders TradeOrders;
}
public class TradeOrders : List<TimeTradeOrder> {
public TradeOrders(params TimeTradeOrder [] orders) : base(orders) {
}
public string GetTradeDescription(TradeContext tradeContext) {
return String.Join(" ", this.Select(order => order.GetTradeDescription(tradeContext)));
}
public void DoTrade(TradeContext tradeContext) {
foreach (var order in this) {
tradeContext.DoTrade(order.TradeType, order.Time);
}
}
public bool IsInTradeTime {
get {
DateTime now = DateTime.Now;
DateTime first = DateTime.Today.Add(this.Min(o => o.Time));
DateTime last = DateTime.Today.Add(this.Max(o => o.Time));
return first <= now && now <= last;
}
}
}
public class TradeContext {
public string Instrument;
public Func<DateTime, float> GetPrice;
public DateTime Date;
public List<Tuple<TradeType, float>> positions = new List<Tuple<TradeType, float>>();
public float Profit = 0f;
public bool IsValid = true;
public TradeContext() {
GetPrice = GetPriceImpl;
}
public void DoTrade(TradeType tradeType, TimeSpan time) {
float currentPrice = GetPrice(Date.AddTicks(time.Ticks));
if(float.IsNaN(currentPrice)) {
IsValid = false;
return;
}
if (tradeType != TradeType.Settle) {
positions.Add(new Tuple<TradeType, float>(tradeType, currentPrice));
} else {
foreach(var position in positions) {
if(position.Item1 == TradeType.Ask) {
Profit += currentPrice - position.Item2;
} else {
Profit += position.Item2 - currentPrice;
}
}
positions.Clear();
}
}
private float GetPriceImpl(DateTime dateTime) {
return new CandlesticksGetter() {
Start = dateTime.AddMinutes(-10),
Granularity = "M1",
Count = 10,
Instrument = this.Instrument
}.Execute().Reverse().Where(c => !c.IsNull)
.Select(c => c.Close).DefaultIfEmpty(float.NaN).First();
}
}
public interface TradeCondition {
bool IsMatch(out Signal signal, TradeContext tradeContext);
string GetCheckDescription();
}
public class TradeConditionAnd : TradeCondition {
public TradeCondition[] TradeConditions;
public string GetCheckDescription() {
return String.Join("かつ", TradeConditions.Select(s => "("+s.GetCheckDescription()+")"));
}
public bool IsMatch(out Signal signal, TradeContext tradeContext) {
signal = null;
foreach(var c in TradeConditions) {
Signal s = null;
bool result = c.IsMatch(out s, tradeContext);
if(s != null) {
if(signal == null) {
signal = new AndSignal();
}
((AndSignal)signal).Add(s);
}
if(result == false) {
return false;
}
}
return true;
}
public class AndSignal : Signal {
private List<Signal> signals = new List<Signal>();
public void Add(Signal signal) {
signals.Add(signal);
}
public bool IsCheckFinished {
get {
return signals.Where(s => s.IsCheckFinished == false).Count() == 0;
}
}
public bool IsValid {
get {
return signals.Where(s => s.IsValid == false).Count() == 0;
}
}
public string GetCheckResultDescription() {
return String.Join(" ", signals.Select(s => s.GetCheckResultDescription()));
}
}
}
public class TimeTradeOrder {
public TradeType TradeType;
public TimeSpan Time;
public string Instrument;
public string GetTradeDescription(TradeContext tradeContext) {
DateTime priceGettableTime = DateTime.Now.AddSeconds(-5);
float tradeStartPrice = float.NaN;
var builder = new StringBuilder();
builder.Append(Time.ToString());
builder.Append(" ");
builder.Append(this.TradeType);
builder.Append(" ");
DateTime tradeStartDateTime = tradeContext.Date.AddTicks(this.Time.Ticks);
if (tradeStartDateTime < priceGettableTime) {
tradeStartPrice = tradeContext.GetPrice(tradeStartDateTime);
builder.Append(PriceFormatter.Format(tradeStartPrice, Instrument));
} else {
builder.Append("???");
}
return builder.ToString();
}
}
public interface Signal {
string GetCheckResultDescription();
bool IsCheckFinished {
get;
}
bool IsValid {
get;
}
}
}
<file_sep>/CandlesticksCommon/TimePattern.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace Candlesticks
{
class TimeOfDayPattern : TradeCondition
{
public TimeSpan CheckStartTime;
public TimeSpan CheckEndTime;
public bool IsCheckUp;
public string Instrument = null;
public TimeOfDayPattern() {
}
public bool IsMatch(out Candlesticks.Signal signal, TradeContext tradeContext) {
signal = null;
DateTime date = tradeContext.Date;
if(date.Add(CheckStartTime) > date.Add(CheckEndTime)) {
throw new Exception("checkStartDateTime > checkEndDateTime");
}
if (date.Add(CheckStartTime) >= DateTime.Now) {
return false;
}
signal = new Signal() {
Pattern = this,
};
float startPrice = tradeContext.GetPrice(date.Add(CheckStartTime));
((Signal)signal).CheckStartPrice = startPrice;
if (date.Add(CheckEndTime) >= DateTime.Now) {
return false;
}
float endPrice = tradeContext.GetPrice(date.Add(CheckEndTime));
((Signal)signal).CheckEndPrice = endPrice;
if (this.IsCheckUp) {
return endPrice > startPrice;
} else {
return endPrice < startPrice;
}
}
public string GetCheckDescription() {
return "["+this.Instrument + "] " + CheckStartTime + "~" + CheckEndTime +
"の間に価格が" + (IsCheckUp ? "上がっていたら" : "下がっていたら");
}
public class Signal : Candlesticks.Signal {
public TimeOfDayPattern Pattern;
public float CheckStartPrice = float.NaN;
public float CheckEndPrice = float.NaN;
public string GetCheckResultDescription() {
string priceFormat = PriceFormatter.GetPriceFormat(Pattern.Instrument);
return CheckStartPrice.ToString(priceFormat) + "[" + Pattern.CheckStartTime + "]→"
+ CheckEndPrice.ToString(priceFormat) + "[" + Pattern.CheckEndTime + "](" +
(CheckStartPrice < CheckEndPrice ? "+" : "") + (CheckEndPrice - CheckStartPrice).ToString(priceFormat) + ")";
}
public bool IsValid {
get {
return !float.IsNaN(CheckStartPrice) && !float.IsNaN(CheckEndPrice);
}
}
public bool IsCheckFinished {
get {
return DateTime.Today.Add(Pattern.CheckEndTime) <= DateTime.Now;
}
}
}
public struct Time {
int Hour;
int Minutes;
public Time(TimeSpan timeSpan) {
this.Hour = timeSpan.Hours;
this.Minutes = timeSpan.Minutes;
}
public Time(int hour, int minute) {
this.Hour = hour;
this.Minutes = minute;
}
public long Ticks {
get {
return ((Hour * 60L) + Minutes) * 60L * 10000000L;
}
}
public DateTime Todays {
get {
return DateTime.Today.AddTicks(this.Ticks);
}
}
public DateTime ToDateTime(DateTime date) {
return date.AddTicks(this.Ticks);
}
public override string ToString() {
return Hour + ":" + Minutes.ToString("D2");
}
public TimeSpan TimeSpan {
get {
return new TimeSpan(Hour, Minutes, 0);
}
}
}
}
}
<file_sep>/Candlesticks/MouseTestForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Candlesticks {
public partial class MouseTestForm : Form {
[DllImport("USER32.dll", CallingConvention = CallingConvention.StdCall)]
static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
private const int MOUSEEVENTF_LEFTDOWN = 0x2;
private const int MOUSEEVENTF_LEFTUP = 0x4;
public MouseTestForm() {
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e) {
}
private void button1_Click(object sender, EventArgs e) {
Cursor.Position = new Point(2375, 756);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
private void MouseTestForm_KeyPress(object sender, KeyPressEventArgs e) {
if (e.KeyChar == 'b') {
Setting.Instance.MouseClickPositionUSD_JPY.Bid = Cursor.Position;
bidCursorPosLabelUsdJpy.Text = Cursor.Position.ToString();
}
if (e.KeyChar == 'a') {
Setting.Instance.MouseClickPositionUSD_JPY.Ask = Cursor.Position;
askCursorPosLabelUsdJpy.Text = Cursor.Position.ToString();
}
if (e.KeyChar == 's') {
Setting.Instance.MouseClickPositionUSD_JPY.Settle = Cursor.Position;
settleCursorPosLabelUsdJpy.Text = Cursor.Position.ToString();
}
if (e.KeyChar == '1') {
Setting.Instance.MouseClickPositionEUR_USD.Bid = Cursor.Position;
bidCursorPosLabelEurUsd.Text = Cursor.Position.ToString();
}
if (e.KeyChar == '2') {
Setting.Instance.MouseClickPositionEUR_USD.Ask = Cursor.Position;
askCursorPosLabelEurUsd.Text = Cursor.Position.ToString();
}
if (e.KeyChar == '3') {
Setting.Instance.MouseClickPositionEUR_USD.Settle = Cursor.Position;
settleCursorPosLabelEurUsd.Text = Cursor.Position.ToString();
}
Setting.Instance.Save();
}
private void button6_Click(object sender, EventArgs e) {
Cursor.Position = Setting.Instance.MouseClickPositionUSD_JPY.Bid;
}
private void button5_Click(object sender, EventArgs e) {
Cursor.Position = Setting.Instance.MouseClickPositionUSD_JPY.Ask;
}
private void button4_Click(object sender, EventArgs e) {
Cursor.Position = Setting.Instance.MouseClickPositionUSD_JPY.Settle;
}
private void button3_Click(object sender, EventArgs e) {
Cursor.Position = Setting.Instance.MouseClickPositionEUR_USD.Bid;
}
private void button2_Click(object sender, EventArgs e) {
Cursor.Position = Setting.Instance.MouseClickPositionEUR_USD.Ask;
}
private void button1_Click_1(object sender, EventArgs e) {
Cursor.Position = Setting.Instance.MouseClickPositionEUR_USD.Settle;
}
private void MouseTestForm_Load(object sender, EventArgs e) {
bidCursorPosLabelUsdJpy.Text = Setting.Instance.MouseClickPositionUSD_JPY.Bid.ToString();
askCursorPosLabelUsdJpy.Text = Setting.Instance.MouseClickPositionUSD_JPY.Ask.ToString();
settleCursorPosLabelUsdJpy.Text = Setting.Instance.MouseClickPositionUSD_JPY.Settle.ToString();
bidCursorPosLabelEurUsd.Text = Setting.Instance.MouseClickPositionEUR_USD.Bid.ToString();
askCursorPosLabelEurUsd.Text = Setting.Instance.MouseClickPositionEUR_USD.Ask.ToString();
settleCursorPosLabelEurUsd.Text = Setting.Instance.MouseClickPositionEUR_USD.Settle.ToString();
}
}
}
<file_sep>/CandlesticksCommon/DBUtils.cs
using Npgsql;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Candlesticks
{
class DBUtils {
private static ThreadLocal<NpgsqlConnection> threadConnection = new ThreadLocal<NpgsqlConnection>();
public static NpgsqlConnection OpenConnection() {
var dbSetting = Setting.Instance.DBConnection;
var conn = new NpgsqlConnection(
"Host=" + dbSetting.Host +
";Port=" + dbSetting.Port +
";Username=" + dbSetting.UserName +
";Password=" + dbSetting.Password +
";Database=" + dbSetting.Database );
conn.Open();
return conn;
}
public static NpgsqlConnection GetConnection() {
return threadConnection.Value;
}
public static ThreadConnection OpenThreadConnection() {
if(threadConnection.Value != null) {
throw new Exception("Already exists thread connection (TODO nested support)");
}
threadConnection.Value = OpenConnection();
return new ThreadConnection();
}
public class ThreadConnection : IDisposable {
#region IDisposable Support
private bool disposedValue = false; // 重複する呼び出しを検出するには
protected virtual void Dispose(bool disposing) {
if (!disposedValue) {
if (disposing) {
DBUtils.threadConnection.Value.Close();
DBUtils.threadConnection.Value = null;
}
disposedValue = true;
}
}
public void Dispose() {
Dispose(true);
}
#endregion
}
}
}
<file_sep>/CandlesticksCommon/PriceFormatter.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Candlesticks
{
class PriceFormatter
{
public static string Format(float price, string instrument) {
return price.ToString(GetPriceFormat(instrument));
}
public static string GetPriceFormat(string instrument) {
string priceFormat = null;
switch (instrument) {
case "USD_JPY":
case "EUR_JPY":
priceFormat = "F3";
break;
case "EUR_USD":
priceFormat = "F5";
break;
default:
throw new Exception();
}
return priceFormat;
}
}
}
<file_sep>/CandlesticksServer/StartingTask.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Candlesticks {
class StartingTask {
private EventServer eventServer;
public void Execute() {
try {
Trace.WriteLine("Candlesticks Server starting...");
this.eventServer = new EventServer();
new OrderBookCollector(eventServer);
new Thread(new ThreadStart(() => { eventServer.Execute(); })).Start();
} catch(Exception e) {
Trace.WriteLine(e.ToString());
throw e;
}
Trace.WriteLine("Candlesticks Server started");
}
public void Stop() {
Trace.WriteLine("Candlesticks Server stopping...");
try {
this.eventServer.Close();
} catch (Exception e) {
Trace.WriteLine(e.ToString());
throw e;
}
Trace.WriteLine("Candlesticks Server setopped");
}
}
}
<file_sep>/Candlesticks/PositionsForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Candlesticks {
public partial class PositionsForm : Form {
private DateTime dateTime;
public PositionsForm() {
InitializeComponent();
}
private void PositionsForm_Load(object sender, EventArgs e) {
dateTime = DateTime.Now;
LoadChart();
EventReceiver.Instance.OrderBookUpdatedEvent += OnOrderBookUpdated;
}
private void OnOrderBookUpdated(OrderBookUpdated orderBookUpdated) {
Invoke(new Action(()=> {
dateTime = DateTime.Now;
LoadChart();
}));
}
private DateTime NormalizeDateTime(DateTime t) {
return new DateTime(t.Year, t.Month, t.Day, t.Hour, t.Minute / 20 * 20, 0, t.Kind);
}
private void LoadChart() {
using (DBUtils.OpenThreadConnection()) {
DateTime start = NormalizeDateTime(dateTime.AddDays(-1));
chart1.Series.Clear();
chart1.ChartAreas.Clear();
chart1.Titles.Clear();
var candles = Candlestick.Aggregate(new CandlesticksGetter() {
Granularity = "M10",
Start = start,
End = start.AddDays(1)
}.Execute().ToList(), 2).ToList();
var positions = new OrderBookPricePointDao(
DBUtils.GetConnection()).GetPositionSummaryGroupByOrderBookDateTime(start, dateTime)
.Select(p => new Tuple<DateTime,float,float>(NormalizeDateTime(p.Item1),p.Item2,p.Item3)).ToList();
DateTime startChart = candles[0].DateTime;
DateTime endChart = candles[candles.Count() - 1].DateTime.AddMinutes(20);
if(candles.Where(c=>!c.IsNull).Count() >= 1) {
CreatePositionSmummaryChartArea(positions, startChart, endChart);
CreateCandlesticksChartArea(candles, positions, startChart, endChart);
}
nextDayButton.Enabled = dateTime.AddDays(1) <= DateTime.Now;
dateLabel.Text = dateTime.ToString("M/dd");
}
}
private List<DateTime> SearchOpenStartPositions(IEnumerable<Tuple<DateTime,float,float>> positions) {
bool isClosed = true;
List<DateTime> result = new List<DateTime>();
foreach(var p in positions) {
if(p.Item2 + p.Item3 >= 99.9f) {
isClosed = true;
} else if(isClosed) {
result.Add(p.Item1);
isClosed = false;
}
}
return result;
}
private void CreateCandlesticksChartArea(List<Candlestick> candles, List<Tuple<DateTime, float, float>> summary, DateTime start, DateTime end) {
ChartArea chartArea = new ChartArea("candlesticks");
chart1.ChartAreas.Add(chartArea);
float low = candles.Where(c=>!c.IsNull).Select(c => c.Low).Min();
float high = candles.Where(c => !c.IsNull).Select(c => c.High).Max();
double n = 0.1d;
while (true) {
double d = Math.Round((high - low) / n);
if (d <= 2) {
break;
}
n *= 2;
}
chartArea.AxisX.LabelStyle.Enabled = false;
chartArea.AxisX.MajorGrid.Enabled = true;
chartArea.AxisX.MajorGrid.IntervalType = DateTimeIntervalType.Hours;
chartArea.AxisX.MajorGrid.Interval = 1;
chartArea.AxisX.MinorGrid.Enabled = true;
chartArea.AxisX.MinorGrid.IntervalType = DateTimeIntervalType.Minutes;
chartArea.AxisX.MinorGrid.Interval = 20;
chartArea.AxisX.MinorGrid.LineColor = Color.LightGray;
chartArea.AxisX.Minimum = start.ToOADate();
chartArea.AxisX.Maximum = end.ToOADate();
chartArea.AxisY.Maximum = Math.Ceiling(high / n) * n;
chartArea.AxisY.Minimum = Math.Floor(low / n) * n;
Series openStartSeries = new Series();
chart1.Series.Add(openStartSeries);
openStartSeries.ChartArea = "candlesticks";
openStartSeries.ChartType = SeriesChartType.RangeColumn;
openStartSeries.SetCustomProperty("PixelPointWidth", "2");
foreach (var dateTime in SearchOpenStartPositions(summary)) {
openStartSeries.Points.Add(new DataPoint(dateTime.ToOADate(), new double[] { chartArea.AxisY.Minimum, chartArea.AxisY.Maximum }));
}
Series candleSeries = new Series();
chart1.Series.Add(candleSeries);
candleSeries.ChartArea = "candlesticks";
candleSeries.XValueType = ChartValueType.DateTime;
candleSeries.ChartType = SeriesChartType.Candlestick;
candleSeries.SetCustomProperty("PriceUpColor", "red");
candleSeries.SetCustomProperty("PriceDownColor", "blue");
foreach (var candle in candles) {
if(candle.IsNull) {
continue;
}
DateTime t = candle.DateTime.AddMinutes(10);
// Console.WriteLine(String.Format("{0} {1} {2} {3} {4}",t, candle.High, candle.Low, candle.Open, candle.Close));
candleSeries.Points.Add(new DataPoint(t.ToOADate(), new double[] {
candle.High, candle.Low, candle.Open, candle.Close }) { Color = candle.IsUp() ? Color.Red : Color.Blue });
}
chartArea.AlignWithChartArea = "position_summary";
}
private void CreatePositionSmummaryChartArea(List<Tuple<DateTime, float, float>> summary, DateTime start, DateTime end) {
ChartArea chartArea = new ChartArea("position_summary");
chart1.ChartAreas.Add(chartArea);
chartArea.AxisX.LabelStyle.IntervalType = DateTimeIntervalType.Hours;
chartArea.AxisX.LabelStyle.Interval = 1;
chartArea.AxisX.MajorGrid.Enabled = true;
chartArea.AxisX.MajorGrid.IntervalType = DateTimeIntervalType.Hours;
chartArea.AxisX.MajorGrid.Interval = 1;
chartArea.AxisX.MinorGrid.Enabled = true;
chartArea.AxisX.MinorGrid.IntervalType = DateTimeIntervalType.Minutes;
chartArea.AxisX.MinorGrid.Interval = 20;
chartArea.AxisX.MinorGrid.LineColor = Color.LightGray;
chartArea.AxisX.Minimum = start.ToOADate();
chartArea.AxisX.Maximum = end.ToOADate();
chartArea.AxisY.Maximum = 44;
chartArea.AxisY.Minimum = 30;
chartArea.AxisY.MajorGrid.Enabled = true;
chartArea.AxisY.MajorGrid.Interval = 5;
chartArea.AxisY.MinorGrid.Enabled = true;
chartArea.AxisY.MinorGrid.Interval = 1;
chartArea.AxisY.MinorGrid.LineColor = Color.LightGray;
// chartArea.AxisY.Su
chartArea.AxisY2.Enabled = AxisEnabled.True;
chartArea.AxisY2.Maximum = 70;
chartArea.AxisY2.Minimum = 56;
chartArea.AxisY2.MajorGrid.Enabled = false;
chartArea.AxisY2.MinorGrid.Enabled = false;
chartArea.AxisY2.IsReversed = true;
Series openStartSeries = new Series();
chart1.Series.Add(openStartSeries);
openStartSeries.ChartType = SeriesChartType.RangeColumn;
openStartSeries.SetCustomProperty("PixelPointWidth", "2");
foreach (var dateTime in SearchOpenStartPositions(summary)) {
openStartSeries.Points.Add(new DataPoint(dateTime.ToOADate(), new double[] { chartArea.AxisY.Minimum, chartArea.AxisY.Maximum }));
}
Series shortPositionsSeries = new Series();
chart1.Series.Add(shortPositionsSeries);
shortPositionsSeries.ChartArea = "position_summary";
shortPositionsSeries.ChartType = SeriesChartType.Line;
shortPositionsSeries.YAxisType = AxisType.Primary;
shortPositionsSeries.XValueType = ChartValueType.DateTime;
shortPositionsSeries.Color = Color.Blue;
shortPositionsSeries.LegendText = "short";
Series longPositionsSeries = new Series();
chart1.Series.Add(longPositionsSeries);
longPositionsSeries.ChartArea = "position_summary";
longPositionsSeries.ChartType = SeriesChartType.Line;
longPositionsSeries.YAxisType = AxisType.Secondary;
longPositionsSeries.XValueType = ChartValueType.DateTime;
longPositionsSeries.Color = Color.Red;
longPositionsSeries.LegendText = "long";
foreach (var s in summary) {
// chartArea.AxisX.LabelStyle.Format = "HH";
DateTime t = s.Item1;
shortPositionsSeries.Points.Add(new DataPoint(t.ToOADate(), s.Item2));
longPositionsSeries.Points.Add(new DataPoint(t.ToOADate(), s.Item3) {
AxisLabel = s.Item1.ToString(t.Hour == 0 ? "M/d" : "%H")
});
}
}
private void previousDayButton_Click(object sender, EventArgs e) {
dateTime = dateTime.AddDays(-1);
LoadChart();
}
private void nextDayButton_Click(object sender, EventArgs e) {
dateTime = dateTime.AddDays(1);
LoadChart();
}
private void PositionsForm_FormClosing(object sender, FormClosingEventArgs e) {
EventReceiver.Instance.OrderBookUpdatedEvent -= OnOrderBookUpdated;
}
}
}
<file_sep>/CandlesticksCommon/OandaAPI.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Xml;
using System.Runtime.Serialization;
using System.Net;
using System.Threading;
using System.Text.RegularExpressions;
namespace Candlesticks {
class OandaAPI : IDisposable{
private static OandaAPI instance = new OandaAPI();
public static OandaAPI Instance {
get {
return instance;
}
}
private static string BearerToken {
get {
return Setting.Instance.OandaBearerToken;
}
}
private static string AccountId {
get {
return Setting.Instance.OandaAccountId;
}
}
private static readonly DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private HttpClient client;
public OandaAPI() {
client = new HttpClient();
client.BaseAddress = new Uri("https://api-fxpractice.oanda.com/");
}
// http://www.oanda.com/lang/ja/forex-trading/analysis/currency-units-calculator
// JP225_USD SPX500_USD BCO_USD SGD_HKD NAS100_USD USB10Y_USD US30_USD WTICO_USD
public IEnumerable<OandaCandle> GetCandles(DateTime start, DateTime end, string instrument = "USD_JPY", string granularity = "M30") {
lock(this) {
if (start == end) {
Console.WriteLine("start == end");
return new List<OandaCandle>();
}
string startParam = WebUtility.UrlEncode(XmlConvert.ToString(start, XmlDateTimeSerializationMode.Utc));
string endParam = WebUtility.UrlEncode(XmlConvert.ToString(end, XmlDateTimeSerializationMode.Utc));
return GetCandles("v1/candles?instrument=" + instrument + "&start=" + startParam + "&end=" + endParam + "&candleFormat=midpoint&granularity=" + granularity + "&dailyAlignment=0&alignmentTimezone=Asia%2FTokyo");
}
}
public IEnumerable<OandaCandle> GetCandles(int count, string instrument = "USD_JPY", string granularity = "M30") {
lock (this) {
return GetCandles("v1/candles?instrument=" + instrument + "&count=" + count + "&candleFormat=midpoint&granularity=" + granularity + "&dailyAlignment=0&alignmentTimezone=Asia%2FTokyo");
}
}
public IEnumerable<OandaCandle> GetCandles(string requestUri) {
lock (this) {
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", OandaAPI.BearerToken);
Console.WriteLine(requestUri);
Task<HttpResponseMessage> webTask = client.SendAsync(request);
webTask.Wait();
Task<String> readTask = webTask.Result.Content.ReadAsStringAsync();
readTask.Wait();
if (webTask.Result.StatusCode == HttpStatusCode.NoContent) {
Console.WriteLine("205 NoContent");
return new List<OandaCandle>();
}
if (webTask.Result.StatusCode != HttpStatusCode.OK) {
Console.WriteLine("HttpStatus:" + webTask.Result.StatusCode + " " + readTask.Result);
throw new Exception(readTask.Result);
}
// Console.WriteLine(readTask.Result);
var settings = new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
var serializer = new DataContractJsonSerializer(typeof(OandaCandles), settings);
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(readTask.Result))) {
return ((OandaCandles)serializer.ReadObject(ms)).candles;
}
}
}
public Dictionary<DateTime, PricePoints> GetOrderbookData(string instrument = "USD_JPY", int period = 43200) {
lock(this) {
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "labs/v1/orderbook_data?instrument=" + instrument + "&period=" + period);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", OandaAPI.BearerToken);
Task<HttpResponseMessage> webTask = client.SendAsync(request);
webTask.Wait();
Task<String> readTask = webTask.Result.Content.ReadAsStringAsync();
readTask.Wait();
if (webTask.Result.StatusCode != HttpStatusCode.OK) {
throw new Exception(readTask.Result);
}
var settings = new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
var serializer = new DataContractJsonSerializer(typeof(Dictionary<long, PricePoints>), settings);
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(readTask.Result))) {
Dictionary<DateTime, PricePoints> result = new Dictionary<DateTime, PricePoints>();
foreach (var e in (Dictionary<long, PricePoints>)serializer.ReadObject(ms)) {
result[UNIX_EPOCH.AddSeconds(e.Key).ToLocalTime()] = e.Value;
}
return result;
}
}
}
// 停止するにはHttpClientをDispose
public HttpClient GetPrices(Action<string, DateTime,float,float> receiver, string instrument = "USD_JPY") {
new Thread(new ThreadStart(async () => {
client.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
client.BaseAddress = new Uri("https://stream-fxpractice.oanda.com/");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "v1/prices?accountId=" + AccountId + "&instruments=" + instrument.Replace(",","%2c"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", OandaAPI.BearerToken);
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
StreamReader reader = new StreamReader(await response.Content.ReadAsStreamAsync());
//{"tick":{"instrument":"USD_JPY","time":"2016-03-03T11:44:15.633667Z","bid":113.93,"ask":113.934}}
var regex = new Regex(@"""instrument"":""(.+)"",""time"":""(.+)"",""bid"":(\d+(\.\d+)?),""ask"":(\d+(\.\d+)?)");
// var regex = new Regex(@"""bid"":(\d+(\.\d+)?),""ask"":(\d+(\.\d+)?)");
try {
do {
string s = reader.ReadLine();
var match = regex.Match(s);
if(match.Success) {
receiver(
match.Groups[1].Value,
XmlConvert.ToDateTime(match.Groups[2].Value, XmlDateTimeSerializationMode.Local),
float.Parse(match.Groups[3].Value), float.Parse(match.Groups[5].Value));
Console.WriteLine(">" + s);
}
} while (true);
} catch (IOException ex) {
Console.WriteLine(ex);
}
})).Start();
return client;
}
#region IDisposable Support
private bool disposedValue = false; // 重複する呼び出しを検出するには
protected virtual void Dispose(bool disposing) {
if (!disposedValue) {
if (disposing) {
client.Dispose();
}
disposedValue = true;
}
}
public void Dispose() {
Dispose(true);
}
#endregion
}
class Candles {
private string json;
public Candles(string json) {
this.json = json;
}
public IEnumerable<OandaCandle> Parse() {
var settings = new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
var serializer = new DataContractJsonSerializer(typeof(OandaCandles), settings);
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) {
return ((OandaCandles)serializer.ReadObject(ms)).candles;
}
}
}
[DataContract]
class PricePoints {
[DataMember]
public Dictionary<float, PricePoint> price_points;
[DataMember]
public float rate;
}
[DataContract]
class PricePoint {
[DataMember]
public float os;
[DataMember]
public float ps;
[DataMember]
public float pl;
[DataMember]
public float ol;
}
[DataContract]
class OandaCandles {
[DataMember]
public List<OandaCandle> candles;
}
[DataContract]
class OandaCandle {
[DataMember]
public string time;
[DataMember]
public float openMid;
[DataMember]
public float highMid;
[DataMember]
public float lowMid;
[DataMember]
public float closeMid;
[DataMember]
public int volume;
public DateTime DateTime {
get {
return XmlConvert.ToDateTime(time, XmlDateTimeSerializationMode.Local);
}
}
public Candlestick Candlestick {
get {
Candlestick s = new Candlestick();
s.DateTime = this.DateTime;
s.Open = this.openMid;
s.Close = this.closeMid;
s.High = this.highMid;
s.Low = this.lowMid;
s.Volume = this.volume;
return s;
}
}
}
}
<file_sep>/CandlesticksCommon/CandlestickDao.cs
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace Candlesticks
{
class CandlestickDao {
public CandlestickDao() {
}
public IEnumerable<Entity> GetBy(string instrument, string granularity, DateTime start, DateTime end) {
using (var cmd = new NpgsqlCommand()) {
cmd.Connection = DBUtils.GetConnection();
cmd.CommandText = "select id,date_time,open,high,low,close,volume from candlestick where instrument = :instrument and granularity = :granularity and :start <= date_time and date_time < :end order by date_time";
cmd.Parameters.Add(new NpgsqlParameter("instrument", DbType.String));
cmd.Parameters.Add(new NpgsqlParameter("granularity", DbType.String));
cmd.Parameters.Add(new NpgsqlParameter("start", DbType.DateTime));
cmd.Parameters.Add(new NpgsqlParameter("end", DbType.DateTime));
cmd.Parameters["instrument"].Value = instrument;
cmd.Parameters["granularity"].Value = granularity;
cmd.Parameters["start"].Value = start;
cmd.Parameters["end"].Value = end;
using (var dr = cmd.ExecuteReader()) {
while (dr.Read()) {
var entity = new Entity();
entity.Dao = this;
entity.Id = (Int64)dr[0];
entity.Instrument = instrument;
entity.Granularity = granularity;
entity.DateTime = (DateTime)dr[1];
entity.Open = (float)((decimal)dr[2]);
entity.High = (float)((decimal)dr[3]);
entity.Low = (float)((decimal)dr[4]);
entity.Close = (float)((decimal)dr[5]);
entity.Volume = (int)dr[6];
yield return entity;
}
}
}
}
public Entity CreateNewEntity() {
return new Entity() { Dao = this };
}
public class Entity {
public CandlestickDao Dao;
public Int64 Id;
public string Instrument;
public string Granularity;
public DateTime DateTime;
public float Open;
public float High;
public float Low;
public float Close;
public int Volume;
public void Save() {
using (var cmd = new NpgsqlCommand()) {
cmd.Connection = DBUtils.GetConnection();
cmd.CommandText = "insert into candlestick(instrument,granularity,date_time,open,high,low,close,volume) values(:instrument,:granularity,:date_time,:open,:high,:low,:close,:volume) returning id";
cmd.Parameters.Add(new NpgsqlParameter("instrument", DbType.String));
cmd.Parameters.Add(new NpgsqlParameter("granularity", DbType.String));
cmd.Parameters.Add(new NpgsqlParameter("date_time", DbType.DateTime));
cmd.Parameters.Add(new NpgsqlParameter("open", DbType.Single));
cmd.Parameters.Add(new NpgsqlParameter("high", DbType.Single));
cmd.Parameters.Add(new NpgsqlParameter("low", DbType.Single));
cmd.Parameters.Add(new NpgsqlParameter("close", DbType.Single));
cmd.Parameters.Add(new NpgsqlParameter("volume", DbType.Int32));
cmd.Parameters["instrument"].Value = this.Instrument;
cmd.Parameters["granularity"].Value = this.Granularity;
cmd.Parameters["date_time"].Value = this.DateTime;
cmd.Parameters["open"].Value = this.Open;
cmd.Parameters["high"].Value = this.High;
cmd.Parameters["low"].Value = this.Low;
cmd.Parameters["close"].Value = this.Close;
cmd.Parameters["volume"].Value = this.Volume;
this.Id = (Int64)cmd.ExecuteScalar();
}
}
public Candlestick Candlestick {
get {
Candlestick result = new Candlestick();
result.DateTime = this.DateTime;
result.Open = this.Open;
result.High = this.High;
result.Low = this.Low;
result.Close = this.Close;
result.Volume = this.Volume;
return result;
}
}
}
}
}
<file_sep>/CandlesticksCommon/OrderBookDao.cs
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace Candlesticks
{
class OrderBookDao
{
private NpgsqlConnection connection;
public OrderBookDao(NpgsqlConnection connection) {
this.connection = connection;
}
public Int64 GetCountByDateTime(string instrument, DateTime dateTime) {
using (var cmd = new NpgsqlCommand()) {
cmd.Connection = connection;
cmd.CommandText = "select count(*) from order_book where instrument=:instrument and date_time=:date_time";
cmd.Parameters.Add(new NpgsqlParameter("instrument", DbType.String));
cmd.Parameters.Add(new NpgsqlParameter("date_time", DbType.DateTime));
cmd.Parameters["instrument"].Value = instrument;
cmd.Parameters["date_time"].Value = dateTime;
using (var dr = cmd.ExecuteReader()) {
if (dr.Read()) {
return (Int64)dr[0];
}
throw new Exception();
}
}
}
public IEnumerable<Entity> GetByInstrumentOrderByDateTimeDescendant(string instrument) {
using (var cmd = new NpgsqlCommand()) {
cmd.Connection = connection;
cmd.CommandText = "select id, date_time, rate from order_book where instrument=:instrument order by date_time desc ";
cmd.Parameters.Add(new NpgsqlParameter("instrument", DbType.String));
cmd.Parameters["instrument"].Value = instrument;
using (var dr = cmd.ExecuteReader()) {
while (dr.Read()) {
var entity = new Entity();
entity.Connection = connection;
entity.Id = (Int64)dr[0];
entity.DateTime = (DateTime)dr[1];
entity.Rate =(float) ((decimal)dr[2]);
yield return entity;
}
}
}
}
public Entity GetByInstrumentAndDateTime(string instrument, DateTime dateTime) {
using (var cmd = new NpgsqlCommand()) {
cmd.Connection = connection;
cmd.CommandText = "select id, date_time, rate from order_book where instrument=:instrument and date_time=:date_time";
cmd.Parameters.Add(new NpgsqlParameter("date_time", DbType.DateTime));
cmd.Parameters.Add(new NpgsqlParameter("instrument", DbType.String));
cmd.Parameters["date_time"].Value = dateTime;
cmd.Parameters["instrument"].Value = instrument;
using (var dr = cmd.ExecuteReader()) {
while (dr.Read()) {
var entity = new Entity();
entity.Connection = connection;
entity.Id = (Int64)dr[0];
entity.DateTime = (DateTime)dr[1];
entity.Rate = (float)((decimal)dr[2]);
return entity;
}
}
}
return null;
}
public class Entity {
public NpgsqlConnection Connection;
public Int64 Id;
public string Instrument;
public DateTime DateTime;
public float Rate;
public DateTime NormalizedDateTime {
get {
return new DateTime(DateTime.Year, DateTime.Month, DateTime.Day, DateTime.Hour, DateTime.Minute, 0, DateTime.Kind);
}
}
public IEnumerable<OrderBookPricePointDao.Entity> GetPricePointsOrderByPrice() {
return new OrderBookPricePointDao(Connection).GetByOrderBookOrderByPrice(Id);
}
}
}
}
<file_sep>/Candlesticks/CauseAndEffectForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Candlesticks {
public partial class CauseAndEffectForm : Form {
public CauseAndEffectForm() {
InitializeComponent();
}
private void RunTask(object sender, Action<Report> action) {
Report.RunTask(sender, action, dataGridView1, taskStatus);
}
private void button1_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
using(DBUtils.OpenThreadConnection()) {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
string[] causes = new string[] {
"WTICO_USD","US30_USD","JP225_USD","USB10Y_USD","USD_JPY","EUR_USD"
};
string[] effects = new string[] {
"WTICO_USD","US30_USD","JP225_USD","USB10Y_USD","USD_JPY","EUR_USD"
};
Tuple<string, TimeSpan>[] granularityTuples = new Tuple<string, TimeSpan>[] {
new Tuple<string,TimeSpan>("D",new TimeSpan(365*5,0,0,0)),
new Tuple<string,TimeSpan>("H1",new TimeSpan(365*5,0,0,0)),
new Tuple<string,TimeSpan>("M10",new TimeSpan(365,0,0,0)),
new Tuple<string,TimeSpan>("M1",new TimeSpan(365,0,0,0)),
};
report.SetHeader("effect", "cause", "granularity", "↑↑->↑", "↑↓->↑", "↓↑->↑", "↓↓->↑", "↑↑->↓", "↑↓->↓", "↓↑->↓", "↓↓->↓");
foreach (var granularityTuple in granularityTuples) {
foreach (string effect in effects) {
foreach (string cause in causes) {
if(effect == cause) {
continue;
}
ReportCauseAndEffect(granularityTuple, effect, cause, report);
}
}
}
}
});
}
private static void ReportCauseAndEffect(Tuple<string, TimeSpan> granularityTuple, string effect, string cause, Report report) {
DateTime start = DateTime.Today.AddTicks(-granularityTuple.Item2.Ticks);
DateTime end = DateTime.Today;
var effectCandles = new CandlesticksGetter() {
Instrument = effect,
Granularity = granularityTuple.Item1,
Start = start,
End = end
}.Execute().ToList();
var causeCandles = new CandlesticksGetter() {
Instrument = cause,
Granularity = granularityTuple.Item1,
Start = start,
End = end
}.Execute().ToList();
int i = 0, j = 0;
Dictionary<int, int> summary = new Dictionary<int, int>();
int prevUpDown = -1;
while (i < effectCandles.Count() && j < causeCandles.Count()) {
var effectCandle = effectCandles[i];
var causeCandle = causeCandles[j];
if (effectCandle.IsNull || effectCandle.DateTime < causeCandle.DateTime || effectCandle.Close == effectCandle.Open) {
i++;
continue;
}
if (causeCandle.IsNull || effectCandle.DateTime > causeCandle.DateTime || causeCandle.Close == causeCandle.Open) {
j++;
continue;
}
if (prevUpDown != -1) {
int key = prevUpDown + (effectCandle.IsUp() ? 0 : 4);
if (summary.ContainsKey(key) == false) {
summary[key] = 0;
}
summary[key]++;
}
prevUpDown = (effectCandle.IsUp() ? 0 : 2) + (causeCandle.IsUp() ? 0 : 1);
i++;
j++;
}
report.Write(effect, cause, granularityTuple.Item1);
for (int updown=0; updown<8; updown++) {
report.Write(summary.ContainsKey(updown) ? summary[updown] : 0);
}
report.WriteLine();
}
private class CauseContext {
public Candlestick[] Candles;
public bool IsUp;
public int Index = 0;
public Candlestick CurrentCandle {
get {
return Candles[Index];
}
}
public bool IsMatch {
get {
return Candles[Index].IsUp() == IsUp;
}
}
}
private static void ReportEffectAndCauseCombination(Report report, List<CauseContext> causeContexts, bool effectIsUp) {
int prev = -1;
int matchCount = 0;
int total = 0;
while (causeContexts.Count(c => c.Index >= c.Candles.Count()) == 0) {
bool indexIncrement = false;
DateTime maxDateTime = causeContexts.Max(c => c.CurrentCandle.DateTime);
foreach (var causeContext in causeContexts) {
if (causeContext.CurrentCandle.IsNull || maxDateTime > causeContext.CurrentCandle.DateTime) {
causeContext.Index++;
indexIncrement = true;
}
}
if(indexIncrement) {
continue;
}
if (prev == 1) {
if (causeContexts[0].CurrentCandle.IsUp() == effectIsUp) {
matchCount++;
}
total++;
}
if (causeContexts.Count(c => !c.IsMatch) == 0) {
prev = 1;
} else {
prev = 0;
}
foreach (var causeContext in causeContexts) {
causeContext.Index++;
}
}
report.WriteLine(matchCount, total);
report.WriteLine();
}
private void 因果EUR_USD_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
using (DBUtils.OpenThreadConnection()) {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("↑↑↑↑->↓", "total");
DateTime start = DateTime.Today.AddTicks(-new TimeSpan(365 * 5, 0, 0, 0).Ticks);
DateTime end = DateTime.Today;
var causeContexts = new List<CauseContext>();
foreach (var cause in new string[] { "EUR_USD", "WTICO_USD", "US30_USD", "JP225_USD" }) {
var causeCandles = new CandlesticksGetter() {
Instrument = cause,
Granularity = "D",
Start = start,
End = end
}.Execute().ToArray();
causeContexts.Add(new CauseContext() {
Candles = causeCandles,
IsUp = true
});
}
ReportEffectAndCauseCombination(report, causeContexts, false);
}
});
}
private void 因果USD_JPY_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
using (DBUtils.OpenThreadConnection()) {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("↑↓↓↓↓->↓", "total");
DateTime start = DateTime.Today.AddTicks(-new TimeSpan(365, 0, 0, 0).Ticks);
DateTime end = DateTime.Today;
var causeContexts = new List<CauseContext>();
var instruments = new string[] { "USD_JPY", "WTICO_USD", "US30_USD", "JP225_USD", "EUR_USD" };
var isUps = new bool[] { true,false,false,false,false };
foreach(var t in instruments.Zip(isUps,(i,isUp)=>new Tuple<string,bool>(i,isUp))) {
var causeCandles = new CandlesticksGetter() {
Instrument = t.Item1,
Granularity = "M1",
Start = start,
End = end
}.Execute().ToArray();
causeContexts.Add(new CauseContext() {
Candles = causeCandles,
IsUp = t.Item2
});
}
ReportEffectAndCauseCombination(report, causeContexts, false);
}
});
}
}
}
<file_sep>/CandlesticksCommon/TradePosition.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Candlesticks {
struct TradePosition {
public int Time;
public float Price;
public TradeType TradeType;
public float HighSettlementPrice;
public float LowSettlementPrice;
}
public enum TradeType {
Bid, Ask, Settle
}
static class TradeTypeExt {
public static TradeType Reverse(this TradeType t) {
if(t == TradeType.Bid) {
return TradeType.Ask;
}
else {
return TradeType.Bid;
}
}
}
}
<file_sep>/Candlesticks/DateTimeBestForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Candlesticks {
public partial class 日時ベスト正順通年5年10分足EUR_USD : Form {
public 日時ベスト正順通年5年10分足EUR_USD() {
InitializeComponent();
}
private void RunTask(object sender, Action<Report> action) {
Report.RunTask(sender, action, dataGridView1, taskStatus);
}
private IEnumerable<Candlestick> GetM30Candles(TimeSpan span) {
return Candlestick.Aggregate(GetM10Candles(span), 3);
}
private IEnumerable<Candlestick> GetM10Candles(TimeSpan span, string instrument = "USD_JPY") {
using (DBUtils.OpenThreadConnection()) {
return new CandlesticksGetter() {
Start = DateTime.Today.AddTicks(-span.Ticks),
End = DateTime.Today,
Granularity = "M10",
Instrument = instrument
}.Execute();
}
}
private static void ReportGroupByTradeStartTime(Report report, BestTradeTime bestTradeTime) {
var dict = new Dictionary<int, List<Tuple<int[], int[]>>>();
foreach (var t in bestTradeTime.Calculate()) {
int tradeStartTime = t.Item1[2];
if (!dict.ContainsKey(tradeStartTime)) {
dict[tradeStartTime] = new List<Tuple<int[], int[]>>();
}
dict[tradeStartTime].Add(t);
}
var list = new List<Tuple<int[], int[]>>();
foreach (var tuples in dict.Values) {
list.Add(tuples.OrderByDescending(t => bestTradeTime.Comparator(t.Item2)).First());
}
foreach (var t in list.OrderByDescending(t => bestTradeTime.Comparator(t.Item2))) {
foreach (var time in t.Item1) {
report.Write(bestTradeTime.HMString(time));
}
foreach (var c in t.Item2) {
report.Write(c);
}
report.WriteLine();
}
}
private void ReportMultiCondition(Report report, TradeOrders tradeOrders, TradeCondition[] conditions, IEnumerable<Candlestick> candles) {
report.SetHeader("condition","prifit rate","profit count","total match");
var dateTimePrice = new Dictionary<DateTime, float>();
var dateSet = new HashSet<DateTime>();
foreach (var c in candles) {
if (c.IsNull) {
continue;
}
dateTimePrice[c.DateTime] = c.Open;
dateSet.Add(c.DateTime.Date);
}
Func<DateTime, float> getPrice = dateTime =>
dateTimePrice.ContainsKey(dateTime) ? dateTimePrice[dateTime] : float.NaN;
int c1, c2, c3, c4, total;
int r1, r2, r3, r4;
r1 = r2 = r3 = r4 = c1 = c2 = c3 = c4 = total = 0;
foreach (var date in dateSet) {
var m = new List<bool>();
bool isValid = true;
foreach (var condition in conditions) {
TradeContext c = new TradeContext() {
Instrument = tradeOrders[0].Instrument,
Date = date,
GetPrice = getPrice,
};
Signal signal;
m.Add(condition.IsMatch(out signal, c));
if (signal == null || signal.IsValid == false) {
isValid = false;
}
}
if (!isValid) {
continue;
}
TradeContext context = new TradeContext() {
Instrument = tradeOrders[0].Instrument,
Date = date,
GetPrice = getPrice,
};
tradeOrders.DoTrade(context);
if(context.IsValid==false) {
continue;
}
bool isSuccess = context.Profit > 0f;
total++;
if (!m[0] && !m[1]) {
c1++;
r1 += isSuccess ? 1 : 0;
}
if (m[0] && !m[1]) {
c2++;
r2 += isSuccess ? 1 : 0;
}
if (!m[0] && m[1]) {
c3++;
r3 += isSuccess ? 1 : 0;
}
if (m[0] && m[1]) {
c4++;
r4 += isSuccess ? 1 : 0;
}
}
report.WriteLine("!p1 && !p2", (float)r1 / c1, r1, c1);
report.WriteLine("p1 && !p2", (float)r2 / c2, r2, c2);
report.WriteLine("!p1 && p2", (float)r3 / c3, r3, c3);
report.WriteLine("p1 && p2", (float)r4 / c4, r4, c4);
report.WriteLine("total", (float)(r1 + r2 + r3 + r4) / (c1 + c2 + c3 + c4), r1 + r2 + r3 + r4, c1 + c2 + c3 + c4);
}
private static bool IsIntersect(int[] range1, int [] range2) {
if (range1[0] == range2[0] && range1[1] == range2[1]) {
return true;
}
if (range2[0] < range1[1] && range1[1] < range2[1]) {
return true;
}
if (range1[0] < range2[1] && range2[1] < range1[1]) {
return true;
}
if (range2[0] < range1[0] && range1[0] < range2[1]) {
return true;
}
if (range1[0] < range2[0] && range2[0] < range1[1]) {
return true;
}
return false;
}
private static void ReportGroupByTradeStartAndEndTime(Report report, BestTradeTime bestTradeTime) {
var dict = new Dictionary<int[], List<Tuple<int[], int[]>>>();
foreach (var t in bestTradeTime.Calculate()) {
if(bestTradeTime.Comparator(t.Item2) < 5500) {
continue;
}
int tradeStartTime = t.Item1[2];
int tradeEndTime = t.Item1[3];
int[] key = new int[] { tradeStartTime, tradeEndTime };
if (!dict.ContainsKey(key)) {
dict[key] = new List<Tuple<int[], int[]>>();
}
dict[key].Add(t);
}
var list = new List<Tuple<int[], int[]>>();
foreach (var tuples in dict.Values) {
int[] pre = null;
foreach (var t in tuples.OrderByDescending(t => bestTradeTime.Comparator(t.Item2))) {
if(pre != null) {
if(IsIntersect(pre,t.Item1)) {
continue;
}
}
pre = t.Item1;
list.Add(t);
}
}
foreach (var t in list.OrderByDescending(t => bestTradeTime.Comparator(t.Item2)).Take(10000)) {
foreach (var time in t.Item1) {
report.Write(bestTradeTime.HMString(time));
}
foreach (var c in t.Item2) {
report.Write(c);
}
report.WriteLine();
}
}
private void 日時ベスト冬時間5年_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 6;
report.IsForceOverride = true;
report.Comment = "冬時間";
report.SetHeader("start", "end", "start", "end", "↑↑", "↑↓", "↓↑", "↓↓");
var bestTradeTime = new BestTradeTime(GetM30Candles(new TimeSpan(365 * 5, 0, 0, 0))) {
IsSummerTime = false
};
foreach (var t in bestTradeTime.Calculate(100)) {
foreach (var time in t.Item1) {
report.Write(bestTradeTime.HMString(time));
}
foreach (var c in t.Item2) {
report.Write(c);
}
report.WriteLine();
}
});
}
private void 日時ベスト冬時間3ヶ月_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = false;
report.Comment = "冬時間";
report.SetHeader("start", "end", "start", "end", "↑↑", "↑↓", "↓↑", "↓↓");
var bestTradeTime = new BestTradeTime(GetM30Candles(new TimeSpan(3 * 30, 0, 0, 0))) {
IsSummerTime = false
};
foreach (var t in bestTradeTime.Calculate(100)) {
foreach (var time in t.Item1) {
report.Write(bestTradeTime.HMString(time));
}
foreach (var c in t.Item2) {
report.Write(c);
}
report.WriteLine();
}
});
}
private void 日時ベスト夏時間5年_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 6;
report.IsForceOverride = true;
report.Comment = "冬時間";
report.SetHeader("start", "end", "start", "end", "↑↑", "↑↓", "↓↑", "↓↓");
var bestTradeTime = new BestTradeTime(GetM30Candles(new TimeSpan(365 * 5, 0, 0, 0))) {
IsSummerTime = true
};
foreach (var t in bestTradeTime.Calculate(100)) {
foreach (var time in t.Item1) {
report.Write(bestTradeTime.HMString(time));
}
foreach (var c in t.Item2) {
report.Write(c);
}
report.WriteLine();
}
});
}
private void 日時ベスト通年5年10分足_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("start", "end", "start", "end", "↑↑", "↑↓", "↓↑", "↓↓");
var bestTradeTime = new BestTradeTime(GetM10Candles(new TimeSpan(365 * 5, 0, 0, 0))) {
Granularity = new TimeSpan(0, 10, 0)
};
ReportGroupByTradeStartTime(report, bestTradeTime);
});
}
private void 日時ベスト通年5年10分足12時_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("start", "end", "start", "end", "↑↑", "↑↓", "↓↑", "↓↓");
var bestTradeTime = new BestTradeTime(GetM10Candles(new TimeSpan(5 * 365, 0, 0, 0))) {
Granularity = new TimeSpan(0, 10, 0),
ShiftHour = 12,
};
ReportGroupByTradeStartTime(report, bestTradeTime);
});
}
private void 日時ベスト通年5年10分足12時EUR_USD_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("start", "end", "start", "end", "↑↑", "↑↓", "↓↑", "↓↓");
var bestTradeTime = new BestTradeTime(GetM10Candles(new TimeSpan(5 * 365, 0, 0, 0), "EUR_USD")) {
Granularity = new TimeSpan(0, 10, 0),
ShiftHour = 12,
};
ReportGroupByTradeStartTime(report, bestTradeTime);
});
}
private void 日時ベスト正順通年5年10分足_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("start", "end", "start", "end", "↑↑", "↑↓", "↓↑", "↓↓");
var bestTradeTime = new BestTradeTime(GetM10Candles(new TimeSpan(365 * 5, 0, 0, 0))) {
Granularity = new TimeSpan(0, 10, 0),
Comparator = f => (int)(Math.Max((double)f[0] / (f[0] + f[1]), (double)f[3] / (f[2] + f[3])) * 10000)
};
ReportGroupByTradeStartTime(report, bestTradeTime);
});
}
private void 日時ベスト正順通年5年10分足EURUSD_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("start", "end", "start", "end", "↑↑", "↑↓", "↓↑", "↓↓");
var bestTradeTime = new BestTradeTime(GetM10Candles(new TimeSpan(365 * 5, 0, 0, 0), "EUR_USD")) {
Granularity = new TimeSpan(0, 10, 0),
Comparator = f => (int)(Math.Max((double)f[0] / (f[0] + f[1]), (double)f[3] / (f[2] + f[3])) * 10000)
};
ReportGroupByTradeStartTime(report, bestTradeTime);
});
}
private void EURUSD1100_1140_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 2;
report.IsForceOverride = true;
report.Comment = "";
var tradeOrders = new TradeOrders(
new TimeTradeOrder() {
Instrument = "EUR_USD",
TradeType = TradeType.Ask,
Time = new TimeSpan(11, 00, 0),
},
new TimeTradeOrder() {
Instrument = "EUR_USD",
TradeType = TradeType.Settle,
Time = new TimeSpan(11, 40, 0),
}
);
TradeCondition[] conditions = new TimeOfDayPattern[] {
new TimeOfDayPattern() {
Instrument = "EUR_USD",
CheckStartTime = new TimeSpan(8, 50, 0),
CheckEndTime = new TimeSpan(11, 00, 0),
IsCheckUp = false,
},
new TimeOfDayPattern() {
Instrument = "EUR_USD",
CheckStartTime = new TimeSpan(6, 50, 0),
CheckEndTime = new TimeSpan(7, 50, 0),
IsCheckUp = true,
},
};
ReportMultiCondition(report, tradeOrders, conditions, GetM10Candles(new TimeSpan(365 * 5, 0, 0, 0), "EUR_USD"));
});
}
private void EURUSD1100_1140_rev_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 2;
report.IsForceOverride = true;
report.Comment = "";
var tradeOrders = new TradeOrders(
new TimeTradeOrder() {
Instrument = "EUR_USD",
TradeType = TradeType.Bid,
Time = new TimeSpan(11, 00, 0),
},
new TimeTradeOrder() {
Instrument = "EUR_USD",
TradeType = TradeType.Settle,
Time = new TimeSpan(11, 40, 0),
}
);
TradeCondition[] conditions = new TimeOfDayPattern[] {
new TimeOfDayPattern() {
Instrument = "EUR_USD",
CheckStartTime = new TimeSpan(8, 50, 0),
CheckEndTime = new TimeSpan(11, 00, 0),
IsCheckUp = true,
},
new TimeOfDayPattern() {
Instrument = "EUR_USD",
CheckStartTime = new TimeSpan(6, 50, 0),
CheckEndTime = new TimeSpan(7, 50, 0),
IsCheckUp = false,
},
};
ReportMultiCondition(report, tradeOrders, conditions, GetM10Candles(new TimeSpan(365 * 5, 0, 0, 0), "EUR_USD"));
});
}
private void USDJPY0550_0710_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
var tradeOrders = new TradeOrders(
new TimeTradeOrder() {
Instrument = "USD_JPY",
TradeType = TradeType.Ask,
Time = new TimeSpan(5, 50, 0),
},
new TimeTradeOrder() {
Instrument = "USD_JPY",
TradeType = TradeType.Settle,
Time = new TimeSpan(7, 10, 0),
}
);
TradeCondition[] conditions = new TimeOfDayPattern[] {
new TimeOfDayPattern() {
Instrument = "USD_JPY",
CheckStartTime = new TimeSpan(0, 30, 0),
CheckEndTime = new TimeSpan(4, 50, 0),
IsCheckUp = false,
},
new TimeOfDayPattern() {
Instrument = "USD_JPY",
CheckStartTime = new TimeSpan(0, 20, 0),
CheckEndTime = new TimeSpan(5, 40, 0),
IsCheckUp = false,
},
};
ReportMultiCondition(report, tradeOrders, conditions, GetM10Candles(new TimeSpan(365 * 5, 0, 0, 0), "USD_JPY"));
});
}
private static float GetDoubleCheckProbability(int [] s) {
float result = 0;
for (int i = 0; i < 8; i += 2) {
float p0 = (float)s[i] / (s[i] + s[i+1]);
float p1 = 1 - p0;
result = Math.Max(result, p0);
result = Math.Max(result, p1);
}
return result;
}
private static float GetDoubleCheckProbability(int[] s, bool isUp) {
float result = 0;
for (int i = 0; i < 8; i += 2) {
float p0 = (float)s[i] / (s[i] + s[i + 1]);
float p1 = 1 - p0;
if (isUp) {
result = Math.Max(result, p0);
} else {
result = Math.Max(result, p1);
}
}
return result;
}
private void 日時ベスト通年複合5年10分足_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 4;
report.IsForceOverride = true;
report.Comment = "USDJPY_0610_0710_夏時間_下落";
report.SetHeader("start", "end", "start", "end", "↑↑↑", "↑↑↓", "↑↓↑", "↑↓↓", "↓↑↑", "↓↑↓", "↓↓↑", "↓↓↓","rate");
var bestTradeTime = new BestTradeTime(GetM10Candles(new TimeSpan(365 * 5, 0, 0, 0))) {
Granularity = new TimeSpan(0, 10, 0),
IsSummerTime = true
};
List<Tuple<int[], int[], float>> list = new List<Tuple<int[], int[], float>>();
foreach(var t in bestTradeTime.CalculateDoubleCheckRange(new TimeSpan(6, 10, 0), new TimeSpan(7, 10, 0))) {
var p = GetDoubleCheckProbability(t.Item2,false);
if(p < 0.50f) {
continue;
}
list.Add(new Tuple<int[],int[],float>(t.Item1, t.Item2, p));
}
foreach(var t in list.OrderByDescending(t => t.Item3).Take(1000)) {
foreach(var checkTime in t.Item1) {
report.Write(bestTradeTime.HMString(checkTime));
}
foreach (var count in t.Item2) {
report.Write(count);
}
report.WriteLine(t.Item3);
}
});
}
}
}
<file_sep>/Candlesticks/Report.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Candlesticks {
class Report : IDisposable {
private StreamWriter writer = null;
private int columnIndex = 0;
private int rowIndex = 0;
public Report() {
}
public DataGridView DataGridView {
get;
set;
}
public Control StatusControl {
get;
set;
}
public string BasePath {
get;
set;
}
public string Name {
get;
set;
}
public int Version {
get;
set;
}
public string Comment {
get;
set;
}
public bool IsForceOverride {
get;
set;
}
public string CsvFilePath {
get {
return this.BasePath + "\\" + this.Name + "-" + this.Version + "-" + this.Comment + ".csv";
}
}
public void SetHeader(params string[] args) {
string path = this.CsvFilePath;
if (!this.IsForceOverride && File.Exists(path)) {
LoadReport(path);
throw new ReportExistedException();
}
writer = new StreamWriter(path, false, Encoding.GetEncoding("Shift_JIS"));
this.DataGridView.Invoke(new Action(() => {
this.DataGridView.Columns.Clear();
this.DataGridView.Rows.Clear();
foreach (string arg in args) {
this.DataGridView.Columns.Add(arg, arg);
}
}));
foreach (var a in args) {
writer.Write(a);
writer.Write(',');
Console.Write(a);
Console.Write(' ');
}
writer.WriteLine();
Console.WriteLine();
this.StatusControl.Invoke(new Action(() => {
this.StatusControl.Text = "title:" + this.Name + " version:" + this.Version + " comment:" + this.Comment + " status:Running...";
}));
}
private void LoadReport(string path) {
using (StreamReader reader = new StreamReader(path, Encoding.GetEncoding("Shift_JIS"))) {
this.DataGridView.Invoke(new Action(() => {
this.DataGridView.Columns.Clear();
this.DataGridView.Rows.Clear();
foreach (var header in reader.ReadLine().Split(',')) {
Console.Write(header);
Console.Write(' ');
this.DataGridView.Columns.Add(header, header);
}
}));
string line = null;
while ((line = reader.ReadLine()) != null) {
WriteLine(line.Split(','));
}
}
}
public void WriteLine(params object[] args) {
Write(args);
WriteLine();
}
public void Write(params object[] args) {
foreach (var a in args) {
if(writer != null) {
writer.Write(a);
writer.Write(',');
}
Console.Write(a);
Console.Write(' ');
}
this.DataGridView.Invoke(new Action(() => {
if(columnIndex == 0) {
this.DataGridView.Rows.Add();
}
foreach (var a in args) {
this.DataGridView.Rows[rowIndex].Cells[columnIndex++].Value = a;
}}));
}
public void WriteLine() {
if (writer != null) {
writer.WriteLine();
}
Console.WriteLine();
columnIndex = 0;
rowIndex++;
}
public static void RunTask(object sender, Action<Report> action, DataGridView dataGridView, Control status) {
Task.Run(() => {
using (var report = new Report() {
Name = ((Control)sender).Text,
BasePath = Setting.Instance.DataFilePath,
DataGridView = dataGridView,
StatusControl = status,
}) {
try {
action(report);
} catch (ReportExistedException) {
}
}
});
}
#region IDisposable Support
private bool disposedValue = false;
protected virtual void Dispose(bool disposing) {
this.StatusControl.Invoke(new Action(() => {
if(writer == null) {
this.StatusControl.Text = "title:" + this.Name + " version:" + this.Version + " comment:" + this.Comment + " status:Loaded!";
} else {
this.StatusControl.Text = "title:" + this.Name + " version:" + this.Version + " comment:" + this.Comment + " status:Finished!";
}
}));
if (!disposedValue) {
if (disposing) {
if(writer != null) {
writer.Close();
writer.Dispose();
writer = null;
}
}
disposedValue = true;
}
}
public void Dispose() {
Dispose(true);
}
#endregion
}
class ReportExistedException : Exception {
}
}
<file_sep>/Candlesticks/Form1.cs
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Candlesticks {
public partial class Form1 : Form {
public string REPORT_PATH {
get {
return Setting.Instance.DataFilePath;
}
}
public string DATA_PATH {
get {
return Setting.Instance.DataFilePath;
}
}
private Report report;
public Form1() {
InitializeComponent();
}
private List<TradePosition> positions = new List<TradePosition>();
private void Form1_Load(object sender, EventArgs e) {
new Thread(new ThreadStart(() => { EventReceiver.Instance.Execute(); })).Start();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
Console.WriteLine("Form1_FormClosed");
EventReceiver.Instance.Dispose();
Application.Exit();
}
private void button1_Click(object sender, EventArgs e) {
int range = 8;
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\h1.csv"));
for(int t = range; t < list.Count(); t++) {
// DoSettlement(t, list[t].Close);
float low = list.GetRange(t - range, range).Select(s => s.Low).Min();
if(list[t].Close < low) {
DoTrade(t, TradeType.Ask, list[t].Close);
// sell list[t].Close
}
float high = list.GetRange(t - range, range).Select(s => s.High).Max();
if (list[t].Close > high) {
DoTrade(t, TradeType.Bid, list[t].Close);
}
}
}
private void DoSettlement(int t, float price) {
bool f = false;
float money = 0;
foreach (var position in positions) {
f = true;
if (position.TradeType == TradeType.Ask) {
money += price - position.Price;
} else {
money += position.Price - price;
}
}
if (f) {
positions.Clear();
Console.Out.WriteLine(t + "," + money);
}
}
private void DoTrade(int t, TradeType tradeType, float price) {
bool f = false;
float money = 0;
int score = 0;
foreach (var position in positions.Where(p => p.TradeType == tradeType.Reverse())) {
if (position.TradeType == TradeType.Ask) {
money += price - position.Price;
score += price - position.Price > 0 ? 1 : -1;
} else {
money += position.Price - price;
score += position.Price - price - position.Price > 0 ? 1 : -1;
}
f = true;
}
if(f) {
positions.Clear();
} else {
if (positions.Count() == 0) {
positions.Add(new TradePosition() {
Price = price,
TradeType = tradeType,
});
}
}
if(f) {
Console.Out.WriteLine(t+","+money+","+ score);
}
}
private void button2_Click(object sender, EventArgs e) {
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\h1.csv"));
Dictionary<int, int> upD = new Dictionary<int, int>();
Dictionary<int, int> downD = new Dictionary<int, int>();
int c = 0;
bool isUp = false;
foreach (var stick in list) {
if(stick.Close > stick.Open) {
if(isUp) {
c++;
} else {
if (!downD.ContainsKey(c+1)) {
downD[c + 1] = 0;
}
downD[c + 1]++;
c = 0;
isUp = true;
}
} else {
if (!isUp) {
c++;
} else {
if (!upD.ContainsKey(c + 1)) {
upD[c + 1] = 0;
}
upD[c + 1]++;
c = 0;
isUp = false;
}
}
}
foreach(var k in upD.Keys.OrderBy(k=>k)) {
Console.Out.WriteLine(k+","+upD[k]);
}
foreach (var k in downD.Keys.OrderBy(k => k)) {
Console.Out.WriteLine(k + "," + downD[k]);
}
}
private void button3_Click(object sender, EventArgs e) {
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\h1.csv"));
Dictionary<string, List<Candlestick>> dayOftheWeekTimeDict = new Dictionary<string, List<Candlestick>>();
foreach(var stick in list) {
string key = stick.DateTime.DayOfWeek + " " + stick.DateTime.Hour;
if(dayOftheWeekTimeDict.ContainsKey(key) == false) {
dayOftheWeekTimeDict[key] = new List<Candlestick>();
}
dayOftheWeekTimeDict[key].Add(stick);
}
foreach (var dayOfWeek in Enum.GetNames(typeof(DayOfWeek))) {
for(int h=0; h<24; h++) {
List<Candlestick> l = null;
dayOftheWeekTimeDict.TryGetValue(dayOfWeek + " " + h, out l);
if(l != null) {
Console.Out.WriteLine(dayOfWeek+","+h+","+l.Where(s => s.IsUp()).Count() + "," + l.Count());
}
}
}
}
private void button4_Click(object sender, EventArgs e) {
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\h1.csv"));
List<Dictionary<string, Candlestick>> dayOfWeekTable = new List<Dictionary<string, Candlestick>>();
Dictionary<string, Candlestick> dict = new Dictionary<string, Candlestick>();
DayOfWeek oldDayOfWeek = DayOfWeek.Friday;
foreach (var stick in list) {
if(stick.DateTime.DayOfWeek < oldDayOfWeek) {
dict = new Dictionary<string, Candlestick>();
dayOfWeekTable.Add(dict);
}
string key = stick.DateTime.DayOfWeek + " " + stick.DateTime.Hour;
dict.Add(key, stick);
oldDayOfWeek = stick.DateTime.DayOfWeek;
}
foreach(var d in dayOfWeekTable) {
try {
float d1 = d[DayOfWeek.Tuesday + " 17"].Close - d[DayOfWeek.Monday + " 9"].Open;
float d2 = d[DayOfWeek.Friday + " 17"].Close - d[DayOfWeek.Thursday + " 9"].Open;
Console.Out.WriteLine(d1 + "," + d2);
} catch(Exception) {
}
}
}
private void button5_Click(object sender, EventArgs e) {
int range = 10;
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\h1.csv"));
for (int t = range; t < list.Count(); t++) {
float low = list.GetRange(t - range, range).Select(s => s.Low).Min();
if (list[t].Close < low) {
int r = Math.Min(range, list.Count() - t);
float h = list.GetRange(t, range).Select(s => s.High).Max();
float l = list.GetRange(t, range).Select(s => s.Low).Min();
Console.Out.WriteLine(list[t].Close+","+h + ","+l);
}
/* float high = list.GetRange(t - range, range).Select(s => s.High).Max();
if (list[t].Close > high) {
DoTrade(t, TradeType.Buy, list[t].Close);
}*/
}
}
private void button6_Click(object sender, EventArgs e) {
int range = 10;
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\h1.csv"));
List<TradePosition> positions = new List<TradePosition>();
for (int t = range; t < list.Count(); t++) {
float CurrentPrice = list[t].Close;
List<TradePosition> done = new List<TradePosition>();
foreach(TradePosition p in positions) {
if(list[t].Low <= p.LowSettlementPrice) {
if (list[t].High >= p.HighSettlementPrice) {
Console.WriteLine((t - p.Time) + ",0");
done.Add(p);
} else {
Console.WriteLine((t - p.Time) + "," + (p.LowSettlementPrice - p.Price));
done.Add(p);
}
}
else if(list[t].High >= p.HighSettlementPrice) {
Console.WriteLine((t - p.Time) + "," +( p.HighSettlementPrice - p.Price));
done.Add(p);
}
}
positions.RemoveAll(p => done.Contains(p));
float low = list.GetRange(t - range, range).Select(s => s.Low).Min();
if (CurrentPrice < low && positions.Count() == 0) {
positions.Add(new TradePosition() {
Time = t, TradeType = TradeType.Ask, Price = CurrentPrice,
HighSettlementPrice = CurrentPrice + 0.2f,
LowSettlementPrice = CurrentPrice - 0.2f
});
}
}
}
private void button7_Click(object sender, EventArgs e) {
int range = 10;
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\h1.csv"));
for (int t = range; t < list.Count(); t++) {
float low = list.GetRange(t - range, range).Select(s => s.Low).Min();
if (list[t].Close < low && t < list.Count() - range * 2) {
for(int i=1; i<=range*2; i++) {
Console.Out.Write(list[t + i].Close - list[t].Close+",");
}
Console.Out.WriteLine();
}
}
}
private string FormatHourMinute(int t) {
return (t / 2 < 10 ? "0" : "") + t / 2 + ":" + (t % 2==0?"00":"30");
}
private string FormatWeekHourMinute(int t) {
int dw = t / 48;
return new char[] { '日', '月', '火', '水', '木', '金', '土' }[dw] + FormatHourMinute(t % 48);
}
private IEnumerable<Candlestick> GetByDateRangeM30(DateTime start, DateTime end) {
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\m30-5y.csv"));
foreach(var c in list) {
if(start <= c.DateTime && c.DateTime < end) {
yield return c;
}
}
}
private IEnumerable<Tuple<int[], int[]>> GetBestTradeTime(IEnumerable<Candlestick> list, int limit, bool isSummerTime) {
return new BestTradeTime(list) { IsSummerTime = isSummerTime }.Calculate(limit);
}
private IEnumerable<Tuple<int[], int[]>> GetBestTradeWeekTime(IEnumerable<Candlestick> list, int limit) {
DayOfWeek oldDayOfWeek = new DayOfWeek();
Candlestick[] hmList = null;
List<Candlestick[]> dateList = new List<Candlestick[]>();
foreach (var c in list) {
if (hmList==null || oldDayOfWeek > c.DateTime.DayOfWeek) {
hmList = new Candlestick[48*7];
dateList.Add(hmList);
}
oldDayOfWeek = c.DateTime.DayOfWeek;
hmList[(int)c.DateTime.DayOfWeek * 48 + c.DateTime.Hour * 2 + (c.DateTime.Minute == 30 ? 1 : 0)] = c;
}
List<Tuple<int[], int[]>> summary = new List<Tuple<int[], int[]>>();
for (int s1 = 0; s1 < 7 * 48 - 6; s1++) {
for (int e1 = s1 + 1; e1 < s1 + 6; e1++) {
for (int s2 = e1 + 1; s2 < 7 * 48 - 6; s2++) {
for (int e2 = s2 + 1; e2 < s2 + 6; e2++) {
int[] dayResult = new int[4];
bool f = false;
foreach (var hml in dateList) {
try {
float d1 = hml[e1].Close - hml[s1].Open;
float d2 = hml[e2].Close - hml[s2].Open;
if (hml[e1].Close==0 || hml[s1].Open == 0 || hml[s2].Open == 0 || hml[e2].Close == 0 ) {
continue;
}
dayResult[(d1 >= 0 ? 0 : 2) + (d2 >= 0 ? 0 : 1)]++;
f = true;
} catch (Exception) {
}
}
if(f) {
summary.Add(new Tuple<int[], int[]>(new int[] { s1, e1, s2, e2 }, dayResult));
}
}
}
}
}
int i = 0;
foreach (var t in summary.OrderByDescending(t => (float)(t.Item2[1] + t.Item2[2]) /*/ t.Item2.Sum()*/)) {
if (i >= limit) {
break;
}
yield return t;
i++;
}
}
private IEnumerable<Tuple<DateTime,float,bool>> CheckTrade(IEnumerable<Candlestick> list, int[] tradeTimes) {
DateTime oldDate = new DateTime();
Candlestick[] hmList = null;
List<Candlestick[]> dateList = new List<Candlestick[]>();
foreach (var c in list) {
if (!oldDate.Equals(c.DateTime.Date)) {
hmList = new Candlestick[48];
dateList.Add(hmList);
oldDate = c.DateTime.Date;
}
hmList[c.DateTime.Hour * 2 + (c.DateTime.Minute == 30 ? 1 : 0)] = c;
}
foreach (var hml in dateList) {
if(tradeTimes.Count(tt=>hml[tt].Open==0) >= 1) {
continue;
}
float sd = hml[tradeTimes[1]].Close - hml[tradeTimes[0]].Open;
float ed = hml[tradeTimes[3]].Close - hml[tradeTimes[2]].Open;
if (sd > 0) {
yield return new Tuple<DateTime, float,bool>(hml[tradeTimes[0]].DateTime, -ed,false);
} else if (sd < 0) {
yield return new Tuple<DateTime, float,bool>(hml[tradeTimes[0]].DateTime, ed,true);
}
}
}
private IEnumerable<Tuple<DateTime, float>> CheckWeekTrade(IEnumerable<Candlestick> list, int[] tradeTimes) {
DayOfWeek oldDayOfWeek = new DayOfWeek();
Candlestick[] hmList = null;
List<Candlestick[]> dateList = new List<Candlestick[]>();
foreach (var c in list) {
if (hmList == null || oldDayOfWeek > c.DateTime.DayOfWeek) {
hmList = new Candlestick[48 * 7];
dateList.Add(hmList);
}
oldDayOfWeek = c.DateTime.DayOfWeek;
hmList[(int)c.DateTime.DayOfWeek * 48 + c.DateTime.Hour * 2 + (c.DateTime.Minute == 30 ? 1 : 0)] = c;
}
foreach (var hml in dateList) {
if (tradeTimes.Count(tt => hml[tt].Open == 0) >= 1) {
continue;
}
float sd = hml[tradeTimes[1]].Close - hml[tradeTimes[0]].Open;
float ed = hml[tradeTimes[3]].Close - hml[tradeTimes[2]].Open;
if (sd > 0) {
yield return new Tuple<DateTime, float>(hml[tradeTimes[0]].DateTime, -ed);
} else if (sd < 0) {
yield return new Tuple<DateTime, float>(hml[tradeTimes[0]].DateTime, ed);
}
}
}
private void RunTask(object sender, Action<Report> action) {
Task.Run(() => {
using (this.report = new Report() {
Name = ((Control)sender).Text,
BasePath = REPORT_PATH,
DataGridView = dataGridView1,
StatusControl = taskStatus,
}) {
try {
action(this.report);
} catch(ReportExistedException) {
}
}
});
}
private void excelButton_Click(object sender, EventArgs e) {
if (this.report != null) {
System.Diagnostics.Process.Start("excel.exe", this.report.CsvFilePath);
}
}
private void 日時ベスト(object sender, EventArgs ev) {
new 日時ベスト正順通年5年10分足EUR_USD().Show();
}
private void 日時ベスト特定日時検証(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.Comment = "0000-0430_0500-0700";
report.SetHeader("date", "balance", "isbuy", "isplus");
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\m30-5y.csv"));
DateTime oldDate = new DateTime();
Candlestick[] hmList = null;
List<Candlestick[]> dateList = new List<Candlestick[]>();
foreach (var c in list) {
if (!oldDate.Equals(c.DateTime.Date)) {
hmList = new Candlestick[48];
dateList.Add(hmList);
oldDate = c.DateTime.Date;
}
hmList[c.DateTime.Hour * 2 + (c.DateTime.Minute == 30 ? 1 : 0)] = c;
}
foreach (var t in CheckTrade(new CandlesticksReader().Read(DATA_PATH + @"\m30-5y.csv"), new int[] { 0, 9, 10, 14 })) {
report.WriteLine(t.Item1.Year + "/" + t.Item1.Month + "/" + t.Item1.Day,t.Item2,(t.Item3 ? "1" : "0"),(t.Item2 > 0 ? "1" : "0"));
}
});
}
private void 日時ベスト検証リミット別(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.Comment = "";
report.SetHeader("limit","usable","total","ratio","avg");
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\m30-5y.csv"));
for (int limit = 1; limit <= 40; limit += 2) {
DateTime startTime = list[0].DateTime;
int total = 0;
int usable = 0;
float summ = 0;
while (true) {
DateTime endTime = startTime.AddMonths(24);
DateTime checkEndTime = endTime.AddMonths(1);
List<Candlestick> targetList = new List<Candlestick>(list.Where(c => startTime <= c.DateTime && c.DateTime < endTime));
List<Candlestick> checkList = new List<Candlestick>(list.Where(c => endTime <= c.DateTime && c.DateTime < checkEndTime));
if (checkList.Count == 0) {
break;
}
foreach (var t in GetBestTradeTime(targetList, limit, false)) {
float m = CheckTrade(checkList, t.Item1).Sum(r => r.Item2);
if (m > 1 * 30 * 0.003f) {
usable++;
}
summ += m;
total++;
}
startTime = startTime.AddMonths(1);
}
report.WriteLine(limit,usable,total,(float)usable / total,summ / total);
}
});
}
private void 日時ベスト検証期間別(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.Comment = "";
report.IsForceOverride = true;
report.SetHeader("month", "usable", "total", "ratio", "avg", "max", "min");
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\m30-5y.csv"));
for (int month = 1; month <= 48; month++) {
DateTime startTime = list[0].DateTime;
int total = 0;
int usable = 0;
float summ = 0;
float max = float.MinValue;
float min = float.MaxValue;
while (true) {
DateTime endTime = startTime.AddMonths(month);
DateTime checkEndTime = endTime.AddMonths(1);
List<Candlestick> targetList = new List<Candlestick>(list.Where(c => startTime <= c.DateTime && c.DateTime < endTime));
List<Candlestick> checkList = new List<Candlestick>(list.Where(c => endTime <= c.DateTime && c.DateTime < checkEndTime));
if (checkList.Count == 0) {
break;
}
foreach (var t in GetBestTradeTime(targetList, 5, false)) {
float m = CheckTrade(checkList, t.Item1).Sum(r => r.Item2) - 1 * 20 * 0.003f;
if (m > 0) {
usable++;
}
summ += m;
max = Math.Max(max, m);
min = Math.Min(min, m);
total++;
}
startTime = startTime.AddMonths(1);
}
report.WriteLine(month, usable, total, (float)usable / total, summ / total, max, min);
}
});
}
private void 日時ベスト検証リスク(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("date", "balance");
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\m30-5y.csv"));
DateTime startTime = list[0].DateTime;
int total = 0;
int usable = 0;
float summ = 0;
float max = float.MinValue;
float min = float.MaxValue;
while (true) {
DateTime endTime = startTime.AddMonths(30);
DateTime checkEndTime = endTime.AddMonths(1);
List<Candlestick> targetList = new List<Candlestick>(list.Where(c => startTime <= c.DateTime && c.DateTime < endTime));
List<Candlestick> checkList = new List<Candlestick>(list.Where(c => endTime <= c.DateTime && c.DateTime < checkEndTime));
if (checkList.Count == 0) {
break;
}
foreach (var t in GetBestTradeTime(targetList, 5, false)) {
float m = CheckTrade(checkList, t.Item1).Sum(r => r.Item2) - 1 * 20 * 0.003f;
report.WriteLine(endTime.Year + "-" + endTime.Month, m);
if (m > 0) {
usable++;
}
summ += m;
max = Math.Max(max, m);
min = Math.Min(min, m);
total++;
}
startTime = startTime.AddMonths(1);
}
});
}
private void 曜日ベスト(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.Comment = "";
report.IsForceOverride = true;
report.SetHeader("start", "end", "start", "end", "↑↑", "↑↓", "↓↑", "↓↓", "ratio");
foreach (var t in GetBestTradeWeekTime((new CandlesticksReader().Read(DATA_PATH + @"\m30-5y.csv")), 80)) {
foreach (var time in t.Item1) {
report.Write(FormatWeekHourMinute(time));
}
foreach (var c in t.Item2) {
report.Write(c);
}
report.Write((float)(t.Item2[1] + t.Item2[2]) / t.Item2.Sum());
report.WriteLine();
}
});
}
private void 曜日ベスト検証(object sender, EventArgs ea) {
RunTask(sender,(Report report) => {
report.Version = 3;
report.IsForceOverride = false;
report.SetHeader("month", "usable", "total", "ratio", "avg", "max", "min");
List<Candlestick> list = new List<Candlestick>(new CandlesticksReader().Read(DATA_PATH + @"\m30-5y.csv"));
DateTime startTime = list[0].DateTime;
int total = 0;
int usable = 0;
float summ = 0;
float max = float.MinValue;
float min = float.MaxValue;
while (true) {
DateTime endTime = startTime.AddMonths(32);
DateTime checkEndTime = endTime.AddMonths(1);
List<Candlestick> targetList = new List<Candlestick>(list.Where(c => startTime <= c.DateTime && c.DateTime < endTime));
List<Candlestick> checkList = new List<Candlestick>(list.Where(c => endTime <= c.DateTime && c.DateTime < checkEndTime));
if (checkList.Count == 0) {
break;
}
int usableInMonth = 0;
int totalInMonth = 0;
float summInMonth = 0;
float maxInMonth = float.MinValue;
float minInMonth = float.MaxValue;
foreach (var t in GetBestTradeWeekTime(targetList, 20)) {
float m = CheckWeekTrade(checkList, t.Item1).Sum(r => r.Item2) - 1 * 4 * 0.003f;
if (m > 0) {
usableInMonth++;
}
summInMonth += m;
maxInMonth = Math.Max(maxInMonth, m);
minInMonth = Math.Min(minInMonth, m);
totalInMonth++;
}
report.WriteLine(endTime.Year + "/" + endTime.Month, usableInMonth, totalInMonth, (float)usableInMonth / totalInMonth, summInMonth / totalInMonth, maxInMonth, minInMonth);
total += totalInMonth;
usable += usableInMonth;
summ += summInMonth;
max = Math.Max(max, maxInMonth);
min = Math.Min(min, minInMonth);
startTime = startTime.AddMonths(1);
}
report.WriteLine("total", usable, total, (float)usable / total, summ / total, max, min);
});
}
private void 秒足取得(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = true;
report.SetHeader("time","open","high","low","close","volume");
DateTime current = DateTime.Now;
using(DBUtils.OpenThreadConnection()) {
foreach(var c in new CandlesticksGetter() {
Instrument = "USD_JPY",
Granularity = "M1",
Start = new DateTime(2011, 4,1, 0,00,0,DateTimeKind.Local),
End = new DateTime(2016, 3, 2, 16, 30, 0, DateTimeKind.Local),
}.Execute()) {
// report.WriteLine(c.Time, c.Open, c.High, c.Low, c.Close, c.Volume);
}
}
/*
var end = (new CandlesticksGetter() {
Granularity = "H1"
}.GetAlignTime(current.AddHours(-11)));
foreach (var c in new OandaAPI().GetCandles(current.AddHours(-12), end, "USD_JPY","H1")) {
report.WriteLine(c.DateTime, c.openMid, c.highMid, c.lowMid, c.closeMid, c.volume);
}*/
});
}
private void オーダーブック取得(object sender, EventArgs ev) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = true;
DateTime current = DateTime.UtcNow;
var data = new OandaAPI().GetOrderbookData();
var pricePoints = data[data.Keys.Max()];
report.Comment = data.Keys.Max().ToString().Replace('/','-').Replace(':','-').Replace(' ','_');
report.SetHeader("price", "order_long", "order_short", "pos_long", "pos_short");
foreach (var e in pricePoints.price_points.Keys.OrderBy(k=>k)) {
var p = pricePoints.price_points[e];
report.WriteLine(e, p.ol, p.os, p.pl, p.ps);
}
});
}
struct GetBestTradeTimePinBarResult {
public bool IsUp1;
public bool IsUp2;
public int pinbarType;
}
private int GetBestTradeTimePinBarResultIndex(bool IsUp1, bool IsUp2, int pinbarType) {
return ((IsUp1 ? 1 : 0) * 2 + (IsUp2 ? 1 : 0)) * 3 + pinbarType;
}
private IEnumerable<Tuple<int[], int[]>> GetBestTradeTimePinBar(IEnumerable<Candlestick> list, int limit) {
DateTime oldDate = new DateTime();
Candlestick[] hmList = null;
List<Candlestick[]> dateList = new List<Candlestick[]>();
foreach (var c in list) {
if (!oldDate.Equals(c.DateTime.Date)) {
hmList = new Candlestick[48];
dateList.Add(hmList);
oldDate = c.DateTime.Date;
}
hmList[c.DateTime.Hour * 2 + (c.DateTime.Minute == 30 ? 1 : 0)] = c;
}
List<Tuple<int[], int[]>> summary = new List<Tuple<int[], int[]>>();
for (int s1 = 0; s1 < 48 - 12; s1++) {
for (int e1 = s1 + 1; e1 < s1 + 12; e1++) {
for (int s2 = e1 + 1; s2 < 48 - 12; s2++) {
for (int e2 = s2 + 1; e2 < s2 + 12; e2++) {
int[] dayResult = new int[12];
summary.Add(new Tuple<int[], int[]>(new int[] { s1, e1, s2, e2 }, dayResult));
foreach (var hml in dateList) {
try {
if (hml[e1].Close == 0 || hml[s1].Open == 0 || hml[s2].Open == 0 || hml[e2].Close == 0) {
continue;
}
float d1 = hml[e1].Close - hml[s1].Open;
float d2 = hml[e2].Close - hml[s2].Open;
var c1 = Candlestick.Aggregate(hml.Skip(s1).Take(e1 - s1 + 1));
int barType;
if(c1.IsPinbar(true, 0.3f, 0.1f)) {
barType = 1;
} else if(c1.IsPinbar(false, 0.3f, 0.1f)) {
barType = 2;
} else {
barType = 0;
}
dayResult[GetBestTradeTimePinBarResultIndex(d1 >= 0, d2 >= 0,barType)]++;
} catch (Exception) {
}
}
}
}
}
}
int best = 0;
foreach (var t in summary.OrderByDescending(t =>
new int[] { 0, 1, 2 }.Max( barType=> t.Item2[GetBestTradeTimePinBarResultIndex(true, false, barType)]) +
new int[] { 0, 1, 2 }.Max(barType => t.Item2[GetBestTradeTimePinBarResultIndex(false, true, barType)])) ) {
if (best >= limit) {
break;
}
yield return t;
best++;
}
}
private void 日時ベストピンバー(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("start", "end", "start", "end",
"↑↑", "↑上↑", "↑下↑",
"↑↓", "↑上↓", "↑下↓",
"↓↑", "↓上↑", "↓下↑",
"↓↓", "↓上↓", "↓下↓");
foreach (var t in GetBestTradeTimePinBar((new CandlesticksReader().Read(DATA_PATH + @"\m30-5y.csv")), 100)) {
foreach (var time in t.Item1) {
report.Write(FormatHourMinute(time));
}
foreach (var c in t.Item2) {
report.Write(c);
}
report.WriteLine();
}
});
}
private void 日時ベスト時間ずらし(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("start", "end", "start", "end", "↑↑", "↑↓", "↓↑", "↓↓");
BestTradeTime bestTradeTime = new BestTradeTime(new CandlesticksReader().Read(DATA_PATH + @"\m30-5y.csv"));
bestTradeTime.ShiftHour = 12;
foreach (var t in bestTradeTime.Calculate(100)) {
foreach (var time in t.Item1) {
report.Write(bestTradeTime.HMString(time));
}
foreach (var c in t.Item2) {
report.Write(c);
}
report.WriteLine();
}
});
}
private void 日時上下ベスト(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "";
report.SetHeader("start", "end", "start", "end", "↑↑", "↑↓", "↓↑", "↓↓");
BestTradeTime bestTradeTime = new BestTradeTime(new CandlesticksReader().Read(DATA_PATH + @"\m30-5y.csv"));
bestTradeTime.Comparator = f => f[1] - f[0];
foreach (var t in bestTradeTime.Calculate(100)) {
foreach (var time in t.Item1) {
report.Write(bestTradeTime.HMString(time));
}
foreach (var c in t.Item2) {
report.Write(c);
}
report.WriteLine();
}
});
}
private void オーダーブックビュー(object sender, EventArgs e) {
// d.ShowDialog(this);
}
private void 設定ToolStripMenuItem_Click(object sender, EventArgs e) {
var dialog = new SettingDialog();
dialog.ShowDialog(this);
}
private void 原油因果_Click(object sender, EventArgs ev) {
RunTask(sender, (Report report) => {
report.Version = 3;
report.IsForceOverride = true;
report.Comment = "時間帯";
report.SetHeader("開始","終了","原油t","ドル円t","上昇量", "↑↑", "↑↓", "↓↑", "↓↓");
using (DBUtils.OpenThreadConnection()) {
DateTime start = DateTime.Now.AddYears(-1);
DateTime end = DateTime.Now.AddHours(-1);
var wtico = new CandlesticksGetter() {
Instrument = "WTICO_USD",
Granularity = "M10",
Start = start,
End = end
}.Execute().ToList();
var usdjpy = new CandlesticksGetter() {
Instrument = "USD_JPY",
Granularity = "M10",
Start = start,
End = end
}.Execute().ToList();
Console.WriteLine("wtico:" + wtico.Count() + " usdjpy:" + usdjpy.Count());
for(TimeSpan s = new TimeSpan(0,0,0); s < new TimeSpan(24,0,0); s += new TimeSpan(1,0,0)) {
for (TimeSpan e = s + new TimeSpan(1, 0, 0); e < new TimeSpan(24, 0, 0); e += new TimeSpan(1, 0, 0)) {
StiUsdJpy(s,e, wtico, usdjpy, report, 6, 4, 0);
}
}
/* for (float d = 0; d < 1f; d += 0.01f) {
StiUsdJpy(wtico, usdjpy, report, 6, 4, d);
}*/
}
});
}
private void StiUsdJpy(TimeSpan start, TimeSpan end, List<Candlestick> wtico, List<Candlestick> usdjpy, Report report, int n, int m, float thrashold) {
int upup = 0;
int updown = 0;
int downup = 0;
int downdown = 0;
for (int i = 0; i < wtico.Count() - (n + m); i++) {
if (wtico[i].DateTime != usdjpy[i].DateTime) {
Console.WriteLine("different time");
}
TimeSpan t = wtico[i].DateTime.TimeOfDay;
if(!(start <= t && t < end)) {
continue;
}
var w = TakeRange(wtico, i, i + n);
if (w.Count(c => c.IsNull) >= 1) {
continue;
}
if (Candlestick.Aggregate(w).IsUp(thrashold)) {
var u = TakeRange(usdjpy, i + n, i + n + m);
if (u.Count(c => c.IsNull) >= 1) {
continue;
}
if (Candlestick.Aggregate(u).IsUp()) {
upup++;
} else {
updown++;
}
} else {
var u = TakeRange(usdjpy, i + n, i + n + m);
if (u.Count(c => c.IsNull) >= 1) {
continue;
}
if (Candlestick.Aggregate(u).IsUp()) {
downup++;
} else {
downdown++;
}
}
}
report.WriteLine(start,end,n,m,thrashold, upup, updown, downup, downdown);
}
private IEnumerable<T> TakeRange<T>(List<T> list, int s, int e) {
for(int i= s; i< e; i++) {
yield return list[i];
}
}
private void くるくる_Click(object sender, EventArgs e) {
Simulator simulator = new Simulator(null);
bool first = true;
foreach(var current in simulator) {
if(first) {
current.Ask(10);
current.Bid(5);
first = false;
} else {
}
}
}
private class CheckRange {
public TimeSpan start;
public TimeSpan end;
public bool isInRange = false;
public Candlestick sum;
public Action<CheckRange> endTimeFunc = delegate { };
public float maxUp = float.MinValue;
public float maxDown = float.MaxValue;
public int upCount;
public int downCount;
public float totalInUp;
public float totalInDown;
public void Check(Candlestick candle) {
if (candle.DateTime.TimeOfDay == start && candle.IsNull == false) {
isInRange = true;
sum = candle;
} else if (isInRange) {
if (candle.IsNull) {
isInRange = false;
} else if (candle.DateTime.TimeOfDay == end) {
isInRange = false;
endTimeFunc(this);
} else {
sum = sum.Add(candle);
}
}
}
}
private void 区間の特徴_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
using(DBUtils.OpenThreadConnection()) {
report.Version = 6;
// report.IsForceOverride = true;
report.Comment = "夏時間";
report.SetHeader("区間1", "区間2", "区間3", "区間4", "最高値", "最安値", "終値");
DateTime start = DateTime.Now.AddYears(-5);
DateTime end = DateTime.Now.AddHours(-1);
/* CheckRange signal = new CheckRange() {
start = new TimeSpan(0, 0, 0),
end = new TimeSpan(5,30,0)
};*/
CheckRange[] sub = new CheckRange[] {
new CheckRange() {
start = new TimeSpan(5, 30, 0),
end = new TimeSpan(6, 00, 0)
},
new CheckRange() {
start = new TimeSpan(6, 00, 0),
end = new TimeSpan(6, 30, 0)
},
new CheckRange() {
start = new TimeSpan(6, 30, 0),
end = new TimeSpan(7, 00, 0)
},
new CheckRange() {
start = new TimeSpan(7, 00, 0),
end = new TimeSpan(7, 30, 0)
}
};
CheckRange total = new CheckRange() {
start = new TimeSpan(5, 30, 0),
end = new TimeSpan(7, 30, 0),
endTimeFunc = new Action<CheckRange>((range) => {
foreach(var s in sub) {
report.Write(s.sum.Close - s.sum.Open);
}
report.WriteLine(
range.sum.High - range.sum.Open, range.sum.Low - range.sum.Open, range.sum.Close - range.sum.Open);
})
};
TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
foreach (var candle in new CandlesticksGetter() {
Instrument = "USD_JPY",
Granularity = "M10",
Start = start,
End = end
}.Execute()) {
if(est.IsDaylightSavingTime(candle.DateTime)==false) {
continue;
}
// signal.Check(candle);
foreach(var s in sub) {
s.Check(candle);
}
total.Check(candle);
}
}
});
}
private void ベスト区間_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
using (DBUtils.OpenThreadConnection()) {
report.Version = 1;
report.IsForceOverride = true;
report.Comment = "直近1年";
report.SetHeader("時間範囲", "夏時間?", "上昇率", "平均変動額", "平均上昇額", "平均下降額","最大上昇", "最大下降");
DateTime start = DateTime.Now.AddYears(-1);
DateTime end = DateTime.Now.AddHours(-1);
foreach (bool isSummerTime in new bool[] { true, false }) {
List<CheckRange> ranges = new List<CheckRange>();
for (int i = 0; i < 48; i++) {
ranges.Add(new CheckRange() {
start = new TimeSpan(i / 2, (i % 2) * 30, 0),
end = new TimeSpan((i + 1) / 2, ((i + 1) % 2) * 30, 0),
endTimeFunc = new Action<CheckRange>((range) => {
float delta = range.sum.Close - range.sum.Open;
if (delta > 0) {
range.upCount++;
range.maxUp = Math.Max(range.maxUp, delta);
range.totalInUp += delta;
} else {
range.downCount++;
range.maxDown = Math.Min(range.maxDown, delta);
range.totalInDown += delta;
}
})
});
}
TimeZoneInfo est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
foreach (var candle in new CandlesticksGetter() {
Instrument = "USD_JPY",
Granularity = "M10",
Start = start,
End = end
}.Execute()) {
if (est.IsDaylightSavingTime(candle.DateTime) != isSummerTime) {
continue;
}
foreach (var s in ranges) {
s.Check(candle);
}
}
foreach (var s in ranges) {
report.WriteLine(s.start + "-" + s.end, isSummerTime, (float)s.upCount / (s.upCount + s.downCount), (s.totalInUp + s.totalInDown) / (s.upCount + s.downCount), s.totalInUp / s.upCount, s.totalInDown / s.downCount, s.maxUp, s.maxDown);
}
}
}
});
}
private void ストリーミングテスト_Click(object sender, EventArgs e) {
// new OandaAPI().GetPrices((bid,ask)=>{ Console.WriteLine("bid:"+bid+" ask:"+ask); }, "USD_JPY");
}
private void オーダーブックToolStripMenuItem_Click(object sender, EventArgs e) {
new OrderBookForm().Show();
}
private void シグナルToolStripMenuItem_Click(object sender, EventArgs e) {
new SignalForm().Show();
}
private void チャートToolStripMenuItem_Click(object sender, EventArgs e) {
new ChartForm().Show();
}
private void ポジション傾向ToolStripMenuItem_Click(object sender, EventArgs e) {
new PositionsForm().Show();
}
private void 価格急変_Click(object sender, EventArgs e) {
RunTask(sender, (Report report) => {
/*
report.Version = 1;
report.IsForceOverride = true;
report.SetHeader("pips","count");
using (DBUtils.OpenThreadConnection()) {
DateTime start = DateTime.Now.AddYears(-5);
DateTime end = DateTime.Now.AddHours(-1);
var usdjpy = new CandlesticksGetter() {
Instrument = "USD_JPY",
Granularity = "M10",
Start = start,
End = end
}.Execute().ToList();
Dictionary<int, int> sum = new Dictionary<int,int>();
foreach(var c in usdjpy) {
var d = Math.Abs(c.Close - c.Open);
var key = (int)Math.Round(d*10);
if(sum.ContainsKey(key) == false) {
sum[key] = 1;
} else {
sum[key]++;
}
}
foreach (var key in sum.Keys.OrderBy(k=>k)) {
report.WriteLine(key, sum[key]);
}
}*/
/*
report.Version = 2;
report.IsForceOverride = true;
report.Comment = "次足の振幅";
report.SetHeader("振幅");
using (DBUtils.OpenThreadConnection()) {
DateTime start = DateTime.Now.AddYears(-5);
DateTime end = DateTime.Now.AddHours(-1);
var usdjpy = new CandlesticksGetter() {
Instrument = "USD_JPY",
Granularity = "M10",
Start = start,
End = end
}.Execute().ToList();
Dictionary<int, int> sum = new Dictionary<int,int>();
for(int t=0; t<usdjpy.Count(); t++) {
var c = usdjpy[t];
var d = Math.Max(c.Open - c.Low, c.High - c.Open);
if ( d >= 0.2) {
var c1 = usdjpy[t + 1];
var d1 = Math.Max(c1.Open - c1.Low,c1.High - c1.Open);
report.WriteLine(d1);
}
}
}*/
/*
report.Version = 3;
report.IsForceOverride = true;
report.Comment = "平均振幅";
report.SetHeader("平均振幅");
using (DBUtils.OpenThreadConnection()) {
DateTime start = DateTime.Now.AddYears(-5);
DateTime end = DateTime.Now.AddHours(-1);
var usdjpy = new CandlesticksGetter() {
Instrument = "USD_JPY",
Granularity = "M10",
Start = start,
End = end
}.Execute().ToList();
float sum = 0;
for (int t = 0; t < usdjpy.Count(); t++) {
var c = usdjpy[t];
var d = Math.Max(c.Open - c.Low, c.High - c.Open);
sum += d;
}
report.WriteLine(sum / usdjpy.Count());
}*/
report.Version = 6;
report.IsForceOverride = true;
report.Comment = "逆方向振幅";
report.SetHeader("逆方向最大振幅","逆方向振幅","正方向最大振幅");
using (DBUtils.OpenThreadConnection()) {
DateTime start = DateTime.Now.AddYears(-5);
DateTime end = DateTime.Now.AddHours(-1);
var usdjpy = new CandlesticksGetter() {
Instrument = "USD_JPY",
Granularity = "M10",
Start = start,
End = end
}.Execute().ToList();
Dictionary<int, int> sum = new Dictionary<int, int>();
for (int t = 0; t < usdjpy.Count(); t++) {
var c = usdjpy[t];
var d = Math.Abs(c.Close-c.Open);
if (d >= 0.2) {
var c1 = usdjpy[t + 1];
report.WriteLine(c.IsUp() ? c1.Open - c1.Low : c1.High - c1.Open, (c.IsUp()==c1.IsUp() ? -1 : 1) * Math.Abs(c1.Open-c1.Close),c.IsUp() ? c1.High - c1.Open :c1.Open - c1.Low);
}
}
}
});
}
private void マウステスト_Click(object sender, EventArgs e) {
new MouseTestForm().Show();
}
private void 因果_Click(object sender, EventArgs e) {
new CauseAndEffectForm().Show();
}
private void チャート研究_Click(object sender, EventArgs e) {
new ChartLabForm().Show();
}
private void OrderBook研究_Click(object sender, EventArgs e) {
new OrderBookLabForm().Show();
}
}
}
<file_sep>/CandlesticksCommon/Simulator.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Candlesticks
{
class Simulator : IEnumerable<Simulator.Current>
{
IEnumerable<Candlestick> candles;
public float Money { get; set; }
public List<Position> Positions { get; set; }
public Simulator(IEnumerable<Candlestick> candles) {
this.candles = candles;
this.Positions = new List<Position>();
}
public IEnumerator<Current> GetEnumerator() {
return new CurrentEnumrator(this,candles.GetEnumerator());
}
IEnumerator IEnumerable.GetEnumerator() {
return new CurrentEnumrator(this,candles.GetEnumerator());
}
public class CurrentEnumrator : IEnumerator<Current> {
private Simulator simulator;
private IEnumerator<Candlestick> enumerator;
public CurrentEnumrator(Simulator simulator, IEnumerator<Candlestick> enumerator) {
this.enumerator = enumerator;
this.simulator = simulator;
}
public Current Current {
get {
return new Current(this,enumerator.Current);
}
}
object IEnumerator.Current {
get {
return new Current(this, enumerator.Current);
}
}
public void Dispose() {
enumerator.Dispose();
}
public bool MoveNext() {
return enumerator.MoveNext();
}
public void Reset() {
enumerator.Reset();
}
public void Settle(Position position, int volume) {
this.simulator.Money += position.Settle(enumerator.Current, volume);
if(position.Volume == 0) {
this.simulator.Positions.Remove(position);
}
}
public Position Ask(Current current,int n) {
Position result = new Position(current, TradeType.Ask, n);
this.simulator.Positions.Add(result);
return result;
}
public Position Bid(Current current,int n) {
Position result = new Position(current, TradeType.Bid, n);
this.simulator.Positions.Add(result);
return result;
}
}
public class Current {
private CurrentEnumrator enumerator;
private Candlestick candlestick;
public Current(CurrentEnumrator enumerator, Candlestick candlestick) {
this.enumerator = enumerator;
this.candlestick = candlestick;
}
public Candlestick Candlestick {
get {
return candlestick;
}
}
public Position Ask(int n) {
return enumerator.Ask(this,n);
}
public Position Bid(int n) {
return enumerator.Bid(this,n);
}
public void Settle(Position position, int volume) {
enumerator.Settle(position,volume);
}
}
public class Position {
private Current current;
private TradeType tradeType;
private int volume;
public Position(Current current, TradeType tradeType, int volume) {
this.current = current;
this.tradeType = tradeType;
this.volume = volume;
}
public void Settle(int volume = 0) {
current.Settle(this,volume == 0 ? this.volume : volume);
}
public float Settle(Candlestick candlestick, int volume) {
if(volume > this.volume) {
throw new Exception();
}
this.volume -= volume;
float d = (candlestick.Close - current.Candlestick.Close) * volume;
if(tradeType == TradeType.Ask) {
return d;
} else {
return -d;
}
}
public int Volume {
get {
return volume;
}
}
}
}
}
<file_sep>/Candlesticks/ChartForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Candlesticks {
public partial class ChartForm : Form {
private static string[] INSTRUMENTS = { "USD_JPY", "EUR_JPY", "EUR_USD", "US30_USD", "JP225_USD","EU50_EUR" };
private string instrument = "US30_USD";
private string granularity = "M1";
private OandaAPI oandaApi = null;
private List<OandaCandle> candles;
public ChartForm() {
InitializeComponent();
}
private void ChartForm_Load(object sender, EventArgs e) {
oandaApi = new OandaAPI();
candles = oandaApi.GetCandles(100,instrument,granularity).ToList();
chart1.Series.Clear();
chart1.ChartAreas.Clear();
chart1.Titles.Clear();
float low = candles.Select(c => c.lowMid).Min();
float high = candles.Select(c => c.highMid).Max();
ChartArea chartArea = new ChartArea();
chart1.ChartAreas.Add(chartArea);
chartArea.AxisX.LabelStyle.Format = "T";
double n = 0.1d;
while(true) {
double d = Math.Round((high - low) / n);
if (d <= 2) {
break;
}
n *= 2;
}
chartArea.AxisY.Maximum = Math.Ceiling(high / n) * n;
chartArea.AxisY.Minimum = Math.Floor(low / n) * n;
Series candleSeries = new Series();
chart1.Series.Add(candleSeries);
candleSeries.XValueType = ChartValueType.DateTime;
candleSeries.ChartType = SeriesChartType.Candlestick;
foreach(var candle in candles) {
candleSeries.Points.Add(new DataPoint(candle.DateTime.ToOADate(),new double[] { candle.highMid, candle.lowMid, candle.openMid, candle.closeMid }));
}
}
private void ChartForm_FormClosed(object sender, FormClosedEventArgs e) {
if (oandaApi != null) {
oandaApi.Dispose();
}
}
private void instrument1ComboBox_SelectedIndexChanged(object sender, EventArgs e) {
}
private void instrument2ComboBox_SelectedIndexChanged(object sender, EventArgs e) {
}
private void candleRadioButton_CheckedChanged(object sender, EventArgs e) {
}
private void lineRadioButton_CheckedChanged(object sender, EventArgs e) {
}
}
}
| 7faece9552452d442c627f90535f67665eaca346 | [
"C#",
"SQL"
] | 39 | C# | algoke/Candlesticks | 2c5f89930b2ce38aa82807199223c5a870d19a11 | c8e86fc0bd5a40a569875d9d43326466160c9673 |
refs/heads/master | <repo_name>danielhv1300/parqueadro_front<file_sep>/e2e/src/vehicle.po.ts
import {
browser,
element,
by,
ExpectedConditions,
ProtractorExpectedConditions,
ElementFinder,
$
} from 'protractor';
export class RegisterPage {
until: ProtractorExpectedConditions;
constructor() {
this.until = ExpectedConditions;
}
// navegando
navigateTo(url = 'Registrar'): Promise<void> {
return browser.get(`${browser.baseUrl}${url}`) as Promise<void>;
}
// devolver elementos del DOM
obtenerTipoVehiculo(): ElementFinder {
return $('#tipoVehiculo');
}
// Obtiene placa
obtenerPlaca(): ElementFinder {
return $('#placa');
}
// Obtiene toast
obtenerToast(): ElementFinder {
return element(by.className('toast-message'));
}
// Obtiene botón registrar
obtenerBotonRegistrar(): ElementFinder {
return $('#registrarBtn');
}
// Obtiene botón sacar
obtenerBotonSacar(placa: string): ElementFinder {
return $('#btnSacar' + placa );
}
// Obtiene botón registrar pago
obtenerBotonRegistrarPago(placa: string): ElementFinder {
return $('#btnRegistrarPago' + placa);
}
// Obtiene cilindraje
obtenerCilindraje(): ElementFinder {
return $('#cilindraje');
}
// devolver contenido de elementos del DOM en el toast
async obtenerTextoDelToast(): Promise<string> {
return await this.obtenerToast().getText();
}
// modificar elementos del DOM para asignar valores a la placa
async asignarTextoPlaca(text: string): Promise<void> {
return await this.obtenerPlaca().sendKeys(text);
}
// Asigna valores al select de opciones para tipo de vehiculo
async asignarTipoVehiculo(optionI: number): Promise<void> {
// Tick to wait until options apear
await browser.sleep(500);
// End tick
const options: ElementFinder[] = await this.obtenerTipoVehiculo().all(
by.tagName('option')
);
options[optionI].click();
}
async asignarTextoCilindraje(cilindraje: number): Promise<void> {
return await this.obtenerCilindraje().sendKeys(cilindraje);
}
// click en elementos
async clickBotonRegistrar(): Promise<void> {
await this.obtenerBotonRegistrar().click();
}
async clickTipoVehiculo(): Promise<void> {
await this.obtenerTipoVehiculo().click();
}
async clickBotonSacar(placa: string): Promise<void> {
await this.obtenerBotonSacar(placa).click();
}
async clickBtnRegistrarPagoButton(placa: string): Promise<void> {
await this.obtenerBotonRegistrarPago(placa).click();
}
// metodos en espera de accion
async esperarQueAparezcaToast(): Promise<void> {
return await this.esperarAQueAparezca(this.obtenerToast());
}
async esperarAQueAparezcaCilindraje(): Promise<void> {
return await this.esperarAQueAparezca(this.obtenerCilindraje());
}
async esperarAQueAparezca(elemento: ElementFinder): Promise<void> {
const id = await elemento.getId();
return await browser.wait(
this.until.presenceOf(elemento),
5000,
`Elemento ${id} taking too long to appear in the DOM`
);
}
}
<file_sep>/src/app/vehiculo/lista-vehiculos/lista-vehiculos.component.ts
import { Vehiculo } from './../shared/vehiculo.model';
import { Component, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-lista-vehiculos',
templateUrl: './lista-vehiculos.component.html',
styleUrls: ['./lista-vehiculos.component.css']
})
export class ListaVehiculosComponent {
@Input() vehiculos: Vehiculo[];
@Output() actualizarVehiculo = new EventEmitter<string>();
@Output() pagoRegistrado = new EventEmitter<string>();
constructor() {}
sacarVehiculo(placa: string) {
this.actualizarVehiculo.emit(placa);
}
registrarPago(placa: string) {
this.pagoRegistrado.emit(placa);
}
}
<file_sep>/src/app/vehiculo/formulario-registro/formulario-registro.component.ts
import {
Component,
OnInit,
Output,
EventEmitter
} from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { VehiculoService } from '../shared/vehiculo.service';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-formulario-registro',
templateUrl: './formulario-registro.component.html',
styleUrls: ['./formulario-registro.component.css']
})
export class FormularioRegistroComponent implements OnInit {
formularioRegistro: FormGroup;
// Notifico al componente padre que un vehiculo fue registrado para que cargue el listado
@Output() vehiculoRegistrado = new EventEmitter<void>();
constructor(
private formBuilder: FormBuilder,
private service: VehiculoService,
private toastr: ToastrService
) {}
ngOnInit() {
this.resetForm();
}
onSubmit() {
this.formularioRegistro.value.cilindraje = this.formularioRegistro.value.cilindraje.toString();
this.service.crearVehiculo(this.formularioRegistro.value).subscribe(
res => {
this.toastr.success('Registro de vehiculo exitoso');
this.vehiculoRegistrado.emit();
this.resetForm();
},
error => {
this.toastr.error(error.error.message); // Mensaje de respuesta que se compara con el de Protractor
}
);
}
resetForm() {
this.formularioRegistro = this.formBuilder.group({
placa: '',
tipoVehiculo: '',
cilindraje: ''
});
}
}
<file_sep>/src/app/vehiculo/shared/vehiculo.service.ts
import { Injectable } from '@angular/core';
import { Vehiculo } from './vehiculo.model';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class VehiculoService {
vehiculos: Vehiculo[];
vehiculoPath = '/vehiculo/';
constructor(private http: HttpClient) {}
crearVehiculo(vehiculo) {
return this.http.post(environment.apiUrl + this.vehiculoPath, vehiculo);
}
salidaVehiculo(placa) {
this.http
.put(environment.apiUrl + this.vehiculoPath + placa, null)
.subscribe(valor => {
const vehiculo = this.vehiculos.find(u => u.placa === placa);
vehiculo.valor = valor as number;
});
}
marcarPago(placa) {
this.vehiculos = this.vehiculos.filter(u => u.placa !== placa);
}
listarVehiculos() {
this.http
.get<Vehiculo[]>(environment.apiUrl + this.vehiculoPath)
.subscribe(respuesta => {
this.vehiculos = respuesta;
});
}
}
<file_sep>/e2e/src/vehicle.e2e-spec.ts
import { RegisterPage } from './vehicle.po';
describe('Welcome to parqueadero!', () => {
let registerPage: RegisterPage;
const placaCarro = 'YUV449';
const placaMoto = 'UVZ73F';
const placaIniciaConACarro = 'AYU479';
const placaIniciaConAMoto = 'AUY57N';
const tipoVehiculoCarro = 0;
const tipoVehiculoMoto = 1;
const cilindrajeMoto = 300;
beforeEach(async () => {
registerPage = new RegisterPage();
await registerPage.navigateTo();
});
it('Registro vehiculo carro', async () => {
// Arrange
const expectedMessage = 'Registro de vehiculo exitoso';
await registerPage.asignarTextoPlaca(placaCarro);
await registerPage.clickTipoVehiculo();
await registerPage.asignarTipoVehiculo(tipoVehiculoCarro);
await registerPage.clickBotonRegistrar();
await registerPage.esperarQueAparezcaToast();
// Act
const toastContent = await registerPage.obtenerTextoDelToast();
// Assert
expect(toastContent.trim()).toEqual(expectedMessage);
});
it('Registro vehiculo carro ingresado', async () => {
// Arrange
const expectedMessage =
'Ya existe un vehiculo dentro del parqueadero con la placa que desea ingresar';
await registerPage.asignarTextoPlaca(placaCarro);
await registerPage.clickTipoVehiculo();
await registerPage.asignarTipoVehiculo(tipoVehiculoCarro);
await registerPage.clickBotonRegistrar();
await registerPage.esperarQueAparezcaToast();
// Act
const toastContent = await registerPage.obtenerTextoDelToast();
// Assert
expect(toastContent.trim()).toEqual(expectedMessage);
});
it('Registro vehiculo moto', async () => {
// Arrange
const expectedMessage = 'Registro de vehiculo exitoso';
await registerPage.asignarTextoPlaca(placaMoto);
await registerPage.clickTipoVehiculo();
await registerPage.asignarTipoVehiculo(tipoVehiculoMoto);
await registerPage.esperarAQueAparezcaCilindraje();
await registerPage.asignarTextoCilindraje(cilindrajeMoto);
await registerPage.clickBotonRegistrar();
await registerPage.esperarQueAparezcaToast();
// Act
const toastContent = await registerPage.obtenerTextoDelToast();
// Assert
expect(toastContent.trim()).toEqual(expectedMessage);
});
it('Registro vehiculo moto ingresado', async () => {
// Arrange
const expectedMessage =
'Ya existe un vehiculo dentro del parqueadero con la placa que desea ingresar';
await registerPage.asignarTextoPlaca(placaMoto);
await registerPage.clickTipoVehiculo();
await registerPage.asignarTipoVehiculo(tipoVehiculoMoto);
await registerPage.esperarAQueAparezcaCilindraje();
await registerPage.asignarTextoCilindraje(cilindrajeMoto);
await registerPage.clickBotonRegistrar();
await registerPage.esperarQueAparezcaToast();
// Act
const toastContent = await registerPage.obtenerTextoDelToast();
// Assert
expect(toastContent.trim()).toEqual(expectedMessage);
});
it('Retirar vehiculo carro', async () => {
// Arrange - Act - Assert
await registerPage.obtenerBotonSacar(placaCarro);
await registerPage.clickBotonSacar(placaCarro);
await registerPage.obtenerBotonRegistrarPago(placaCarro);
await registerPage.clickBtnRegistrarPagoButton(placaCarro);
});
it('Retirar vehiculo moto', async () => {
// Arrange - Act - Assert
await registerPage.obtenerBotonSacar(placaMoto);
await registerPage.clickBotonSacar(placaMoto);
await registerPage.obtenerBotonRegistrarPago(placaMoto);
await registerPage.clickBtnRegistrarPagoButton(placaMoto);
});
it('Restriccion por placa carro', async () => {
// Arrange
const expectedMessage =
'Los vehiculos que inician con la letra A en su placa, solo ingresan los dias domingos y lunes';
await registerPage.asignarTextoPlaca(placaIniciaConACarro);
await registerPage.clickTipoVehiculo();
await registerPage.asignarTipoVehiculo(tipoVehiculoCarro);
await registerPage.clickBotonRegistrar();
await registerPage.esperarQueAparezcaToast();
// Act
const toastContent = await registerPage.obtenerTextoDelToast();
// Assert
expect(toastContent.trim()).toEqual(expectedMessage);
});
it('Restriccion por placa moto', async () => {
// Arrange
const expectedMessage =
'Los vehiculos que inician con la letra A en su placa, solo ingresan los dias domingos y lunes';
await registerPage.asignarTextoPlaca(placaIniciaConAMoto);
await registerPage.clickTipoVehiculo();
await registerPage.asignarTipoVehiculo(tipoVehiculoMoto);
await registerPage.esperarAQueAparezcaCilindraje();
await registerPage.asignarTextoCilindraje(cilindrajeMoto);
await registerPage.clickBotonRegistrar();
await registerPage.esperarQueAparezcaToast();
// Act
const toastContent = await registerPage.obtenerTextoDelToast();
// Assert
expect(toastContent.trim()).toEqual(expectedMessage);
});
it('Tipo de vehiculo obligatioro Moto', async () => {
// Arrange
const expectedMessage =
'El tipo de vehiculo no puede estar vacio.';
await registerPage.asignarTextoPlaca(placaMoto);
await registerPage.clickBotonRegistrar();
await registerPage.esperarQueAparezcaToast();
// Act
const toastContent = await registerPage.obtenerTextoDelToast();
// Assert
expect(toastContent.trim()).toEqual(expectedMessage);
});
it('Tipo de vehiculo obligatioro carro', async () => {
// Arrange
const expectedMessage =
'El tipo de vehiculo no puede estar vacio.';
await registerPage.asignarTextoPlaca(placaCarro);
await registerPage.clickBotonRegistrar();
await registerPage.esperarQueAparezcaToast();
// Act
const toastContent = await registerPage.obtenerTextoDelToast();
// Assert
expect(toastContent.trim()).toEqual(expectedMessage);
});
it('Placa obligatoria carro', async () => {
// Arrange
const expectedMessage =
'Es necesario que ingrese la placa del vehiculo';
await registerPage.asignarTextoPlaca('');
await registerPage.clickTipoVehiculo();
await registerPage.asignarTipoVehiculo(tipoVehiculoCarro);
await registerPage.clickBotonRegistrar();
await registerPage.esperarQueAparezcaToast();
// Act
const toastContent = await registerPage.obtenerTextoDelToast();
// Assert
expect(toastContent.trim()).toEqual(expectedMessage);
});
it('Placa obligatoria moto', async () => {
// Arrange
const expectedMessage =
'Es necesario que ingrese la placa del vehiculo';
await registerPage.asignarTextoPlaca('');
await registerPage.clickTipoVehiculo();
await registerPage.asignarTipoVehiculo(tipoVehiculoMoto);
await registerPage.esperarAQueAparezcaCilindraje();
await registerPage.asignarTextoCilindraje(cilindrajeMoto);
await registerPage.clickBotonRegistrar();
await registerPage.esperarQueAparezcaToast();
// Act
const toastContent = await registerPage.obtenerTextoDelToast();
// Assert
expect(toastContent.trim()).toEqual(expectedMessage);
});
});
<file_sep>/src/app/vehiculo/shared/vehiculo.model.ts
export interface Vehiculo {
placa: string;
tipoVehiculo: string;
cilindraje?: string;
fechaIngreso: Date;
fechaSalida?: Date;
valor?: number;
}
<file_sep>/src/app/vehiculo/vehiculo.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { VistaComponent } from './vista/vista.component';
import { FormularioRegistroComponent } from './formulario-registro/formulario-registro.component';
import { ListaVehiculosComponent } from './lista-vehiculos/lista-vehiculos.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { VehiculoComponent } from './vehiculo.component';
@NgModule({
declarations: [VistaComponent, FormularioRegistroComponent, ListaVehiculosComponent, VehiculoComponent],
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
]
})
export class VehiculoModule { }
<file_sep>/src/app/vehiculo/vehiculo.component.ts
import { Component, OnInit } from '@angular/core';
import { VehiculoService } from './shared/vehiculo.service';
@Component({
selector: 'app-vehicul',
templateUrl: './vehiculo.component.html',
styleUrls: ['./vehiculo.component.css']
})
export class VehiculoComponent implements OnInit {
constructor(public service: VehiculoService) {
}
ngOnInit() {
this.getVehicles();
}
getVehicles() {
this.service.listarVehiculos();
}
sacarVehiculo(placa) {
this.service.salidaVehiculo(placa);
}
marcarPago(placa) {
this.service.marcarPago(placa);
}
}
| 895005895814969c9ca25fc73b93b2b330145a2d | [
"TypeScript"
] | 8 | TypeScript | danielhv1300/parqueadro_front | 0804222069a78dc48c4224171d8cec7a518b6e7a | 41f12e99ffadfbdb758ad2fc732d902e6259ff60 |
refs/heads/master | <repo_name>vesper8/tailwindui-crawler<file_sep>/transformers/prefixClasses/tailwind-classes.js
module.exports = {
classes: [
'container',
'sr-only',
'not-sr-only',
'focus:sr-only',
'focus:not-sr-only',
'appearance-none',
'bg-fixed',
'bg-local',
'bg-scroll',
'bg-transparent',
'bg-white',
'bg-black',
'bg-gray-50',
'bg-gray-100',
'bg-gray-200',
'bg-gray-300',
'bg-gray-400',
'bg-gray-500',
'bg-gray-600',
'bg-gray-700',
'bg-gray-800',
'bg-gray-900',
'bg-cool-gray-50',
'bg-cool-gray-100',
'bg-cool-gray-200',
'bg-cool-gray-300',
'bg-cool-gray-400',
'bg-cool-gray-500',
'bg-cool-gray-600',
'bg-cool-gray-700',
'bg-cool-gray-800',
'bg-cool-gray-900',
'bg-red-50',
'bg-red-100',
'bg-red-200',
'bg-red-300',
'bg-red-400',
'bg-red-500',
'bg-red-600',
'bg-red-700',
'bg-red-800',
'bg-red-900',
'bg-orange-50',
'bg-orange-100',
'bg-orange-200',
'bg-orange-300',
'bg-orange-400',
'bg-orange-500',
'bg-orange-600',
'bg-orange-700',
'bg-orange-800',
'bg-orange-900',
'bg-yellow-50',
'bg-yellow-100',
'bg-yellow-200',
'bg-yellow-300',
'bg-yellow-400',
'bg-yellow-500',
'bg-yellow-600',
'bg-yellow-700',
'bg-yellow-800',
'bg-yellow-900',
'bg-green-50',
'bg-green-100',
'bg-green-200',
'bg-green-300',
'bg-green-400',
'bg-green-500',
'bg-green-600',
'bg-green-700',
'bg-green-800',
'bg-green-900',
'bg-teal-50',
'bg-teal-100',
'bg-teal-200',
'bg-teal-300',
'bg-teal-400',
'bg-teal-500',
'bg-teal-600',
'bg-teal-700',
'bg-teal-800',
'bg-teal-900',
'bg-blue-50',
'bg-blue-100',
'bg-blue-200',
'bg-blue-300',
'bg-blue-400',
'bg-blue-500',
'bg-blue-600',
'bg-blue-700',
'bg-blue-800',
'bg-blue-900',
'bg-indigo-50',
'bg-indigo-100',
'bg-indigo-200',
'bg-indigo-300',
'bg-indigo-400',
'bg-indigo-500',
'bg-indigo-600',
'bg-indigo-700',
'bg-indigo-800',
'bg-indigo-900',
'bg-purple-50',
'bg-purple-100',
'bg-purple-200',
'bg-purple-300',
'bg-purple-400',
'bg-purple-500',
'bg-purple-600',
'bg-purple-700',
'bg-purple-800',
'bg-purple-900',
'bg-pink-50',
'bg-pink-100',
'bg-pink-200',
'bg-pink-300',
'bg-pink-400',
'bg-pink-500',
'bg-pink-600',
'bg-pink-700',
'bg-pink-800',
'bg-pink-900',
'hover:bg-transparent:hover',
'hover:bg-white:hover',
'hover:bg-black:hover',
'hover:bg-gray-50:hover',
'hover:bg-gray-100:hover',
'hover:bg-gray-200:hover',
'hover:bg-gray-300:hover',
'hover:bg-gray-400:hover',
'hover:bg-gray-500:hover',
'hover:bg-gray-600:hover',
'hover:bg-gray-700:hover',
'hover:bg-gray-800:hover',
'hover:bg-gray-900:hover',
'hover:bg-cool-gray-50:hover',
'hover:bg-cool-gray-100:hover',
'hover:bg-cool-gray-200:hover',
'hover:bg-cool-gray-300:hover',
'hover:bg-cool-gray-400:hover',
'hover:bg-cool-gray-500:hover',
'hover:bg-cool-gray-600:hover',
'hover:bg-cool-gray-700:hover',
'hover:bg-cool-gray-800:hover',
'hover:bg-cool-gray-900:hover',
'hover:bg-red-50:hover',
'hover:bg-red-100:hover',
'hover:bg-red-200:hover',
'hover:bg-red-300:hover',
'hover:bg-red-400:hover',
'hover:bg-red-500:hover',
'hover:bg-red-600:hover',
'hover:bg-red-700:hover',
'hover:bg-red-800:hover',
'hover:bg-red-900:hover',
'hover:bg-orange-50:hover',
'hover:bg-orange-100:hover',
'hover:bg-orange-200:hover',
'hover:bg-orange-300:hover',
'hover:bg-orange-400:hover',
'hover:bg-orange-500:hover',
'hover:bg-orange-600:hover',
'hover:bg-orange-700:hover',
'hover:bg-orange-800:hover',
'hover:bg-orange-900:hover',
'hover:bg-yellow-50:hover',
'hover:bg-yellow-100:hover',
'hover:bg-yellow-200:hover',
'hover:bg-yellow-300:hover',
'hover:bg-yellow-400:hover',
'hover:bg-yellow-500:hover',
'hover:bg-yellow-600:hover',
'hover:bg-yellow-700:hover',
'hover:bg-yellow-800:hover',
'hover:bg-yellow-900:hover',
'hover:bg-green-50:hover',
'hover:bg-green-100:hover',
'hover:bg-green-200:hover',
'hover:bg-green-300:hover',
'hover:bg-green-400:hover',
'hover:bg-green-500:hover',
'hover:bg-green-600:hover',
'hover:bg-green-700:hover',
'hover:bg-green-800:hover',
'hover:bg-green-900:hover',
'hover:bg-teal-50:hover',
'hover:bg-teal-100:hover',
'hover:bg-teal-200:hover',
'hover:bg-teal-300:hover',
'hover:bg-teal-400:hover',
'hover:bg-teal-500:hover',
'hover:bg-teal-600:hover',
'hover:bg-teal-700:hover',
'hover:bg-teal-800:hover',
'hover:bg-teal-900:hover',
'hover:bg-blue-50:hover',
'hover:bg-blue-100:hover',
'hover:bg-blue-200:hover',
'hover:bg-blue-300:hover',
'hover:bg-blue-400:hover',
'hover:bg-blue-500:hover',
'hover:bg-blue-600:hover',
'hover:bg-blue-700:hover',
'hover:bg-blue-800:hover',
'hover:bg-blue-900:hover',
'hover:bg-indigo-50:hover',
'hover:bg-indigo-100:hover',
'hover:bg-indigo-200:hover',
'hover:bg-indigo-300:hover',
'hover:bg-indigo-400:hover',
'hover:bg-indigo-500:hover',
'hover:bg-indigo-600:hover',
'hover:bg-indigo-700:hover',
'hover:bg-indigo-800:hover',
'hover:bg-indigo-900:hover',
'hover:bg-purple-50:hover',
'hover:bg-purple-100:hover',
'hover:bg-purple-200:hover',
'hover:bg-purple-300:hover',
'hover:bg-purple-400:hover',
'hover:bg-purple-500:hover',
'hover:bg-purple-600:hover',
'hover:bg-purple-700:hover',
'hover:bg-purple-800:hover',
'hover:bg-purple-900:hover',
'hover:bg-pink-50:hover',
'hover:bg-pink-100:hover',
'hover:bg-pink-200:hover',
'hover:bg-pink-300:hover',
'hover:bg-pink-400:hover',
'hover:bg-pink-500:hover',
'hover:bg-pink-600:hover',
'hover:bg-pink-700:hover',
'hover:bg-pink-800:hover',
'hover:bg-pink-900:hover',
'focus:bg-transparent',
'focus:bg-white',
'focus:bg-black',
'focus:bg-gray-50',
'focus:bg-gray-100',
'focus:bg-gray-200',
'focus:bg-gray-300',
'focus:bg-gray-400',
'focus:bg-gray-500',
'focus:bg-gray-600',
'focus:bg-gray-700',
'focus:bg-gray-800',
'focus:bg-gray-900',
'focus:bg-cool-gray-50',
'focus:bg-cool-gray-100',
'focus:bg-cool-gray-200',
'focus:bg-cool-gray-300',
'focus:bg-cool-gray-400',
'focus:bg-cool-gray-500',
'focus:bg-cool-gray-600',
'focus:bg-cool-gray-700',
'focus:bg-cool-gray-800',
'focus:bg-cool-gray-900',
'focus:bg-red-50',
'focus:bg-red-100',
'focus:bg-red-200',
'focus:bg-red-300',
'focus:bg-red-400',
'focus:bg-red-500',
'focus:bg-red-600',
'focus:bg-red-700',
'focus:bg-red-800',
'focus:bg-red-900',
'focus:bg-orange-50',
'focus:bg-orange-100',
'focus:bg-orange-200',
'focus:bg-orange-300',
'focus:bg-orange-400',
'focus:bg-orange-500',
'focus:bg-orange-600',
'focus:bg-orange-700',
'focus:bg-orange-800',
'focus:bg-orange-900',
'focus:bg-yellow-50',
'focus:bg-yellow-100',
'focus:bg-yellow-200',
'focus:bg-yellow-300',
'focus:bg-yellow-400',
'focus:bg-yellow-500',
'focus:bg-yellow-600',
'focus:bg-yellow-700',
'focus:bg-yellow-800',
'focus:bg-yellow-900',
'focus:bg-green-50',
'focus:bg-green-100',
'focus:bg-green-200',
'focus:bg-green-300',
'focus:bg-green-400',
'focus:bg-green-500',
'focus:bg-green-600',
'focus:bg-green-700',
'focus:bg-green-800',
'focus:bg-green-900',
'focus:bg-teal-50',
'focus:bg-teal-100',
'focus:bg-teal-200',
'focus:bg-teal-300',
'focus:bg-teal-400',
'focus:bg-teal-500',
'focus:bg-teal-600',
'focus:bg-teal-700',
'focus:bg-teal-800',
'focus:bg-teal-900',
'focus:bg-blue-50',
'focus:bg-blue-100',
'focus:bg-blue-200',
'focus:bg-blue-300',
'focus:bg-blue-400',
'focus:bg-blue-500',
'focus:bg-blue-600',
'focus:bg-blue-700',
'focus:bg-blue-800',
'focus:bg-blue-900',
'focus:bg-indigo-50',
'focus:bg-indigo-100',
'focus:bg-indigo-200',
'focus:bg-indigo-300',
'focus:bg-indigo-400',
'focus:bg-indigo-500',
'focus:bg-indigo-600',
'focus:bg-indigo-700',
'focus:bg-indigo-800',
'focus:bg-indigo-900',
'focus:bg-purple-50',
'focus:bg-purple-100',
'focus:bg-purple-200',
'focus:bg-purple-300',
'focus:bg-purple-400',
'focus:bg-purple-500',
'focus:bg-purple-600',
'focus:bg-purple-700',
'focus:bg-purple-800',
'focus:bg-purple-900',
'focus:bg-pink-50',
'focus:bg-pink-100',
'focus:bg-pink-200',
'focus:bg-pink-300',
'focus:bg-pink-400',
'focus:bg-pink-500',
'focus:bg-pink-600',
'focus:bg-pink-700',
'focus:bg-pink-800',
'focus:bg-pink-900',
'active:bg-transparent:active',
'active:bg-white:active',
'active:bg-black:active',
'active:bg-gray-50:active',
'active:bg-gray-100:active',
'active:bg-gray-200:active',
'active:bg-gray-300:active',
'active:bg-gray-400:active',
'active:bg-gray-500:active',
'active:bg-gray-600:active',
'active:bg-gray-700:active',
'active:bg-gray-800:active',
'active:bg-gray-900:active',
'active:bg-cool-gray-50:active',
'active:bg-cool-gray-100:active',
'active:bg-cool-gray-200:active',
'active:bg-cool-gray-300:active',
'active:bg-cool-gray-400:active',
'active:bg-cool-gray-500:active',
'active:bg-cool-gray-600:active',
'active:bg-cool-gray-700:active',
'active:bg-cool-gray-800:active',
'active:bg-cool-gray-900:active',
'active:bg-red-50:active',
'active:bg-red-100:active',
'active:bg-red-200:active',
'active:bg-red-300:active',
'active:bg-red-400:active',
'active:bg-red-500:active',
'active:bg-red-600:active',
'active:bg-red-700:active',
'active:bg-red-800:active',
'active:bg-red-900:active',
'active:bg-orange-50:active',
'active:bg-orange-100:active',
'active:bg-orange-200:active',
'active:bg-orange-300:active',
'active:bg-orange-400:active',
'active:bg-orange-500:active',
'active:bg-orange-600:active',
'active:bg-orange-700:active',
'active:bg-orange-800:active',
'active:bg-orange-900:active',
'active:bg-yellow-50:active',
'active:bg-yellow-100:active',
'active:bg-yellow-200:active',
'active:bg-yellow-300:active',
'active:bg-yellow-400:active',
'active:bg-yellow-500:active',
'active:bg-yellow-600:active',
'active:bg-yellow-700:active',
'active:bg-yellow-800:active',
'active:bg-yellow-900:active',
'active:bg-green-50:active',
'active:bg-green-100:active',
'active:bg-green-200:active',
'active:bg-green-300:active',
'active:bg-green-400:active',
'active:bg-green-500:active',
'active:bg-green-600:active',
'active:bg-green-700:active',
'active:bg-green-800:active',
'active:bg-green-900:active',
'active:bg-teal-50:active',
'active:bg-teal-100:active',
'active:bg-teal-200:active',
'active:bg-teal-300:active',
'active:bg-teal-400:active',
'active:bg-teal-500:active',
'active:bg-teal-600:active',
'active:bg-teal-700:active',
'active:bg-teal-800:active',
'active:bg-teal-900:active',
'active:bg-blue-50:active',
'active:bg-blue-100:active',
'active:bg-blue-200:active',
'active:bg-blue-300:active',
'active:bg-blue-400:active',
'active:bg-blue-500:active',
'active:bg-blue-600:active',
'active:bg-blue-700:active',
'active:bg-blue-800:active',
'active:bg-blue-900:active',
'active:bg-indigo-50:active',
'active:bg-indigo-100:active',
'active:bg-indigo-200:active',
'active:bg-indigo-300:active',
'active:bg-indigo-400:active',
'active:bg-indigo-500:active',
'active:bg-indigo-600:active',
'active:bg-indigo-700:active',
'active:bg-indigo-800:active',
'active:bg-indigo-900:active',
'active:bg-purple-50:active',
'active:bg-purple-100:active',
'active:bg-purple-200:active',
'active:bg-purple-300:active',
'active:bg-purple-400:active',
'active:bg-purple-500:active',
'active:bg-purple-600:active',
'active:bg-purple-700:active',
'active:bg-purple-800:active',
'active:bg-purple-900:active',
'active:bg-pink-50:active',
'active:bg-pink-100:active',
'active:bg-pink-200:active',
'active:bg-pink-300:active',
'active:bg-pink-400:active',
'active:bg-pink-500:active',
'active:bg-pink-600:active',
'active:bg-pink-700:active',
'active:bg-pink-800:active',
'active:bg-pink-900:active',
'bg-bottom',
'bg-center',
'bg-left',
'bg-left-bottom',
'bg-left-top',
'bg-right',
'bg-right-bottom',
'bg-right-top',
'bg-top',
'bg-repeat',
'bg-no-repeat',
'bg-repeat-x',
'bg-repeat-y',
'bg-repeat-round',
'bg-repeat-space',
'bg-auto',
'bg-cover',
'bg-contain',
'border-collapse',
'border-separate',
'border-transparent',
'border-white',
'border-black',
'border-gray-50',
'border-gray-100',
'border-gray-200',
'border-gray-300',
'border-gray-400',
'border-gray-500',
'border-gray-600',
'border-gray-700',
'border-gray-800',
'border-gray-900',
'border-cool-gray-50',
'border-cool-gray-100',
'border-cool-gray-200',
'border-cool-gray-300',
'border-cool-gray-400',
'border-cool-gray-500',
'border-cool-gray-600',
'border-cool-gray-700',
'border-cool-gray-800',
'border-cool-gray-900',
'border-red-50',
'border-red-100',
'border-red-200',
'border-red-300',
'border-red-400',
'border-red-500',
'border-red-600',
'border-red-700',
'border-red-800',
'border-red-900',
'border-orange-50',
'border-orange-100',
'border-orange-200',
'border-orange-300',
'border-orange-400',
'border-orange-500',
'border-orange-600',
'border-orange-700',
'border-orange-800',
'border-orange-900',
'border-yellow-50',
'border-yellow-100',
'border-yellow-200',
'border-yellow-300',
'border-yellow-400',
'border-yellow-500',
'border-yellow-600',
'border-yellow-700',
'border-yellow-800',
'border-yellow-900',
'border-green-50',
'border-green-100',
'border-green-200',
'border-green-300',
'border-green-400',
'border-green-500',
'border-green-600',
'border-green-700',
'border-green-800',
'border-green-900',
'border-teal-50',
'border-teal-100',
'border-teal-200',
'border-teal-300',
'border-teal-400',
'border-teal-500',
'border-teal-600',
'border-teal-700',
'border-teal-800',
'border-teal-900',
'border-blue-50',
'border-blue-100',
'border-blue-200',
'border-blue-300',
'border-blue-400',
'border-blue-500',
'border-blue-600',
'border-blue-700',
'border-blue-800',
'border-blue-900',
'border-indigo-50',
'border-indigo-100',
'border-indigo-200',
'border-indigo-300',
'border-indigo-400',
'border-indigo-500',
'border-indigo-600',
'border-indigo-700',
'border-indigo-800',
'border-indigo-900',
'border-purple-50',
'border-purple-100',
'border-purple-200',
'border-purple-300',
'border-purple-400',
'border-purple-500',
'border-purple-600',
'border-purple-700',
'border-purple-800',
'border-purple-900',
'border-pink-50',
'border-pink-100',
'border-pink-200',
'border-pink-300',
'border-pink-400',
'border-pink-500',
'border-pink-600',
'border-pink-700',
'border-pink-800',
'border-pink-900',
'hover:border-transparent:hover',
'hover:border-white:hover',
'hover:border-black:hover',
'hover:border-gray-50:hover',
'hover:border-gray-100:hover',
'hover:border-gray-200:hover',
'hover:border-gray-300:hover',
'hover:border-gray-400:hover',
'hover:border-gray-500:hover',
'hover:border-gray-600:hover',
'hover:border-gray-700:hover',
'hover:border-gray-800:hover',
'hover:border-gray-900:hover',
'hover:border-cool-gray-50:hover',
'hover:border-cool-gray-100:hover',
'hover:border-cool-gray-200:hover',
'hover:border-cool-gray-300:hover',
'hover:border-cool-gray-400:hover',
'hover:border-cool-gray-500:hover',
'hover:border-cool-gray-600:hover',
'hover:border-cool-gray-700:hover',
'hover:border-cool-gray-800:hover',
'hover:border-cool-gray-900:hover',
'hover:border-red-50:hover',
'hover:border-red-100:hover',
'hover:border-red-200:hover',
'hover:border-red-300:hover',
'hover:border-red-400:hover',
'hover:border-red-500:hover',
'hover:border-red-600:hover',
'hover:border-red-700:hover',
'hover:border-red-800:hover',
'hover:border-red-900:hover',
'hover:border-orange-50:hover',
'hover:border-orange-100:hover',
'hover:border-orange-200:hover',
'hover:border-orange-300:hover',
'hover:border-orange-400:hover',
'hover:border-orange-500:hover',
'hover:border-orange-600:hover',
'hover:border-orange-700:hover',
'hover:border-orange-800:hover',
'hover:border-orange-900:hover',
'hover:border-yellow-50:hover',
'hover:border-yellow-100:hover',
'hover:border-yellow-200:hover',
'hover:border-yellow-300:hover',
'hover:border-yellow-400:hover',
'hover:border-yellow-500:hover',
'hover:border-yellow-600:hover',
'hover:border-yellow-700:hover',
'hover:border-yellow-800:hover',
'hover:border-yellow-900:hover',
'hover:border-green-50:hover',
'hover:border-green-100:hover',
'hover:border-green-200:hover',
'hover:border-green-300:hover',
'hover:border-green-400:hover',
'hover:border-green-500:hover',
'hover:border-green-600:hover',
'hover:border-green-700:hover',
'hover:border-green-800:hover',
'hover:border-green-900:hover',
'hover:border-teal-50:hover',
'hover:border-teal-100:hover',
'hover:border-teal-200:hover',
'hover:border-teal-300:hover',
'hover:border-teal-400:hover',
'hover:border-teal-500:hover',
'hover:border-teal-600:hover',
'hover:border-teal-700:hover',
'hover:border-teal-800:hover',
'hover:border-teal-900:hover',
'hover:border-blue-50:hover',
'hover:border-blue-100:hover',
'hover:border-blue-200:hover',
'hover:border-blue-300:hover',
'hover:border-blue-400:hover',
'hover:border-blue-500:hover',
'hover:border-blue-600:hover',
'hover:border-blue-700:hover',
'hover:border-blue-800:hover',
'hover:border-blue-900:hover',
'hover:border-indigo-50:hover',
'hover:border-indigo-100:hover',
'hover:border-indigo-200:hover',
'hover:border-indigo-300:hover',
'hover:border-indigo-400:hover',
'hover:border-indigo-500:hover',
'hover:border-indigo-600:hover',
'hover:border-indigo-700:hover',
'hover:border-indigo-800:hover',
'hover:border-indigo-900:hover',
'hover:border-purple-50:hover',
'hover:border-purple-100:hover',
'hover:border-purple-200:hover',
'hover:border-purple-300:hover',
'hover:border-purple-400:hover',
'hover:border-purple-500:hover',
'hover:border-purple-600:hover',
'hover:border-purple-700:hover',
'hover:border-purple-800:hover',
'hover:border-purple-900:hover',
'hover:border-pink-50:hover',
'hover:border-pink-100:hover',
'hover:border-pink-200:hover',
'hover:border-pink-300:hover',
'hover:border-pink-400:hover',
'hover:border-pink-500:hover',
'hover:border-pink-600:hover',
'hover:border-pink-700:hover',
'hover:border-pink-800:hover',
'hover:border-pink-900:hover',
'focus:border-transparent',
'focus:border-white',
'focus:border-black',
'focus:border-gray-50',
'focus:border-gray-100',
'focus:border-gray-200',
'focus:border-gray-300',
'focus:border-gray-400',
'focus:border-gray-500',
'focus:border-gray-600',
'focus:border-gray-700',
'focus:border-gray-800',
'focus:border-gray-900',
'focus:border-cool-gray-50',
'focus:border-cool-gray-100',
'focus:border-cool-gray-200',
'focus:border-cool-gray-300',
'focus:border-cool-gray-400',
'focus:border-cool-gray-500',
'focus:border-cool-gray-600',
'focus:border-cool-gray-700',
'focus:border-cool-gray-800',
'focus:border-cool-gray-900',
'focus:border-red-50',
'focus:border-red-100',
'focus:border-red-200',
'focus:border-red-300',
'focus:border-red-400',
'focus:border-red-500',
'focus:border-red-600',
'focus:border-red-700',
'focus:border-red-800',
'focus:border-red-900',
'focus:border-orange-50',
'focus:border-orange-100',
'focus:border-orange-200',
'focus:border-orange-300',
'focus:border-orange-400',
'focus:border-orange-500',
'focus:border-orange-600',
'focus:border-orange-700',
'focus:border-orange-800',
'focus:border-orange-900',
'focus:border-yellow-50',
'focus:border-yellow-100',
'focus:border-yellow-200',
'focus:border-yellow-300',
'focus:border-yellow-400',
'focus:border-yellow-500',
'focus:border-yellow-600',
'focus:border-yellow-700',
'focus:border-yellow-800',
'focus:border-yellow-900',
'focus:border-green-50',
'focus:border-green-100',
'focus:border-green-200',
'focus:border-green-300',
'focus:border-green-400',
'focus:border-green-500',
'focus:border-green-600',
'focus:border-green-700',
'focus:border-green-800',
'focus:border-green-900',
'focus:border-teal-50',
'focus:border-teal-100',
'focus:border-teal-200',
'focus:border-teal-300',
'focus:border-teal-400',
'focus:border-teal-500',
'focus:border-teal-600',
'focus:border-teal-700',
'focus:border-teal-800',
'focus:border-teal-900',
'focus:border-blue-50',
'focus:border-blue-100',
'focus:border-blue-200',
'focus:border-blue-300',
'focus:border-blue-400',
'focus:border-blue-500',
'focus:border-blue-600',
'focus:border-blue-700',
'focus:border-blue-800',
'focus:border-blue-900',
'focus:border-indigo-50',
'focus:border-indigo-100',
'focus:border-indigo-200',
'focus:border-indigo-300',
'focus:border-indigo-400',
'focus:border-indigo-500',
'focus:border-indigo-600',
'focus:border-indigo-700',
'focus:border-indigo-800',
'focus:border-indigo-900',
'focus:border-purple-50',
'focus:border-purple-100',
'focus:border-purple-200',
'focus:border-purple-300',
'focus:border-purple-400',
'focus:border-purple-500',
'focus:border-purple-600',
'focus:border-purple-700',
'focus:border-purple-800',
'focus:border-purple-900',
'focus:border-pink-50',
'focus:border-pink-100',
'focus:border-pink-200',
'focus:border-pink-300',
'focus:border-pink-400',
'focus:border-pink-500',
'focus:border-pink-600',
'focus:border-pink-700',
'focus:border-pink-800',
'focus:border-pink-900',
'rounded-none',
'rounded-sm',
'rounded',
'rounded-md',
'rounded-lg',
'rounded-full',
'rounded-t-none',
'rounded-r-none',
'rounded-b-none',
'rounded-l-none',
'rounded-t-sm',
'rounded-r-sm',
'rounded-b-sm',
'rounded-l-sm',
'rounded-t',
'rounded-r',
'rounded-b',
'rounded-l',
'rounded-t-md',
'rounded-r-md',
'rounded-b-md',
'rounded-l-md',
'rounded-t-lg',
'rounded-r-lg',
'rounded-b-lg',
'rounded-l-lg',
'rounded-t-full',
'rounded-r-full',
'rounded-b-full',
'rounded-l-full',
'rounded-tl-none',
'rounded-tr-none',
'rounded-br-none',
'rounded-bl-none',
'rounded-tl-sm',
'rounded-tr-sm',
'rounded-br-sm',
'rounded-bl-sm',
'rounded-tl',
'rounded-tr',
'rounded-br',
'rounded-bl',
'rounded-tl-md',
'rounded-tr-md',
'rounded-br-md',
'rounded-bl-md',
'rounded-tl-lg',
'rounded-tr-lg',
'rounded-br-lg',
'rounded-bl-lg',
'rounded-tl-full',
'rounded-tr-full',
'rounded-br-full',
'rounded-bl-full',
'border-solid',
'border-dashed',
'border-dotted',
'border-double',
'border-none',
'border-0',
'border-2',
'border-4',
'border-8',
'border',
'border-t-0',
'border-r-0',
'border-b-0',
'border-l-0',
'border-t-2',
'border-r-2',
'border-b-2',
'border-l-2',
'border-t-4',
'border-r-4',
'border-b-4',
'border-l-4',
'border-t-8',
'border-r-8',
'border-b-8',
'border-l-8',
'border-t',
'border-r',
'border-b',
'border-l',
'box-border',
'box-content',
'cursor-auto',
'cursor-default',
'cursor-pointer',
'cursor-wait',
'cursor-text',
'cursor-move',
'cursor-not-allowed',
'block',
'inline-block',
'inline',
'flex',
'inline-flex',
'grid',
'table',
'table-caption',
'table-cell',
'table-column',
'table-column-group',
'table-footer-group',
'table-header-group',
'table-row-group',
'table-row',
'hidden',
'flex-row',
'flex-row-reverse',
'flex-col',
'flex-col-reverse',
'flex-wrap',
'flex-wrap-reverse',
'flex-no-wrap',
'items-start',
'items-end',
'items-center',
'items-baseline',
'items-stretch',
'self-auto',
'self-start',
'self-end',
'self-center',
'self-stretch',
'justify-start',
'justify-end',
'justify-center',
'justify-between',
'justify-around',
'justify-evenly',
'content-center',
'content-start',
'content-end',
'content-between',
'content-around',
'flex-1',
'flex-auto',
'flex-initial',
'flex-none',
'flex-grow-0',
'flex-grow',
'flex-shrink-0',
'flex-shrink',
'order-1',
'order-2',
'order-3',
'order-4',
'order-5',
'order-6',
'order-7',
'order-8',
'order-9',
'order-10',
'order-11',
'order-12',
'order-first',
'order-last',
'order-none',
'float-right',
'float-left',
'float-none',
'clearfix:after',
'clear-left',
'clear-right',
'clear-both',
'font-sans',
'font-serif',
'font-mono',
'font-hairline',
'font-thin',
'font-light',
'font-normal',
'font-medium',
'font-semibold',
'font-bold',
'font-extrabold',
'font-black',
'hover:font-hairline:hover',
'hover:font-thin:hover',
'hover:font-light:hover',
'hover:font-normal:hover',
'hover:font-medium:hover',
'hover:font-semibold:hover',
'hover:font-bold:hover',
'hover:font-extrabold:hover',
'hover:font-black:hover',
'focus:font-hairline',
'focus:font-thin',
'focus:font-light',
'focus:font-normal',
'focus:font-medium',
'focus:font-semibold',
'focus:font-bold',
'focus:font-extrabold',
'focus:font-black',
'h-0',
'h-1',
'h-2',
'h-3',
'h-4',
'h-5',
'h-6',
'h-7',
'h-8',
'h-9',
'h-10',
'h-11',
'h-12',
'h-13',
'h-14',
'h-15',
'h-16',
'h-20',
'h-24',
'h-28',
'h-32',
'h-36',
'h-40',
'h-48',
'h-56',
'h-60',
'h-64',
'h-72',
'h-80',
'h-96',
'h-auto',
'h-px',
'h-05',
'h-25',
'h-35',
'h-1/2',
'h-1/3',
'h-2/3',
'h-1/4',
'h-2/4',
'h-3/4',
'h-1/5',
'h-2/5',
'h-3/5',
'h-4/5',
'h-1/6',
'h-2/6',
'h-3/6',
'h-4/6',
'h-5/6',
'h-1/12',
'h-2/12',
'h-3/12',
'h-4/12',
'h-5/12',
'h-6/12',
'h-7/12',
'h-8/12',
'h-9/12',
'h-10/12',
'h-11/12',
'h-full',
'h-screen',
'leading-3',
'leading-4',
'leading-5',
'leading-6',
'leading-7',
'leading-8',
'leading-9',
'leading-10',
'leading-none',
'leading-tight',
'leading-snug',
'leading-normal',
'leading-relaxed',
'leading-loose',
'list-inside',
'list-outside',
'list-none',
'list-disc',
'list-decimal',
'm-0',
'm-1',
'm-2',
'm-3',
'm-4',
'm-5',
'm-6',
'm-7',
'm-8',
'm-9',
'm-10',
'm-11',
'm-12',
'm-13',
'm-14',
'm-15',
'm-16',
'm-20',
'm-24',
'm-28',
'm-32',
'm-36',
'm-40',
'm-48',
'm-56',
'm-60',
'm-64',
'm-72',
'm-80',
'm-96',
'm-auto',
'm-px',
'm-05',
'm-25',
'm-35',
'm-1/2',
'm-1/3',
'm-2/3',
'm-1/4',
'm-2/4',
'm-3/4',
'm-1/5',
'm-2/5',
'm-3/5',
'm-4/5',
'm-1/6',
'm-2/6',
'm-3/6',
'm-4/6',
'm-5/6',
'm-1/12',
'm-2/12',
'm-3/12',
'm-4/12',
'm-5/12',
'm-6/12',
'm-7/12',
'm-8/12',
'm-9/12',
'm-10/12',
'm-11/12',
'm-full',
'-m-1',
'-m-2',
'-m-3',
'-m-4',
'-m-5',
'-m-6',
'-m-7',
'-m-8',
'-m-9',
'-m-10',
'-m-11',
'-m-12',
'-m-13',
'-m-14',
'-m-15',
'-m-16',
'-m-20',
'-m-24',
'-m-28',
'-m-32',
'-m-36',
'-m-40',
'-m-48',
'-m-56',
'-m-60',
'-m-64',
'-m-72',
'-m-80',
'-m-96',
'-m-px',
'-m-05',
'-m-25',
'-m-35',
'-m-1/2',
'-m-1/3',
'-m-2/3',
'-m-1/4',
'-m-2/4',
'-m-3/4',
'-m-1/5',
'-m-2/5',
'-m-3/5',
'-m-4/5',
'-m-1/6',
'-m-2/6',
'-m-3/6',
'-m-4/6',
'-m-5/6',
'-m-1/12',
'-m-2/12',
'-m-3/12',
'-m-4/12',
'-m-5/12',
'-m-6/12',
'-m-7/12',
'-m-8/12',
'-m-9/12',
'-m-10/12',
'-m-11/12',
'-m-full',
'my-0',
'mx-0',
'my-1',
'mx-1',
'my-2',
'mx-2',
'my-3',
'mx-3',
'my-4',
'mx-4',
'my-5',
'mx-5',
'my-6',
'mx-6',
'my-7',
'mx-7',
'my-8',
'mx-8',
'my-9',
'mx-9',
'my-10',
'mx-10',
'my-11',
'mx-11',
'my-12',
'mx-12',
'my-13',
'mx-13',
'my-14',
'mx-14',
'my-15',
'mx-15',
'my-16',
'mx-16',
'my-20',
'mx-20',
'my-24',
'mx-24',
'my-28',
'mx-28',
'my-32',
'mx-32',
'my-36',
'mx-36',
'my-40',
'mx-40',
'my-48',
'mx-48',
'my-56',
'mx-56',
'my-60',
'mx-60',
'my-64',
'mx-64',
'my-72',
'mx-72',
'my-80',
'mx-80',
'my-96',
'mx-96',
'my-auto',
'mx-auto',
'my-px',
'mx-px',
'my-05',
'mx-05',
'my-25',
'mx-25',
'my-35',
'mx-35',
'my-1/2',
'mx-1/2',
'my-1/3',
'mx-1/3',
'my-2/3',
'mx-2/3',
'my-1/4',
'mx-1/4',
'my-2/4',
'mx-2/4',
'my-3/4',
'mx-3/4',
'my-1/5',
'mx-1/5',
'my-2/5',
'mx-2/5',
'my-3/5',
'mx-3/5',
'my-4/5',
'mx-4/5',
'my-1/6',
'mx-1/6',
'my-2/6',
'mx-2/6',
'my-3/6',
'mx-3/6',
'my-4/6',
'mx-4/6',
'my-5/6',
'mx-5/6',
'my-1/12',
'mx-1/12',
'my-2/12',
'mx-2/12',
'my-3/12',
'mx-3/12',
'my-4/12',
'mx-4/12',
'my-5/12',
'mx-5/12',
'my-6/12',
'mx-6/12',
'my-7/12',
'mx-7/12',
'my-8/12',
'mx-8/12',
'my-9/12',
'mx-9/12',
'my-10/12',
'mx-10/12',
'my-11/12',
'mx-11/12',
'my-full',
'mx-full',
'-my-1',
'-mx-1',
'-my-2',
'-mx-2',
'-my-3',
'-mx-3',
'-my-4',
'-mx-4',
'-my-5',
'-mx-5',
'-my-6',
'-mx-6',
'-my-7',
'-mx-7',
'-my-8',
'-mx-8',
'-my-9',
'-mx-9',
'-my-10',
'-mx-10',
'-my-11',
'-mx-11',
'-my-12',
'-mx-12',
'-my-13',
'-mx-13',
'-my-14',
'-mx-14',
'-my-15',
'-mx-15',
'-my-16',
'-mx-16',
'-my-20',
'-mx-20',
'-my-24',
'-mx-24',
'-my-28',
'-mx-28',
'-my-32',
'-mx-32',
'-my-36',
'-mx-36',
'-my-40',
'-mx-40',
'-my-48',
'-mx-48',
'-my-56',
'-mx-56',
'-my-60',
'-mx-60',
'-my-64',
'-mx-64',
'-my-72',
'-mx-72',
'-my-80',
'-mx-80',
'-my-96',
'-mx-96',
'-my-px',
'-mx-px',
'-my-05',
'-mx-05',
'-my-25',
'-mx-25',
'-my-35',
'-mx-35',
'-my-1/2',
'-mx-1/2',
'-my-1/3',
'-mx-1/3',
'-my-2/3',
'-mx-2/3',
'-my-1/4',
'-mx-1/4',
'-my-2/4',
'-mx-2/4',
'-my-3/4',
'-mx-3/4',
'-my-1/5',
'-mx-1/5',
'-my-2/5',
'-mx-2/5',
'-my-3/5',
'-mx-3/5',
'-my-4/5',
'-mx-4/5',
'-my-1/6',
'-mx-1/6',
'-my-2/6',
'-mx-2/6',
'-my-3/6',
'-mx-3/6',
'-my-4/6',
'-mx-4/6',
'-my-5/6',
'-mx-5/6',
'-my-1/12',
'-mx-1/12',
'-my-2/12',
'-mx-2/12',
'-my-3/12',
'-mx-3/12',
'-my-4/12',
'-mx-4/12',
'-my-5/12',
'-mx-5/12',
'-my-6/12',
'-mx-6/12',
'-my-7/12',
'-mx-7/12',
'-my-8/12',
'-mx-8/12',
'-my-9/12',
'-mx-9/12',
'-my-10/12',
'-mx-10/12',
'-my-11/12',
'-mx-11/12',
'-my-full',
'-mx-full',
'mt-0',
'mr-0',
'mb-0',
'ml-0',
'mt-1',
'mr-1',
'mb-1',
'ml-1',
'mt-2',
'mr-2',
'mb-2',
'ml-2',
'mt-3',
'mr-3',
'mb-3',
'ml-3',
'mt-4',
'mr-4',
'mb-4',
'ml-4',
'mt-5',
'mr-5',
'mb-5',
'ml-5',
'mt-6',
'mr-6',
'mb-6',
'ml-6',
'mt-7',
'mr-7',
'mb-7',
'ml-7',
'mt-8',
'mr-8',
'mb-8',
'ml-8',
'mt-9',
'mr-9',
'mb-9',
'ml-9',
'mt-10',
'mr-10',
'mb-10',
'ml-10',
'mt-11',
'mr-11',
'mb-11',
'ml-11',
'mt-12',
'mr-12',
'mb-12',
'ml-12',
'mt-13',
'mr-13',
'mb-13',
'ml-13',
'mt-14',
'mr-14',
'mb-14',
'ml-14',
'mt-15',
'mr-15',
'mb-15',
'ml-15',
'mt-16',
'mr-16',
'mb-16',
'ml-16',
'mt-20',
'mr-20',
'mb-20',
'ml-20',
'mt-24',
'mr-24',
'mb-24',
'ml-24',
'mt-28',
'mr-28',
'mb-28',
'ml-28',
'mt-32',
'mr-32',
'mb-32',
'ml-32',
'mt-36',
'mr-36',
'mb-36',
'ml-36',
'mt-40',
'mr-40',
'mb-40',
'ml-40',
'mt-48',
'mr-48',
'mb-48',
'ml-48',
'mt-56',
'mr-56',
'mb-56',
'ml-56',
'mt-60',
'mr-60',
'mb-60',
'ml-60',
'mt-64',
'mr-64',
'mb-64',
'ml-64',
'mt-72',
'mr-72',
'mb-72',
'ml-72',
'mt-80',
'mr-80',
'mb-80',
'ml-80',
'mt-96',
'mr-96',
'mb-96',
'ml-96',
'mt-auto',
'mr-auto',
'mb-auto',
'ml-auto',
'mt-px',
'mr-px',
'mb-px',
'ml-px',
'mt-05',
'mr-05',
'mb-05',
'ml-05',
'mt-25',
'mr-25',
'mb-25',
'ml-25',
'mt-35',
'mr-35',
'mb-35',
'ml-35',
'mt-1/2',
'mr-1/2',
'mb-1/2',
'ml-1/2',
'mt-1/3',
'mr-1/3',
'mb-1/3',
'ml-1/3',
'mt-2/3',
'mr-2/3',
'mb-2/3',
'ml-2/3',
'mt-1/4',
'mr-1/4',
'mb-1/4',
'ml-1/4',
'mt-2/4',
'mr-2/4',
'mb-2/4',
'ml-2/4',
'mt-3/4',
'mr-3/4',
'mb-3/4',
'ml-3/4',
'mt-1/5',
'mr-1/5',
'mb-1/5',
'ml-1/5',
'mt-2/5',
'mr-2/5',
'mb-2/5',
'ml-2/5',
'mt-3/5',
'mr-3/5',
'mb-3/5',
'ml-3/5',
'mt-4/5',
'mr-4/5',
'mb-4/5',
'ml-4/5',
'mt-1/6',
'mr-1/6',
'mb-1/6',
'ml-1/6',
'mt-2/6',
'mr-2/6',
'mb-2/6',
'ml-2/6',
'mt-3/6',
'mr-3/6',
'mb-3/6',
'ml-3/6',
'mt-4/6',
'mr-4/6',
'mb-4/6',
'ml-4/6',
'mt-5/6',
'mr-5/6',
'mb-5/6',
'ml-5/6',
'mt-1/12',
'mr-1/12',
'mb-1/12',
'ml-1/12',
'mt-2/12',
'mr-2/12',
'mb-2/12',
'ml-2/12',
'mt-3/12',
'mr-3/12',
'mb-3/12',
'ml-3/12',
'mt-4/12',
'mr-4/12',
'mb-4/12',
'ml-4/12',
'mt-5/12',
'mr-5/12',
'mb-5/12',
'ml-5/12',
'mt-6/12',
'mr-6/12',
'mb-6/12',
'ml-6/12',
'mt-7/12',
'mr-7/12',
'mb-7/12',
'ml-7/12',
'mt-8/12',
'mr-8/12',
'mb-8/12',
'ml-8/12',
'mt-9/12',
'mr-9/12',
'mb-9/12',
'ml-9/12',
'mt-10/12',
'mr-10/12',
'mb-10/12',
'ml-10/12',
'mt-11/12',
'mr-11/12',
'mb-11/12',
'ml-11/12',
'mt-full',
'mr-full',
'mb-full',
'ml-full',
'-mt-1',
'-mr-1',
'-mb-1',
'-ml-1',
'-mt-2',
'-mr-2',
'-mb-2',
'-ml-2',
'-mt-3',
'-mr-3',
'-mb-3',
'-ml-3',
'-mt-4',
'-mr-4',
'-mb-4',
'-ml-4',
'-mt-5',
'-mr-5',
'-mb-5',
'-ml-5',
'-mt-6',
'-mr-6',
'-mb-6',
'-ml-6',
'-mt-7',
'-mr-7',
'-mb-7',
'-ml-7',
'-mt-8',
'-mr-8',
'-mb-8',
'-ml-8',
'-mt-9',
'-mr-9',
'-mb-9',
'-ml-9',
'-mt-10',
'-mr-10',
'-mb-10',
'-ml-10',
'-mt-11',
'-mr-11',
'-mb-11',
'-ml-11',
'-mt-12',
'-mr-12',
'-mb-12',
'-ml-12',
'-mt-13',
'-mr-13',
'-mb-13',
'-ml-13',
'-mt-14',
'-mr-14',
'-mb-14',
'-ml-14',
'-mt-15',
'-mr-15',
'-mb-15',
'-ml-15',
'-mt-16',
'-mr-16',
'-mb-16',
'-ml-16',
'-mt-20',
'-mr-20',
'-mb-20',
'-ml-20',
'-mt-24',
'-mr-24',
'-mb-24',
'-ml-24',
'-mt-28',
'-mr-28',
'-mb-28',
'-ml-28',
'-mt-32',
'-mr-32',
'-mb-32',
'-ml-32',
'-mt-36',
'-mr-36',
'-mb-36',
'-ml-36',
'-mt-40',
'-mr-40',
'-mb-40',
'-ml-40',
'-mt-48',
'-mr-48',
'-mb-48',
'-ml-48',
'-mt-56',
'-mr-56',
'-mb-56',
'-ml-56',
'-mt-60',
'-mr-60',
'-mb-60',
'-ml-60',
'-mt-64',
'-mr-64',
'-mb-64',
'-ml-64',
'-mt-72',
'-mr-72',
'-mb-72',
'-ml-72',
'-mt-80',
'-mr-80',
'-mb-80',
'-ml-80',
'-mt-96',
'-mr-96',
'-mb-96',
'-ml-96',
'-mt-px',
'-mr-px',
'-mb-px',
'-ml-px',
'-mt-05',
'-mr-05',
'-mb-05',
'-ml-05',
'-mt-25',
'-mr-25',
'-mb-25',
'-ml-25',
'-mt-35',
'-mr-35',
'-mb-35',
'-ml-35',
'-mt-1/2',
'-mr-1/2',
'-mb-1/2',
'-ml-1/2',
'-mt-1/3',
'-mr-1/3',
'-mb-1/3',
'-ml-1/3',
'-mt-2/3',
'-mr-2/3',
'-mb-2/3',
'-ml-2/3',
'-mt-1/4',
'-mr-1/4',
'-mb-1/4',
'-ml-1/4',
'-mt-2/4',
'-mr-2/4',
'-mb-2/4',
'-ml-2/4',
'-mt-3/4',
'-mr-3/4',
'-mb-3/4',
'-ml-3/4',
'-mt-1/5',
'-mr-1/5',
'-mb-1/5',
'-ml-1/5',
'-mt-2/5',
'-mr-2/5',
'-mb-2/5',
'-ml-2/5',
'-mt-3/5',
'-mr-3/5',
'-mb-3/5',
'-ml-3/5',
'-mt-4/5',
'-mr-4/5',
'-mb-4/5',
'-ml-4/5',
'-mt-1/6',
'-mr-1/6',
'-mb-1/6',
'-ml-1/6',
'-mt-2/6',
'-mr-2/6',
'-mb-2/6',
'-ml-2/6',
'-mt-3/6',
'-mr-3/6',
'-mb-3/6',
'-ml-3/6',
'-mt-4/6',
'-mr-4/6',
'-mb-4/6',
'-ml-4/6',
'-mt-5/6',
'-mr-5/6',
'-mb-5/6',
'-ml-5/6',
'-mt-1/12',
'-mr-1/12',
'-mb-1/12',
'-ml-1/12',
'-mt-2/12',
'-mr-2/12',
'-mb-2/12',
'-ml-2/12',
'-mt-3/12',
'-mr-3/12',
'-mb-3/12',
'-ml-3/12',
'-mt-4/12',
'-mr-4/12',
'-mb-4/12',
'-ml-4/12',
'-mt-5/12',
'-mr-5/12',
'-mb-5/12',
'-ml-5/12',
'-mt-6/12',
'-mr-6/12',
'-mb-6/12',
'-ml-6/12',
'-mt-7/12',
'-mr-7/12',
'-mb-7/12',
'-ml-7/12',
'-mt-8/12',
'-mr-8/12',
'-mb-8/12',
'-ml-8/12',
'-mt-9/12',
'-mr-9/12',
'-mb-9/12',
'-ml-9/12',
'-mt-10/12',
'-mr-10/12',
'-mb-10/12',
'-ml-10/12',
'-mt-11/12',
'-mr-11/12',
'-mb-11/12',
'-ml-11/12',
'-mt-full',
'-mr-full',
'-mb-full',
'-ml-full',
'max-h-0',
'max-h-1',
'max-h-2',
'max-h-3',
'max-h-4',
'max-h-5',
'max-h-6',
'max-h-7',
'max-h-8',
'max-h-9',
'max-h-10',
'max-h-11',
'max-h-12',
'max-h-13',
'max-h-14',
'max-h-15',
'max-h-16',
'max-h-20',
'max-h-24',
'max-h-28',
'max-h-32',
'max-h-36',
'max-h-40',
'max-h-48',
'max-h-56',
'max-h-60',
'max-h-64',
'max-h-72',
'max-h-80',
'max-h-96',
'max-h-screen',
'max-h-px',
'max-h-05',
'max-h-25',
'max-h-35',
'max-h-1/2',
'max-h-1/3',
'max-h-2/3',
'max-h-1/4',
'max-h-2/4',
'max-h-3/4',
'max-h-1/5',
'max-h-2/5',
'max-h-3/5',
'max-h-4/5',
'max-h-1/6',
'max-h-2/6',
'max-h-3/6',
'max-h-4/6',
'max-h-5/6',
'max-h-1/12',
'max-h-2/12',
'max-h-3/12',
'max-h-4/12',
'max-h-5/12',
'max-h-6/12',
'max-h-7/12',
'max-h-8/12',
'max-h-9/12',
'max-h-10/12',
'max-h-11/12',
'max-h-full',
'max-w-none',
'max-w-xs',
'max-w-sm',
'max-w-md',
'max-w-lg',
'max-w-xl',
'max-w-2xl',
'max-w-3xl',
'max-w-4xl',
'max-w-5xl',
'max-w-6xl',
'max-w-7xl',
'max-w-full',
'max-w-screen-sm',
'max-w-screen-md',
'max-w-screen-lg',
'max-w-screen-xl',
'min-h-0',
'min-h-full',
'min-h-screen',
'min-w-0',
'min-w-full',
'object-contain',
'object-cover',
'object-fill',
'object-none',
'object-scale-down',
'object-bottom',
'object-center',
'object-left',
'object-left-bottom',
'object-left-top',
'object-right',
'object-right-bottom',
'object-right-top',
'object-top',
'opacity-0',
'opacity-25',
'opacity-50',
'opacity-75',
'opacity-100',
'hover:opacity-0:hover',
'hover:opacity-25:hover',
'hover:opacity-50:hover',
'hover:opacity-75:hover',
'hover:opacity-100:hover',
'focus:opacity-0',
'focus:opacity-25',
'focus:opacity-50',
'focus:opacity-75',
'focus:opacity-100',
'outline-none',
'focus:outline-none',
'overflow-auto',
'overflow-hidden',
'overflow-visible',
'overflow-scroll',
'overflow-x-auto',
'overflow-y-auto',
'overflow-x-hidden',
'overflow-y-hidden',
'overflow-x-visible',
'overflow-y-visible',
'overflow-x-scroll',
'overflow-y-scroll',
'scrolling-touch',
'scrolling-auto',
'p-0',
'p-1',
'p-2',
'p-3',
'p-4',
'p-5',
'p-6',
'p-7',
'p-8',
'p-9',
'p-10',
'p-11',
'p-12',
'p-13',
'p-14',
'p-15',
'p-16',
'p-20',
'p-24',
'p-28',
'p-32',
'p-36',
'p-40',
'p-48',
'p-56',
'p-60',
'p-64',
'p-72',
'p-80',
'p-96',
'p-px',
'p-05',
'p-25',
'p-35',
'p-1/2',
'p-1/3',
'p-2/3',
'p-1/4',
'p-2/4',
'p-3/4',
'p-1/5',
'p-2/5',
'p-3/5',
'p-4/5',
'p-1/6',
'p-2/6',
'p-3/6',
'p-4/6',
'p-5/6',
'p-1/12',
'p-2/12',
'p-3/12',
'p-4/12',
'p-5/12',
'p-6/12',
'p-7/12',
'p-8/12',
'p-9/12',
'p-10/12',
'p-11/12',
'p-full',
'py-0',
'px-0',
'py-1',
'px-1',
'py-2',
'px-2',
'py-3',
'px-3',
'py-4',
'px-4',
'py-5',
'px-5',
'py-6',
'px-6',
'py-7',
'px-7',
'py-8',
'px-8',
'py-9',
'px-9',
'py-10',
'px-10',
'py-11',
'px-11',
'py-12',
'px-12',
'py-13',
'px-13',
'py-14',
'px-14',
'py-15',
'px-15',
'py-16',
'px-16',
'py-20',
'px-20',
'py-24',
'px-24',
'py-28',
'px-28',
'py-32',
'px-32',
'py-36',
'px-36',
'py-40',
'px-40',
'py-48',
'px-48',
'py-56',
'px-56',
'py-60',
'px-60',
'py-64',
'px-64',
'py-72',
'px-72',
'py-80',
'px-80',
'py-96',
'px-96',
'py-px',
'px-px',
'py-05',
'px-05',
'py-25',
'px-25',
'py-35',
'px-35',
'py-1/2',
'px-1/2',
'py-1/3',
'px-1/3',
'py-2/3',
'px-2/3',
'py-1/4',
'px-1/4',
'py-2/4',
'px-2/4',
'py-3/4',
'px-3/4',
'py-1/5',
'px-1/5',
'py-2/5',
'px-2/5',
'py-3/5',
'px-3/5',
'py-4/5',
'px-4/5',
'py-1/6',
'px-1/6',
'py-2/6',
'px-2/6',
'py-3/6',
'px-3/6',
'py-4/6',
'px-4/6',
'py-5/6',
'px-5/6',
'py-1/12',
'px-1/12',
'py-2/12',
'px-2/12',
'py-3/12',
'px-3/12',
'py-4/12',
'px-4/12',
'py-5/12',
'px-5/12',
'py-6/12',
'px-6/12',
'py-7/12',
'px-7/12',
'py-8/12',
'px-8/12',
'py-9/12',
'px-9/12',
'py-10/12',
'px-10/12',
'py-11/12',
'px-11/12',
'py-full',
'px-full',
'pt-0',
'pr-0',
'pb-0',
'pl-0',
'pt-1',
'pr-1',
'pb-1',
'pl-1',
'pt-2',
'pr-2',
'pb-2',
'pl-2',
'pt-3',
'pr-3',
'pb-3',
'pl-3',
'pt-4',
'pr-4',
'pb-4',
'pl-4',
'pt-5',
'pr-5',
'pb-5',
'pl-5',
'pt-6',
'pr-6',
'pb-6',
'pl-6',
'pt-7',
'pr-7',
'pb-7',
'pl-7',
'pt-8',
'pr-8',
'pb-8',
'pl-8',
'pt-9',
'pr-9',
'pb-9',
'pl-9',
'pt-10',
'pr-10',
'pb-10',
'pl-10',
'pt-11',
'pr-11',
'pb-11',
'pl-11',
'pt-12',
'pr-12',
'pb-12',
'pl-12',
'pt-13',
'pr-13',
'pb-13',
'pl-13',
'pt-14',
'pr-14',
'pb-14',
'pl-14',
'pt-15',
'pr-15',
'pb-15',
'pl-15',
'pt-16',
'pr-16',
'pb-16',
'pl-16',
'pt-20',
'pr-20',
'pb-20',
'pl-20',
'pt-24',
'pr-24',
'pb-24',
'pl-24',
'pt-28',
'pr-28',
'pb-28',
'pl-28',
'pt-32',
'pr-32',
'pb-32',
'pl-32',
'pt-36',
'pr-36',
'pb-36',
'pl-36',
'pt-40',
'pr-40',
'pb-40',
'pl-40',
'pt-48',
'pr-48',
'pb-48',
'pl-48',
'pt-56',
'pr-56',
'pb-56',
'pl-56',
'pt-60',
'pr-60',
'pb-60',
'pl-60',
'pt-64',
'pr-64',
'pb-64',
'pl-64',
'pt-72',
'pr-72',
'pb-72',
'pl-72',
'pt-80',
'pr-80',
'pb-80',
'pl-80',
'pt-96',
'pr-96',
'pb-96',
'pl-96',
'pt-px',
'pr-px',
'pb-px',
'pl-px',
'pt-05',
'pr-05',
'pb-05',
'pl-05',
'pt-25',
'pr-25',
'pb-25',
'pl-25',
'pt-35',
'pr-35',
'pb-35',
'pl-35',
'pt-1/2',
'pr-1/2',
'pb-1/2',
'pl-1/2',
'pt-1/3',
'pr-1/3',
'pb-1/3',
'pl-1/3',
'pt-2/3',
'pr-2/3',
'pb-2/3',
'pl-2/3',
'pt-1/4',
'pr-1/4',
'pb-1/4',
'pl-1/4',
'pt-2/4',
'pr-2/4',
'pb-2/4',
'pl-2/4',
'pt-3/4',
'pr-3/4',
'pb-3/4',
'pl-3/4',
'pt-1/5',
'pr-1/5',
'pb-1/5',
'pl-1/5',
'pt-2/5',
'pr-2/5',
'pb-2/5',
'pl-2/5',
'pt-3/5',
'pr-3/5',
'pb-3/5',
'pl-3/5',
'pt-4/5',
'pr-4/5',
'pb-4/5',
'pl-4/5',
'pt-1/6',
'pr-1/6',
'pb-1/6',
'pl-1/6',
'pt-2/6',
'pr-2/6',
'pb-2/6',
'pl-2/6',
'pt-3/6',
'pr-3/6',
'pb-3/6',
'pl-3/6',
'pt-4/6',
'pr-4/6',
'pb-4/6',
'pl-4/6',
'pt-5/6',
'pr-5/6',
'pb-5/6',
'pl-5/6',
'pt-1/12',
'pr-1/12',
'pb-1/12',
'pl-1/12',
'pt-2/12',
'pr-2/12',
'pb-2/12',
'pl-2/12',
'pt-3/12',
'pr-3/12',
'pb-3/12',
'pl-3/12',
'pt-4/12',
'pr-4/12',
'pb-4/12',
'pl-4/12',
'pt-5/12',
'pr-5/12',
'pb-5/12',
'pl-5/12',
'pt-6/12',
'pr-6/12',
'pb-6/12',
'pl-6/12',
'pt-7/12',
'pr-7/12',
'pb-7/12',
'pl-7/12',
'pt-8/12',
'pr-8/12',
'pb-8/12',
'pl-8/12',
'pt-9/12',
'pr-9/12',
'pb-9/12',
'pl-9/12',
'pt-10/12',
'pr-10/12',
'pb-10/12',
'pl-10/12',
'pt-11/12',
'pr-11/12',
'pb-11/12',
'pl-11/12',
'pt-full',
'pr-full',
'pb-full',
'pl-full',
'placeholder-transparent',
'placeholder-white',
'placeholder-black',
'placeholder-gray-50',
'placeholder-gray-100',
'placeholder-gray-200',
'placeholder-gray-300',
'placeholder-gray-400',
'placeholder-gray-500',
'placeholder-gray-600',
'placeholder-gray-700',
'placeholder-gray-800',
'placeholder-gray-900',
'placeholder-cool-gray-50',
'placeholder-cool-gray-100',
'placeholder-cool-gray-200',
'placeholder-cool-gray-300',
'placeholder-cool-gray-400',
'placeholder-cool-gray-500',
'placeholder-cool-gray-600',
'placeholder-cool-gray-700',
'placeholder-cool-gray-800',
'placeholder-cool-gray-900',
'placeholder-red-50',
'placeholder-red-100',
'placeholder-red-200',
'placeholder-red-300',
'placeholder-red-400',
'placeholder-red-500',
'placeholder-red-600',
'placeholder-red-700',
'placeholder-red-800',
'placeholder-red-900',
'placeholder-orange-50',
'placeholder-orange-100',
'placeholder-orange-200',
'placeholder-orange-300',
'placeholder-orange-400',
'placeholder-orange-500',
'placeholder-orange-600',
'placeholder-orange-700',
'placeholder-orange-800',
'placeholder-orange-900',
'placeholder-yellow-50',
'placeholder-yellow-100',
'placeholder-yellow-200',
'placeholder-yellow-300',
'placeholder-yellow-400',
'placeholder-yellow-500',
'placeholder-yellow-600',
'placeholder-yellow-700',
'placeholder-yellow-800',
'placeholder-yellow-900',
'placeholder-green-50',
'placeholder-green-100',
'placeholder-green-200',
'placeholder-green-300',
'placeholder-green-400',
'placeholder-green-500',
'placeholder-green-600',
'placeholder-green-700',
'placeholder-green-800',
'placeholder-green-900',
'placeholder-teal-50',
'placeholder-teal-100',
'placeholder-teal-200',
'placeholder-teal-300',
'placeholder-teal-400',
'placeholder-teal-500',
'placeholder-teal-600',
'placeholder-teal-700',
'placeholder-teal-800',
'placeholder-teal-900',
'placeholder-blue-50',
'placeholder-blue-100',
'placeholder-blue-200',
'placeholder-blue-300',
'placeholder-blue-400',
'placeholder-blue-500',
'placeholder-blue-600',
'placeholder-blue-700',
'placeholder-blue-800',
'placeholder-blue-900',
'placeholder-indigo-50',
'placeholder-indigo-100',
'placeholder-indigo-200',
'placeholder-indigo-300',
'placeholder-indigo-400',
'placeholder-indigo-500',
'placeholder-indigo-600',
'placeholder-indigo-700',
'placeholder-indigo-800',
'placeholder-indigo-900',
'placeholder-purple-50',
'placeholder-purple-100',
'placeholder-purple-200',
'placeholder-purple-300',
'placeholder-purple-400',
'placeholder-purple-500',
'placeholder-purple-600',
'placeholder-purple-700',
'placeholder-purple-800',
'placeholder-purple-900',
'placeholder-pink-50',
'placeholder-pink-100',
'placeholder-pink-200',
'placeholder-pink-300',
'placeholder-pink-400',
'placeholder-pink-500',
'placeholder-pink-600',
'placeholder-pink-700',
'placeholder-pink-800',
'placeholder-pink-900',
'focus:placeholder-transparent',
'focus:placeholder-white',
'focus:placeholder-black',
'focus:placeholder-gray-50',
'focus:placeholder-gray-100',
'focus:placeholder-gray-200',
'focus:placeholder-gray-300',
'focus:placeholder-gray-400',
'focus:placeholder-gray-500',
'focus:placeholder-gray-600',
'focus:placeholder-gray-700',
'focus:placeholder-gray-800',
'focus:placeholder-gray-900',
'focus:placeholder-cool-gray-50',
'focus:placeholder-cool-gray-100',
'focus:placeholder-cool-gray-200',
'focus:placeholder-cool-gray-300',
'focus:placeholder-cool-gray-400',
'focus:placeholder-cool-gray-500',
'focus:placeholder-cool-gray-600',
'focus:placeholder-cool-gray-700',
'focus:placeholder-cool-gray-800',
'focus:placeholder-cool-gray-900',
'focus:placeholder-red-50',
'focus:placeholder-red-100',
'focus:placeholder-red-200',
'focus:placeholder-red-300',
'focus:placeholder-red-400',
'focus:placeholder-red-500',
'focus:placeholder-red-600',
'focus:placeholder-red-700',
'focus:placeholder-red-800',
'focus:placeholder-red-900',
'focus:placeholder-orange-50',
'focus:placeholder-orange-100',
'focus:placeholder-orange-200',
'focus:placeholder-orange-300',
'focus:placeholder-orange-400',
'focus:placeholder-orange-500',
'focus:placeholder-orange-600',
'focus:placeholder-orange-700',
'focus:placeholder-orange-800',
'focus:placeholder-orange-900',
'focus:placeholder-yellow-50',
'focus:placeholder-yellow-100',
'focus:placeholder-yellow-200',
'focus:placeholder-yellow-300',
'focus:placeholder-yellow-400',
'focus:placeholder-yellow-500',
'focus:placeholder-yellow-600',
'focus:placeholder-yellow-700',
'focus:placeholder-yellow-800',
'focus:placeholder-yellow-900',
'focus:placeholder-green-50',
'focus:placeholder-green-100',
'focus:placeholder-green-200',
'focus:placeholder-green-300',
'focus:placeholder-green-400',
'focus:placeholder-green-500',
'focus:placeholder-green-600',
'focus:placeholder-green-700',
'focus:placeholder-green-800',
'focus:placeholder-green-900',
'focus:placeholder-teal-50',
'focus:placeholder-teal-100',
'focus:placeholder-teal-200',
'focus:placeholder-teal-300',
'focus:placeholder-teal-400',
'focus:placeholder-teal-500',
'focus:placeholder-teal-600',
'focus:placeholder-teal-700',
'focus:placeholder-teal-800',
'focus:placeholder-teal-900',
'focus:placeholder-blue-50',
'focus:placeholder-blue-100',
'focus:placeholder-blue-200',
'focus:placeholder-blue-300',
'focus:placeholder-blue-400',
'focus:placeholder-blue-500',
'focus:placeholder-blue-600',
'focus:placeholder-blue-700',
'focus:placeholder-blue-800',
'focus:placeholder-blue-900',
'focus:placeholder-indigo-50',
'focus:placeholder-indigo-100',
'focus:placeholder-indigo-200',
'focus:placeholder-indigo-300',
'focus:placeholder-indigo-400',
'focus:placeholder-indigo-500',
'focus:placeholder-indigo-600',
'focus:placeholder-indigo-700',
'focus:placeholder-indigo-800',
'focus:placeholder-indigo-900',
'focus:placeholder-purple-50',
'focus:placeholder-purple-100',
'focus:placeholder-purple-200',
'focus:placeholder-purple-300',
'focus:placeholder-purple-400',
'focus:placeholder-purple-500',
'focus:placeholder-purple-600',
'focus:placeholder-purple-700',
'focus:placeholder-purple-800',
'focus:placeholder-purple-900',
'focus:placeholder-pink-50',
'focus:placeholder-pink-100',
'focus:placeholder-pink-200',
'focus:placeholder-pink-300',
'focus:placeholder-pink-400',
'focus:placeholder-pink-500',
'focus:placeholder-pink-600',
'focus:placeholder-pink-700',
'focus:placeholder-pink-800',
'focus:placeholder-pink-900',
'pointer-events-none',
'pointer-events-auto',
'static',
'fixed',
'absolute',
'relative',
'sticky',
'inset-0',
'inset-1',
'inset-2',
'inset-3',
'inset-4',
'inset-5',
'inset-6',
'inset-7',
'inset-8',
'inset-9',
'inset-10',
'inset-11',
'inset-12',
'inset-13',
'inset-14',
'inset-15',
'inset-16',
'inset-20',
'inset-24',
'inset-28',
'inset-32',
'inset-36',
'inset-40',
'inset-48',
'inset-56',
'inset-60',
'inset-64',
'inset-72',
'inset-80',
'inset-96',
'inset-auto',
'inset-px',
'inset-05',
'inset-25',
'inset-35',
'inset-1/2',
'inset-1/3',
'inset-2/3',
'inset-1/4',
'inset-2/4',
'inset-3/4',
'inset-1/5',
'inset-2/5',
'inset-3/5',
'inset-4/5',
'inset-1/6',
'inset-2/6',
'inset-3/6',
'inset-4/6',
'inset-5/6',
'inset-1/12',
'inset-2/12',
'inset-3/12',
'inset-4/12',
'inset-5/12',
'inset-6/12',
'inset-7/12',
'inset-8/12',
'inset-9/12',
'inset-10/12',
'inset-11/12',
'inset-full',
'inset-y-0',
'inset-x-0',
'inset-y-1',
'inset-x-1',
'inset-y-2',
'inset-x-2',
'inset-y-3',
'inset-x-3',
'inset-y-4',
'inset-x-4',
'inset-y-5',
'inset-x-5',
'inset-y-6',
'inset-x-6',
'inset-y-7',
'inset-x-7',
'inset-y-8',
'inset-x-8',
'inset-y-9',
'inset-x-9',
'inset-y-10',
'inset-x-10',
'inset-y-11',
'inset-x-11',
'inset-y-12',
'inset-x-12',
'inset-y-13',
'inset-x-13',
'inset-y-14',
'inset-x-14',
'inset-y-15',
'inset-x-15',
'inset-y-16',
'inset-x-16',
'inset-y-20',
'inset-x-20',
'inset-y-24',
'inset-x-24',
'inset-y-28',
'inset-x-28',
'inset-y-32',
'inset-x-32',
'inset-y-36',
'inset-x-36',
'inset-y-40',
'inset-x-40',
'inset-y-48',
'inset-x-48',
'inset-y-56',
'inset-x-56',
'inset-y-60',
'inset-x-60',
'inset-y-64',
'inset-x-64',
'inset-y-72',
'inset-x-72',
'inset-y-80',
'inset-x-80',
'inset-y-96',
'inset-x-96',
'inset-y-auto',
'inset-x-auto',
'inset-y-px',
'inset-x-px',
'inset-y-05',
'inset-x-05',
'inset-y-25',
'inset-x-25',
'inset-y-35',
'inset-x-35',
'inset-y-1/2',
'inset-x-1/2',
'inset-y-1/3',
'inset-x-1/3',
'inset-y-2/3',
'inset-x-2/3',
'inset-y-1/4',
'inset-x-1/4',
'inset-y-2/4',
'inset-x-2/4',
'inset-y-3/4',
'inset-x-3/4',
'inset-y-1/5',
'inset-x-1/5',
'inset-y-2/5',
'inset-x-2/5',
'inset-y-3/5',
'inset-x-3/5',
'inset-y-4/5',
'inset-x-4/5',
'inset-y-1/6',
'inset-x-1/6',
'inset-y-2/6',
'inset-x-2/6',
'inset-y-3/6',
'inset-x-3/6',
'inset-y-4/6',
'inset-x-4/6',
'inset-y-5/6',
'inset-x-5/6',
'inset-y-1/12',
'inset-x-1/12',
'inset-y-2/12',
'inset-x-2/12',
'inset-y-3/12',
'inset-x-3/12',
'inset-y-4/12',
'inset-x-4/12',
'inset-y-5/12',
'inset-x-5/12',
'inset-y-6/12',
'inset-x-6/12',
'inset-y-7/12',
'inset-x-7/12',
'inset-y-8/12',
'inset-x-8/12',
'inset-y-9/12',
'inset-x-9/12',
'inset-y-10/12',
'inset-x-10/12',
'inset-y-11/12',
'inset-x-11/12',
'inset-y-full',
'inset-x-full',
'top-0',
'right-0',
'bottom-0',
'left-0',
'top-1',
'right-1',
'bottom-1',
'left-1',
'top-2',
'right-2',
'bottom-2',
'left-2',
'top-3',
'right-3',
'bottom-3',
'left-3',
'top-4',
'right-4',
'bottom-4',
'left-4',
'top-5',
'right-5',
'bottom-5',
'left-5',
'top-6',
'right-6',
'bottom-6',
'left-6',
'top-7',
'right-7',
'bottom-7',
'left-7',
'top-8',
'right-8',
'bottom-8',
'left-8',
'top-9',
'right-9',
'bottom-9',
'left-9',
'top-10',
'right-10',
'bottom-10',
'left-10',
'top-11',
'right-11',
'bottom-11',
'left-11',
'top-12',
'right-12',
'bottom-12',
'left-12',
'top-13',
'right-13',
'bottom-13',
'left-13',
'top-14',
'right-14',
'bottom-14',
'left-14',
'top-15',
'right-15',
'bottom-15',
'left-15',
'top-16',
'right-16',
'bottom-16',
'left-16',
'top-20',
'right-20',
'bottom-20',
'left-20',
'top-24',
'right-24',
'bottom-24',
'left-24',
'top-28',
'right-28',
'bottom-28',
'left-28',
'top-32',
'right-32',
'bottom-32',
'left-32',
'top-36',
'right-36',
'bottom-36',
'left-36',
'top-40',
'right-40',
'bottom-40',
'left-40',
'top-48',
'right-48',
'bottom-48',
'left-48',
'top-56',
'right-56',
'bottom-56',
'left-56',
'top-60',
'right-60',
'bottom-60',
'left-60',
'top-64',
'right-64',
'bottom-64',
'left-64',
'top-72',
'right-72',
'bottom-72',
'left-72',
'top-80',
'right-80',
'bottom-80',
'left-80',
'top-96',
'right-96',
'bottom-96',
'left-96',
'top-auto',
'right-auto',
'bottom-auto',
'left-auto',
'top-px',
'right-px',
'bottom-px',
'left-px',
'top-05',
'right-05',
'bottom-05',
'left-05',
'top-25',
'right-25',
'bottom-25',
'left-25',
'top-35',
'right-35',
'bottom-35',
'left-35',
'top-1/2',
'right-1/2',
'bottom-1/2',
'left-1/2',
'top-1/3',
'right-1/3',
'bottom-1/3',
'left-1/3',
'top-2/3',
'right-2/3',
'bottom-2/3',
'left-2/3',
'top-1/4',
'right-1/4',
'bottom-1/4',
'left-1/4',
'top-2/4',
'right-2/4',
'bottom-2/4',
'left-2/4',
'top-3/4',
'right-3/4',
'bottom-3/4',
'left-3/4',
'top-1/5',
'right-1/5',
'bottom-1/5',
'left-1/5',
'top-2/5',
'right-2/5',
'bottom-2/5',
'left-2/5',
'top-3/5',
'right-3/5',
'bottom-3/5',
'left-3/5',
'top-4/5',
'right-4/5',
'bottom-4/5',
'left-4/5',
'top-1/6',
'right-1/6',
'bottom-1/6',
'left-1/6',
'top-2/6',
'right-2/6',
'bottom-2/6',
'left-2/6',
'top-3/6',
'right-3/6',
'bottom-3/6',
'left-3/6',
'top-4/6',
'right-4/6',
'bottom-4/6',
'left-4/6',
'top-5/6',
'right-5/6',
'bottom-5/6',
'left-5/6',
'top-1/12',
'right-1/12',
'bottom-1/12',
'left-1/12',
'top-2/12',
'right-2/12',
'bottom-2/12',
'left-2/12',
'top-3/12',
'right-3/12',
'bottom-3/12',
'left-3/12',
'top-4/12',
'right-4/12',
'bottom-4/12',
'left-4/12',
'top-5/12',
'right-5/12',
'bottom-5/12',
'left-5/12',
'top-6/12',
'right-6/12',
'bottom-6/12',
'left-6/12',
'top-7/12',
'right-7/12',
'bottom-7/12',
'left-7/12',
'top-8/12',
'right-8/12',
'bottom-8/12',
'left-8/12',
'top-9/12',
'right-9/12',
'bottom-9/12',
'left-9/12',
'top-10/12',
'right-10/12',
'bottom-10/12',
'left-10/12',
'top-11/12',
'right-11/12',
'bottom-11/12',
'left-11/12',
'top-full',
'right-full',
'bottom-full',
'left-full',
'resize-none',
'resize-y',
'resize-x',
'resize',
'shadow-xs',
'shadow-sm',
'shadow',
'shadow-md',
'shadow-lg',
'shadow-xl',
'shadow-2xl',
'shadow-inner',
'shadow-outline',
'shadow-none',
'shadow-solid',
'shadow-outline-gray',
'shadow-outline-blue',
'shadow-outline-teal',
'shadow-outline-green',
'shadow-outline-yellow',
'shadow-outline-orange',
'shadow-outline-red',
'shadow-outline-pink',
'shadow-outline-purple',
'shadow-outline-indigo',
'hover:shadow-xs:hover',
'hover:shadow-sm:hover',
'hover:shadow:hover',
'hover:shadow-md:hover',
'hover:shadow-lg:hover',
'hover:shadow-xl:hover',
'hover:shadow-2xl:hover',
'hover:shadow-inner:hover',
'hover:shadow-outline:hover',
'hover:shadow-none:hover',
'hover:shadow-solid:hover',
'hover:shadow-outline-gray:hover',
'hover:shadow-outline-blue:hover',
'hover:shadow-outline-teal:hover',
'hover:shadow-outline-green:hover',
'hover:shadow-outline-yellow:hover',
'hover:shadow-outline-orange:hover',
'hover:shadow-outline-red:hover',
'hover:shadow-outline-pink:hover',
'hover:shadow-outline-purple:hover',
'hover:shadow-outline-indigo:hover',
'focus:shadow-xs',
'focus:shadow-sm',
'focus:shadow',
'focus:shadow-md',
'focus:shadow-lg',
'focus:shadow-xl',
'focus:shadow-2xl',
'focus:shadow-inner',
'focus:shadow-outline',
'focus:shadow-none',
'focus:shadow-solid',
'focus:shadow-outline-gray',
'focus:shadow-outline-blue',
'focus:shadow-outline-teal',
'focus:shadow-outline-green',
'focus:shadow-outline-yellow',
'focus:shadow-outline-orange',
'focus:shadow-outline-red',
'focus:shadow-outline-pink',
'focus:shadow-outline-purple',
'focus:shadow-outline-indigo',
'fill-current',
'stroke-current',
'stroke-0',
'stroke-1',
'stroke-2',
'table-auto',
'table-fixed',
'text-left',
'text-center',
'text-right',
'text-justify',
'text-transparent',
'text-white',
'text-black',
'text-gray-50',
'text-gray-100',
'text-gray-200',
'text-gray-300',
'text-gray-400',
'text-gray-500',
'text-gray-600',
'text-gray-700',
'text-gray-800',
'text-gray-900',
'text-cool-gray-50',
'text-cool-gray-100',
'text-cool-gray-200',
'text-cool-gray-300',
'text-cool-gray-400',
'text-cool-gray-500',
'text-cool-gray-600',
'text-cool-gray-700',
'text-cool-gray-800',
'text-cool-gray-900',
'text-red-50',
'text-red-100',
'text-red-200',
'text-red-300',
'text-red-400',
'text-red-500',
'text-red-600',
'text-red-700',
'text-red-800',
'text-red-900',
'text-orange-50',
'text-orange-100',
'text-orange-200',
'text-orange-300',
'text-orange-400',
'text-orange-500',
'text-orange-600',
'text-orange-700',
'text-orange-800',
'text-orange-900',
'text-yellow-50',
'text-yellow-100',
'text-yellow-200',
'text-yellow-300',
'text-yellow-400',
'text-yellow-500',
'text-yellow-600',
'text-yellow-700',
'text-yellow-800',
'text-yellow-900',
'text-green-50',
'text-green-100',
'text-green-200',
'text-green-300',
'text-green-400',
'text-green-500',
'text-green-600',
'text-green-700',
'text-green-800',
'text-green-900',
'text-teal-50',
'text-teal-100',
'text-teal-200',
'text-teal-300',
'text-teal-400',
'text-teal-500',
'text-teal-600',
'text-teal-700',
'text-teal-800',
'text-teal-900',
'text-blue-50',
'text-blue-100',
'text-blue-200',
'text-blue-300',
'text-blue-400',
'text-blue-500',
'text-blue-600',
'text-blue-700',
'text-blue-800',
'text-blue-900',
'text-indigo-50',
'text-indigo-100',
'text-indigo-200',
'text-indigo-300',
'text-indigo-400',
'text-indigo-500',
'text-indigo-600',
'text-indigo-700',
'text-indigo-800',
'text-indigo-900',
'text-purple-50',
'text-purple-100',
'text-purple-200',
'text-purple-300',
'text-purple-400',
'text-purple-500',
'text-purple-600',
'text-purple-700',
'text-purple-800',
'text-purple-900',
'text-pink-50',
'text-pink-100',
'text-pink-200',
'text-pink-300',
'text-pink-400',
'text-pink-500',
'text-pink-600',
'text-pink-700',
'text-pink-800',
'text-pink-900',
'hover:text-transparent:hover',
'hover:text-white:hover',
'hover:text-black:hover',
'hover:text-gray-50:hover',
'hover:text-gray-100:hover',
'hover:text-gray-200:hover',
'hover:text-gray-300:hover',
'hover:text-gray-400:hover',
'hover:text-gray-500:hover',
'hover:text-gray-600:hover',
'hover:text-gray-700:hover',
'hover:text-gray-800:hover',
'hover:text-gray-900:hover',
'hover:text-cool-gray-50:hover',
'hover:text-cool-gray-100:hover',
'hover:text-cool-gray-200:hover',
'hover:text-cool-gray-300:hover',
'hover:text-cool-gray-400:hover',
'hover:text-cool-gray-500:hover',
'hover:text-cool-gray-600:hover',
'hover:text-cool-gray-700:hover',
'hover:text-cool-gray-800:hover',
'hover:text-cool-gray-900:hover',
'hover:text-red-50:hover',
'hover:text-red-100:hover',
'hover:text-red-200:hover',
'hover:text-red-300:hover',
'hover:text-red-400:hover',
'hover:text-red-500:hover',
'hover:text-red-600:hover',
'hover:text-red-700:hover',
'hover:text-red-800:hover',
'hover:text-red-900:hover',
'hover:text-orange-50:hover',
'hover:text-orange-100:hover',
'hover:text-orange-200:hover',
'hover:text-orange-300:hover',
'hover:text-orange-400:hover',
'hover:text-orange-500:hover',
'hover:text-orange-600:hover',
'hover:text-orange-700:hover',
'hover:text-orange-800:hover',
'hover:text-orange-900:hover',
'hover:text-yellow-50:hover',
'hover:text-yellow-100:hover',
'hover:text-yellow-200:hover',
'hover:text-yellow-300:hover',
'hover:text-yellow-400:hover',
'hover:text-yellow-500:hover',
'hover:text-yellow-600:hover',
'hover:text-yellow-700:hover',
'hover:text-yellow-800:hover',
'hover:text-yellow-900:hover',
'hover:text-green-50:hover',
'hover:text-green-100:hover',
'hover:text-green-200:hover',
'hover:text-green-300:hover',
'hover:text-green-400:hover',
'hover:text-green-500:hover',
'hover:text-green-600:hover',
'hover:text-green-700:hover',
'hover:text-green-800:hover',
'hover:text-green-900:hover',
'hover:text-teal-50:hover',
'hover:text-teal-100:hover',
'hover:text-teal-200:hover',
'hover:text-teal-300:hover',
'hover:text-teal-400:hover',
'hover:text-teal-500:hover',
'hover:text-teal-600:hover',
'hover:text-teal-700:hover',
'hover:text-teal-800:hover',
'hover:text-teal-900:hover',
'hover:text-blue-50:hover',
'hover:text-blue-100:hover',
'hover:text-blue-200:hover',
'hover:text-blue-300:hover',
'hover:text-blue-400:hover',
'hover:text-blue-500:hover',
'hover:text-blue-600:hover',
'hover:text-blue-700:hover',
'hover:text-blue-800:hover',
'hover:text-blue-900:hover',
'hover:text-indigo-50:hover',
'hover:text-indigo-100:hover',
'hover:text-indigo-200:hover',
'hover:text-indigo-300:hover',
'hover:text-indigo-400:hover',
'hover:text-indigo-500:hover',
'hover:text-indigo-600:hover',
'hover:text-indigo-700:hover',
'hover:text-indigo-800:hover',
'hover:text-indigo-900:hover',
'hover:text-purple-50:hover',
'hover:text-purple-100:hover',
'hover:text-purple-200:hover',
'hover:text-purple-300:hover',
'hover:text-purple-400:hover',
'hover:text-purple-500:hover',
'hover:text-purple-600:hover',
'hover:text-purple-700:hover',
'hover:text-purple-800:hover',
'hover:text-purple-900:hover',
'hover:text-pink-50:hover',
'hover:text-pink-100:hover',
'hover:text-pink-200:hover',
'hover:text-pink-300:hover',
'hover:text-pink-400:hover',
'hover:text-pink-500:hover',
'hover:text-pink-600:hover',
'hover:text-pink-700:hover',
'hover:text-pink-800:hover',
'hover:text-pink-900:hover',
'focus-within:text-transparent',
'focus-within:text-white',
'focus-within:text-black',
'focus-within:text-gray-50',
'focus-within:text-gray-100',
'focus-within:text-gray-200',
'focus-within:text-gray-300',
'focus-within:text-gray-400',
'focus-within:text-gray-500',
'focus-within:text-gray-600',
'focus-within:text-gray-700',
'focus-within:text-gray-800',
'focus-within:text-gray-900',
'focus-within:text-cool-gray-50',
'focus-within:text-cool-gray-100',
'focus-within:text-cool-gray-200',
'focus-within:text-cool-gray-300',
'focus-within:text-cool-gray-400',
'focus-within:text-cool-gray-500',
'focus-within:text-cool-gray-600',
'focus-within:text-cool-gray-700',
'focus-within:text-cool-gray-800',
'focus-within:text-cool-gray-900',
'focus-within:text-red-50',
'focus-within:text-red-100',
'focus-within:text-red-200',
'focus-within:text-red-300',
'focus-within:text-red-400',
'focus-within:text-red-500',
'focus-within:text-red-600',
'focus-within:text-red-700',
'focus-within:text-red-800',
'focus-within:text-red-900',
'focus-within:text-orange-50',
'focus-within:text-orange-100',
'focus-within:text-orange-200',
'focus-within:text-orange-300',
'focus-within:text-orange-400',
'focus-within:text-orange-500',
'focus-within:text-orange-600',
'focus-within:text-orange-700',
'focus-within:text-orange-800',
'focus-within:text-orange-900',
'focus-within:text-yellow-50',
'focus-within:text-yellow-100',
'focus-within:text-yellow-200',
'focus-within:text-yellow-300',
'focus-within:text-yellow-400',
'focus-within:text-yellow-500',
'focus-within:text-yellow-600',
'focus-within:text-yellow-700',
'focus-within:text-yellow-800',
'focus-within:text-yellow-900',
'focus-within:text-green-50',
'focus-within:text-green-100',
'focus-within:text-green-200',
'focus-within:text-green-300',
'focus-within:text-green-400',
'focus-within:text-green-500',
'focus-within:text-green-600',
'focus-within:text-green-700',
'focus-within:text-green-800',
'focus-within:text-green-900',
'focus-within:text-teal-50',
'focus-within:text-teal-100',
'focus-within:text-teal-200',
'focus-within:text-teal-300',
'focus-within:text-teal-400',
'focus-within:text-teal-500',
'focus-within:text-teal-600',
'focus-within:text-teal-700',
'focus-within:text-teal-800',
'focus-within:text-teal-900',
'focus-within:text-blue-50',
'focus-within:text-blue-100',
'focus-within:text-blue-200',
'focus-within:text-blue-300',
'focus-within:text-blue-400',
'focus-within:text-blue-500',
'focus-within:text-blue-600',
'focus-within:text-blue-700',
'focus-within:text-blue-800',
'focus-within:text-blue-900',
'focus-within:text-indigo-50',
'focus-within:text-indigo-100',
'focus-within:text-indigo-200',
'focus-within:text-indigo-300',
'focus-within:text-indigo-400',
'focus-within:text-indigo-500',
'focus-within:text-indigo-600',
'focus-within:text-indigo-700',
'focus-within:text-indigo-800',
'focus-within:text-indigo-900',
'focus-within:text-purple-50',
'focus-within:text-purple-100',
'focus-within:text-purple-200',
'focus-within:text-purple-300',
'focus-within:text-purple-400',
'focus-within:text-purple-500',
'focus-within:text-purple-600',
'focus-within:text-purple-700',
'focus-within:text-purple-800',
'focus-within:text-purple-900',
'focus-within:text-pink-50',
'focus-within:text-pink-100',
'focus-within:text-pink-200',
'focus-within:text-pink-300',
'focus-within:text-pink-400',
'focus-within:text-pink-500',
'focus-within:text-pink-600',
'focus-within:text-pink-700',
'focus-within:text-pink-800',
'focus-within:text-pink-900',
'focus:text-transparent',
'focus:text-white',
'focus:text-black',
'focus:text-gray-50',
'focus:text-gray-100',
'focus:text-gray-200',
'focus:text-gray-300',
'focus:text-gray-400',
'focus:text-gray-500',
'focus:text-gray-600',
'focus:text-gray-700',
'focus:text-gray-800',
'focus:text-gray-900',
'focus:text-cool-gray-50',
'focus:text-cool-gray-100',
'focus:text-cool-gray-200',
'focus:text-cool-gray-300',
'focus:text-cool-gray-400',
'focus:text-cool-gray-500',
'focus:text-cool-gray-600',
'focus:text-cool-gray-700',
'focus:text-cool-gray-800',
'focus:text-cool-gray-900',
'focus:text-red-50',
'focus:text-red-100',
'focus:text-red-200',
'focus:text-red-300',
'focus:text-red-400',
'focus:text-red-500',
'focus:text-red-600',
'focus:text-red-700',
'focus:text-red-800',
'focus:text-red-900',
'focus:text-orange-50',
'focus:text-orange-100',
'focus:text-orange-200',
'focus:text-orange-300',
'focus:text-orange-400',
'focus:text-orange-500',
'focus:text-orange-600',
'focus:text-orange-700',
'focus:text-orange-800',
'focus:text-orange-900',
'focus:text-yellow-50',
'focus:text-yellow-100',
'focus:text-yellow-200',
'focus:text-yellow-300',
'focus:text-yellow-400',
'focus:text-yellow-500',
'focus:text-yellow-600',
'focus:text-yellow-700',
'focus:text-yellow-800',
'focus:text-yellow-900',
'focus:text-green-50',
'focus:text-green-100',
'focus:text-green-200',
'focus:text-green-300',
'focus:text-green-400',
'focus:text-green-500',
'focus:text-green-600',
'focus:text-green-700',
'focus:text-green-800',
'focus:text-green-900',
'focus:text-teal-50',
'focus:text-teal-100',
'focus:text-teal-200',
'focus:text-teal-300',
'focus:text-teal-400',
'focus:text-teal-500',
'focus:text-teal-600',
'focus:text-teal-700',
'focus:text-teal-800',
'focus:text-teal-900',
'focus:text-blue-50',
'focus:text-blue-100',
'focus:text-blue-200',
'focus:text-blue-300',
'focus:text-blue-400',
'focus:text-blue-500',
'focus:text-blue-600',
'focus:text-blue-700',
'focus:text-blue-800',
'focus:text-blue-900',
'focus:text-indigo-50',
'focus:text-indigo-100',
'focus:text-indigo-200',
'focus:text-indigo-300',
'focus:text-indigo-400',
'focus:text-indigo-500',
'focus:text-indigo-600',
'focus:text-indigo-700',
'focus:text-indigo-800',
'focus:text-indigo-900',
'focus:text-purple-50',
'focus:text-purple-100',
'focus:text-purple-200',
'focus:text-purple-300',
'focus:text-purple-400',
'focus:text-purple-500',
'focus:text-purple-600',
'focus:text-purple-700',
'focus:text-purple-800',
'focus:text-purple-900',
'focus:text-pink-50',
'focus:text-pink-100',
'focus:text-pink-200',
'focus:text-pink-300',
'focus:text-pink-400',
'focus:text-pink-500',
'focus:text-pink-600',
'focus:text-pink-700',
'focus:text-pink-800',
'focus:text-pink-900',
'active:text-transparent:active',
'active:text-white:active',
'active:text-black:active',
'active:text-gray-50:active',
'active:text-gray-100:active',
'active:text-gray-200:active',
'active:text-gray-300:active',
'active:text-gray-400:active',
'active:text-gray-500:active',
'active:text-gray-600:active',
'active:text-gray-700:active',
'active:text-gray-800:active',
'active:text-gray-900:active',
'active:text-cool-gray-50:active',
'active:text-cool-gray-100:active',
'active:text-cool-gray-200:active',
'active:text-cool-gray-300:active',
'active:text-cool-gray-400:active',
'active:text-cool-gray-500:active',
'active:text-cool-gray-600:active',
'active:text-cool-gray-700:active',
'active:text-cool-gray-800:active',
'active:text-cool-gray-900:active',
'active:text-red-50:active',
'active:text-red-100:active',
'active:text-red-200:active',
'active:text-red-300:active',
'active:text-red-400:active',
'active:text-red-500:active',
'active:text-red-600:active',
'active:text-red-700:active',
'active:text-red-800:active',
'active:text-red-900:active',
'active:text-orange-50:active',
'active:text-orange-100:active',
'active:text-orange-200:active',
'active:text-orange-300:active',
'active:text-orange-400:active',
'active:text-orange-500:active',
'active:text-orange-600:active',
'active:text-orange-700:active',
'active:text-orange-800:active',
'active:text-orange-900:active',
'active:text-yellow-50:active',
'active:text-yellow-100:active',
'active:text-yellow-200:active',
'active:text-yellow-300:active',
'active:text-yellow-400:active',
'active:text-yellow-500:active',
'active:text-yellow-600:active',
'active:text-yellow-700:active',
'active:text-yellow-800:active',
'active:text-yellow-900:active',
'active:text-green-50:active',
'active:text-green-100:active',
'active:text-green-200:active',
'active:text-green-300:active',
'active:text-green-400:active',
'active:text-green-500:active',
'active:text-green-600:active',
'active:text-green-700:active',
'active:text-green-800:active',
'active:text-green-900:active',
'active:text-teal-50:active',
'active:text-teal-100:active',
'active:text-teal-200:active',
'active:text-teal-300:active',
'active:text-teal-400:active',
'active:text-teal-500:active',
'active:text-teal-600:active',
'active:text-teal-700:active',
'active:text-teal-800:active',
'active:text-teal-900:active',
'active:text-blue-50:active',
'active:text-blue-100:active',
'active:text-blue-200:active',
'active:text-blue-300:active',
'active:text-blue-400:active',
'active:text-blue-500:active',
'active:text-blue-600:active',
'active:text-blue-700:active',
'active:text-blue-800:active',
'active:text-blue-900:active',
'active:text-indigo-50:active',
'active:text-indigo-100:active',
'active:text-indigo-200:active',
'active:text-indigo-300:active',
'active:text-indigo-400:active',
'active:text-indigo-500:active',
'active:text-indigo-600:active',
'active:text-indigo-700:active',
'active:text-indigo-800:active',
'active:text-indigo-900:active',
'active:text-purple-50:active',
'active:text-purple-100:active',
'active:text-purple-200:active',
'active:text-purple-300:active',
'active:text-purple-400:active',
'active:text-purple-500:active',
'active:text-purple-600:active',
'active:text-purple-700:active',
'active:text-purple-800:active',
'active:text-purple-900:active',
'active:text-pink-50:active',
'active:text-pink-100:active',
'active:text-pink-200:active',
'active:text-pink-300:active',
'active:text-pink-400:active',
'active:text-pink-500:active',
'active:text-pink-600:active',
'active:text-pink-700:active',
'active:text-pink-800:active',
'active:text-pink-900:active',
'text-xs',
'text-sm',
'text-base',
'text-lg',
'text-xl',
'text-2xl',
'text-3xl',
'text-4xl',
'text-5xl',
'text-6xl',
'italic',
'not-italic',
'uppercase',
'lowercase',
'capitalize',
'normal-case',
'underline',
'line-through',
'no-underline',
'hover:underline:hover',
'hover:line-through:hover',
'hover:no-underline:hover',
'focus:underline',
'focus:line-through',
'focus:no-underline',
'antialiased',
'subpixel-antialiased',
'tracking-tighter',
'tracking-tight',
'tracking-normal',
'tracking-wide',
'tracking-wider',
'tracking-widest',
'select-none',
'select-text',
'select-all',
'select-auto',
'align-baseline',
'align-top',
'align-middle',
'align-bottom',
'align-text-top',
'align-text-bottom',
'visible',
'invisible',
'whitespace-normal',
'whitespace-no-wrap',
'whitespace-pre',
'whitespace-pre-line',
'whitespace-pre-wrap',
'break-normal',
'break-words',
'break-all',
'truncate',
'w-0',
'w-1',
'w-2',
'w-3',
'w-4',
'w-5',
'w-6',
'w-7',
'w-8',
'w-9',
'w-10',
'w-11',
'w-12',
'w-13',
'w-14',
'w-15',
'w-16',
'w-20',
'w-24',
'w-28',
'w-32',
'w-36',
'w-40',
'w-48',
'w-56',
'w-60',
'w-64',
'w-72',
'w-80',
'w-96',
'w-auto',
'w-px',
'w-05',
'w-25',
'w-35',
'w-1/2',
'w-1/3',
'w-2/3',
'w-1/4',
'w-2/4',
'w-3/4',
'w-1/5',
'w-2/5',
'w-3/5',
'w-4/5',
'w-1/6',
'w-2/6',
'w-3/6',
'w-4/6',
'w-5/6',
'w-1/12',
'w-2/12',
'w-3/12',
'w-4/12',
'w-5/12',
'w-6/12',
'w-7/12',
'w-8/12',
'w-9/12',
'w-10/12',
'w-11/12',
'w-full',
'w-screen',
'z-0',
'z-10',
'z-20',
'z-30',
'z-40',
'z-50',
'z-auto',
'focus-within:z-0',
'focus-within:z-10',
'focus-within:z-20',
'focus-within:z-30',
'focus-within:z-40',
'focus-within:z-50',
'focus-within:z-auto',
'focus:z-0',
'focus:z-10',
'focus:z-20',
'focus:z-30',
'focus:z-40',
'focus:z-50',
'focus:z-auto',
'gap-0',
'gap-1',
'gap-2',
'gap-3',
'gap-4',
'gap-5',
'gap-6',
'gap-7',
'gap-8',
'gap-9',
'gap-10',
'gap-11',
'gap-12',
'gap-13',
'gap-14',
'gap-15',
'gap-16',
'gap-20',
'gap-24',
'gap-28',
'gap-32',
'gap-36',
'gap-40',
'gap-48',
'gap-56',
'gap-60',
'gap-64',
'gap-72',
'gap-80',
'gap-96',
'gap-px',
'gap-05',
'gap-25',
'gap-35',
'gap-1/2',
'gap-1/3',
'gap-2/3',
'gap-1/4',
'gap-2/4',
'gap-3/4',
'gap-1/5',
'gap-2/5',
'gap-3/5',
'gap-4/5',
'gap-1/6',
'gap-2/6',
'gap-3/6',
'gap-4/6',
'gap-5/6',
'gap-1/12',
'gap-2/12',
'gap-3/12',
'gap-4/12',
'gap-5/12',
'gap-6/12',
'gap-7/12',
'gap-8/12',
'gap-9/12',
'gap-10/12',
'gap-11/12',
'gap-full',
'col-gap-0',
'col-gap-1',
'col-gap-2',
'col-gap-3',
'col-gap-4',
'col-gap-5',
'col-gap-6',
'col-gap-7',
'col-gap-8',
'col-gap-9',
'col-gap-10',
'col-gap-11',
'col-gap-12',
'col-gap-13',
'col-gap-14',
'col-gap-15',
'col-gap-16',
'col-gap-20',
'col-gap-24',
'col-gap-28',
'col-gap-32',
'col-gap-36',
'col-gap-40',
'col-gap-48',
'col-gap-56',
'col-gap-60',
'col-gap-64',
'col-gap-72',
'col-gap-80',
'col-gap-96',
'col-gap-px',
'col-gap-05',
'col-gap-25',
'col-gap-35',
'col-gap-1/2',
'col-gap-1/3',
'col-gap-2/3',
'col-gap-1/4',
'col-gap-2/4',
'col-gap-3/4',
'col-gap-1/5',
'col-gap-2/5',
'col-gap-3/5',
'col-gap-4/5',
'col-gap-1/6',
'col-gap-2/6',
'col-gap-3/6',
'col-gap-4/6',
'col-gap-5/6',
'col-gap-1/12',
'col-gap-2/12',
'col-gap-3/12',
'col-gap-4/12',
'col-gap-5/12',
'col-gap-6/12',
'col-gap-7/12',
'col-gap-8/12',
'col-gap-9/12',
'col-gap-10/12',
'col-gap-11/12',
'col-gap-full',
'row-gap-0',
'row-gap-1',
'row-gap-2',
'row-gap-3',
'row-gap-4',
'row-gap-5',
'row-gap-6',
'row-gap-7',
'row-gap-8',
'row-gap-9',
'row-gap-10',
'row-gap-11',
'row-gap-12',
'row-gap-13',
'row-gap-14',
'row-gap-15',
'row-gap-16',
'row-gap-20',
'row-gap-24',
'row-gap-28',
'row-gap-32',
'row-gap-36',
'row-gap-40',
'row-gap-48',
'row-gap-56',
'row-gap-60',
'row-gap-64',
'row-gap-72',
'row-gap-80',
'row-gap-96',
'row-gap-px',
'row-gap-05',
'row-gap-25',
'row-gap-35',
'row-gap-1/2',
'row-gap-1/3',
'row-gap-2/3',
'row-gap-1/4',
'row-gap-2/4',
'row-gap-3/4',
'row-gap-1/5',
'row-gap-2/5',
'row-gap-3/5',
'row-gap-4/5',
'row-gap-1/6',
'row-gap-2/6',
'row-gap-3/6',
'row-gap-4/6',
'row-gap-5/6',
'row-gap-1/12',
'row-gap-2/12',
'row-gap-3/12',
'row-gap-4/12',
'row-gap-5/12',
'row-gap-6/12',
'row-gap-7/12',
'row-gap-8/12',
'row-gap-9/12',
'row-gap-10/12',
'row-gap-11/12',
'row-gap-full',
'grid-flow-row',
'grid-flow-col',
'grid-flow-row-dense',
'grid-flow-col-dense',
'grid-cols-1',
'grid-cols-2',
'grid-cols-3',
'grid-cols-4',
'grid-cols-5',
'grid-cols-6',
'grid-cols-7',
'grid-cols-8',
'grid-cols-9',
'grid-cols-10',
'grid-cols-11',
'grid-cols-12',
'grid-cols-none',
'col-auto',
'col-span-1',
'col-span-2',
'col-span-3',
'col-span-4',
'col-span-5',
'col-span-6',
'col-span-7',
'col-span-8',
'col-span-9',
'col-span-10',
'col-span-11',
'col-span-12',
'col-start-1',
'col-start-2',
'col-start-3',
'col-start-4',
'col-start-5',
'col-start-6',
'col-start-7',
'col-start-8',
'col-start-9',
'col-start-10',
'col-start-11',
'col-start-12',
'col-start-13',
'col-start-auto',
'col-end-1',
'col-end-2',
'col-end-3',
'col-end-4',
'col-end-5',
'col-end-6',
'col-end-7',
'col-end-8',
'col-end-9',
'col-end-10',
'col-end-11',
'col-end-12',
'col-end-13',
'col-end-auto',
'grid-rows-1',
'grid-rows-2',
'grid-rows-3',
'grid-rows-4',
'grid-rows-5',
'grid-rows-6',
'grid-rows-none',
'row-auto',
'row-span-1',
'row-span-2',
'row-span-3',
'row-span-4',
'row-span-5',
'row-span-6',
'row-start-1',
'row-start-2',
'row-start-3',
'row-start-4',
'row-start-5',
'row-start-6',
'row-start-7',
'row-start-auto',
'row-end-1',
'row-end-2',
'row-end-3',
'row-end-4',
'row-end-5',
'row-end-6',
'row-end-7',
'row-end-auto',
'transform',
'transform-none',
'origin-center',
'origin-top',
'origin-top-right',
'origin-right',
'origin-bottom-right',
'origin-bottom',
'origin-bottom-left',
'origin-left',
'origin-top-left',
'scale-0',
'scale-50',
'scale-75',
'scale-90',
'scale-95',
'scale-100',
'scale-105',
'scale-110',
'scale-125',
'scale-150',
'scale-x-0',
'scale-x-50',
'scale-x-75',
'scale-x-90',
'scale-x-95',
'scale-x-100',
'scale-x-105',
'scale-x-110',
'scale-x-125',
'scale-x-150',
'scale-y-0',
'scale-y-50',
'scale-y-75',
'scale-y-90',
'scale-y-95',
'scale-y-100',
'scale-y-105',
'scale-y-110',
'scale-y-125',
'scale-y-150',
'hover:scale-0:hover',
'hover:scale-50:hover',
'hover:scale-75:hover',
'hover:scale-90:hover',
'hover:scale-95:hover',
'hover:scale-100:hover',
'hover:scale-105:hover',
'hover:scale-110:hover',
'hover:scale-125:hover',
'hover:scale-150:hover',
'hover:scale-x-0:hover',
'hover:scale-x-50:hover',
'hover:scale-x-75:hover',
'hover:scale-x-90:hover',
'hover:scale-x-95:hover',
'hover:scale-x-100:hover',
'hover:scale-x-105:hover',
'hover:scale-x-110:hover',
'hover:scale-x-125:hover',
'hover:scale-x-150:hover',
'hover:scale-y-0:hover',
'hover:scale-y-50:hover',
'hover:scale-y-75:hover',
'hover:scale-y-90:hover',
'hover:scale-y-95:hover',
'hover:scale-y-100:hover',
'hover:scale-y-105:hover',
'hover:scale-y-110:hover',
'hover:scale-y-125:hover',
'hover:scale-y-150:hover',
'focus:scale-0',
'focus:scale-50',
'focus:scale-75',
'focus:scale-90',
'focus:scale-95',
'focus:scale-100',
'focus:scale-105',
'focus:scale-110',
'focus:scale-125',
'focus:scale-150',
'focus:scale-x-0',
'focus:scale-x-50',
'focus:scale-x-75',
'focus:scale-x-90',
'focus:scale-x-95',
'focus:scale-x-100',
'focus:scale-x-105',
'focus:scale-x-110',
'focus:scale-x-125',
'focus:scale-x-150',
'focus:scale-y-0',
'focus:scale-y-50',
'focus:scale-y-75',
'focus:scale-y-90',
'focus:scale-y-95',
'focus:scale-y-100',
'focus:scale-y-105',
'focus:scale-y-110',
'focus:scale-y-125',
'focus:scale-y-150',
'rotate-0',
'rotate-45',
'rotate-90',
'rotate-180',
'-rotate-180',
'-rotate-90',
'-rotate-45',
'hover:rotate-0:hover',
'hover:rotate-45:hover',
'hover:rotate-90:hover',
'hover:rotate-180:hover',
'hover:-rotate-180:hover',
'hover:-rotate-90:hover',
'hover:-rotate-45:hover',
'focus:rotate-0',
'focus:rotate-45',
'focus:rotate-90',
'focus:rotate-180',
'focus:-rotate-180',
'focus:-rotate-90',
'focus:-rotate-45',
'translate-x-0',
'translate-x-1',
'translate-x-2',
'translate-x-3',
'translate-x-4',
'translate-x-5',
'translate-x-6',
'translate-x-7',
'translate-x-8',
'translate-x-9',
'translate-x-10',
'translate-x-11',
'translate-x-12',
'translate-x-13',
'translate-x-14',
'translate-x-15',
'translate-x-16',
'translate-x-20',
'translate-x-24',
'translate-x-28',
'translate-x-32',
'translate-x-36',
'translate-x-40',
'translate-x-48',
'translate-x-56',
'translate-x-60',
'translate-x-64',
'translate-x-72',
'translate-x-80',
'translate-x-96',
'translate-x-px',
'translate-x-05',
'translate-x-25',
'translate-x-35',
'translate-x-1/2',
'translate-x-1/3',
'translate-x-2/3',
'translate-x-1/4',
'translate-x-2/4',
'translate-x-3/4',
'translate-x-1/5',
'translate-x-2/5',
'translate-x-3/5',
'translate-x-4/5',
'translate-x-1/6',
'translate-x-2/6',
'translate-x-3/6',
'translate-x-4/6',
'translate-x-5/6',
'translate-x-1/12',
'translate-x-2/12',
'translate-x-3/12',
'translate-x-4/12',
'translate-x-5/12',
'translate-x-6/12',
'translate-x-7/12',
'translate-x-8/12',
'translate-x-9/12',
'translate-x-10/12',
'translate-x-11/12',
'translate-x-full',
'-translate-x-1',
'-translate-x-2',
'-translate-x-3',
'-translate-x-4',
'-translate-x-5',
'-translate-x-6',
'-translate-x-7',
'-translate-x-8',
'-translate-x-9',
'-translate-x-10',
'-translate-x-11',
'-translate-x-12',
'-translate-x-13',
'-translate-x-14',
'-translate-x-15',
'-translate-x-16',
'-translate-x-20',
'-translate-x-24',
'-translate-x-28',
'-translate-x-32',
'-translate-x-36',
'-translate-x-40',
'-translate-x-48',
'-translate-x-56',
'-translate-x-60',
'-translate-x-64',
'-translate-x-72',
'-translate-x-80',
'-translate-x-96',
'-translate-x-px',
'-translate-x-05',
'-translate-x-25',
'-translate-x-35',
'-translate-x-1/2',
'-translate-x-1/3',
'-translate-x-2/3',
'-translate-x-1/4',
'-translate-x-2/4',
'-translate-x-3/4',
'-translate-x-1/5',
'-translate-x-2/5',
'-translate-x-3/5',
'-translate-x-4/5',
'-translate-x-1/6',
'-translate-x-2/6',
'-translate-x-3/6',
'-translate-x-4/6',
'-translate-x-5/6',
'-translate-x-1/12',
'-translate-x-2/12',
'-translate-x-3/12',
'-translate-x-4/12',
'-translate-x-5/12',
'-translate-x-6/12',
'-translate-x-7/12',
'-translate-x-8/12',
'-translate-x-9/12',
'-translate-x-10/12',
'-translate-x-11/12',
'-translate-x-full',
'translate-y-0',
'translate-y-1',
'translate-y-2',
'translate-y-3',
'translate-y-4',
'translate-y-5',
'translate-y-6',
'translate-y-7',
'translate-y-8',
'translate-y-9',
'translate-y-10',
'translate-y-11',
'translate-y-12',
'translate-y-13',
'translate-y-14',
'translate-y-15',
'translate-y-16',
'translate-y-20',
'translate-y-24',
'translate-y-28',
'translate-y-32',
'translate-y-36',
'translate-y-40',
'translate-y-48',
'translate-y-56',
'translate-y-60',
'translate-y-64',
'translate-y-72',
'translate-y-80',
'translate-y-96',
'translate-y-px',
'translate-y-05',
'translate-y-25',
'translate-y-35',
'translate-y-1/2',
'translate-y-1/3',
'translate-y-2/3',
'translate-y-1/4',
'translate-y-2/4',
'translate-y-3/4',
'translate-y-1/5',
'translate-y-2/5',
'translate-y-3/5',
'translate-y-4/5',
'translate-y-1/6',
'translate-y-2/6',
'translate-y-3/6',
'translate-y-4/6',
'translate-y-5/6',
'translate-y-1/12',
'translate-y-2/12',
'translate-y-3/12',
'translate-y-4/12',
'translate-y-5/12',
'translate-y-6/12',
'translate-y-7/12',
'translate-y-8/12',
'translate-y-9/12',
'translate-y-10/12',
'translate-y-11/12',
'translate-y-full',
'-translate-y-1',
'-translate-y-2',
'-translate-y-3',
'-translate-y-4',
'-translate-y-5',
'-translate-y-6',
'-translate-y-7',
'-translate-y-8',
'-translate-y-9',
'-translate-y-10',
'-translate-y-11',
'-translate-y-12',
'-translate-y-13',
'-translate-y-14',
'-translate-y-15',
'-translate-y-16',
'-translate-y-20',
'-translate-y-24',
'-translate-y-28',
'-translate-y-32',
'-translate-y-36',
'-translate-y-40',
'-translate-y-48',
'-translate-y-56',
'-translate-y-60',
'-translate-y-64',
'-translate-y-72',
'-translate-y-80',
'-translate-y-96',
'-translate-y-px',
'-translate-y-05',
'-translate-y-25',
'-translate-y-35',
'-translate-y-1/2',
'-translate-y-1/3',
'-translate-y-2/3',
'-translate-y-1/4',
'-translate-y-2/4',
'-translate-y-3/4',
'-translate-y-1/5',
'-translate-y-2/5',
'-translate-y-3/5',
'-translate-y-4/5',
'-translate-y-1/6',
'-translate-y-2/6',
'-translate-y-3/6',
'-translate-y-4/6',
'-translate-y-5/6',
'-translate-y-1/12',
'-translate-y-2/12',
'-translate-y-3/12',
'-translate-y-4/12',
'-translate-y-5/12',
'-translate-y-6/12',
'-translate-y-7/12',
'-translate-y-8/12',
'-translate-y-9/12',
'-translate-y-10/12',
'-translate-y-11/12',
'-translate-y-full',
'hover:translate-x-0:hover',
'hover:translate-x-1:hover',
'hover:translate-x-2:hover',
'hover:translate-x-3:hover',
'hover:translate-x-4:hover',
'hover:translate-x-5:hover',
'hover:translate-x-6:hover',
'hover:translate-x-7:hover',
'hover:translate-x-8:hover',
'hover:translate-x-9:hover',
'hover:translate-x-10:hover',
'hover:translate-x-11:hover',
'hover:translate-x-12:hover',
'hover:translate-x-13:hover',
'hover:translate-x-14:hover',
'hover:translate-x-15:hover',
'hover:translate-x-16:hover',
'hover:translate-x-20:hover',
'hover:translate-x-24:hover',
'hover:translate-x-28:hover',
'hover:translate-x-32:hover',
'hover:translate-x-36:hover',
'hover:translate-x-40:hover',
'hover:translate-x-48:hover',
'hover:translate-x-56:hover',
'hover:translate-x-60:hover',
'hover:translate-x-64:hover',
'hover:translate-x-72:hover',
'hover:translate-x-80:hover',
'hover:translate-x-96:hover',
'hover:translate-x-px:hover',
'hover:translate-x-05:hover',
'hover:translate-x-25:hover',
'hover:translate-x-35:hover',
'hover:translate-x-1/2:hover',
'hover:translate-x-1/3:hover',
'hover:translate-x-2/3:hover',
'hover:translate-x-1/4:hover',
'hover:translate-x-2/4:hover',
'hover:translate-x-3/4:hover',
'hover:translate-x-1/5:hover',
'hover:translate-x-2/5:hover',
'hover:translate-x-3/5:hover',
'hover:translate-x-4/5:hover',
'hover:translate-x-1/6:hover',
'hover:translate-x-2/6:hover',
'hover:translate-x-3/6:hover',
'hover:translate-x-4/6:hover',
'hover:translate-x-5/6:hover',
'hover:translate-x-1/12:hover',
'hover:translate-x-2/12:hover',
'hover:translate-x-3/12:hover',
'hover:translate-x-4/12:hover',
'hover:translate-x-5/12:hover',
'hover:translate-x-6/12:hover',
'hover:translate-x-7/12:hover',
'hover:translate-x-8/12:hover',
'hover:translate-x-9/12:hover',
'hover:translate-x-10/12:hover',
'hover:translate-x-11/12:hover',
'hover:translate-x-full:hover',
'hover:-translate-x-1:hover',
'hover:-translate-x-2:hover',
'hover:-translate-x-3:hover',
'hover:-translate-x-4:hover',
'hover:-translate-x-5:hover',
'hover:-translate-x-6:hover',
'hover:-translate-x-7:hover',
'hover:-translate-x-8:hover',
'hover:-translate-x-9:hover',
'hover:-translate-x-10:hover',
'hover:-translate-x-11:hover',
'hover:-translate-x-12:hover',
'hover:-translate-x-13:hover',
'hover:-translate-x-14:hover',
'hover:-translate-x-15:hover',
'hover:-translate-x-16:hover',
'hover:-translate-x-20:hover',
'hover:-translate-x-24:hover',
'hover:-translate-x-28:hover',
'hover:-translate-x-32:hover',
'hover:-translate-x-36:hover',
'hover:-translate-x-40:hover',
'hover:-translate-x-48:hover',
'hover:-translate-x-56:hover',
'hover:-translate-x-60:hover',
'hover:-translate-x-64:hover',
'hover:-translate-x-72:hover',
'hover:-translate-x-80:hover',
'hover:-translate-x-96:hover',
'hover:-translate-x-px:hover',
'hover:-translate-x-05:hover',
'hover:-translate-x-25:hover',
'hover:-translate-x-35:hover',
'hover:-translate-x-1/2:hover',
'hover:-translate-x-1/3:hover',
'hover:-translate-x-2/3:hover',
'hover:-translate-x-1/4:hover',
'hover:-translate-x-2/4:hover',
'hover:-translate-x-3/4:hover',
'hover:-translate-x-1/5:hover',
'hover:-translate-x-2/5:hover',
'hover:-translate-x-3/5:hover',
'hover:-translate-x-4/5:hover',
'hover:-translate-x-1/6:hover',
'hover:-translate-x-2/6:hover',
'hover:-translate-x-3/6:hover',
'hover:-translate-x-4/6:hover',
'hover:-translate-x-5/6:hover',
'hover:-translate-x-1/12:hover',
'hover:-translate-x-2/12:hover',
'hover:-translate-x-3/12:hover',
'hover:-translate-x-4/12:hover',
'hover:-translate-x-5/12:hover',
'hover:-translate-x-6/12:hover',
'hover:-translate-x-7/12:hover',
'hover:-translate-x-8/12:hover',
'hover:-translate-x-9/12:hover',
'hover:-translate-x-10/12:hover',
'hover:-translate-x-11/12:hover',
'hover:-translate-x-full:hover',
'hover:translate-y-0:hover',
'hover:translate-y-1:hover',
'hover:translate-y-2:hover',
'hover:translate-y-3:hover',
'hover:translate-y-4:hover',
'hover:translate-y-5:hover',
'hover:translate-y-6:hover',
'hover:translate-y-7:hover',
'hover:translate-y-8:hover',
'hover:translate-y-9:hover',
'hover:translate-y-10:hover',
'hover:translate-y-11:hover',
'hover:translate-y-12:hover',
'hover:translate-y-13:hover',
'hover:translate-y-14:hover',
'hover:translate-y-15:hover',
'hover:translate-y-16:hover',
'hover:translate-y-20:hover',
'hover:translate-y-24:hover',
'hover:translate-y-28:hover',
'hover:translate-y-32:hover',
'hover:translate-y-36:hover',
'hover:translate-y-40:hover',
'hover:translate-y-48:hover',
'hover:translate-y-56:hover',
'hover:translate-y-60:hover',
'hover:translate-y-64:hover',
'hover:translate-y-72:hover',
'hover:translate-y-80:hover',
'hover:translate-y-96:hover',
'hover:translate-y-px:hover',
'hover:translate-y-05:hover',
'hover:translate-y-25:hover',
'hover:translate-y-35:hover',
'hover:translate-y-1/2:hover',
'hover:translate-y-1/3:hover',
'hover:translate-y-2/3:hover',
'hover:translate-y-1/4:hover',
'hover:translate-y-2/4:hover',
'hover:translate-y-3/4:hover',
'hover:translate-y-1/5:hover',
'hover:translate-y-2/5:hover',
'hover:translate-y-3/5:hover',
'hover:translate-y-4/5:hover',
'hover:translate-y-1/6:hover',
'hover:translate-y-2/6:hover',
'hover:translate-y-3/6:hover',
'hover:translate-y-4/6:hover',
'hover:translate-y-5/6:hover',
'hover:translate-y-1/12:hover',
'hover:translate-y-2/12:hover',
'hover:translate-y-3/12:hover',
'hover:translate-y-4/12:hover',
'hover:translate-y-5/12:hover',
'hover:translate-y-6/12:hover',
'hover:translate-y-7/12:hover',
'hover:translate-y-8/12:hover',
'hover:translate-y-9/12:hover',
'hover:translate-y-10/12:hover',
'hover:translate-y-11/12:hover',
'hover:translate-y-full:hover',
'hover:-translate-y-1:hover',
'hover:-translate-y-2:hover',
'hover:-translate-y-3:hover',
'hover:-translate-y-4:hover',
'hover:-translate-y-5:hover',
'hover:-translate-y-6:hover',
'hover:-translate-y-7:hover',
'hover:-translate-y-8:hover',
'hover:-translate-y-9:hover',
'hover:-translate-y-10:hover',
'hover:-translate-y-11:hover',
'hover:-translate-y-12:hover',
'hover:-translate-y-13:hover',
'hover:-translate-y-14:hover',
'hover:-translate-y-15:hover',
'hover:-translate-y-16:hover',
'hover:-translate-y-20:hover',
'hover:-translate-y-24:hover',
'hover:-translate-y-28:hover',
'hover:-translate-y-32:hover',
'hover:-translate-y-36:hover',
'hover:-translate-y-40:hover',
'hover:-translate-y-48:hover',
'hover:-translate-y-56:hover',
'hover:-translate-y-60:hover',
'hover:-translate-y-64:hover',
'hover:-translate-y-72:hover',
'hover:-translate-y-80:hover',
'hover:-translate-y-96:hover',
'hover:-translate-y-px:hover',
'hover:-translate-y-05:hover',
'hover:-translate-y-25:hover',
'hover:-translate-y-35:hover',
'hover:-translate-y-1/2:hover',
'hover:-translate-y-1/3:hover',
'hover:-translate-y-2/3:hover',
'hover:-translate-y-1/4:hover',
'hover:-translate-y-2/4:hover',
'hover:-translate-y-3/4:hover',
'hover:-translate-y-1/5:hover',
'hover:-translate-y-2/5:hover',
'hover:-translate-y-3/5:hover',
'hover:-translate-y-4/5:hover',
'hover:-translate-y-1/6:hover',
'hover:-translate-y-2/6:hover',
'hover:-translate-y-3/6:hover',
'hover:-translate-y-4/6:hover',
'hover:-translate-y-5/6:hover',
'hover:-translate-y-1/12:hover',
'hover:-translate-y-2/12:hover',
'hover:-translate-y-3/12:hover',
'hover:-translate-y-4/12:hover',
'hover:-translate-y-5/12:hover',
'hover:-translate-y-6/12:hover',
'hover:-translate-y-7/12:hover',
'hover:-translate-y-8/12:hover',
'hover:-translate-y-9/12:hover',
'hover:-translate-y-10/12:hover',
'hover:-translate-y-11/12:hover',
'hover:-translate-y-full:hover',
'focus:translate-x-0',
'focus:translate-x-1',
'focus:translate-x-2',
'focus:translate-x-3',
'focus:translate-x-4',
'focus:translate-x-5',
'focus:translate-x-6',
'focus:translate-x-7',
'focus:translate-x-8',
'focus:translate-x-9',
'focus:translate-x-10',
'focus:translate-x-11',
'focus:translate-x-12',
'focus:translate-x-13',
'focus:translate-x-14',
'focus:translate-x-15',
'focus:translate-x-16',
'focus:translate-x-20',
'focus:translate-x-24',
'focus:translate-x-28',
'focus:translate-x-32',
'focus:translate-x-36',
'focus:translate-x-40',
'focus:translate-x-48',
'focus:translate-x-56',
'focus:translate-x-60',
'focus:translate-x-64',
'focus:translate-x-72',
'focus:translate-x-80',
'focus:translate-x-96',
'focus:translate-x-px',
'focus:translate-x-05',
'focus:translate-x-25',
'focus:translate-x-35',
'focus:translate-x-1/2',
'focus:translate-x-1/3',
'focus:translate-x-2/3',
'focus:translate-x-1/4',
'focus:translate-x-2/4',
'focus:translate-x-3/4',
'focus:translate-x-1/5',
'focus:translate-x-2/5',
'focus:translate-x-3/5',
'focus:translate-x-4/5',
'focus:translate-x-1/6',
'focus:translate-x-2/6',
'focus:translate-x-3/6',
'focus:translate-x-4/6',
'focus:translate-x-5/6',
'focus:translate-x-1/12',
'focus:translate-x-2/12',
'focus:translate-x-3/12',
'focus:translate-x-4/12',
'focus:translate-x-5/12',
'focus:translate-x-6/12',
'focus:translate-x-7/12',
'focus:translate-x-8/12',
'focus:translate-x-9/12',
'focus:translate-x-10/12',
'focus:translate-x-11/12',
'focus:translate-x-full',
'focus:-translate-x-1',
'focus:-translate-x-2',
'focus:-translate-x-3',
'focus:-translate-x-4',
'focus:-translate-x-5',
'focus:-translate-x-6',
'focus:-translate-x-7',
'focus:-translate-x-8',
'focus:-translate-x-9',
'focus:-translate-x-10',
'focus:-translate-x-11',
'focus:-translate-x-12',
'focus:-translate-x-13',
'focus:-translate-x-14',
'focus:-translate-x-15',
'focus:-translate-x-16',
'focus:-translate-x-20',
'focus:-translate-x-24',
'focus:-translate-x-28',
'focus:-translate-x-32',
'focus:-translate-x-36',
'focus:-translate-x-40',
'focus:-translate-x-48',
'focus:-translate-x-56',
'focus:-translate-x-60',
'focus:-translate-x-64',
'focus:-translate-x-72',
'focus:-translate-x-80',
'focus:-translate-x-96',
'focus:-translate-x-px',
'focus:-translate-x-05',
'focus:-translate-x-25',
'focus:-translate-x-35',
'focus:-translate-x-1/2',
'focus:-translate-x-1/3',
'focus:-translate-x-2/3',
'focus:-translate-x-1/4',
'focus:-translate-x-2/4',
'focus:-translate-x-3/4',
'focus:-translate-x-1/5',
'focus:-translate-x-2/5',
'focus:-translate-x-3/5',
'focus:-translate-x-4/5',
'focus:-translate-x-1/6',
'focus:-translate-x-2/6',
'focus:-translate-x-3/6',
'focus:-translate-x-4/6',
'focus:-translate-x-5/6',
'focus:-translate-x-1/12',
'focus:-translate-x-2/12',
'focus:-translate-x-3/12',
'focus:-translate-x-4/12',
'focus:-translate-x-5/12',
'focus:-translate-x-6/12',
'focus:-translate-x-7/12',
'focus:-translate-x-8/12',
'focus:-translate-x-9/12',
'focus:-translate-x-10/12',
'focus:-translate-x-11/12',
'focus:-translate-x-full',
'focus:translate-y-0',
'focus:translate-y-1',
'focus:translate-y-2',
'focus:translate-y-3',
'focus:translate-y-4',
'focus:translate-y-5',
'focus:translate-y-6',
'focus:translate-y-7',
'focus:translate-y-8',
'focus:translate-y-9',
'focus:translate-y-10',
'focus:translate-y-11',
'focus:translate-y-12',
'focus:translate-y-13',
'focus:translate-y-14',
'focus:translate-y-15',
'focus:translate-y-16',
'focus:translate-y-20',
'focus:translate-y-24',
'focus:translate-y-28',
'focus:translate-y-32',
'focus:translate-y-36',
'focus:translate-y-40',
'focus:translate-y-48',
'focus:translate-y-56',
'focus:translate-y-60',
'focus:translate-y-64',
'focus:translate-y-72',
'focus:translate-y-80',
'focus:translate-y-96',
'focus:translate-y-px',
'focus:translate-y-05',
'focus:translate-y-25',
'focus:translate-y-35',
'focus:translate-y-1/2',
'focus:translate-y-1/3',
'focus:translate-y-2/3',
'focus:translate-y-1/4',
'focus:translate-y-2/4',
'focus:translate-y-3/4',
'focus:translate-y-1/5',
'focus:translate-y-2/5',
'focus:translate-y-3/5',
'focus:translate-y-4/5',
'focus:translate-y-1/6',
'focus:translate-y-2/6',
'focus:translate-y-3/6',
'focus:translate-y-4/6',
'focus:translate-y-5/6',
'focus:translate-y-1/12',
'focus:translate-y-2/12',
'focus:translate-y-3/12',
'focus:translate-y-4/12',
'focus:translate-y-5/12',
'focus:translate-y-6/12',
'focus:translate-y-7/12',
'focus:translate-y-8/12',
'focus:translate-y-9/12',
'focus:translate-y-10/12',
'focus:translate-y-11/12',
'focus:translate-y-full',
'focus:-translate-y-1',
'focus:-translate-y-2',
'focus:-translate-y-3',
'focus:-translate-y-4',
'focus:-translate-y-5',
'focus:-translate-y-6',
'focus:-translate-y-7',
'focus:-translate-y-8',
'focus:-translate-y-9',
'focus:-translate-y-10',
'focus:-translate-y-11',
'focus:-translate-y-12',
'focus:-translate-y-13',
'focus:-translate-y-14',
'focus:-translate-y-15',
'focus:-translate-y-16',
'focus:-translate-y-20',
'focus:-translate-y-24',
'focus:-translate-y-28',
'focus:-translate-y-32',
'focus:-translate-y-36',
'focus:-translate-y-40',
'focus:-translate-y-48',
'focus:-translate-y-56',
'focus:-translate-y-60',
'focus:-translate-y-64',
'focus:-translate-y-72',
'focus:-translate-y-80',
'focus:-translate-y-96',
'focus:-translate-y-px',
'focus:-translate-y-05',
'focus:-translate-y-25',
'focus:-translate-y-35',
'focus:-translate-y-1/2',
'focus:-translate-y-1/3',
'focus:-translate-y-2/3',
'focus:-translate-y-1/4',
'focus:-translate-y-2/4',
'focus:-translate-y-3/4',
'focus:-translate-y-1/5',
'focus:-translate-y-2/5',
'focus:-translate-y-3/5',
'focus:-translate-y-4/5',
'focus:-translate-y-1/6',
'focus:-translate-y-2/6',
'focus:-translate-y-3/6',
'focus:-translate-y-4/6',
'focus:-translate-y-5/6',
'focus:-translate-y-1/12',
'focus:-translate-y-2/12',
'focus:-translate-y-3/12',
'focus:-translate-y-4/12',
'focus:-translate-y-5/12',
'focus:-translate-y-6/12',
'focus:-translate-y-7/12',
'focus:-translate-y-8/12',
'focus:-translate-y-9/12',
'focus:-translate-y-10/12',
'focus:-translate-y-11/12',
'focus:-translate-y-full',
'skew-x-0',
'skew-x-3',
'skew-x-6',
'skew-x-12',
'-skew-x-12',
'-skew-x-6',
'-skew-x-3',
'skew-y-0',
'skew-y-3',
'skew-y-6',
'skew-y-12',
'-skew-y-12',
'-skew-y-6',
'-skew-y-3',
'hover:skew-x-0:hover',
'hover:skew-x-3:hover',
'hover:skew-x-6:hover',
'hover:skew-x-12:hover',
'hover:-skew-x-12:hover',
'hover:-skew-x-6:hover',
'hover:-skew-x-3:hover',
'hover:skew-y-0:hover',
'hover:skew-y-3:hover',
'hover:skew-y-6:hover',
'hover:skew-y-12:hover',
'hover:-skew-y-12:hover',
'hover:-skew-y-6:hover',
'hover:-skew-y-3:hover',
'focus:skew-x-0',
'focus:skew-x-3',
'focus:skew-x-6',
'focus:skew-x-12',
'focus:-skew-x-12',
'focus:-skew-x-6',
'focus:-skew-x-3',
'focus:skew-y-0',
'focus:skew-y-3',
'focus:skew-y-6',
'focus:skew-y-12',
'focus:-skew-y-12',
'focus:-skew-y-6',
'focus:-skew-y-3',
'transition-none',
'transition-all',
'transition',
'transition-colors',
'transition-opacity',
'transition-shadow',
'transition-transform',
'ease-linear',
'ease-in',
'ease-out',
'ease-in-out',
'duration-75',
'duration-100',
'duration-150',
'duration-200',
'duration-300',
'duration-500',
'duration-700',
'duration-1000',
],
}
| f467f1c044801730104a3cea64b2e1ac4136a168 | [
"JavaScript"
] | 1 | JavaScript | vesper8/tailwindui-crawler | 39bdfe0b46f4c427f1b98e1d2079223f3955593d | abb07abe91bdcce6f38ae4d8161a732b12ee9331 |
HEAD | <repo_name>rqmok/android_device_huawei_u8800<file_sep>/scripts/scripts.mk
# Use this script to copy other scripts to the product out directory
LOCAL_PATH := device/huawei/u8800/scripts
PRODUCT_COPY_FILES += \
$(LOCAL_PATH)/20uncapfps:system/etc/init.d/20uncapfps \
<file_sep>/device_u8800.mk
LOCAL_PATH := device/huawei/u8800
# Correct bootanimation size for the screen
TARGET_BOOTANIMATION_NAME := vertical-480x800
# The gps config appropriate for this device
$(call inherit-product, device/common/gps/gps_us_supl.mk)
# Use standard dalvik heap sizes
$(call inherit-product, frameworks/native/build/phone-hdpi-512-dalvik-heap.mk)
# Vendor Makefile (if exists)
$(call inherit-product-if-exists, vendor/huawei/u8800/u8800-vendor.mk)
# Call Gapps makefile (if exists)
$(call inherit-product-if-exists, device/huawei/u8800/gapps/Gapps.mk)
# Call Script MakeFile (if exists)
$(call inherit-product-if-exists, device/huawei/u8800/scripts/scripts.mk)
# Call prebuilt script (if exists)
$(call inherit-product-if-exists, device/huawei/u8800/prebuilt/prebuilt.mk)
DEVICE_PACKAGE_OVERLAYS += device/huawei/u8800/overlay
PRODUCT_AAPT_CONFIG := normal hdpi
PRODUCT_AAPT_PREF_CONFIG := hdpi
# Live Wallpapers
PRODUCT_PACKAGES += \
LiveWallpapers \
LiveWallpapersPicker \
VisualizationWallpapers \
librs_jni
# Video
PRODUCT_PACKAGES += \
libOmxCore \
libOmxVdec \
libOmxVenc \
libmm-omxcore \
libdivxdrmdecrypt \
libstagefrighthw
# Graphics
PRODUCT_PACKAGES += \
gralloc.msm7x30 \
copybit.msm7x30 \
hwcomposer.msm7x30 \
libmemalloc \
liboverlay \
libQcomUI \
libtilerenderer \
libI420colorconvert \
libc2dcolorconvert
# Audio
PRODUCT_PACKAGES += \
audio.primary.msm7x30 \
audio_policy.msm7x30 \
audio.a2dp.default \
libaudioutils
# Lights
PRODUCT_PACKAGES += \
lights.msm7x30
# GPS
PRODUCT_PACKAGES += \
gps.msm7x30
# Wifi
PRODUCT_PACKAGES += \
lib_driver_cmd_wext \
libreadmac
# Apps
PRODUCT_PACKAGES += \
Torch \
# Other
PRODUCT_PACKAGES += \
camera.msm7x30 \
power.msm7x30 \
dexpreopt
# Filesystem management tools
PRODUCT_PACKAGES += \
make_ext4fs \
setup_fs
# Misc
PRODUCT_PACKAGES += \
com.android.future.usb.accessory
# we have enough storage space to hold precise GC data
PRODUCT_TAGS += dalvik.gc.type-precise
# Hardware-specific features
PRODUCT_COPY_FILES += \
frameworks/native/data/etc/android.hardware.wifi.xml:system/etc/permissions/android.hardware.wifi.xml \
frameworks/native/data/etc/android.hardware.camera.autofocus.xml:system/etc/permissions/android.hardware.camera.autofocus.xml \
frameworks/native/data/etc/android.hardware.camera.flash-autofocus.xml:system/etc/permissions/android.hardware.camera.flash-autofocus.xml \
frameworks/native/data/etc/android.hardware.location.gps.xml:system/etc/permissions/android.hardware.location.gps.xml \
frameworks/native/data/etc/android.hardware.sensor.light.xml:system/etc/permissions/android.hardware.sensor.light.xml \
frameworks/native/data/etc/android.hardware.sensor.proximity.xml:system/etc/permissions/android.hardware.sensor.proximity.xml \
frameworks/native/data/etc/android.hardware.touchscreen.multitouch.xml:system/etc/permissions/android.hardware.touchscreen.multitouch.xml \
frameworks/native/data/etc/android.hardware.touchscreen.multitouch.distinct.xml:system/etc/permissions/android.hardware.touchscreen.multitouch.distinct.xml \
frameworks/native/data/etc/android.hardware.sensor.compass.xml:system/etc/permissions/android.hardware.sensor.compass.xml \
frameworks/native/data/etc/android.hardware.usb.accessory.xml:system/etc/permissions/android.hardware.usb.accessory.xml \
frameworks/native/data/etc/android.hardware.usb.host.xml:system/etc/permissions/android.hardware.usb.host.xml \
frameworks/native/data/etc/handheld_core_hardware.xml:system/etc/permissions/handheld_core_hardware.xml
# Init files for ramdisk
PRODUCT_COPY_FILES += \
$(LOCAL_PATH)/root/fstab.sdcard:root/fstab.sdcard \
$(LOCAL_PATH)/root/fstab.u8800:root/fstab.u8800 \
$(LOCAL_PATH)/root/init.emmc.rc:root/init.emmc.rc \
$(LOCAL_PATH)/root/init.qcom.sh:root/init.qcom.sh \
$(LOCAL_PATH)/root/init.qcom.rc:root/init.qcom.rc \
$(LOCAL_PATH)/root/ueventd.qcom.rc:root/ueventd.qcom.rc \
$(LOCAL_PATH)/root/init.qcom.usb.sh:root/init.qcom.usb.sh \
$(LOCAL_PATH)/root/init.qcom.usb.rc:root/init.qcom.usb.rc \
$(LOCAL_PATH)/root/init.target.rc:root/init.target.rc
$(call inherit-product, $(SRC_TARGET_DIR)/product/languages_full.mk)
$(call inherit-product, $(SRC_TARGET_DIR)/product/full_base.mk)
$(call inherit-product, $(SRC_TARGET_DIR)/product/telephony.mk)
$(call inherit-product, device/common/gps/gps_as_supl.mk)
$(call inherit-product, build/target/product/full_base_telephony.mk)
PRODUCT_BUILD_PROP_OVERRIDES += BUILD_UTC_DATE=0
PRODUCT_NAME := full_u8800
PRODUCT_DEVICE := u8800
<file_sep>/vendorsetup.sh
# Appropriate lunch combos for successful build for Huawei U8800
add_lunch_combo cm_u8800-userdebug
add_lunch_combo cm_u8800-eng
<file_sep>/setup-makefiles.sh
#!/bin/bash
#
# Copyright (C) 2012 The Android Open-Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
VENDOR=huawei
DEVICE=u8800
OUTDIR=vendor/$VENDOR/$DEVICE
PULLDIR=$OUTDIR/proprietary/pulled
MAKEFILE=../../../$OUTDIR/$DEVICE-vendor-blobs.mk
echo -e "\e[00;35mWriting "$(basename $MAKEFILE) "\e[00m"
(cat << EOF) > $MAKEFILE
#
# Copyright (C) 2012 The Android Open-Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This file is generated by device/$VENDOR/$DEVICE/setup-makefiles.sh
# Prebuilt libraries that are needed to build open-source libraries
PRODUCT_COPY_FILES += \\
EOF
# First check for libraries that need to be linked.
while read file
do
# Skip the line if it is a comment or empty line.
if [[ ${file:0:1} == "#" ]] || [[ ${file:0:1} != "-" ]] || [[ $file == "" ]]; then
continue
fi
# Remove the "-".
file=${file:1}
# We have to put the correct line ending, depending on if we had a file
# previously.
if [[ $wasfile == true ]]; then
echo " \\" >> $MAKEFILE
fi
echo -en "\t$PULLDIR/$file:obj/lib/$(basename $file)" >> $MAKEFILE
wasfile=true
done < proprietary-files.txt
# Clear the variables before using them again.
unset file
unset wasfile
# Secondly add standard libraries.
echo -e "\n\nPRODUCT_COPY_FILES += \\" >> $MAKEFILE
while read file
do
# Skip the line if it is a comment or empty line.
if [[ ${file:0:1} == "#" ]] || [[ $file == "" ]]; then
continue
# If we have "-" in front of the file, remove it.
elif [[ ${file:0:1} == "-" ]]; then
file=${file:1}
fi
# We have to put the correct line ending, depending on if we had a file
# previously.
if [[ $wasfile == true ]]; then
echo " \\" >> $MAKEFILE
fi
echo -en "\t$PULLDIR/$file:system/$file" >> $MAKEFILE
wasfile=true
done < proprietary-files.txt
# Write newline at end of file.
echo "" >> $MAKEFILE
MAKEFILE=../../../$OUTDIR/$DEVICE-vendor.mk
echo -e "\e[00;35mWriting "$(basename $MAKEFILE) "\e[00m"
(cat << EOF) > $MAKEFILE
#
# Copyright (C) 2012 The Android Open-Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This file is generated by device/$VENDOR/$DEVICE/setup-makefiles.sh
# Pick up overlay for features that depend on non-open-source files
DEVICE_PACKAGE_OVERLAYS += $OUTDIR/overlay
\$(call inherit-product, $OUTDIR/$DEVICE-vendor-blobs.mk)
\$(call inherit-product-if-exists, $OUTDIR/$DEVICE-external-blobs.mk)
EOF
MAKEFILE=../../../$OUTDIR/BoardConfigVendor.mk
echo -e "\e[00;35mWriting "$(basename $MAKEFILE) "\e[00m"
(cat << EOF) > $MAKEFILE
#
# Copyright (C) 2012 The Android Open-Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This file is generated by device/$VENDOR/$DEVICE/setup-makefiles.sh
EOF
<file_sep>/README.md
android_device_huawei_u8800
===========================
CyanogenMod device configuration for u8800
<file_sep>/cm.mk
## Specify phone tech before including full_phone
$(call inherit-product, vendor/cm/config/gsm.mk)
# Release name
PRODUCT_RELEASE_NAME := u8800
# Inherit some common CM stuff.
$(call inherit-product, vendor/cm/config/common_full_phone.mk)
# Inherit device configuration
$(call inherit-product, device/huawei/u8800/device_u8800.mk)
TARGET_SCREEN_HEIGHT := 800
TARGET_SCREEN_WIDTH := 480
## Device identifier. This must come after all inclusions
PRODUCT_DEVICE := u8800
PRODUCT_NAME := cm_u8800
PRODUCT_BRAND := huawei
PRODUCT_MODEL := u8800
PRODUCT_MANUFACTURER := huawei
<file_sep>/BoardConfig.mk
USE_CAMERA_STUB := true
# inherit from the proprietary version
-include vendor/huawei/u8800/BoardConfigVendor.mk
TARGET_SPECIFIC_HEADER_PATH := device/huawei/u8800/include
TARGET_ARCH := arm
TARGET_ARCH_VARIANT := armv7-a-neon
TARGET_ARCH_VARIANT_CPU := cortex-a8
ARCH_ARM_HAVE_NEON := true
ARCH_ARM_HAVE_TLS_REGISTER := true
TARGET_BOARD_PLATFORM := msm7x30
TARGET_BOARD_PLATFORM_GPU := qcom-adreno200
TARGET_CPU_ABI := armeabi-v7a
TARGET_CPU_ABI2 := armeabi
TARGET_NO_RADIOIMAGE := true
TARGET_NO_BOOTLOADER := true
TARGET_BOOTLOADER_BOARD_NAME := u8800
ARCH_ARM_HAVE_ARMV7A := true
ARCH_ARMV6_ARMV7 := true
TARGET_GLOBAL_CFLAGS += -mfpu=neon -mfloat-abi=softfp
TARGET_GLOBAL_CPPFLAGS += -mfpu=neon -mfloat-abi=softfp
COMMON_GLOBAL_CFLAGS += -DQCOM_LEGACY_OMX
COMMON_GLOBAL_CFLAGS += -DQCOM_ICS_DECODERS -DQCOM_NO_SECURE_PLAYBACK
COMMON_GLOBAL_CFLAGS += -DQCOM_ICS_COMPAT
TARGET_USE_SCORPION_BIONIC_OPTIMIZATION := true
TARGET_USE_SCORPION_PLD_SET := true
TARGET_SCORPION_BIONIC_PLDOFFS := 6
TARGET_SCORPION_BIONIC_PLDSIZE := 128
#BOARD_USE_SKIA_LCDTEXT := true
# Adreno200
BOARD_USES_ADRENO_200 := true
HAVE_ADRENO200_SOURCE := true
HAVE_ADRENO200_SC_SOURCE := true
HAVE_ADRENO200_FIRMWARE := true
# Filesystem
BOARD_WANTS_EMMC_BOOT := true
TARGET_USERIMAGES_USE_EXT4 := true
TARGET_USERIMAGES_SPARSE_EXT_DISABLED := true
BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
BOARD_SYSTEMIMAGE_PARTITION_SIZE := 402653184 # 384MB
BOARD_FLASH_BLOCK_SIZE := 512
BOARD_VOLD_MAX_PARTITIONS := 14
# Qualcomm Hardware
BOARD_USES_QCOM_HARDWARE := true
COMMON_GLOBAL_CFLAGS += -DQCOM_HARDWARE
BOARD_USES_QCOM_LIBS := true
BOARD_USES_QCOM_LIBRPC := true
BOARD_USE_QCOM_PMEM := true
# Wifi
BOARD_WPA_SUPPLICANT_DRIVER := NL80211
BOARD_HOSTAPD_DRIVER := NL80211
BOARD_WPA_SUPPLICANT_PRIVATE_LIB := lib_driver_cmd_wext
BOARD_HOSTAPD_PRIVATE_LIB := lib_driver_cmd_wext
WPA_SUPPLICANT_VERSION := VER_0_8_X
HOSTAPD_VERSION := VER_0_8_X
WIFI_DRIVER_MODULE_PATH := "/system/lib/modules/wlan.ko"
WIFI_DRIVER_MODULE_NAME := "wlan"
WIFI_DRIVER_MODULE_ARG := ""
WIFI_EXT_MODULE_PATH := "/system/lib/modules/librasdioif.ko"
WIFI_EXT_MODULE_NAME := "librasdioif"
WIFI_EXT_MODULE_ARG := ""
WIFI_FIRMWARE_LOADER := ""
WIFI_DRIVER_FW_PATH_STA := "sta"
WIFI_DRIVER_FW_PATH_AP := "ap"
WIFI_DRIVER_FW_PATH_P2P := "p2p"
BOARD_WLAN_DEVICE := qcwcn
BOARD_HAS_QCOM_WLAN := true
# Graphics/Display
TARGET_HARDWARE_3D := false
USE_OPENGL_RENDERER := true
COMMON_GLOBAL_CFLAGS += -DREFRESH_RATE=60
TARGET_USES_C2D_COMPOSITION := true
TARGET_GRALLOC_USES_ASHMEM := true
#BOARD_USES_QCNE := true
TARGET_USES_SF_BYPASS := false
TARGET_HAVE_TSLIB := true
BOARD_EGL_CFG := device/huawei/u8800/egl.cfg
TARGET_NO_HW_VSYNC := true
TARGET_USES_ION := false
TARGET_PROVIDES_LIBLIGHTS := true
#COMMON_GLOBAL_CFLAGS += -DGENLOCK_IOC_DREADLOCK -DANCIENT_GL
#TARGET_USES_OVERLAY := true
#TARGET_USES_GENLOCK := true
# Kernel
#TARGET_PREBUILT_KERNEL := device/huawei/u8800/kernel
TARGET_NO_KERNEL := false
TARGET_KERNEL_CUSTOM_TOOLCHAIN := arm-eabi-4.4.3
TARGET_KERNEL_SOURCE := kernel/huawei/u8800
TARGET_KERNEL_CONFIG := u8800_defconfig
BOARD_KERNEL_CMDLINE := console=ttyDCC0 androidboot.hardware=qcom
BOARD_KERNEL_BASE := 0x00200000
BOARD_KERNEL_PAGESIZE := 4096
# GPS
BOARD_USES_QCOM_GPS := true
BOARD_VENDOR_QCOM_GPS_LOC_API_HARDWARE := msm7x30
BOARD_VENDOR_QCOM_GPS_LOC_API_AMSS_VERSION := 50000
BOARD_GPS_LIBRARIES := libloc_api
# Bluetooth
BOARD_HAVE_BLUETOOTH := true
BOARD_HAVE_BLUETOOTH_BCM := false
# Camera
BOARD_CAMERA_LIBRARIES := libcamera
BOARD_NEEDS_MEMORYHEAPPMEM := true
COMMON_GLOBAL_CFLAGS += -DICS_CAMERA_BLOB
# Recovery
BOARD_HAS_NO_SELECT_BUTTON := true
# Webkit
WITH_JIT := true
ENABLE_JSC_JIT := true
JS_ENGINE := v8
HTTP := chrome
ENABLE_WEBGL := true
TARGET_FORCE_CPU_UPLOAD := true
WEBCORE_INPAGE_VIDEO := true
# FM
BOARD_HAVE_FM_RADIO := true
BOARD_GLOBAL_CFLAGS += -DHAVE_FM_RADIO
# ETC
TARGET_SPECIFIC_HEADER_PATH := device/huawei/u8800/include
# Recovery
DEVICE_RESOLUTION := 480x800
RECOVERY_GRAPHICS_USE_LINELENGTH := true
BOARD_HAS_NO_REAL_SDCARD := true
TW_NO_REBOOT_BOOTLOADER := true
TW_INTERNAL_STORAGE_PATH := "/emmc"
TW_INTERNAL_STORAGE_MOUNT_POINT := "emmc"
TW_EXTERNAL_STORAGE_PATH := "/sdcard"
TW_EXTERNAL_STORAGE_MOUNT_POINT := "sdcard"
BOARD_HAS_JANKY_BACKBUFFER := true
BOARD_RECOVERY_CHARGEMODE := true
BOARD_RECOVERY_RMT_STORAGE := true
TARGET_USE_CUSTOM_LUN_FILE_PATH := /sys/devices/platform/msm_hsusb/gadget/lun
TARGET_USE_CUSTOM_SECOND_LUN_NUM := 2
BOARD_UMS_LUNFILE := /sys/devices/platform/msm_hsusb/gadget/lun0/file
BOARD_VOLD_MAX_PARTITIONS := 20
BOARD_VOLD_EMMC_SHARES_DEV_MAJOR := true
TW_DEFAULT_EXTERNAL_STORAGE := true
TARGET_RECOVERY_PIXEL_FORMAT := "RGB_565"
# Custom releasetools
TARGET_PROVIDES_RELEASETOOLS := true
TARGET_RELEASETOOL_OTA_FROM_TARGET_SCRIPT := ./device/huawei/u8800/releasetools/ota_from_target_files
# Use this flag if the board has a ext4 partition larger than 2gb
#BOARD_HAS_LARGE_FILESYSTEM := true
<file_sep>/prebuilt/prebuilt.mk
# This makefile is used to copy all of the prebuilt files to the product rom
# etc
PRODUCT_COPY_FILES += \
device/huawei/u8800/prebuilt/etc/bluetooth/audio.conf:system/etc/bluetooth/audio.conf \
device/huawei/u8800/prebuilt/etc/bluetooth/auto_pairing.conf:system/etc/bluetooth/auto_pairing.conf \
device/huawei/u8800/prebuilt/etc/bluetooth/blacklist.conf:system/etc/bluetooth/blacklist.conf \
device/huawei/u8800/prebuilt/etc/bluetooth/input.conf:system/etc/bluetooth/input.conf \
device/huawei/u8800/prebuilt/etc/bluetooth/main.conf:system/etc/bluetooth/main.conf \
device/huawei/u8800/prebuilt/etc/bluetooth/network.conf:system/etc/bluetooth/network.conf \
device/huawei/u8800/prebuilt/etc/firmware/wlan/cfg.dat:system/etc/firmware/wlan/cfg.dat \
device/huawei/u8800/prebuilt/etc/firmware/wlan/cfg_new.dat:system/etc/firmware/wlan/cfg_new.dat \
device/huawei/u8800/prebuilt/etc/firmware/wlan/hostapd_default.conf:system/etc/firmware/wlan/hostapd_default.conf \
device/huawei/u8800/prebuilt/etc/firmware/wlan/qcom_cfg.ini:system/etc/firmware/wlan/qcom_cfg.ini \
device/huawei/u8800/prebuilt/etc/firmware/wlan/qcom_fw.bin:system/etc/firmware/wlan/qcom_fw.bin \
device/huawei/u8800/prebuilt/etc/firmware/wlan/qcom_wapi_fw.bin:system/etc/firmware/wlan/qcom_wapi_fw.bin \
device/huawei/u8800/prebuilt/etc/firmware/wlan/qcom_wlan_nv.bin:system/etc/firmware/wlan/qcom_wlan_nv.bin \
device/huawei/u8800/prebuilt/etc/firmware/a225p5_pm4.fw:system/etc/firmware/a225p5_pm4.fw \
device/huawei/u8800/prebuilt/etc/firmware/a225_pfp.fw:system/etc/firmware/a225_pfp.fw \
device/huawei/u8800/prebuilt/etc/firmware/a225_pm4.fw:system/etc/firmware/a225_pm4.fw \
device/huawei/u8800/prebuilt/etc/firmware/leia_pfp_470.fw:system/etc/firmware/leia_pfp_470.fw \
device/huawei/u8800/prebuilt/etc/firmware/leia_pm4_470.fw:system/etc/firmware/leia_pm4_470.fw \
device/huawei/u8800/prebuilt/etc/firmware/yamato_pfp.fw:system/etc/firmware/yamato_pfp.fw \
device/huawei/u8800/prebuilt/etc/firmware/yamato_pm4.fw:system/etc/firmware/yamato_pm4.fw \
device/huawei/u8800/prebuilt/etc/firmware/a300_pfp.fw:system/etc/firmware/a300_pfp.fw \
device/huawei/u8800/prebuilt/etc/firmware/a300_pm4.fw:system/etc/firmware/a300_pm4.fw \
device/huawei/u8800/prebuilt/etc/firmware/cyttsp_7630_fluid.hex:system/etc/firmware/cyttsp_7630_fluid.hex \
device/huawei/u8800/prebuilt/etc/firmware/vidc_720p_command_control.fw:system/etc/firmware/vidc_720p_command_control.fw \
device/huawei/u8800/prebuilt/etc/firmware/vidc_720p_h263_dec_mc.fw:system/etc/firmware/vidc_720p_h263_dec_mc.fw \
device/huawei/u8800/prebuilt/etc/firmware/vidc_720p_h264_dec_mc.fw:system/etc/firmware/vidc_720p_h264_dec_mc.fw \
device/huawei/u8800/prebuilt/etc/firmware/vidc_720p_h264_enc_mc.fw:system/etc/firmware/vidc_720p_h264_enc_mc.fw \
device/huawei/u8800/prebuilt/etc/firmware/vidc_720p_mp4_dec_mc.fw:system/etc/firmware/vidc_720p_mp4_dec_mc.fw \
device/huawei/u8800/prebuilt/etc/firmware/vidc_720p_mp4_enc_mc.fw:system/etc/firmware/vidc_720p_mp4_enc_mc.fw \
device/huawei/u8800/prebuilt/etc/firmware/vidc_720p_vc1_dec_mc.fw:system/etc/firmware/vidc_720p_vc1_dec_mc.fw \
device/huawei/u8800/prebuilt/etc/wifi/hostapd_default.conf:system/etc/wifi/hostapd_default.conf \
device/huawei/u8800/prebuilt/etc/wifi/wpa_supplicant.conf:system/etc/wifi/wpa_supplicant.conf \
device/huawei/u8800/prebuilt/etc/audio_policy.conf:system/etc/audio_policy.conf \
device/huawei/u8800/prebuilt/etc/init.qcom.bt.sh:system/etc/init.qcom.bt.sh \
device/huawei/u8800/prebuilt/etc/init.qcom.coex.sh:system/etc/init.qcom.coex.sh \
device/huawei/u8800/prebuilt/etc/init.qcom.fm.sh:system/etc/init.qcom.fm.sh \
device/huawei/u8800/prebuilt/etc/init.qcom.post_boot.sh:system/etc/init.qcom.post_boot.sh \
device/huawei/u8800/prebuilt/etc/init.qcom.sdio.sh:system/etc/init.qcom.sdio.sh \
device/huawei/u8800/prebuilt/etc/init.qcom.wifi.sh:system/etc/init.qcom.wifi.sh \
device/huawei/u8800/prebuilt/etc/media_codecs.xml:system/etc/media_codecs.xml \
device/huawei/u8800/prebuilt/etc/media_profiles.xml:system/etc/media_profiles.xml \
device/huawei/u8800/prebuilt/etc/vold.fstab:system/etc/vold.fstab \
device/huawei/u8800/prebuilt/etc/dhcpcd/dhcpcd.conf:system/etc/dhcpcd/dhcpcd.conf \
device/huawei/u8800/prebuilt/etc/gps.conf:system/etc/gps.conf \
# lib
PRODUCT_COPY_FILES += \
device/huawei/u8800/prebuilt/lib/hw/sensors.default.so:system/lib/hw/sensors.default.so \
device/huawei/u8800/prebuilt/lib/hw/camera.msm7x30.so:system/lib/hw/camera.msm7x30.so \
device/huawei/u8800/prebuilt/lib/modules/librasdioif.ko:system/lib/modules/librasdioif.ko \
device/huawei/u8800/prebuilt/lib/modules/wlan.ko:system/lib/modules/wlan.ko \
device/huawei/u8800/prebuilt/lib/egl/eglsubAndroid.so:system/lib/egl/eglsubAndroid.so \
device/huawei/u8800/prebuilt/lib/egl/libEGL_adreno200.so:system/lib/egl/libEGL_adreno200.so \
device/huawei/u8800/prebuilt/lib/egl/libGLES_android.so:system/lib/egl/libGLES_android.so \
device/huawei/u8800/prebuilt/lib/egl/libGLESv1_CM_adreno200.so:system/lib/egl/libGLESv1_CM_adreno200.so \
device/huawei/u8800/prebuilt/lib/egl/libGLESv2_adreno200.so:system/lib/egl/libGLESv2_adreno200.so \
device/huawei/u8800/prebuilt/lib/egl/libq3dtools_adreno200.so:system/lib/egl/libq3dtools_adreno200.so \
device/huawei/u8800/prebuilt/lib/egl/libGLESv2S3D_adreno200.so:system/lib/egl/libGLESv2S3D_adreno200.so \
device/huawei/u8800/prebuilt/lib/libc2d2_z180.so:system/lib/libc2d2_z180.so \
device/huawei/u8800/prebuilt/lib/libC2D2.so:system/lib/libC2D2.so \
device/huawei/u8800/prebuilt/lib/libgsl.so:system/lib/libgsl.so \
device/huawei/u8800/prebuilt/lib/libOpenVG.so:system/lib/libOpenVG.so \
device/huawei/u8800/prebuilt/lib/libsc-a2xx.so:system/lib/libsc-a2xx.so \
# usr
PRODUCT_COPY_FILES += \
device/huawei/u8800/prebuilt/usr/keychars/surf_keypad.kcm:system/usr/keychars/surf_keypad.kcm \
device/huawei/u8800/prebuilt/usr/keylayout/7k_handset.kl:system/usr/keylayout/7k_handset.kl \
device/huawei/u8800/prebuilt/usr/keylayout/fluid-keypad.kl:system/usr/keylayout/fluid-keypad.kl \
device/huawei/u8800/prebuilt/usr/keylayout/msm_tma300_ts.kl:system/usr/keylayout/msm_tma300_ts.kl \
device/huawei/u8800/prebuilt/usr/keylayout/qwerty.kl:system/usr/keylayout/qwerty.kl \
device/huawei/u8800/prebuilt/usr/keylayout/surf_keypad.kl:system/usr/keylayout/surf_keypad.kl \
device/huawei/u8800/prebuilt/usr/idc/atmel-rmi-touchscreen.idc:system/usr/idc/atmel-rmi-touchscreen.idc \
device/huawei/u8800/prebuilt/usr/idc/synaptics.idc:system/usr/idc/synaptics.idc \
<file_sep>/extract-files.sh
#!/bin/bash
#
# Copyright (C) 2012 The Android Open-Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This script checks if there is a device to pull from, downloads the files to
# their corresponding directories in $BASE. After downloading it gives the
# correct permissions to libraries and binaries.
# Assign vendor names used in directories.
VENDOR=huawei
DEVICE=u8800
BASE=../../../vendor/$VENDOR/$DEVICE/proprietary/pulled
PULL_BASE=system
# Global array used for pulling files.
filelist=()
function getFileList
{
filelist=()
while read file
do
# Skip the line if it is a comment or empty line.
if [[ ${file:0:1} == "#" ]] || [[ $file == "" ]]; then
continue
# If we have - in front of the file, remove it.
elif [[ ${file:0:1} == "-" ]]; then
file=${file:1}
fi
filelist+=($file)
done < proprietary-files.txt
}
function pullAdb
{
# Start ADB server.
adb start-server
# List devices through ADB.
devices=$(adb devices)
# Back up IFS.
OLD_IFS="$IFS"
# Give newline char as splitter.
IFS=$'\n'
devicefound=false
for line in $devices; do
# First line is not showing any devices
if [[ "$line" =~ "List of devices attached" ]]
then
continue
# If we found a device, exit the loop.
elif [[ "$line" =~ "device" ]]
then
devicefound=$line
fi
done
# Revert back to original IFS.
IFS="$OLD_IFS"
# If no device found, let's wait for one.
if [[ "$devicefound" == false ]]; then
echo "Waiting for device..."
adb wait-for-device
fi
echo "Found "$devicefound
getFileList
for file in ${filelist[@]}; do
echo -en "\e[00;34mPulling $file "
# Find the directory name.
dir=$(dirname $file)
if [ ! -d $BASE/$dir ]; then
mkdir -p $BASE/$dir
fi
adb pull $PULL_BASE/$file $BASE/$file
echo -en "\e[00m"
done
}
function pullZip
{
getFileList
for file in ${filelist[@]}; do
# Find the directory name.
dir=$(dirname $file)
if [ ! -d $BASE/$dir ]; then
mkdir -p $BASE/$dir
fi
echo -e "\e[00;34mPulling $file\e[00m"
unzip -j $PARAMETER $PULL_BASE/$file -d $BASE/$dir > /dev/null
done
}
# Remove old files (if exists)
rm -rf $BASE/*
PARAMETER=$1
# Check if file is specified.
if [[ -f $PARAMETER ]] && [[ ${PARAMETER##*.} == "zip" ]]
then
echo "Pulling from zip"
pullZip
else
echo "Pulling from device"
pullAdb
fi
# Give correct permissions.
echo "Setting correct permissions..."
# Give newline char as splitter.
IFS=$'\n'
# Only chmod if we have the directory (and files).
if [[ -d "$BASE/lib" ]]; then
for library in $(find $BASE/lib -type f -name *.so); do
echo -e "\e[00;32mSetting permission 644 on "$(basename $library)"\e[00m"
chmod 644 $library
done
fi
# Only chmod if we have the directory (and files).
if [[ -d "$BASE/bin" ]]; then
for binary in $(find $BASE/bin -type f); do
echo -e "\e[00;32mSetting permission 755 on "$(basename $binary)"\e[00m"
chmod 755 $binary
done
fi
# Revert back to original IFS.
IFS="$OLD_IFS"
# Start the makefiles script which adds the makefiles for Android.
echo "Executing setup-makefiles.sh"
./setup-makefiles.sh
| 5224495199d73c53cb8ff8cf822eda097f488be6 | [
"Markdown",
"Makefile",
"Shell"
] | 9 | Makefile | rqmok/android_device_huawei_u8800 | f97d32af1aaf0dd4fad58e6654e88cf6d6ae9c8d | dc08071ce05c8dd2540e21e4df6fa1c6b7ce3712 |
refs/heads/master | <repo_name>neerajachennuru/Varibles<file_sep>/Variables/src/Empolyee.java
public class Empolyee {
private String name;
private int number;
private int salary;
public Empolyee (){
}
public Empolyee ( String name, int number , int salary){
this.name = name;
this.number = number;
this.salary = salary;
}
public String toString (){
return name + " " + number + " " + salary ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
| 7c2896e647d080c661d21b943d3ffdb3ce6ec5f3 | [
"Java"
] | 1 | Java | neerajachennuru/Varibles | 6b4d0a3e5245038e58dcb5b731bf9e5935ba64ce | 452048e6e1e8edb2ee7985dcd8d456574adcee0c |
refs/heads/master | <file_sep>package cn.com.reservoirpro.detection.yantu;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import cn.com.reservoirpro.R;
public class YantuValueDetrctionActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yantu_value_detrction);
}
}
<file_sep>package cn.com.reservoirpro.detection;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import cn.com.reservoirpro.R;
import cn.com.reservoirpro.detection.liuliang.LiuliangActivity;
import cn.com.reservoirpro.detection.shexiang.ShexiangActivoty;
import cn.com.reservoirpro.detection.shuiwei.ShuiweiActivity;
import cn.com.reservoirpro.detection.shuizhi.ShuizhiActivity;
import cn.com.reservoirpro.detection.yantu.YantuDectionActivity;
/**
* 监测站
*/
public class DetectionActivity extends Activity {
private ListView detectionList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detection);
detectionList= (ListView) findViewById(R.id.detectionList);
ArrayList<Map<String,String>> datalist = new ArrayList<>();
Map<String,String> item =new HashMap<String,String>();
item.put("name", "岩土类传感器");
datalist.add(item);
Map<String,String> item1 =new HashMap<String,String>();
item1.put("name","流量统计");
datalist.add(item1);
Map<String,String> item2 =new HashMap<String,String>();
item2.put("name","水位");
datalist.add(item2);
Map<String,String> item3 =new HashMap<String,String>();
item3.put("name", "水质");
datalist.add(item3);
Map<String,String> item4 =new HashMap<String,String>();
item4.put("name", "摄像仪");
datalist.add(item4);
SimpleAdapter myAdapter = new SimpleAdapter(DetectionActivity.this, datalist, R.layout.about_list_item, new String[]{"name"}, new int[]{R.id.item_name});
detectionList.setAdapter(myAdapter);
detectionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
startActivity(new Intent(DetectionActivity.this, YantuDectionActivity.class));
break;
case 1:
startActivity(new Intent(DetectionActivity.this, LiuliangActivity.class));
break;
case 2:
startActivity(new Intent(DetectionActivity.this, ShuiweiActivity.class));
break;
case 3:
startActivity(new Intent(DetectionActivity.this, ShuizhiActivity.class));
break;
case 4:
startActivity(new Intent(DetectionActivity.this, ShexiangActivoty.class));
break;
}
}
});
}
}
<file_sep>package cn.com.reservoirpro.detection.yantu;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import cn.com.reservoirpro.R;
public class YanTuValueActivity extends AppCompatActivity {
private ListView yantuValueList1,yantuValueList2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yan_tu_value);
ArrayList<Map<String,String>> datalist = new ArrayList<>();
for(int i=0;i<10;i++){
Map<String,String> item =new HashMap<String,String>();
item.put("name",i+ "#基岩变位计");
item.put("value", "0 mm");
datalist.add(item);
}
// Map<String,String> item =new HashMap<String,String>();
// item.put("name", "406监控点");
// datalist.add(item);
// Map<String,String> item1 =new HashMap<String,String>();
// item1.put("name","201监控点");
// datalist.add(item1);
// Map<String,String> item2 =new HashMap<String,String>();
// item2.put("name","803监控点");
// datalist.add(item2);
// Map<String,String> item3 =new HashMap<String,String>();
// item3.put("name", "607监控点");
// datalist.add(item3);
yantuValueList1 =(ListView)findViewById(R.id.yantuValueList1);
SimpleAdapter myAdapter = new SimpleAdapter(YanTuValueActivity.this, datalist, R.layout.list_value_item_layout, new String[]{"name","value"}, new int[]{R.id.name,R.id.value});
yantuValueList1.setAdapter(myAdapter);
yantuValueList2 =(ListView)findViewById(R.id.yantuValueList2);
yantuValueList2.setAdapter(myAdapter);
}
}
<file_sep>package cn.com.reservoirpro.detection.yantu;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import cn.com.reservoirpro.R;
public class YantuDectionActivity extends AppCompatActivity {
private ListView detectionChoseList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yantu_dection);
detectionChoseList= (ListView)findViewById(R.id.detectionChoseList);
ArrayList<Map<String,String>> datalist = new ArrayList<>();
Map<String,String> item =new HashMap<String,String>();
item.put("name", "406监控点");
item.put("value", "406监控点");
datalist.add(item);
Map<String,String> item1 =new HashMap<String,String>();
item1.put("name","201监控点");
item1.put("value", "406监控点");
datalist.add(item1);
Map<String,String> item2 =new HashMap<String,String>();
item2.put("name","803监控点");
item2.put("value", "406监控点");
datalist.add(item2);
Map<String,String> item3 =new HashMap<String,String>();
item3.put("name", "607监控点");
item3.put("value", "406监控点");
datalist.add(item3);
SimpleAdapter myAdapter = new SimpleAdapter(YantuDectionActivity.this, datalist, R.layout.about_list_item, new String[]{"name","value"}, new int[]{R.id.item_name,R.id.value});
detectionChoseList.setAdapter(myAdapter);
detectionChoseList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(YantuDectionActivity.this,YanTuValueActivity.class));
}
});
}
}
<file_sep>package cn.com.reservoirpro.common.communication.webservers;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.json.JSONException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import cn.com.reservoirpro.R;
import cn.com.reservoirpro.common.util.Constants;
import cn.com.reservoirpro.common.util.Util;
/**
* @author coolszy
* @date 2012-4-26
* @blog http://blog.92coding.com
*/
public class UpdateManager {
/* 下载中 */
private static final int DOWNLOAD = 2;
/* 下载结束 */
private static final int DOWNLOAD_FINISH = 3;
private static final int CHECK_UPDATE = 1;// 是否需要更新
private static final int FAIL = 0;// 失败
/* 保存解析的XML信息 */
HashMap<String, String> mHashMap;
/* 下载保存路径 */
private String mSavePath;
/* 记录进度条数量 */
private int progress;
/* 是否取消更新 */
private boolean cancelUpdate = false;
private Context mContext;
/* 更新进度条 */
private ProgressBar mProgress;
private Dialog mDownloadDialog;
private String downLoadPakUrl;
private Handler handler;// 外部传入的handler
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
// 正在下载
case DOWNLOAD:
// 设置进度条位置
mProgress.setProgress(progress);
break;
case DOWNLOAD_FINISH:
// 安装文件
installApk();
break;
case CHECK_UPDATE: // 成功获取新版本信息
// 安装文件
if (downLoadPakUrl.contains("http://")) {
// 显示提示对话框,如果需要强行安装最新,不需要通过这个提示对话框
// showNoticeDialog();
showDownloadDialog();// 直接跳过提示
} else {
Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_LONG).show();
if (handler != null)
handler.sendEmptyMessage(99);// 回传一个继续登陆的消息,只有不需要更新才能继续登陆,其他情况都不进行登陆
}
break;
default:
break;
}
};
};
public UpdateManager(Context context, Handler handler) {
this.mContext = context;
this.handler = handler;// 不需要互动的话,则设置为null
}
// 读取输入流中的数据,返回字节数组byte[]
// public byte[] readInputStream(InputStream inStream) throws Exception {
// // 此类实现了一个输出流,其中的数据被写入一个 byte 数组
// ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// // 字节数组
// byte[] buffer = new byte[1024];
// int len = 0;
// // 从输入流中读取一定数量的字节,并将其存储在缓冲区数组buffer 中
// while ((len = inStream.read(buffer)) != -1) {
// // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流
// outStream.write(buffer, 0, len);
// }
// inStream.close();
// // toByteArray()创建一个新分配的 byte 数组。
// return outStream.toByteArray();
// }
/**
* 检测软件更新
*/
public void checkUpdate() {
// downLoadPakUrl =
// "http://192.168.12.188/DownFile/apk/MaterialsFlowSystem.apk";
// downLoadPakUrl="";
// mHandler.sendEmptyMessage(CHECK_UPDATE);
// 获取当前软件版本
ArrayList<Map<String, Object>> putData = new ArrayList<Map<String, Object>>();
Map<String, Object> item = new HashMap<String, Object>();
item.put("mothName", "tempvision");
try {
item.put("mothValue", String.valueOf(Util.getVersionCode(mContext)));
putData.add(item);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
mHandler.sendEmptyMessage(FAIL);
}
ThreadWebServer webServer = new ThreadWebServer(mContext, Util.GetURL(mContext, Constants.SERVER_1), "GetVesion", putData);
webServer.getResult(new WebSerResult() {
@Override
public void Success(String result) throws JSONException {
// TODO Auto-generated method stub
// 安装文件
if (result.contains("http://")) {
// 显示提示对话框,如果需要强行安装最新,不需要通过这个提示对话框
// showNoticeDialog();
showDownloadDialog();// 直接跳过提示
} else {
Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_LONG).show();
}
}
@Override
public void Faild(String failString) {
// TODO Auto-generated method stub
}
});
}
/**
* 获取软件版本号
*
* @param context
* @return
*/
// private int getVersionCode(Context context) {
// int versionCode = 0;
// try {
//
// versionCode = context.getPackageManager().getPackageInfo(
// context.getPackageName(), 0).versionCode;
// } catch (NameNotFoundException e) {
// e.printStackTrace();
// }
// return versionCode;
// }
/**
* 显示软件更新对话框,如果需要强行安装最新,不需要通过这个提示对话框
*/
private void showNoticeDialog() {
// 构造对话框
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle("软件更新");
builder.setMessage("检测到新版本,立即更新");
// 更新
builder.setPositiveButton("更新", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 显示下载对话框
showDownloadDialog();
}
});
// 稍后更新
builder.setNegativeButton("稍后更新", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog noticeDialog = builder.create();
noticeDialog.show();
}
/**
* 显示软件下载对话框
*/
private void showDownloadDialog() {
// 构造软件下载对话框
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle("正在更新");
// 给下载对话框增加进度条
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.softupdate_progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
builder.setView(v);
// 取消更新
builder.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 设置取消状态
cancelUpdate = true;
}
});
mDownloadDialog = builder.create();
mDownloadDialog.show();
// 现在文件
downloadApk();
}
/**
* 下载apk文件
*/
private void downloadApk() {
// 启动新线程下载软件
new downloadApkThread().start();
}
/**
* 下载文件线程
*
*/
private class downloadApkThread extends Thread {
@Override
public void run() {
try {
// 判断SD卡是否存在,并且是否具有读写权限 这里可以不用sd卡,因为可能某些设备没有或者sd卡位置不通用
// if (Environment.getExternalStorageState().equals(
// Environment.MEDIA_MOUNTED)) {
// 获得存储卡的路径
// String sdpath = Environment.getExternalStorageDirectory()+
// "/"+"down";
// 获取程序目录的file路径
String sdpath = mContext.getFilesDir().getPath();
mSavePath = sdpath;
URL url = new URL(downLoadPakUrl);
// 创建连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
// 获取文件大小
int length = conn.getContentLength();
// 创建输入流
InputStream is = conn.getInputStream();
File file = new File(mSavePath);
// 判断文件目录是否存在
if (!file.exists()) {
file.mkdir();
}
File apkFile = new File(mSavePath, downLoadPakUrl.substring(downLoadPakUrl.lastIndexOf("/") + 1, downLoadPakUrl.length()));
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
// 缓存
byte buf[] = new byte[1024];
// 写入到文件中
do {
int numread = is.read(buf);
count += numread;
// 计算进度条位置
progress = (int) (((float) count / length) * 100);
// 更新进度
mHandler.sendEmptyMessage(DOWNLOAD);
if (numread <= 0) {
// 下载完成
mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
// 写入文件
fos.write(buf, 0, numread);
} while (!cancelUpdate);// 点击取消就停止下载.
fos.close();
is.close();
// }//判断SD卡是否可用的引号
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 取消下载对话框显示
mDownloadDialog.dismiss();
}
};
/**
* 安装APK文件
*/
private void installApk() {
// 启动新线程安装软件,发现如果不用线程装,第一次可以安装,第二次就不行
new installApkhread().start();
}
/**
* 安装APK线程
*/
private class installApkhread extends Thread {
public void run() {
File apkfile = new File(mSavePath, downLoadPakUrl.substring(downLoadPakUrl.lastIndexOf("/") + 1, downLoadPakUrl.length()));
if (!apkfile.exists()) {
return;
}
try {
Util.changeMode(apkfile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 通过Intent安装APK文件
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
mContext.startActivity(intent);
}
}
}
| a3dca36b9904431b06349e4cbf9f23d1324df75c | [
"Java"
] | 5 | Java | IGisvity/Shuiba | 4d80f0c2e8f7f458cf44e099d0d71b9e57227b1a | 9ee9631c835839e8961d4f1b4b42d7a681dbd211 |
refs/heads/master | <repo_name>ZithaChitra/seq2seq_lstms<file_sep>/README.md
# seq2seq_lstms
Simple Implementation of sequence to sequence model for language translation using keras
<file_sep>/manythings/train/train_model.py
from typing import Dict
import importlib
import numpy as np
from manythings.util_yaml import yaml_loader
import click
import wandb
from wandb.keras import WandbCallback
import mlflow
from mlflow.models.signature import ModelSignature
from mlflow.types.schema import Schema, TensorSpec
# api_key = os.environ['WANDB_API_KEY']
@click.command()
@click.argument("experiment-config",
type=click.Path(exists=True),
default="manythings/experiment.yaml")
@click.option("--latent_dim", default=300)
@click.option("--decay", default=1.0e-06)
@click.option("--dropout", default=0.2)
@click.option("--epochs", default=3)
@click.option("--learn_rate", default=0.01)
@click.option("--momentum", default=0.9)
def main(experiment_config, latent_dim: int, decay: float, dropout: float,
epochs: int, learn_rate: float, momentum: float):
""" Update values in experiment configuration file """
exp_config = yaml_loader("manythings/experiment.yaml")
proj_name = exp_config.get("project_name")
net_name = exp_config.get("network")["name"]
net_args = exp_config.get("network")["net_args"]
net_args["hidden_layer_size"] = latent_dim
net_args["decay"] = decay
net_args["dropout"] = dropout
net_args["epochs"] = epochs
net_args["learn_rate"] = learn_rate
net_args["momentum"] = momentum
dataset_cls = exp_config.get("dataset")["name"]
dataset_args = exp_config.get("dataset")["dataset_args"]
model = exp_config.get("model")
wandb.login()
train(proj_name, model, dataset_cls, net_name, net_args, dataset_args)
def train(
proj_name: str,
Model: str,
dataset_cls: str,
net_fn: str,
net_args: Dict,
dataset_args: Dict,
):
""" Train Function """
dataset_module = importlib.import_module(
f"manythings.data.dta_{dataset_cls}")
dataset_cls_ = getattr(dataset_module, dataset_cls)
network_module = importlib.import_module(f"manythings.networks.{net_fn}")
network_fn_ = getattr(network_module, net_fn)
model_module = importlib.import_module(f"manythings.models.{Model}")
model_cls_ = getattr(model_module, Model)
config = {
"model": Model,
"dataset_cls": dataset_cls,
"net_fn": net_fn,
"net_args": net_args,
"dataset_args": dataset_args
}
input_schema = Schema([
TensorSpec(np.dtype(np.uint8), (-1, 71), "encoder_input"),
TensorSpec(np.dtype(np.uint8), (-1, 93), "decoder_input")
])
output_schema = Schema([TensorSpec(np.dtype(np.float32), (-1, 93))])
signature = ModelSignature(inputs=input_schema, outputs=output_schema)
data = dataset_cls_()
data.load_or_generate()
data.preprocess()
with wandb.init(project=proj_name, config=config):
""""""
config = wandb.config
model = model_cls_(dataset_cls_, network_fn_, net_args, dataset_args)
callbacks = [WandbCallback(
# training_data=(
# [data.encoder_input_data, data.decoder_input_data],
# data.decoder_target_data
# ),
# log_weights=True,
# log_gradients=True
)]
model.fit(callbacks=callbacks)
mlflow.keras.save_model(model.network,
"saved_models/seq2seq",
signature=signature)
if __name__ == "__main__":
main()
<file_sep>/manythings/train/train.py
from tensorflow import keras
import pathlib
from manythings.data.dta_ManyThings import ManyThings
from manythings.networks.nn_lstm import Seq2Seq
import os
import wandb
from wandb.keras import WandbCallback
import click
@click.command()
@click.option("--latent_dim", default=250, help="latent dim of lstm layer")
def train_model(
latent_dim,
project_name: str="manythings",
use_wandb: bool=True
):
# A simple example of how to combine the data
# and the lstm neural net to create a model
path = pathlib.Path.cwd() / "saved_models" / "weights"
# model_path = os.path.join(path, "lstm.h5")
model_weights_path = os.path.join(path, "nn_lstm_weights.hdf5")
# The ManyThings class creates an easy to use interface
# to the dataset
data = ManyThings()
data.load_or_generate()
data.preprocess()
encoder_input_data = data.encoder_input_data
decoder_input_data = data.decoder_input_data
decoder_target_data = data.decoder_target_data
num_encoder_tokens = data.num_encoder_tokens
num_decoder_tokens = data.num_decoder_tokens
input_texts = data.input_texts
batch_size = 100 # Batch size for training.
epochs = 2
model = Seq2Seq(
num_encoder_tokens=num_encoder_tokens, num_decoder_tokens=num_decoder_tokens,
latent_dim=latent_dim
)
model.training_model.compile(
optimizer="rmsprop", loss="categorical_crossentropy", metrics=["accuracy"]
)
checkpoint_callback = keras.callbacks.ModelCheckpoint(
model_weights_path, monitor="val_loss", save_best_only=True
)
if use_wandb:
with wandb.init(project=project_name) as run:
model.training_model.fit(
[encoder_input_data, decoder_input_data],
decoder_target_data,
batch_size=batch_size,
epochs=epochs,
validation_split=0.2,
callbacks=[checkpoint_callback, WandbCallback()],
)
model.training_model.save(model_weights_path)
model_artifact = wandb.Artifact("Seq2Seq", type="model")
model_artifact.add_file(model_weights_path)
run.log_artifact(model_artifact)
else:
model.training_model.fit(
[encoder_input_data, decoder_input_data],
decoder_target_data,
batch_size=batch_size,
epochs=epochs,
validation_split=0.2,
callbacks=[checkpoint_callback, WandbCallback()])
model.training_model.save(model_weights_path)
if __name__ == "__main__":
train_model()<file_sep>/setup.py
from setuptools import setup, find_packages
import pathlib
from os import path
__version__ = "0.1.0"
cwd = pathlib.Path.cwd()
# get dependencies and installs
with open(path.join(cwd, "requirements.txt"), encoding="utf-8") as f:
all_reqs = f.read().split("\n")
install_requires = [x.strip() for x in all_reqs if "git+" not in x]
dependency_links = [x.strp().replace("git+", "") for x in all_reqs if x.startswith("git+")]
setup(
name="ManyThings",
version=__version__,
packages=find_packages(),
install_requires=install_requires,
dependency_links=dependency_links,
)<file_sep>/manythings/networks/nn_lstm.py
from tensorflow import keras
from tensorflow.keras import layers
class Seq2Seq():
def __init__(
self,num_encoder_tokens: int=64,
num_decoder_tokens: int=64,
latent_dim: int=300,
model_weights: str=None
):
self.latent_dim = latent_dim
self.num_decoder_tokens = num_decoder_tokens
self.num_encoder_tokens = num_encoder_tokens
self.encoder_input = layers.Input(shape=(None, self.num_encoder_tokens), name="encoder_input")
self.encoder_lstm = layers.LSTM(self.latent_dim, return_state=True, name="encoder_lstm")
_, state_h, state_c = self.encoder_lstm(self.encoder_input)
self.encoder_state = [state_h, state_c]
self.decoder_input = layers.Input(shape=(None, self.num_decoder_tokens), name="decoder_input")
self.decoder_lstm = layers.LSTM(self.latent_dim, return_sequences=True, return_state=True, name="decoder_lstm")
decoder_lstm_output, _, _ = self.decoder_lstm(self.decoder_input, initial_state=self.encoder_state)
self.decoder_dense = layers.Dense(num_decoder_tokens, activation="softmax", name="decoder_dense")
dense_output = self.decoder_dense(decoder_lstm_output)
self.training_model = keras.Model([self.encoder_input, self.decoder_input], dense_output)
if model_weights:
self.training_model.load_weights(model_weights)
self.encoder_model, self.decoder_model = self.create_inference_models()
def create_inference_models(self):
encoder_model = keras.Model(self.encoder_input, self.encoder_state, name="encoder_model")
self.decoder_state_input_h = layers.Input(shape=(self.latent_dim,), name="decoder_state_input_h")
self.decoder_state_input_c = layers.Input(shape=(self.latent_dim,), name="decoder_state_input_c")
decoder_states_inputs = [self.decoder_state_input_h, self.decoder_state_input_c]
decoder_outputs, state_h, state_c = self.decoder_lstm(
self.decoder_input, initial_state=decoder_states_inputs)
self.decoder_states = [state_h, state_c]
decoder_output = self.decoder_dense(decoder_outputs)
decoder_model = keras.Model(
[self.decoder_input] + decoder_states_inputs,
[decoder_output] + self.decoder_states,
name="decoder_model")
return [encoder_model, decoder_model]
# model.create_inference_models()
# enc_model = model.encoder_model
# enc_model.summary()
# plot_model(enc_model, show_shapes=True)
<file_sep>/manythings/models/Model.py
"""
A model is a combination of the neural net and the
data used to train it.
"""
from pathlib import Path
from typing import Callable, Dict
from tensorflow import keras as KerasModel
from manythings.util_yaml import yaml_dump, yaml_loader
from tensorflow.keras.optimizers import SGD
DIRNAME = Path(__file__).parents[1].resolve() / "weights"
class Model():
def __init__(
self,
dataset_cls: type,
network_fn,
net_args: Dict,
dataset_args: Dict = None,
):
self.name = f"{self.__class__.__name__}_{dataset_cls.__name__}_{network_fn.__name__}"
if dataset_args == None:
dataset_args = {}
self.data = dataset_cls()
self.data.load_or_generate()
self.data.preprocess()
self.data_shapes = self.data.io_shapes
self.net_args = net_args
self.network = network_fn(num_encoder_tokens=self.data_shapes[0],
num_decoder_tokens=self.data_shapes[1])
self.network.summary()
@property
def weights_filename(self) -> str:
DIRNAME.mkdir(parent=True, exist_ok=True)
return str(DIRNAME / f"{self.name}_weights.h5")
def fit(self, callbacks):
config = self.net_args
sgd = SGD(lr=config["learn_rate"],
decay=config["decay"],
momentum=config["momentum"],
nesterov=True)
# if callbacks in None:
# callbacks = []
self.network.compile(loss="categorical_crossentropy",
optimizer=sgd,
metrics=["accuracy"])
self.network.fit(
[self.data.encoder_input_data, self.data.decoder_input_data],
self.data.decoder_target_data,
validation_split=0.2,
epochs=config["epochs"],
callbacks=callbacks)
<file_sep>/manythings/data/dta_ManyThings.py
"""
http://www.manythings.org/anki/ has a collection
of language pairs that can be used to train
seq2seq models for language translation
"""
import pathlib
import os
from manythings.data.util import download_data
import numpy as np
default_dir = pathlib.Path.cwd() / "manythings" / "datasets"
url = "http://www.manythings.org/anki/" # web url for language pairs datasets
class ManyThings():
def __init__(self, lang1_id: str = "fra", lang2_id: str = "eng"):
self.lang1_id = lang1_id
self.lang2_id = lang2_id
def load_or_generate(self, download_dir=default_dir):
pair_name = f"{self.lang1_id}-{self.lang2_id}"
pair_zip = f"{pair_name}.zip"
# data is should be in Datasets/pair_name
# if not, it is downloaded to that directory
data_parent_dir = os.path.join(default_dir, pair_name)
if not os.path.exists(data_parent_dir):
# dir = os.path.join(default_dir, pair_name)
os.mkdir(data_parent_dir)
download_data(data_parent_dir, pair_name, url + pair_zip)
if os.path.exists(data_parent_dir / f"{self.lang1_id}.txt"):
self.data_txt_file = data_parent_dir / f"{self.lang1_id}.txt"
else:
print("data not properly downloaded or extracted")
else:
data = os.path.join(data_parent_dir, f"{self.lang1_id}.txt")
if os.path.exists(data):
self.data_txt_file = data
else:
print("Data not found in parent directory")
def preprocess(self, num_samples=10000):
data_txt_file = self.data_txt_file
# Vectorize the data.
self.input_texts = []
target_texts = []
input_characters = set()
target_characters = set()
with open(data_txt_file, "r", encoding="utf-8") as f:
lines = f.read().split("\n")
for line in lines[:min(num_samples, len(lines) - 1)]:
input_text, target_text, _ = line.split("\t")
# We use "tab" as the "start sequence" character
# for the targets, and "\n" as "end sequence" character.
target_text = "\t" + target_text + "\n"
self.input_texts.append(input_text)
target_texts.append(target_text)
for char in input_text:
if char not in input_characters:
input_characters.add(char)
for char in target_text:
if char not in target_characters:
target_characters.add(char)
self.input_characters = sorted(list(input_characters))
self.target_characters = sorted(list(target_characters))
self.num_encoder_tokens = len(self.input_characters)
self.num_decoder_tokens = len(self.target_characters)
self.max_encoder_seq_length = max([len(txt) for txt in self.input_texts])
self.max_decoder_seq_length = max([len(txt) for txt in target_texts])
self.io_shapes = [self.num_encoder_tokens, self.num_decoder_tokens]
print("Number of samples:", len(self.input_texts))
print("Number of unique input tokens:", self.num_encoder_tokens)
print("Number of unique output tokens:", self.num_decoder_tokens)
print("Max sequence length for inputs:", self.max_encoder_seq_length)
print("Max sequence length for outputs:", self.max_decoder_seq_length)
self.input_token_index = dict([
(char, i) for i, char in enumerate(self.input_characters)
])
self.target_token_index = dict([
(char, i) for i, char in enumerate(self.target_characters)
])
self.encoder_input_data = np.zeros(
(len(self.input_texts), self.max_encoder_seq_length,
self.num_encoder_tokens),
dtype="float32")
self.decoder_input_data = np.zeros(
(len(self.input_texts), self.max_decoder_seq_length,
self.num_decoder_tokens),
dtype="float32")
self.decoder_target_data = np.zeros(
(len(self.input_texts), self.max_decoder_seq_length,
self.num_decoder_tokens),
dtype="float32")
for i, (input_text,
target_text) in enumerate(zip(self.input_texts, target_texts)):
for t, char in enumerate(input_text):
self.encoder_input_data[i, t, self.input_token_index[char]] = 1.0
self.encoder_input_data[i, t + 1:, self.input_token_index[" "]] = 1.0
for t, char in enumerate(target_text):
# decoder_target_data is ahead of decoder_input_data by one timestep
self.decoder_input_data[i, t, self.target_token_index[char]] = 1.0
if t > 0:
# decoder_target_data will be ahead by one timestep
# and will not include the start character.
self.decoder_target_data[i, t - 1,
self.target_token_index[char]] = 1.0
self.decoder_input_data[i, t + 1:, self.target_token_index[" "]] = 1.0
self.decoder_target_data[i, t:, self.target_token_index[" "]] = 1.0
return
if __name__ == "__main__":
data = ManyThings()
data.load_or_generate()
data.preprocess()
print("Done!")
<file_sep>/manythings/inference/infer.py
import numpy as np
from manythings.data.dta_ManyThings import ManyThings
from manythings.networks.nn_lstm import Seq2Seq
import pathlib
import os
def decode_and_translate(
input_seq, encoder_model, decoder_model,
num_decoder_tokens, target_char_index,
reverse_target_char_index, max_decoder_seq_length
):
encoder_model = encoder_model
decoder_model = decoder_model
# encode the input as state vectors
states_values = encoder_model.predict(input_seq)
# Generate empty target sequence of length 1
target_seq = np.zeros((1, 1, num_decoder_tokens))
# populate the first charector of the target sequence with the start charector
target_seq[0, 0, target_char_index["\t"]] = 1.0
# Sampling loop for a batch of sequences
# (To simplify, here we assume a batch size of one)
stop_condition = False
decoded_sentence = ""
while not stop_condition:
output_tokens, state_h, state_c = decoder_model.predict([target_seq] + states_values)
# Sample a token
sampled_token_index = np.argmax(output_tokens[0, -1, :])
sampled_char = reverse_target_char_index[sampled_token_index]
decoded_sentence += sampled_char
# Exit condition: either hit max length
# or find stop character.
if sampled_char == "\n" or len(decoded_sentence) > max_decoder_seq_length:
stop_condition = True
# Update the target sequence (of length 1).
target_seq = np.zeros((1, 1, num_decoder_tokens))
target_seq[0, 0, sampled_token_index] = 1.0
# Update states
states_value = [state_h, state_c]
return decoded_sentence
def translation_example(weights_name: str="nn_lstm_weights.hdf5"):
weights = pathlib.Path.cwd() / "saved_models" / "weights"
weights_path = os.path.join(weights, weights_name)
data = ManyThings()
data.load_or_generate()
data.preprocess()
encoder_input_data = data.encoder_input_data
num_encoder_tokens = data.num_encoder_tokens
num_decoder_tokens = data.num_decoder_tokens
input_texts = data.input_texts
model = Seq2Seq(
num_encoder_tokens=num_encoder_tokens, num_decoder_tokens=num_decoder_tokens,
model_weights=weights_path)
encoder_model, decoder_model = model.create_inference_models()
target_token_index = data.target_token_index
reverse_target_char_index = dict((i, char) for char, i in target_token_index.items())
max_decoder_seq_length = data.max_decoder_seq_length
for seq_index in range(3):
# Take one sequence (part of the training set)
# for trying out decoding.
input_seq = encoder_input_data[seq_index : seq_index + 1]
decoded_sentence = decode_and_translate(
input_seq,
encoder_model,
decoder_model, num_decoder_tokens, target_token_index,
reverse_target_char_index, max_decoder_seq_length)
print("-")
print("Input sentence:", input_texts[seq_index])
print("Decoded sentence:", decoded_sentence)
return
if __name__ == "__main__":
translation_example()
<file_sep>/requirements.txt
numpy==1.19.5
pyyaml
click
mlflow
wandb
tensorflow==2.2.0
<file_sep>/manythings/data/util.py
import tensorflow as tf
from zipfile import ZipFile
import os
import pandas as pd
def download_data(download_dir, filename, url, unzip=True):
# download file from given url
# download dir is an absolute path
file_path = os.path.join(download_dir, filename)
_ = tf.keras.utils.get_file(
file_path,
url,
)
if unzip:
with ZipFile(file_path) as zip:
zip.printdir()
print("Extracting files from: {file_path}...")
zip.extractall(download_dir)
print("File extraction done !")
| 0b8c187f15d4aa440b70a68bd1d6dab233042b06 | [
"Markdown",
"Python",
"Text"
] | 10 | Markdown | ZithaChitra/seq2seq_lstms | 33b49e73475dc98703029465ea7358187e9ac5c7 | 0d5af8ef043920da403fe9df6ceebf99037d4203 |
refs/heads/master | <file_sep>$(function () {
var iddocente= document.getElementById("search_term").value;
setDocente();
loadTeaching(iddocente, "/sedoc/Teacher/GetLaboresDocente/");
function setDocente() {
$("#work-area").html("");
$("#work-area").append("<table id='TableidTeaching' class='list' style='width:100%'>" +
"<thead><tr><th colspan=3>Labores</th></tr>" +
"<tr class='sub'><th>Labor</th><th>Tipo De Labor</th><th style='width:130px;'>Acción</th></tr></thead>" +
"<tbody></tbody>" +
"</table><br/>");
}
function loadTeaching(idD, route) {
$.getJSON(route, { term: idD }, function (data) {
$.each(data, function (key, val) {
$("#TableidTeaching tbody").append("<tr>" +
"<td>" + val['tipoLabor'] + "</td>" +
"<td>" + val['descripcion'] + "</td>" +
"<td><a class='edit' href='/sedoc/Teacher/Evaluar/" + val['idlabor'] + "'>Evaluar</a> </td>" +
"</tr>");
});
});
}
});<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcSEDOC.Models;
using System.Data.Objects;
using System.Web.Security;
using System.Collections;
using System.Security.Cryptography;
using System.Text;
namespace MvcSEDOC.Controllers
{
public class UserController : SEDOCController
{
public ActionResult Index()
{
return RedirectToAction("Login", "User"); // asi redirijo
}
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(usuario unUsuario)
{
// inicio cambio edv
//string contrasena = "";
// fin cambio edv
if (string.IsNullOrEmpty(unUsuario.emailinstitucional) || string.IsNullOrEmpty(unUsuario.password))
{
ViewBag.Error = "Login o password no pueden estar vacíos";
ViewBag.UserName = "Anónimo";
return View(unUsuario);
}
else
{ //determinar si el usuario existe o no
if (!unUsuario.emailinstitucional.EndsWith("@unicauca.edu.co"))
{
unUsuario.emailinstitucional += "@unicauca.edu.co";
}
if (!Membership.ValidateUser(unUsuario.emailinstitucional, unUsuario.password))
{
ViewBag.Error = "Login o password incorrectos";
ViewBag.UserName = "Anónimo";
return View(unUsuario);
}
try
{
// inicio cambio edv
unUsuario.password = <PASSWORD>(unUsuario.password);
// fin cambio edv
usuario loginusuario = dbEntity.usuario.Single(u => u.emailinstitucional == unUsuario.emailinstitucional && u.password == unUsuario.password);
ViewBag.UserName = unUsuario.emailinstitucional;
FormsAuthentication.SetAuthCookie(unUsuario.emailinstitucional, false);
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
Session["logedUser"] = loginusuario;
Session["currentAcadPeriod"] = ultimoPeriodo.idperiodo;
if (loginusuario.rol.Trim().Equals("Estudiante"))
{
Session["periodoActual"] = 0;
ArrayList lista_roles = new ArrayList();
lista_roles.Add("Estudiante");
Session["roles"] = lista_roles;
return RedirectToAction("Index", "Student");
}
else if (loginusuario.rol.Trim().Equals("Docente"))
{
docente docente = dbEntity.docente.Single(d => d.idusuario == loginusuario.idusuario);
esjefe unjefe = dbEntity.esjefe.FirstOrDefault(es => es.iddocente == docente.iddocente && es.idperiodo == ultimoPeriodo.idperiodo);
// modificado 4 febrero
dirige docdirige = null;
var docenteDocencia = (from d in dbEntity.dirige
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
where lab.idperiodo.Equals(ultimoPeriodo.idperiodo)
where d.idusuario.Equals(docente.idusuario)
select new docenciaSIGELA { nombremateria = "m", grupo = "m", codigomateria = "m" }).Distinct().ToList();
if (docenteDocencia.Count() > 0)
{
docdirige = dbEntity.dirige.FirstOrDefault(l => l.idusuario == docente.idusuario);
}
departamento depto = dbEntity.departamento.Single(d => d.iddepartamento == docente.iddepartamento);
ArrayList lista_roles = new ArrayList();
string redireccion;
Session["depto"] = depto;
Session["periodoActual"] = 0;
Session["docente"] = docente;
Session["docenteId"] = docente.idusuario;
redireccion = "Teacher";
lista_roles.Add("Teacher");
if (docdirige != null)
{
//verificar si es jefe de labor
lista_roles.Add("WorkChief");
redireccion = "WorkChief";
}
if (unjefe != null)
{
Session["docente"] = docente;
lista_roles.Add("DepartmentChief");
redireccion = "DepartmentChief";
}
//INICIO ADICIONADO POR CLARA
adminfacultad adminfac = dbEntity.adminfacultad.FirstOrDefault(q => q.idusuario == loginusuario.idusuario);
Session["adminfac"] = adminfac;
if (adminfac != null)
{
//verificar si es administrador de facultad
facultad facultad = dbEntity.facultad.Single(q => q.idfacultad == adminfac.idfacultad);
Session["fac"] = facultad;
lista_roles.Add("AdminFac");
redireccion = "AdminFac";
}
//FIN ADICONADO POR CLARA
lista_roles.Reverse();
Session["roles"] = lista_roles;
return RedirectToAction("Index", redireccion);
}
else if (loginusuario.rol.Trim().Equals("Coordinador"))
{
Session["periodoActual"] = 0;
usuario docente = dbEntity.usuario.Single(d => d.idusuario == loginusuario.idusuario);
dirige docdirige = dbEntity.dirige.FirstOrDefault(l => l.idusuario == docente.idusuario);
Session["docenteId"] = docente.idusuario;
Session["docente"] = docente;
string redireccion = "Teacher";
ArrayList lista_roles = new ArrayList();
lista_roles.Add("Coordinador");
lista_roles.Add("WorkChief");
redireccion = "WorkChief";
lista_roles.Reverse();
Session["roles"] = lista_roles;
return RedirectToAction("Index1", redireccion);
}// FIN NUEVO 28
else if (loginusuario.rol.Trim().Equals("Administrador"))
{
Session["periodoActual"] = 0;
ArrayList lista_roles = new ArrayList();
lista_roles.Add("Admin");
Session["roles"] = lista_roles;
return RedirectToAction("Index", "Admin");
}
else //Externo
{
Session["periodoActual"] = 0;
dirige usudirige = dbEntity.dirige.SingleOrDefault(l => l.idusuario == unUsuario.idusuario);
if (usudirige != null)
{
string redireccion = "WorkChief";
ArrayList lista_roles = new ArrayList();
lista_roles.Add("WorkChief");
lista_roles.Reverse();
Session["roles"] = lista_roles;
return RedirectToAction("Index", redireccion);
}
}
return RedirectToAction("Login", "User");
}
catch (Exception ex)
{
Utilities.ManageException(ex, Server.MapPath(@"..\generalLog.txt"));
ViewBag.Error = "Login o password incorrectos";
}
}
return View(unUsuario);
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetAcademicPeriods()
{
var periods = dbEntity.periodo_academico.Select(q => new { idperiodo = q.idperiodo, anio = q.anio, numeroperiodo = q.numeroperiodo }).OrderBy(q => q.idperiodo).ToList();
return Json(periods, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
public ActionResult ChangeCurrentAcademicPeriod(int current_academic_period, string controller_name, string view_name)
{
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
Session["currentAcadPeriod"] = current_academic_period;
int periodoSeleccionado = (int)Session["currentAcadPeriod"];
if (ultimoPeriodo.idperiodo == periodoSeleccionado)
{
Session["periodoActual"] = 0;
}
else
{
Session["periodoActual"] = 1;
}
return Redirect(Request.UrlReferrer.ToString());
}
}
}
<file_sep>$(function () {
var des = $("#descp").val();
var tipo = $("#tipo").val();
//var idlabor = $("#search_term").val();
var idlabor = document.getElementById("search_term").value;
setWorkId();
//loadWork(idlabor, "/sedoc/DepartmentChief/SearchProblemasLabor/");
loadWork(idlabor,tipo);
var searchVar = "/sedoc/DepartmentChief/searchTeching/";
function setWorkId() {
$("#work-area").html("");
$("#work-area").append("<table id='TableidWork' class='report' style='width:100%'>" +
"<thead><tr><th colspan=2>Detalles De "+ des + "</th></tr></thead>" +
"<tbody></tbody>" +
"</table><br/>");
}
function loadWork(idL, tip) {
$.getJSON("/sedoc/DepartmentChief/SearchProblemasLabor/", { id: idL, term: tip }, function (data) {
$.each(data, function (key, val) {
$("#TableidWork tbody").append("<tr><th colspan=4>Docente " + val['docente'] + "</th></tr>" +
"<tr><td colspan=2 aling='center'><strong>Problema<strong></td></tr>" +
"<tr class='sub'><td style='width:20%' aling='center'><strong>Descripción</strong></td>" +
"<td>" + val['problemadescripcion'] + "</td></tr>" +
"<tr class='sub'><td style='width:20%' aling='center'><strong>Respuesta</strong></td>" +
"<td >" + val['problemarespuesta'] + "</td></tr>" +
"<tr><td colspan=2 ><strong>Solución</strong></td></tr>" +
"<tr class='sub'><td style='width:20%' aling='center'><strong>Descripción</strong></td>" +
"<td >" + val['soluciondescripcion'] + "</td></tr>" +
"<tr class='sub'><td style='width:20%' aling='center'><strong>Ubicación</strong></td>" +
"<td >" + val['solucionrespuesta'] + "</td></tr>" +
"</tr>");
});
autocompleteTeching();
});
}
function loadDateTable() {
var tabla = document.getElementById("TableidWork");
var numFilas = tabla.rows.length;
for (i = 0; i < numFilas - 2; i++) {
var idLabor = tabla.tBodies[0].rows[i].cells[0].innerHTML;
var idJefe = document.getElementById("idJL" + idLabor).value;
if (idJefe != "") {
//metodo que guarde los datos en la BD
$.getJSON("/sedoc/DepartmentChief/saveChief/", { idL: idLabor, idJ: idJefe }, function (data) {
if (i == numFilas - 2) {
setTimeout(redireccionar, 1000);
}
});
}
}
}
function resultado(data) {
if (data.respuesta == 0) {
alert("Lo siento!, los datos no se pueden guardar... disculpame");
}
}
function redireccionar() {
//var iddocente = document.getElementById("search_term").value;
var pagina = "/sedoc/DepartmentChief/SetChief/" + $("#depto").val();
location.href = pagina;
}
function autocompleteTeching() {
$(".search_Teching").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
$("#idJL" + $(this).attr("id")).val(ui.item.id);
}
}
});
save();
}
//adiciona los botones en la ventana del diajogo guardar
$("#dialogSaveGroupConfirm").dialog({
resizable: false,
autoOpen: false,
height: 140,
modal: true,
buttons: {
"Guardar": function () {
loadDateTable();
$(this).dialog("close");
},
Cancelar: function () {
$(this).dialog("close");
}
}
});
//Cuando el evento click es capturado en el enlace guardar abre el dialogo
function save() {
$('#save').click(function () {
$('#dialogSaveGroupConfirm').dialog('open');
return false;
});
}
});
<file_sep>$(function () {
/************* VARIABLES *********************/
var searchQuestionnaireVar = "/sedoc/AdminFac/SearchQuestionnaire/";
var searchGroupVar = "/sedoc/AdminFac/SearchGroup/";
var groupname = $("#nombre"),
grouppercent = $("#porcentaje"),
allFields = $([]).add(groupname).add(grouppercent),
tips = $(".validateTips");
/*****************FUNCIONES AUXILIARES*****************************/
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("El tamaño del " + n + " debe estar entre " +
min + " y " + max + ".");
return false;
} else {
return true;
}
}
function checkRange(o, n, min, max) {
if (!isNaN(parseFloat(o.val()))) {
var num = parseFloat(o.val());
if (num < min || num > max) {
o.addClass("ui-state-error");
updateTips("El rango del " + n + " debe estar entre " +
min + " y " + max + ".");
return false;
} else {
return true;
}
} else {
o.addClass("ui-state-error");
updateTips("El valor del " + n + " debe ser un numero entre " +
min + " y " + max + ".");
return false;
}
}
/****** Inicializaciones JQuery *******/
$("#search_term").autocomplete({
source: searchQuestionnaireVar,
minLength: 1,
select: function (event, ui) {
$("#work-area").html("");
$("#work-area").append("<table id='TableQuestionnaire' class='list' style='width:100%'>" +
"<thead><tr><th colspan=3>" + ui.item.value + "</th></tr>" +
"<tr class='sub'>" +
"<th>Grupo</th>" +
"<th style='width:130px;'>Acción</th></tr>" +
"</thead></table>" +
"<div id='sortdiv' style='width:100%;'>" +
"<ul id='sortable'></ul>" +
"</div><br/>");
loadGroups(ui.item.id, "/sedoc/AdminFac/GetQuestionnaireGroups/");
loadSortable(ui.item.id);
}
});
$('#dialogEditGroup').dialog({
autoOpen: false,
width: 400,
height: 300,
modal: true,
buttons: {
"Guardar": function () {
var bValid = true;
allFields.removeClass("ui-state-error");
bValid = bValid && checkLength(groupname, "grupo", 3, 250);
bValid = bValid && checkRange(grouppercent, "porcentaje", 1, 100);
if (bValid) {
allFields.removeClass("ui-state-error");
SaveGroup("/sedoc/AdminFac/EditGroup/", $(this));
$(this).dialog("close");
}
},
"Cancelar": function () {
allFields.removeClass("ui-state-error");
$(this).dialog("close");
}
}
});
$("#dialogDeleteGroupConfirm").dialog({
resizable: false,
autoOpen: false,
height: 140,
modal: true,
buttons: {
"Eliminar": function () {
DeleteGroup("/sedoc/AdminFac/DeleteGroup/", $(this));
},
Cancelar: function () {
$(this).dialog("close");
}
}
});
function loadSortable(idq) {
$("#sortable").sortable({
placeholder: "ui-state-highlight",
update: function (event, ui) {
var items = $("#sortable").sortable("toArray");
var arr = [];
$.each(items, function (key, val) {
var idval = val.replace("listElement_", "");
var obj = { id: idval }
arr.push(obj);
});
var data2send = JSON.stringify(arr);
$.ajax({
cache: false,
url: "/sedoc/AdminFac/SortGroups/?stridq=" + idq,
type: 'post',
dataType: 'json',
data: data2send,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data != null) {
$.each(data, function (key, val) {
setEditAction(val['id'], val['label'], val['pos'], val['idc'], val['porc']);
});
} else {
alert("Lo siento!, ocurrio un error ... disculpame")
}
}
});
}
});
$("#sortable").disableSelection();
}
/**************** FUNCIONES AUXILIARES *****************/
function DeleteGroup(route, jquerydialog) {
var idg = $('#idgrupo').val();
if (idg == "") {
alert("El grupo no puede ser eliminado.");
} else {
var grup = '{ "id": ' + idg + ' }';
var request = $.ajax({
cache: false,
url: route,
type: 'POST',
dataType: 'json',
data: grup,
contentType: 'application/json; charset=utf-8',
success: function (data) {
deletedResponse(data, jquerydialog);
}
});
}
}
function SaveGroup(route, jquerydialog) {
var group = getGroup();
if (group != null) {
var request = $.ajax({
cache: false,
url: route,
type: 'POST',
dataType: 'json',
data: group,
contentType: 'application/json; charset=utf-8',
success: function (data) {
savedResponse(data, jquerydialog);
setEditAction(data.idgrupo, data.nombre, data.orden, data.idcuestionario, data.porcentaje);
}
});
}
}
function deletedResponse(data, jquerydialog) {
if (data.idgrupo != 0) {
$('#btnDel' + data.idgrupo).parent().parent().parent().parent().remove();
jquerydialog.dialog("close");
} else {
alert("Lo siento!, la eliminación no se pudo efectuar ... disculpame");
}
}
function savedResponse(data, jquerydialog) {
if (data.idgroup != 0) {
$('#lblEdt' + data.idgrupo).html(data.nombre);
allFields.val("").removeClass("ui-state-error");
updateTips("");
jquerydialog.dialog("close");
// $('#btnDel' + data.idgrupo).parent().parent().find("td").eq(1).html(data.nombre);
// jquerydialog.dialog("close");
} else {
alert("Lo siento!, el registro no se pudo efectuar ... disculpame");
}
}
function setEditAction(idG, nameG, orden, idQ, porc) {
$('#btnEdit' + idG).click(function () {
$('#dialogEditGroup').dialog('open');
$("#idgrupo").val(idG);
$('#nombre').val(nameG);
$("#orden").val(orden);
$("#idcuestionario").val(idQ);
$("#porcentaje").val(porc);
return false;
});
$('#btnDel' + idG).click(function () {
$('#dialogDeleteGroupConfirm').dialog('open');
$('#idgrupo').val(idG);
return false;
});
}
function setQuestionnaireId(ui) {
$("#idQuestionnaire").val(ui.item.id);
$("#work-area").html("");
}
function getGroup() {
var idg = $("#idgrupo").val();
var nom = $("#nombre").val();
var idq = $("#idcuestionario").val();
var ord = $("#orden").val();
var por = $("#porcentaje").val();
return (idg == "" || nom == "" || idq == "" || ord == "" || por == "") ? null : '{ "idgrupo": "' + idg + '", "nombre": "' + nom + '","idcuestionario": "' + idq + '","orden": "' + ord + '","porcentaje": "' + por + '" }';
}
function loadGroups(idQ, route) {
$.getJSON(route, { term: idQ }, function (data) {
$.each(data, function (key, val) {
$("#sortable").append("<li id='listElement_" + val["id"] + "'><table class=list' style='width:100%;'><tr>" +
"<td id='lblEdt" + val['id'] + "'>" + val['label'] + "</td>" +
"<td style='width:130px;'><a href='#' class='edit' id='btnEdit" + val['id'] + "'>Editar</a> |" +
" <a class='delete' href='#' id='btnDel" + val["id"] + "'>Eliminar</a>" +
"</td>" +
"</tr>");
setEditAction(val['id'], val['label'], val['pos'], val['idc'], val['porc']);
});
});
}
});
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcSEDOC.Models;
using System.Data;
using System.Data.Entity;
using System.Diagnostics;
using System.Security.Cryptography;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace MvcSEDOC.Controllers
{
public class TeacherController : SEDOCController
{
public static AutoevaluacionDocente AutoevaluacionDocenteReporte;
// NUEVO 29
public object SessionValue(string keyValue)
{
try
{
return Session[keyValue];
}
catch
{
return RedirectPermanent("/sedoc");
}
}
public double Calificacion(int n1, int n2, int n3, int totalHoras, int totallabor)
{
if (n1 == -1 && n2 == -1 && n3 == -1)
{
return -1;
}
int divisor = 3;
if (n1 == -1) { n1 = 0; divisor--; }
if (n2 == -1) { n2 = 0; divisor--; }
if (n3 == -1) { n3 = 0; divisor--; }
double nota1 = Double.Parse(n1.ToString());
double nota2 = Double.Parse(n2.ToString());
double nota3 = Double.Parse(n3.ToString());
double totalH = Double.Parse(totalHoras.ToString());
double totalL = Double.Parse(totallabor.ToString());
double divicion = (nota1 + nota2 + nota3) / divisor;
double porcentaje = (((100 * totalL) / totalH) / 100);
double resultado = divicion * porcentaje;
return System.Math.Round(resultado, 2);
//return System.Math.Round((((nota1 + nota2 + nota3) / divisor) * (((100 * totalL) / totalH)/100)), 2);
}
// FIN NUEVO 29
[Authorize]
public ActionResult ChangePass()
{
int periodoActualSelec = 0;
periodoActualSelec = (int)SessionValue("periodoActual");
if (periodoActualSelec == 1)
{
return RedirectPermanent("/Teacher/Index");
}
ViewBag.optionmenu = 1;
return View();
}
[Authorize]
public ActionResult ChangePass1()
{
int periodoActualSelec = 0;
periodoActualSelec = (int)SessionValue("periodoActual");
if (periodoActualSelec == 1)
{
return RedirectPermanent("/Teacher/Index");
}
ViewBag.Value1 = "";
ViewBag.Value2 = "";
ViewBag.Value3 = "";
string anterior = "";
string nueva = "";
string repite = "";
string claveA = "";
int campo1 = 0;
int campo2 = 0;
int campo3 = 0;
//int entradas = 7;
//Boolean entro = false;
//Boolean error = false;
anterior = Request.Form["anterior"];
if (anterior == "")
{
campo1 = 1;
ViewBag.Error1 = "entro";
}
else
{
ViewBag.Value1 = anterior;
}
nueva = Request.Form["nueva"];
if (nueva == "")
{
campo2 = 1;
ViewBag.Error2 = "entro";
}
else
{
ViewBag.Value2 = nueva;
}
repite = Request.Form["repite"];
if (repite == "")
{
campo3 = 1;
ViewBag.Error3 = "entro";
}
else
{
ViewBag.Value3 = repite;
}
ViewBag.optionmenu = 1;
if (campo1 == 1 || campo2 == 1 || campo3 == 1)
{
ViewBag.Error = "Los campos con asterisco son obligatorios";
return View();
}
claveA = AdminController.md5(anterior);
try
{
docente logueado = (docente)SessionValue("docente");
usuario NuevaContrasena = dbEntity.usuario.Single(u => u.idusuario == logueado.idusuario && u.password == <PASSWORD>);
if (nueva != repite)
{
ViewBag.Error = "No coinciden la nueva contraseña con la anterior";
return View();
}
else
{
AdminController oControl = new AdminController();
if (!oControl.ActualizarContrasenaUsuarioActual(nueva, anterior))
{
throw new Exception("Invalid Password");
}
nueva = AdminController.md5(nueva);
NuevaContrasena.password = <PASSWORD>;
// dbEntity.usuario.Attach(NuevaContrasena);
dbEntity.ObjectStateManager.ChangeObjectState(NuevaContrasena, EntityState.Modified);
dbEntity.SaveChanges();
ViewBag.Value1 = null;
ViewBag.Value2 = null;
ViewBag.Value3 = null;
ViewBag.Message = "La contraseña se cambio exitosamente";
return View();
}
}
catch
{
ViewBag.Error = "La contraseña anterior es incorrecta";
return View();
}
}
// fin cambiar contraseña
// nuevo 2 febero
public ActionResult ShowScores(int idusuario)
{
ViewBag.optionmenu = 1;
ViewBag.reporte = crearReporte(idusuario);
return View();
}
public ConsolidadoDocente crearReporte(int idUsuario)
{
departamento departamento = (departamento)SessionValue("depto");
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
docente docenteactual = (docente)SessionValue("docente");
int idjefe = docenteactual.idusuario;
usuario jefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idjefe);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
ConsolidadoDocente reporte = new ConsolidadoDocente() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = jefe.nombres + " " + jefe.apellidos, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
List<ResEvaluacionLabor> labores = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join ev in dbEntity.evaluacion on p.idevaluacion equals ev.idevaluacion
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper && u.idusuario == idUsuario
select new ResEvaluacionLabor { idlabor = l.idlabor, evalest = (int)ev.evaluacionestudiante, evalauto = (int)ev.evaluacionautoevaluacion, evaljefe = (int)ev.evaluacionjefe }).ToList();
// NUEVO 1 FEBRERO
//List<ResEvaluacionLabor> OtrasLabores = (from u in dbEntity.usuario
// // join d in dbEntity.docente on u.idusuario equals d.idusuario
// join p in dbEntity.dirige on u.idusuario equals p.idusuario
// join ev in dbEntity.evaluacion on p.idevaluacion equals ev.idevaluacion
// join l in dbEntity.labor on p.idlabor equals l.idlabor
// join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
// where l.idperiodo == currentper && u.idusuario == idUsuario
// select new ResEvaluacionLabor { idlabor = l.idlabor, evalest = (int)ev.evaluacionestudiante, evalauto = (int)ev.evaluacionautoevaluacion, evaljefe = (int)ev.evaluacionjefe }).ToList();
//OtrasLabores = setLabor(OtrasLabores, 0);
// FIN NUEVO 1 FEBRERO
labores = setLabor(labores, 1);
//// INICIO NUEVO 1 FEBRERO
//foreach (ResEvaluacionLabor lab in OtrasLabores)
//{
// labores.Add(lab);
//}
// FIN NUEVO 1 FEBRERO
reporte.totalhorassemana = (Double)labores.Sum(q => q.horasxsemana);
reporte.evaluacioneslabores = DepartmentChiefController.calcularPonderados(labores);
reporte.totalporcentajes = (Double)reporte.evaluacioneslabores.Sum(q => q.porcentaje);
reporte.notafinal = (Double)reporte.evaluacioneslabores.Sum(q => q.acumula);
return reporte;
}
public List<ResEvaluacionLabor> setLabor(List<ResEvaluacionLabor> lista, int opcion)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otra;
foreach (ResEvaluacionLabor labor in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (gestion != null)
{
labor.tipolabor = "Gestión";
labor.tipolaborcorto = "GES";
if (opcion == 1)
{
labor.descripcion = gestion.nombrecargo;
}
else
{
labor.descripcion = "Dirige " + gestion.nombrecargo;
}
labor.horasxsemana = (int)gestion.horassemana;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (social != null)
{
labor.tipolabor = "Social";
labor.tipolaborcorto = "SOC";
if (opcion == 1)
{
labor.descripcion = social.nombreproyecto;
}
else
{
labor.descripcion = "Dirige " + social.nombreproyecto;
}
labor.horasxsemana = (int)social.horassemana;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (investigacion != null)
{
labor.tipolabor = "Investigación";
labor.tipolaborcorto = "INV";
if (opcion == 1)
{
labor.descripcion = investigacion.nombreproyecto;
}
else
{
labor.descripcion = "Dirige " + investigacion.nombreproyecto;
}
labor.horasxsemana = (int)investigacion.horassemana;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGrado != null)
{
labor.tipolabor = "Trabajo de Grado";
labor.tipolaborcorto = "TDG";
if (opcion == 1)
{
labor.descripcion = trabajoDeGrado.titulotrabajo;
}
else
{
labor.descripcion = "Dirige " + trabajoDeGrado.titulotrabajo;
}
labor.horasxsemana = (int)trabajoDeGrado.horassemana;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
labor.tipolabor = "Trabajo de Grado Investigación";
labor.tipolaborcorto = "TDGI";
if (opcion == 1)
{
labor.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
}
else
{
labor.descripcion = "Dirige " + trabajoDeGradoInvestigacion.titulotrabajo;
}
labor.horasxsemana = (int)trabajoDeGradoInvestigacion.horassemana;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (desarrolloProfesoral != null)
{
labor.tipolabor = "Desarrollo Profesoral";
labor.tipolaborcorto = "DP";
if (opcion == 1)
{
labor.descripcion = desarrolloProfesoral.nombreactividad;
}
else
{
labor.descripcion = "Dirige " + desarrolloProfesoral.nombreactividad;
}
labor.horasxsemana = (int)desarrolloProfesoral.horassemana;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (docencia != null)
{
materia materia = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
labor.tipolabor = "Docencia Directa";
labor.tipolaborcorto = "DD";
if (opcion == 1)
{
labor.descripcion = materia.nombremateria;
}
else
{
labor.descripcion = "Dirige " + materia.nombremateria;
}
labor.horasxsemana = (int)docencia.horassemana;
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (otra != null)
{
labor.tipolabor = "OTRA";
labor.tipolaborcorto = "OT";
if (opcion == 1)
{
labor.descripcion = otra.descripcion;
}
else
{
labor.descripcion = "Dirige " + otra.descripcion;
}
labor.horasxsemana = (int)otra.horassemana;
continue;
}
}
return lista;
}
[Authorize]
public ActionResult Index()
{
docente docente = (docente)SessionValue("docente");
return View(docente);
}
[Authorize]
public ActionResult MessegeTeach()
{
return View();
}
#region Labores
[Authorize]
public ActionResult selectWork()
{
docente docente = (docente)SessionValue("docente");
int currentper = (int)SessionValue("currentAcadPeriod");
var users = (from p in dbEntity.participa
join u in dbEntity.usuario on docente.idusuario equals u.idusuario
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
join ev in dbEntity.evaluacion on p.idevaluacion equals ev.idevaluacion
where l.idperiodo == currentper && p.iddocente == docente.iddocente
select new DocenteLabor { idlabor = l.idlabor,iddocente = docente.iddocente, nombres = u.nombres, apellidos = u.apellidos, rol = u.rol }).OrderBy(u => u.apellidos).ToList();
if (users.Count == 0)
{
return RedirectToAction("MessegeTeach", "Teacher");
}
users = setLaborTeach(users);
ViewBag.lista = users;
return View(docente);
}
//MODIFICADO POR CLARA
public List<DocenteLabor> setLaborTeach(List<DocenteLabor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
materia materia;
otras otra;
foreach (DocenteLabor jefe in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (gestion != null)
{
jefe.tipoLabor = "Gestión";
jefe.descripcion = gestion.nombrecargo;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (social != null)
{
jefe.tipoLabor = "Social";
jefe.descripcion = social.nombreproyecto;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (investigacion != null)
{
jefe.tipoLabor = "Investigación";
jefe.descripcion = investigacion.nombreproyecto;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGrado != null)
{
jefe.tipoLabor = "Trabajo De Grado";
jefe.descripcion = trabajoDeGrado.titulotrabajo;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
jefe.tipoLabor = "Trabajo De Grado De Investigación";
jefe.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (desarrolloProfesoral != null)
{
jefe.tipoLabor = "Desarrollo Profesoral";
jefe.descripcion = desarrolloProfesoral.nombreactividad;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (docencia != null)
{
jefe.tipoLabor = "Docencia";
materia = dbEntity.materia.SingleOrDefault(m => m.idmateria == docencia.idmateria);
jefe.descripcion = materia.nombremateria;
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (otra != null)
{
jefe.tipoLabor = "Otra";
jefe.descripcion = otra.descripcion;
continue;
}
}
return lista;
}
//MODIFICADO POR CLARA EDV
// NUEVO 29
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchLabor(string term)
{
docente docente = (docente)SessionValue("docente");
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
var users = new List<DocenteLabor>();
var horasgestion = new List<Horas>();
var horassocial = new List<Horas>();
var horasinvestigacion = new List<Horas>();
var horasstrabajodegrado = new List<Horas>();
var horasstrabajodeinvestigacion = new List<Horas>();
var horasdesarrolloprofe = new List<Horas>();
var horasdocencia = new List<Horas>();
var horasOtras = new List<Horas>();
int totalgestion = 0;
int totalsocial = 0;
int totalinvestigacion = 0;
int totaltrabajodegrado = 0;
int totaltrabajoinvestigacion = 0;
int totaldesarrollo = 0;
int totaldocencia = 0;
int totalOtras = 0;
int totalhoras = 0;
horasgestion = (from p in dbEntity.participa
join g in dbEntity.gestion on p.idlabor equals g.idlabor
join l in dbEntity.labor on p.idlabor equals l.idlabor
where l.idperiodo.Equals(PeriodoSeleccionado.idperiodo)
where p.iddocente == docente.iddocente
select new Horas { Horassemanales = (int)g.horassemana, semanaslaborales = (int)g.semanaslaborales }).ToList();
horassocial = (from p in dbEntity.participa
join s in dbEntity.social on p.idlabor equals s.idlabor
join l in dbEntity.labor on p.idlabor equals l.idlabor
where l.idperiodo.Equals(PeriodoSeleccionado.idperiodo)
where p.iddocente == docente.iddocente
select new Horas { Horassemanales = (int)s.horassemana, semanaslaborales = (int)s.semanaslaborales }).ToList();
horasinvestigacion = (from p in dbEntity.participa
join i in dbEntity.investigacion on p.idlabor equals i.idlabor
join l in dbEntity.labor on p.idlabor equals l.idlabor
where l.idperiodo.Equals(PeriodoSeleccionado.idperiodo)
where p.iddocente == docente.iddocente
select new Horas { Horassemanales = (int)i.horassemana, semanaslaborales = (int)i.semanaslaborales }).ToList();
horasstrabajodegrado = (from p in dbEntity.participa
join tg in dbEntity.trabajodegrado on p.idlabor equals tg.idlabor
join l in dbEntity.labor on p.idlabor equals l.idlabor
where l.idperiodo.Equals(PeriodoSeleccionado.idperiodo)
where p.iddocente == docente.iddocente
select new Horas { Horassemanales = (int)tg.horassemana, semanaslaborales = (int)tg.semanaslaborales }).ToList();
horasstrabajodeinvestigacion = (from p in dbEntity.participa
join tgi in dbEntity.trabajodegradoinvestigacion on p.idlabor equals tgi.idlabor
join l in dbEntity.labor on p.idlabor equals l.idlabor
where l.idperiodo.Equals(PeriodoSeleccionado.idperiodo)
where p.iddocente == docente.iddocente
select new Horas { Horassemanales = (int)tgi.horassemana, semanaslaborales = (int)tgi.semanaslaborales }).ToList();
horasdesarrolloprofe = (from p in dbEntity.participa
join dp in dbEntity.desarrolloprofesoral on p.idlabor equals dp.idlabor
join l in dbEntity.labor on p.idlabor equals l.idlabor
where l.idperiodo.Equals(PeriodoSeleccionado.idperiodo)
where p.iddocente == docente.iddocente
select new Horas { Horassemanales = (int)dp.horassemana, semanaslaborales = (int)dp.semanaslaborales }).ToList();
horasdocencia = (from p in dbEntity.participa
join d in dbEntity.docencia on p.idlabor equals d.idlabor
join l in dbEntity.labor on p.idlabor equals l.idlabor
where l.idperiodo.Equals(PeriodoSeleccionado.idperiodo)
where p.iddocente == docente.iddocente
select new Horas { Horassemanales = (int)d.horassemana, semanaslaborales = (int)d.semanaslaborales }).ToList();
horasOtras = (from p in dbEntity.participa
join ot in dbEntity.otras on p.idlabor equals ot.idlabor
join l in dbEntity.labor on p.idlabor equals l.idlabor
where l.idperiodo.Equals(PeriodoSeleccionado.idperiodo)
where p.iddocente == docente.iddocente
select new Horas { Horassemanales = (int)ot.horassemana, semanaslaborales = 4 }).ToList();
foreach (Horas h in horasgestion)
{
//totalgestion = totalgestion + h.semanaslaborales * h.Horassemanales;
totalgestion = totalgestion + h.Horassemanales;
}
foreach (Horas h in horassocial)
{
//totalsocial = totalsocial + h.semanaslaborales * h.Horassemanales;
totalsocial = totalsocial + h.Horassemanales;
}
foreach (Horas h in horasinvestigacion)
{
//totalinvestigacion = totalinvestigacion + h.semanaslaborales * h.Horassemanales;
totalinvestigacion = totalinvestigacion + h.Horassemanales;
}
foreach (Horas h in horasstrabajodegrado)
{
//totaltrabajodegrado = totaltrabajodegrado + h.semanaslaborales * h.Horassemanales;
totaltrabajodegrado = totaltrabajodegrado + h.Horassemanales;
}
foreach (Horas h in horasstrabajodeinvestigacion)
{
//totaltrabajoinvestigacion = totaltrabajoinvestigacion + h.semanaslaborales * h.Horassemanales;
totaltrabajoinvestigacion = totaltrabajoinvestigacion + h.Horassemanales;
}
foreach (Horas h in horasdesarrolloprofe)
{
//totaldesarrollo = totaldesarrollo + h.semanaslaborales * h.Horassemanales;
totaldesarrollo = totaldesarrollo + h.Horassemanales;
}
foreach (Horas h in horasdocencia)
{
//totaldocencia = totaldocencia + h.semanaslaborales * h.Horassemanales;
totaldocencia = totaldocencia + h.Horassemanales;
}
foreach (Horas h in horasOtras)
{
//totaldocencia = totaldocencia + h.semanaslaborales * h.Horassemanales;
totalOtras = totalOtras + h.Horassemanales;
}
totalhoras = totalgestion + totalsocial + totalinvestigacion + totaltrabajodegrado + totaltrabajoinvestigacion + totaldesarrollo + totaldocencia + totalOtras;
switch (term)
{
case "Gestión":
users = (from p in dbEntity.participa
join g in dbEntity.gestion on p.idlabor equals g.idlabor
join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join l in dbEntity.labor on g.idlabor equals l.idlabor
where p.iddocente == docente.iddocente && l.idperiodo == PeriodoSeleccionado.idperiodo
orderby p.idlabor
select new DocenteLabor { idlabor = p.idlabor, descripcion = g.nombrecargo, evaluacionestudiante = (int)e.evaluacionestudiante, evaluacionjefe = (int)e.evaluacionjefe, evaluacionauto = (int)e.evaluacionautoevaluacion, horasPorLabor = (int)g.horassemana }).ToList();
foreach (DocenteLabor d in users)
{
d.calificacion = Calificacion(d.evaluacionauto, d.evaluacionestudiante, d.evaluacionjefe, totalhoras, d.horasPorLabor);
}
break;
case "Social":
users = (from p in dbEntity.participa
join s in dbEntity.social on p.idlabor equals s.idlabor
join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join l in dbEntity.labor on s.idlabor equals l.idlabor
where p.iddocente == docente.iddocente && l.idperiodo == PeriodoSeleccionado.idperiodo
orderby p.idlabor
select new DocenteLabor { idlabor = p.idlabor, descripcion = s.nombreproyecto, evaluacionestudiante = (int)e.evaluacionestudiante, evaluacionjefe = (int)e.evaluacionjefe, evaluacionauto = (int)e.evaluacionautoevaluacion, horasPorLabor = (int) s.horassemana }).ToList();
foreach (DocenteLabor d in users)
{
d.calificacion = Calificacion(d.evaluacionauto, d.evaluacionestudiante, d.evaluacionjefe, totalhoras, d.horasPorLabor);
}
break;
case "Investigación":
users = (from p in dbEntity.participa
join i in dbEntity.investigacion on p.idlabor equals i.idlabor
join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join l in dbEntity.labor on i.idlabor equals l.idlabor
where p.iddocente == docente.iddocente && l.idperiodo == PeriodoSeleccionado.idperiodo
orderby p.idlabor
select new DocenteLabor { idlabor = p.idlabor, descripcion = i.nombreproyecto, evaluacionestudiante = (int)e.evaluacionestudiante, evaluacionjefe = (int)e.evaluacionjefe, evaluacionauto = (int)e.evaluacionautoevaluacion, horasPorLabor = (int)i.horassemana }).ToList();
foreach (DocenteLabor d in users)
{
d.calificacion = Calificacion(d.evaluacionauto, d.evaluacionestudiante, d.evaluacionjefe, totalhoras, d.horasPorLabor);
}
break;
case "Trabajo de grado":
users = (from p in dbEntity.participa
join tg in dbEntity.trabajodegrado on p.idlabor equals tg.idlabor
join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join l in dbEntity.labor on tg.idlabor equals l.idlabor
where p.iddocente == docente.iddocente && l.idperiodo == PeriodoSeleccionado.idperiodo
orderby p.idlabor
select new DocenteLabor { idlabor = p.idlabor, descripcion = tg.titulotrabajo, evaluacionestudiante = (int)e.evaluacionestudiante, evaluacionjefe = (int)e.evaluacionjefe, evaluacionauto = (int)e.evaluacionautoevaluacion, horasPorLabor = (int)tg.horassemana }).ToList();
foreach (DocenteLabor d in users)
{
d.calificacion = Calificacion(d.evaluacionauto, d.evaluacionestudiante, d.evaluacionjefe, totalhoras, d.horasPorLabor);
}
break;
case "Trabajo de grado investigacion":
users = (from p in dbEntity.participa
join tgi in dbEntity.trabajodegradoinvestigacion on p.idlabor equals tgi.idlabor
join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join l in dbEntity.labor on tgi.idlabor equals l.idlabor
where p.iddocente == docente.iddocente && l.idperiodo == PeriodoSeleccionado.idperiodo
orderby p.idlabor
select new DocenteLabor { idlabor = p.idlabor, descripcion = tgi.titulotrabajo, evaluacionestudiante = (int)e.evaluacionestudiante, evaluacionjefe = (int)e.evaluacionjefe, evaluacionauto = (int)e.evaluacionautoevaluacion, horasPorLabor = (int)tgi.horassemana }).ToList();
foreach (DocenteLabor d in users)
{
d.calificacion = Calificacion(d.evaluacionauto, d.evaluacionestudiante, d.evaluacionjefe, totalhoras, d.horasPorLabor);
}
break;
case "Desarrollo profesoral":
users = (from p in dbEntity.participa
join dp in dbEntity.desarrolloprofesoral on p.idlabor equals dp.idlabor
join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join l in dbEntity.labor on dp.idlabor equals l.idlabor
where p.iddocente == docente.iddocente && l.idperiodo == PeriodoSeleccionado.idperiodo
orderby p.idlabor
select new DocenteLabor { idlabor = p.idlabor, descripcion = dp.nombreactividad, evaluacionestudiante = (int)e.evaluacionestudiante, evaluacionjefe = (int)e.evaluacionjefe, evaluacionauto = (int)e.evaluacionautoevaluacion, horasPorLabor = (int)dp.horassemana }).ToList();
foreach (DocenteLabor d in users)
{
d.calificacion = Calificacion(d.evaluacionauto, d.evaluacionestudiante, d.evaluacionjefe, totalhoras, d.horasPorLabor);
}
break;
case "Docencia":
users = (from p in dbEntity.participa
join d in dbEntity.docencia on p.idlabor equals d.idlabor
join m in dbEntity.materia on d.idmateria equals m.idmateria
join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join l in dbEntity.labor on d.idlabor equals l.idlabor
where p.iddocente == docente.iddocente && l.idperiodo == PeriodoSeleccionado.idperiodo
orderby p.idlabor
select new DocenteLabor { idlabor = p.idlabor, descripcion = m.nombremateria, evaluacionestudiante = (int)e.evaluacionestudiante, evaluacionjefe = (int)e.evaluacionjefe, evaluacionauto = (int)e.evaluacionautoevaluacion, horasPorLabor = (int)d.horassemana }).ToList();
foreach (DocenteLabor d in users)
{
d.calificacion = Calificacion(d.evaluacionauto, d.evaluacionestudiante, d.evaluacionjefe, totalhoras, d.horasPorLabor);
}
break;
case "Otra":
users = (from p in dbEntity.participa
join ot in dbEntity.otras on p.idlabor equals ot.idlabor
join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join l in dbEntity.labor on ot.idlabor equals l.idlabor
where p.iddocente == docente.iddocente && l.idperiodo == PeriodoSeleccionado.idperiodo
orderby p.idlabor
select new DocenteLabor { idlabor = p.idlabor, descripcion = ot.descripcion, evaluacionestudiante = (int)e.evaluacionestudiante, evaluacionjefe = (int)e.evaluacionjefe, evaluacionauto = (int)e.evaluacionautoevaluacion, horasPorLabor = (int)ot.horassemana }).ToList();
foreach (DocenteLabor d in users)
{
d.calificacion = Calificacion(d.evaluacionauto, d.evaluacionestudiante, d.evaluacionjefe, totalhoras, d.horasPorLabor);
}
break;
}
return Json(users, JsonRequestBehavior.AllowGet);
}
// FIN NUEVO 29
//MODIFICADO POR CLARA EDV
[Authorize]
public ActionResult GetLaborType()
{
ViewBag.optionmenu = 1;
docente docente = (docente)SessionValue("docente");
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
var GenreLst = new List<int>();
var NameLabor = new List<String>();
var tipolabor = from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
where l.idperiodo.Equals(PeriodoSeleccionado.idperiodo)
where p.iddocente == docente.iddocente
orderby p.iddocente
select p.idlabor;
//join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
//where l.idperiodo == currentper && p.iddocente == docente.iddocente && p.idautoevaluacion == null
//select new DocenteLabor { idlabor = l.idlabor, iddocente = docente.iddocente, nombres = u.nombres, apellidos = u.apellidos, rol = u.rol }).OrderBy(u => u.apellidos).ToList();
//var tipolabor = from p in dbEntity.participa
// where p.iddocente == docente.iddocente
// //where p.idperiodo.Equals(ultimoPeriodo.idperiodo)
// orderby p.iddocente
// select p.idlabor;
GenreLst.AddRange(tipolabor.Distinct());
foreach (int id in GenreLst)
{
var gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == id);
if (gestion != null)
{
NameLabor.Add("Gestión");
continue;
}
var social = dbEntity.social.SingleOrDefault(g => g.idlabor == id);
if (social != null)
{
NameLabor.Add("Social");
continue;
}
var investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == id);
if (investigacion != null)
{
NameLabor.Add("Investigación");
continue;
}
var trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == id);
if (trabajoDeGrado != null)
{
NameLabor.Add("Trabajo de grado");
continue;
}
var trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == id);
if (trabajoDeGradoInvestigacion != null)
{
NameLabor.Add("Trabajo de grado investigacion");
continue;
}
var desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == id);
if (desarrolloProfesoral != null)
{
NameLabor.Add("Desarrollo profesoral");
continue;
}
var docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == id);
if (docencia != null)
{
NameLabor.Add("Docencia");
continue;
}
var otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == id);
if (otra != null)
{
NameLabor.Add("Otra");
continue;
}
}
//funcion que envia los datos a la lista desplegable del docente
ViewBag.tipoLabor = new SelectList(NameLabor.Distinct());
return View();
}
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetTechingWork(string term)
{
int idD = int.Parse(term);
int currentper = (int)SessionValue("currentAcadPeriod");
var work_ids = dbEntity.participa
.Join(dbEntity.labor,
part => part.idlabor,
lab => lab.idlabor,
(part, lab) => new { participa = part, labor = lab })
.Where(part_lab => part_lab.participa.iddocente == idD && part_lab.labor.idperiodo == currentper);
var gestion_works = dbEntity.gestion
.Join(work_ids,
gest => gest.idlabor,
w_ids => w_ids.labor.idlabor,
(gest, w_ids) => new { gestion = gest, work_ids = w_ids });
var response = gestion_works.Select(l => new { nombreL = l.gestion.nombrecargo, idL = l.gestion.idlabor, idLD = l.work_ids.participa.iddocente }).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
public ActionResult GetWork(string term)
{
int idL = int.Parse(term);
return View();
}
#endregion
// INICIO ADICIONADO POR CLARA
#region ADICIONADO POR CLARA
#region Labores Docentes
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetLaboresDocente(string term)
{
docente docente = (docente)SessionValue("docente");
int currentper = (int)SessionValue("currentAcadPeriod");
int iddocente = int.Parse(term);
var labores = (from p in dbEntity.participa
join u in dbEntity.usuario on docente.idusuario equals u.idusuario
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
where l.idperiodo == currentper && p.iddocente == docente.iddocente && e.calificacion == -1
select new DocenteLabor { idlabor = l.idlabor, iddocente = docente.iddocente, nombres = u.nombres, apellidos = u.apellidos, rol = u.rol }).OrderBy(u => u.apellidos).ToList();
labores = setLaborTeach(labores);
return Json(labores, JsonRequestBehavior.AllowGet);
}
[Authorize]
public ActionResult ListaLaborDocente()
{
docente docente = (docente)SessionValue("docente");
int currentper = (int)SessionValue("currentAcadPeriod");
var users = (from p in dbEntity.participa
join u in dbEntity.usuario on docente.idusuario equals u.idusuario
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper
where p.iddocente == docente.iddocente
select new DocenteLabor { idlabor = l.idlabor, iddocente = docente.iddocente, nombres = u.nombres, apellidos = u.apellidos, rol = u.rol }).OrderBy(u => u.apellidos).ToList();
if (users.Count == 0)
{
return RedirectToAction("MessegeTeach", "Teacher");
}
users = setLaborTeach(users);
ViewBag.lista = users;
return View(docente);
}
#endregion
#region Autoevaluación
[Authorize]
public ActionResult EvaluarLabor()
{
docente docente = (docente)SessionValue("docente");
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
if (currentper != ultimoPeriodo.idperiodo)
{
ViewBag.Error = " No puede realizar autoevaluaciones de periodos anteriores";
}
return View(docente);
}
[Authorize]
public ActionResult Evaluar(int id)
{
docente docente = (docente)SessionValue("docente");
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
if (currentper == ultimoPeriodo.idperiodo)
{
if (ModelState.IsValid)
{
var labores = (from p in dbEntity.participa
join u in dbEntity.usuario on docente.idusuario equals u.idusuario
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where p.idlabor == id && p.iddocente == docente.iddocente
select new DocenteLabor { idlabor = l.idlabor, iddocente = docente.iddocente, nombres = u.nombres, apellidos = u.apellidos, rol = u.rol }).OrderBy(u => u.apellidos).ToList();
labores = setLaborTeach(labores);
var response = labores.Select(l => new DocenteLabor { idlabor = l.idlabor, iddocente = docente.iddocente, nombres = l.nombres, apellidos = l.apellidos, rol = l.rol, tipoLabor = l.tipoLabor, descripcion = l.descripcion }).ToList();
ViewBag.datos = response;
return View();
}
}
else
{
ViewBag.Error = " No puede autoevaluarse en periodos anteriores";
}
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult saveAutoevaluacion(int idL, int idD, int val,string pdes, string psol, string rdes, string rsol )
{
participa auxParticipa = dbEntity.participa.SingleOrDefault(p => p.idlabor == idL && p.iddocente == idD);
if (auxParticipa != null)
{
evaluacion auxEvaluacion = dbEntity.evaluacion.SingleOrDefault(e => e.idevaluacion == auxParticipa.idevaluacion);
autoevaluacion auxAutoEvalaucion = dbEntity.autoevaluacion.SingleOrDefault(a => a.idautoevaluacion == auxParticipa.idautoevaluacion);
auxAutoEvalaucion.calificacion = val;
dbEntity.SaveChanges();
auxEvaluacion.evaluacionautoevaluacion = (int)auxAutoEvalaucion.calificacion;
dbEntity.SaveChanges();
problema auxProblema = dbEntity.problema.SingleOrDefault(p=> p.idautoevaluacion == auxAutoEvalaucion.idautoevaluacion);
auxProblema.descripcion = pdes;
auxProblema.solucion = psol;
dbEntity.SaveChanges();
resultado auxresultado = dbEntity.resultado.SingleOrDefault(r=>r.idautoevaluacion == auxAutoEvalaucion.idautoevaluacion);
auxresultado.descripcion = rdes;
auxresultado.ubicacion = rsol;
dbEntity.SaveChanges();
/// Se genera PDF de soporte de autoevaluacion
Models.Utilities oUtilities = new Models.Utilities();
string spath = Server.MapPath("~/pdfsupport/");
docente oDocente = dbEntity.docente.SingleOrDefault(q => q.iddocente == idD);
usuario oUsuario = dbEntity.usuario.SingleOrDefault(q => q.idusuario == oDocente.idusuario);
string sDescription = TeacherController.getLaborDescripcion(idL);
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico oPeriodo = dbEntity.periodo_academico.SingleOrDefault(q => q.idperiodo == currentper);
Document oDocument = oUtilities.StartPdfWriter(
oDocente.idusuario.ToString(), "autoev",
oPeriodo.anio.ToString() + "-" + oPeriodo.numeroperiodo.ToString() , sDescription, spath);
Font oContentFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL);
System.Text.StringBuilder oBuilder = new System.Text.StringBuilder();
oBuilder.Append("\n\nDocente: " + oUsuario.nombres + " " + oUsuario.apellidos);
oBuilder.Append("\nPeriodo: " + oPeriodo.anio.ToString() + "-" + oPeriodo.numeroperiodo.ToString() );
oBuilder.Append("\nNombre de Labor: " + sDescription );
oBuilder.Append("\nTipo de Evaluación: Autoevaluación");
oBuilder.Append("\nFecha y hora: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
oBuilder.Append("\nCALIFICACIÓN: " + val.ToString() + "\n\n");
Paragraph oContent = new Paragraph(oBuilder.ToString());
oContent.Font = oContentFont;
oContent.Alignment = Element.ALIGN_JUSTIFIED;
oDocument.Add(oContent);
PdfPTable oTable = new PdfPTable(2);
oTable.WidthPercentage = 100;
Rectangle rect = new Rectangle(100, 1000);
oTable.SetWidthPercentage(new float[] { 15, 85 }, rect);
PdfPCell oCell0 = new PdfPCell(new Phrase("PROBLEMAS"));
oCell0.Colspan = 2;
oCell0.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
oCell0.BorderWidth = 0;
oTable.AddCell(oCell0);
PdfPCell oCell1 = new PdfPCell(new Phrase("Descripción"));
oCell1.BorderWidth = 0;
oTable.AddCell(oCell1);
PdfPCell oCell2 = new PdfPCell(new Phrase(pdes));
oCell2.BorderWidth = 0;
oCell2.HorizontalAlignment = PdfPCell.ALIGN_JUSTIFIED;
oTable.AddCell(oCell2);
PdfPCell oCell3 = new PdfPCell(new Phrase("Solución"));
oCell3.BorderWidth = 0;
oTable.AddCell(oCell3);
PdfPCell oCell4 = new PdfPCell(new Phrase(psol));
oCell4.BorderWidth = 0;
oCell4.HorizontalAlignment = PdfPCell.ALIGN_JUSTIFIED;
oTable.AddCell(oCell4);
PdfPCell oCell5 = new PdfPCell(new Phrase("\nRESULTADOS"));
oCell5.BorderWidth = 0;
oCell5.Colspan = 2;
oCell5.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
oTable.AddCell(oCell5);
PdfPCell oCell6 = new PdfPCell(new Phrase("Descripción"));
oCell6.BorderWidth = 0;
oTable.AddCell(oCell6);
PdfPCell oCell7 = new PdfPCell(new Phrase(rdes));
oCell7.BorderWidth = 0;
oCell7.HorizontalAlignment = PdfPCell.ALIGN_JUSTIFIED;
oTable.AddCell(oCell7);
PdfPCell oCell8 = new PdfPCell(new Phrase("Ubicación"));
oCell8.BorderWidth = 0;
oTable.AddCell(oCell8);
PdfPCell oCell9 = new PdfPCell(new Phrase(rsol));
oCell9.BorderWidth = 0;
oCell9.HorizontalAlignment = PdfPCell.ALIGN_JUSTIFIED;
oTable.AddCell(oCell9);
oDocument.Add(oTable);
oDocument.Close();
/// Fin de la generacion del PDF de soporte
var tarea = new { respuesta = 1 };
return Json(tarea, JsonRequestBehavior.AllowGet);
}
else
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
public static string getLaborDescripcion(long idLabor)
{
string sSQLDescripcion = " select ISNULL(materia.nombremateria, isnull(otras.descripcion, isnull(trabajodegrado.titulotrabajo, " +
" isnull(trabajodegradoinvestigacion.titulotrabajo, isnull(gestion.nombrecargo, isnull(social.nombreproyecto, " +
" isnull(investigacion.nombreproyecto, isnull(desarrolloprofesoral.nombreactividad,'')))))))) as descripcion " +
" from labor left join docencia on docencia.idlabor = labor.idlabor " +
" left join materia on docencia.idmateria = materia.idmateria " +
" left join otras on otras.idlabor = labor.idlabor " +
" left join trabajodegrado on trabajodegrado.idlabor = labor.idlabor " +
" left join trabajodegradoinvestigacion on trabajodegradoinvestigacion.idlabor = labor.idlabor " +
" left join gestion on gestion.idlabor = labor.idlabor " +
" left join social on social.idlabor = labor.idlabor " +
" left join investigacion on investigacion.idlabor = labor.idlabor " +
" left join desarrolloprofesoral on desarrolloprofesoral.idlabor = labor.idlabor " +
" where labor.idlabor = " + idLabor.ToString();
sSQLDescripcion = (string)Models.Utilities.ExecuteScalar(sSQLDescripcion);
return sSQLDescripcion;
}
public autoevaluacion GetLastAutoEvaluacion()
{
autoevaluacion lastAutoEvaluacion;
var maxId = (from aev in dbEntity.autoevaluacion
select aev.idautoevaluacion).Max();
lastAutoEvaluacion = dbEntity.autoevaluacion.Single(q => q.idautoevaluacion == maxId);
return lastAutoEvaluacion;
}
#endregion
#region Consultas
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult VerAutoevaluaciones()
{
ViewBag.optionmenu = 1;
docente docente = (docente)SessionValue("docente");
int currentper = (int)SessionValue("currentAcadPeriod");
ViewBag.reporte = crearReporteAutoevalaucion(docente.idusuario);
return View();
}
public AutoevaluacionDocente crearReporteAutoevalaucion(int idUsuario)
{
departamento departamento = (departamento)SessionValue("depto");
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
docente docenteactual = (docente)SessionValue("docente");
int idjefe = docenteactual.idusuario;
usuario jefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idjefe);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
AutoevaluacionDocenteReporte = new AutoevaluacionDocente() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = jefe.nombres + " " + jefe.apellidos, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
List<ResAutoEvaluacionLabor> labores = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join aev in dbEntity.autoevaluacion on p.idautoevaluacion equals aev.idautoevaluacion
join pr in dbEntity.problema on aev.idautoevaluacion equals pr.idautoevaluacion
join re in dbEntity.resultado on aev.idautoevaluacion equals re.idautoevaluacion
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper && u.idusuario == idUsuario && aev.calificacion != -1
select new ResAutoEvaluacionLabor { idlabor = l.idlabor, nota = (int)aev.calificacion, problemadescripcion = pr.descripcion, problemasolucion = pr.solucion, resultadodescripcion = re.descripcion, resultadosolucion = re.ubicacion }).ToList();
labores = setAELabor(labores);
AutoevaluacionDocenteReporte.autoevaluacioneslabores = labores;
return AutoevaluacionDocenteReporte;
}
public List<ResAutoEvaluacionLabor> setAELabor(List<ResAutoEvaluacionLabor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otra;
foreach (ResAutoEvaluacionLabor labor in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (gestion != null)
{
labor.tipolabor = "Gestion";
labor.tipolaborcorto = "GES";
labor.descripcion = gestion.nombrecargo;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (social != null)
{
labor.tipolabor = "Social";
labor.tipolaborcorto = "SOC";
labor.descripcion = social.nombreproyecto;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (investigacion != null)
{
labor.tipolabor = "Investigación";
labor.tipolaborcorto = "INV";
labor.descripcion = investigacion.nombreproyecto;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGrado != null)
{
labor.tipolabor = "Trabajo de Grado";
labor.tipolaborcorto = "TDG";
labor.descripcion = trabajoDeGrado.titulotrabajo;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
labor.tipolabor = "Trabajo de Grado Investigación";
labor.tipolaborcorto = "TDGI";
labor.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (desarrolloProfesoral != null)
{
labor.tipolabor = "Desarrollo Profesoral";
labor.tipolaborcorto = "DP";
labor.descripcion = desarrolloProfesoral.nombreactividad;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (docencia != null)
{
materia materia = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
labor.tipolabor = "Docencia Directa";
labor.tipolaborcorto = "DD";
labor.descripcion = materia.nombremateria;
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (otra != null)
{
labor.tipolabor = "Otra";
labor.tipolaborcorto = "OTR";
labor.descripcion = otra.descripcion;
continue;
}
}
return lista;
}
#endregion
#region Reporte
public ActionResult ExportToExcelAutoevaluacion()
{
SpreadsheetModelAE mySpreadsheetAE = new SpreadsheetModelAE();
int tam = AutoevaluacionDocenteReporte.autoevaluacioneslabores.Count();
String[,] datos = new String[tam, 9];
mySpreadsheetAE.fechaevaluacion = AutoevaluacionDocenteReporte.fechaevaluacion;
mySpreadsheetAE.periodo = "" + AutoevaluacionDocenteReporte.periodonum + " - " + AutoevaluacionDocenteReporte.periodoanio;
mySpreadsheetAE.nombredocente = AutoevaluacionDocenteReporte.nombredocente;
mySpreadsheetAE.nombrejefe = AutoevaluacionDocenteReporte.nombrejefe;
int i = 0;
foreach (ResAutoEvaluacionLabor labor in AutoevaluacionDocenteReporte.autoevaluacioneslabores)
{
datos[i, 0] = ""+ labor.idlabor;
datos[i, 1] = ""+ labor.tipolaborcorto;
datos[i, 2] = ""+ labor.tipolabor;
datos[i, 3] = ""+ labor.descripcion;
datos[i, 4] = "" + labor.nota;
datos[i, 5] = "" + labor.problemadescripcion;
datos[i, 6] = "" + labor.problemasolucion;
datos[i, 7] = "" + labor.resultadodescripcion;
datos[i, 8] = "" + labor.resultadosolucion;
i++;
}
mySpreadsheetAE.labores = datos;
periodo_academico lastAcademicPeriod = GetLastAcademicPeriod();
DateTime Hora = DateTime.Now;
DateTime Hoy = DateTime.Today;
string hora = Hora.ToString("HH:mm");
string hoy = Hoy.ToString("dd-MM");
mySpreadsheetAE.fileName = "Reporte" + lastAcademicPeriod.anio + "-" + lastAcademicPeriod.idperiodo + "_" + hoy + "_" + hora + ".xls";
return View(mySpreadsheetAE);
}
#endregion
#region Evaluación
public evaluacion GetLastEvaluacion()
{
evaluacion lastEvaluacion;
var maxId = (from ev in dbEntity.evaluacion
select ev.idevaluacion).Max();
lastEvaluacion = dbEntity.evaluacion.Single(q => q.idevaluacion == maxId);
return lastEvaluacion;
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult saveEval(int idL, int idD, int val)
{
participa eliminarParticipa = dbEntity.participa.SingleOrDefault(p => p.idlabor == idL && p.iddocente == idD);
if (eliminarParticipa != null)
{
evaluacion auxEvaluacion = dbEntity.evaluacion.SingleOrDefault(e => e.idevaluacion == eliminarParticipa.idevaluacion);
auxEvaluacion.evaluacionautoevaluacion = val;
dbEntity.SaveChanges();
var tarea = new { respuesta = 1 };
return Json(tarea, JsonRequestBehavior.AllowGet);
}
else
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
#endregion
#endregion
// FIN ADICIONADO POR CLARA
[Authorize]
public ActionResult performSelfEvaluation()
{
docente docente = (docente)SessionValue("docente");
return View(docente);
}
}
// NUEVO 29
public class DocenteLabor
{
public int iddocente;
public int idlabor;
public string detalle;
public string nombres;
public string apellidos;
public string rol;
public string tipoLabor;
public string descripcion;
public int evaluacionAutoEvaluacion;
public int evaluacionestudiante;
public int evaluacionauto;
public int evaluacionjefe;
public int totalhoras;
public double calificacion;
public int horasPorLabor;
}
// FIN NUEVO 29
public class Horas
{
public int Horassemanales;
public int semanaslaborales;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcSEDOC.Models
{
public class ChiefEval
{
public int idlabor { get; set; }
public int iddocente { get; set; }
public int idevaluacion { get; set; }
public int idcuestionario { get; set; }
public int EvalEst { get; set; }
public int EvalAut { get; set; }
public List<CE_Question> calificaciones { get; set; }
}
public class StudentEval : ChiefEval
{
public string observaciones { set; get; }
}
public class CE_Question: IComparable
{
public int idgrupo { get; set; }
public int idpregunta { get; set; }
public int calificacion { get; set; }
public int CompareTo(object obj)
{
return idgrupo.CompareTo(((CE_Question)obj).idgrupo);
}
}
}<file_sep>$(function () {
/************* VARIABLES *********************/
var searchFacultadVar = "/sedoc/Admin/SearchFacultad/";
var searchProgramaVar = "/sedoc/Admin/GetFacultadPrograma/";
var proname = $("#nombre"),
allFields = $([]).add(proname),
tips = $(".validateTips");
/*****************FUNCIONES AUXILIARES*****************************/
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("El tamaño del " + n + " debe estar entre " +
min + " y " + max + ".");
return false;
} else {
return true;
}
}
function checkRange(o, n, min, max) {
if (!isNaN(parseFloat(o.val()))) {
var num = parseFloat(o.val());
if (num < min || num > max) {
o.addClass("ui-state-error");
updateTips("El rango del " + n + " debe estar entre " +
min + " y " + max + ".");
return false;
} else {
return true;
}
} else {
o.addClass("ui-state-error");
updateTips("El valor del " + n + " debe ser un numero entre " +
min + " y " + max + ".");
return false;
}
}
/****** Inicializaciones JQuery *******/
$("#search_term").autocomplete({
source: searchFacultadVar,
minLength: 1,
select: function (event, ui) {
$("#work-area").html("");
$("#work-area").append("<table id='TableQuestionnaire' class='list' style='width:100%'>" +
"</thead></table>" +
"<div id='sortdiv' style='width:100%;'>" +
"<ul id='sortable'></ul>" +
"</div><br/>");
loadGroups(ui.item.id, "/sedoc/Admin/GetFacultadPrograma/");
loadSortable(ui.item.id);
}
});
$("#search_term_pro").autocomplete({
//source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setGrupoId(ui);
}
}
});
// $("#search_term_pro").autocomplete({
// //source: searchProgramaVar,
// minLength: 1,
// select: function (event, ui) {
// $("#work-area").html("");
// $("#work-area").append("<table id='TableQuestionnaire' class='list' style='width:100%'>" +
// "</thead></table>" +
// "<div id='sortdiv' style='width:100%;'>" +
// "<ul id='sortable'></ul>" +
// "</div><br/>");
// //loadGroups(ui.item.id, "/sedoc/Admin/GetFacultadPrograma/");
// loadSortable(ui.item.id);
// }
// });
$('#dialogEditPrograma').dialog({
autoOpen: false,
width: 400,
height: 300,
modal: true,
buttons: {
"Guardar": function () {
var bValid = true;
allFields.removeClass("ui-state-error");
//bValid = bValid && checkLength(proname, "grupo", 3, 50);
//if (bValid) {
allFields.removeClass("ui-state-error");
SavePrograma("/sedoc/Admin/EditPrograma/", $(this));
$(this).dialog("close");
//}
},
"Cancelar": function () {
allFields.removeClass("ui-state-error");
$(this).dialog("close");
}
}
});
$("#dialogDeleteProgramaConfirm").dialog({
resizable: false,
autoOpen: false,
height: 140,
modal: true,
buttons: {
"Eliminar": function () {
DeletePrograma("/sedoc/Admin/DeletePrograma/", $(this));
},
Cancelar: function () {
$(this).dialog("close");
}
}
});
function loadSortable(idq) {
$("#sortable").sortable({
placeholder: "ui-state-highlight",
update: function (event, ui) {
var items = $("#sortable").sortable("toArray");
var arr = [];
$.each(items, function (key, val) {
var idval = val.replace("listElement_", "");
var obj = { id: idval }
arr.push(obj);
});
var data2send = JSON.stringify(arr);
$.ajax({
cache: false,
url: "/sedoc/Admin/SortProgramas/?stridq=" + idq,
type: 'post',
dataType: 'json',
data: data2send,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data != null) {
$.each(data, function (key, val) {
setEditAction(val['id'], val['label'], val['idf']);
});
} else {
alert("Lo siento!, ocurrio un error ... disculpame")
}
}
});
}
});
$("#sortable").disableSelection();
}
/**************** FUNCIONES AUXILIARES *****************/
function DeletePrograma(route, jquerydialog) {
var idp = $('#iddepartamento').val();
if (idp == "") {
alert("El programa no puede ser eliminado.");
} else {
var prog = '{ "id": ' + idp + ' }';
var request = $.ajax({
cache: false,
url: route,
type: 'POST',
dataType: 'json',
data: prog,
contentType: 'application/json; charset=utf-8',
success: function (data) {
deletedResponse(data, jquerydialog);
}
});
}
}
function SavePrograma(route, jquerydialog) {
var prog = getPrograma();
if (prog != null) {
var request = $.ajax({
cache: false,
url: route,
type: 'POST',
dataType: 'json',
data: prog,
contentType: 'application/json; charset=utf-8',
success: function (data) {
savedResponse(data, jquerydialog);
setEditAction(data.iddepartamento, data.nombre,data.idfacultad);
}
});
}
}
function savedResponse(data, jquerydialog) {
if (data.iddepartamento != 0) {
$("#work-area").html("");
$('#lblEd' + data.iddepartamento).html(data.nombre);
allFields.val("").removeClass("ui-state-error");
updateTips("");
setEditAction(data.iddepartamento, data.nombre);
jquerydialog.dialog("close");
} else {
updateTips("Lo siento!, el registro no se pudo efectuar ... disculpame");
}
}
function deletedResponse(data, jquerydialog) {
if (data.iddepartamento != 0) {
$("#work-area").html("");
$('#btnDel' + data.iddepartamento).parent().parent().remove();
jquerydialog.dialog("close");
} else {
alert("Lo siento!, la eliminación no se pudo efectuar ... disculpame");
}
}
// function savedResponse(data, jquerydialog) {
// if (data.iddepartamento != 0) {
// $('#btnDel' + data.iddepartamento).parent().parent().find("td").eq(1).html(data.nombre);
// jquerydialog.dialog("close");
// } else {
// alert("Lo siento!, el registro no se pudo efectuar ... disculpame");
// }
// }
function setEditAction(idP, nameP, idF) {
$('#btnEdit' + idP).click(function () {
$('#dialogEditPrograma').dialog('open');
$("#iddepartamento").val(idP);
$('#nombre').val(nameP);
$("#idfacultad").val(idF);
return false;
});
$('#btnDel' + idP).click(function () {
$('#dialogDeleteProgramaConfirm').dialog('open');
$('#iddepartamento').val(idP);
return false;
});
}
function setFacultadId(ui) {
$("#idfacultad").val(ui.item.id);
$("#work-area").html("");
}
function setGrupoId(ui) {
$("#iddepartamento").val(ui.item.id);
}
function getPrograma() {
var idp = $("#iddepartamento").val();
var nom = $("#nombre").val();
var idf = $("#idfacultad").val();
return (idp == "" || nom == "" || idf == "") ? null : '{ "iddepartamento": "' + idp + '", "nombre": "' + nom + '","idfacultad": "' + idf + '" }';
}
function loadGroups(idF, route) {
$.getJSON(route, { term: idF }, function (data) {
$.each(data, function (key, val) {
$("#sortable").append("<li id='listElement_" + val["id"] + "'><table class=list' style='width:100%;'><tr>" +
"<td>" + val['label'] + "</td>" +
"</tr></table></li>");
$("#work-area").html("");
$("#work-area").append("<table id='TableQuestionnaire' class='list' style='width:100%'>" +
"</thead></table>" +
"<div id='sortdiv' style='width:100%;'>" +
"<ul id='sortable'></ul>" +
"</div><br/>");
loadSortable(ui.item.id);
setEditAction(val['id'], val['label'], val['idf']);
});
});
}
});
<file_sep>var searchVar = "/sedoc/Admin/SearchDepartment/";
var nameDept, iddept, idCurrentPeriod, chiefId;
var docenteSelected;
function openDialog(valor,idD) {
docenteSelected = valor;
iddept = idD;
//obtiene el jefe actual
getCurrentDepartmentChief("/sedoc/Admin/GetCurrentDepartmentChief/");
$("#dialogUpDateDepartmentChief").dialog('open');
}
$(function () {
// dialogo para confirmar el cambio de jefe de departamento
$("#dialogUpDateDepartmentChief").dialog({
resizable: false,
autoOpen: false,
height: 320,
modal: true,
buttons: {
"Cambiar": function () {
updateCurrentChief("/sedoc/Admin/UpdateCurrentChief/");
$(this).dialog("close");
},
"Cancelar": function () {
if (chiefId == -1) {
document.getElementById(docenteSelected).checked = false;
} else {
document.getElementById(chiefId).checked = true;
}
$(this).dialog("close");
}
}
});
});
// obtiene el actual jefe de ese departamento
function getCurrentDepartmentChief(route) {
var strDepto = '{"iddepartamento": ' + iddept + ' }';
$.ajax({
cache: false,
url: route,
type: 'Post',
dataType: 'json',
data: strDepto,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data == null) {
chiefId = -1;
} else {
chiefId = data.iddocente;
}
}
});
}
// actualiza el jefe del departamento
function updateCurrentChief(route) {
var worksValue = 1;
if ($('input[id$="chkDocencia"]').is(':checked')) worksValue = worksValue * 3;
if ($('input[id$="chkDesarrollo"]').is(':checked')) worksValue = worksValue * 5;
if ($('input[id$="chkTrabajoGradoInv"]').is(':checked')) worksValue = worksValue * 7;
if ($('input[id$="chkTrabajoGrado"]').is(':checked')) worksValue = worksValue * 11;
if ($('input[id$="chkInvestigacion"]').is(':checked')) worksValue = worksValue * 13;
if ($('input[id$="chkGestion"]').is(':checked')) worksValue = worksValue * 17;
if ($('input[id$="chkSocial"]').is(':checked')) worksValue = worksValue * 19;
if ($('input[id$="chkOtras"]').is(':checked')) worksValue = worksValue * 23;
var param = '{ "idDepartamento": ' + iddept + ', "idDocentAct": ' + chiefId + ', "idDocentNue": ' + docenteSelected + ', "laboresCalc": ' + worksValue + '}';
$.ajax({
cache: false,
url: route,
type: 'POST',
dataType: 'json',
data: param,
contentType: 'application/json; charset=utf-8',
success: function (data) {
iddept = data.iddepartamento;
chiefId = data.iddocente;
idCurrentPeriod = data.idperiodo;
}
});
}
<file_sep>$(function () {
setWorkId();
var iddocente = document.getElementById("search_term").value;
loadWork("1", "/sedoc/DepartmentChief/GetTechingWork/");
var searchVar = "/sedoc/DepartmentChief/searchTeching/";
function setWorkId() {
$("#work-area").html("");
$("#work-area").append("<table id='TableidWork' class='list' style='width:100%'>" +
"<thead><tr><th colspan=5>Labores</th></tr>" +
"<tr class='sub'><th>Id</th>" +
"<th>Profesor</th>" +
"<th>Tipo Labor</th><th>Labor</th>" +
"<th style='width:130px;'>Buscar Jefe</th></tr></thead>" +
"<tbody></tbody>" +
"</table><br/>");
}
function loadWork(idD, route) {
$.getJSON(route, { term: idD }, function (data) {
$.each(data, function (key, val) {
$("#TableidWork tbody").append("<tr>" +
"<td style='width:0;'>" + val['idlabor'] + "</td>" +
"<td>" + val['nombres'] + "</td>" +
"<td>" + val['tipoLabor'] + "</td>" +
"<td>" + val['descripcion'] + "</td>" +
"<td>" + "<input type='hidden' id='idJL" + val['idlabor'] + "' />" +
"<input class='search_Teching' " + " id=" + val['idlabor'] + " />" + "</td>" +
// "<td>" + "<input type='hidden' id='idJH" + val['idlabor'] + "' />" +
// "<input style='width:30px;' class='search_Teching1' " + " id='idJH1" + val['idlabor'] + "' />" + "</td>" +
"</tr>");
});
autocompleteTeching();
});
}
function loadDateTable() {
var tabla = document.getElementById("TableidWork");
var numFilas = tabla.rows.length;
for (i = 0; i < numFilas - 2; i++) {
var idLabor = tabla.tBodies[0].rows[i].cells[0].innerHTML;
var idJefe = document.getElementById("idJL" + idLabor).value;
//var horas = document.getElementById("idJH1" + idLabor).value;
//alert(idLabor +" a " + idJefe + " a " + horas);
if (idJefe != "") {
//metodo que guarde los datos en la BD
$.getJSON("/sedoc/DepartmentChief/saveChief/", { idL: idLabor, idJ: idJefe}, function (data) {
if (i == numFilas - 2) {
// alert(numFilas + " " + i);
setTimeout(redireccionar, 1000);
}
});
}
}
}
function checkRange(o, n, min, max) {
if (!isNaN(parseInt(o.val())) && checkDigits(o)) {
var num = parseInt(o.val());
if (num < min || num > max) {
o.addClass("ui-state-error");
updateTips("El rango de la " + n + " debe estar entre " +
min + " y " + max + ".");
return false;
} else {
return true;
}
} else {
o.addClass("ui-state-error");
updateTips("El valor de la " + n + " debe ser un numero entre " +
min + " y " + max + ".");
return false;
}
}
function checkDigits(o) { //retorna true si solo tiene digitos
solodigitos = true;
for (i = 0; i < o.val().length; i++) {
solodigitos = solodigitos && (o.val().charAt(i) >= '0' && o.val().charAt(i) <= '9');
}
return solodigitos;
}
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function resultado(data) {
if (data.respuesta == 0) {
alert("Lo sentimos, algunos datos no se pueden guardar");
}
}
function redireccionar() {
//var iddocente = document.getElementById("search_term").value;
var pagina = "/sedoc/DepartmentChief/AssignWork/";
location.href = pagina;
}
function autocompleteTeching() {
$(".search_Teching").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
$("#idJL" + $(this).attr("id")).val(ui.item.id);
}
}
});
save();
}
//adiciona los botones en la ventana del diajogo guardar
$("#dialogSaveGroupConfirm").dialog({
resizable: false,
autoOpen: false,
height: 140,
modal: true,
buttons: {
"Guardar": function () {
loadDateTable();
$(this).dialog("close");
},
Cancelar: function () {
$(this).dialog("close");
}
}
});
//Cuando el evento click es capturado en el enlace guardar abre el dialogo
function save() {
$('#save').click(function () {
$('#dialogSaveGroupConfirm').dialog('open');
return false;
});
}
});
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using MvcSEDOC.Models;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Data.OleDb;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Configuration;
namespace MvcSEDOC.Controllers
{
public class AdminController : SEDOCController
{
public static int opcionError;
public ImportDataSheets data_imports = new ImportDataSheets();
public static ConsolidadoLabores ReporteLabores = new ConsolidadoLabores();
List<ConsolidadoDocencia> ReporteMaterias = new List<ConsolidadoDocencia>();
List<ConsolidadoLabores> ReporteLabores1 = new List<ConsolidadoLabores>();
[Authorize]
public ActionResult Index()
{
return View();
}
#region Privilegios
public object SessionValue(string keyValue)
{
try
{
return Session[keyValue];
}
catch
{
return RedirectPermanent("/sedoc");
}
}
[Authorize]
public ActionResult SetPrivileges(int id)
{
if (ModelState.IsValid)
{
Debug.WriteLine("depto 1" + id);
var dep = dbEntity.departamento.SingleOrDefault(q => q.iddepartamento == id);
var response = GetTeachersFromDepartment(id);
ViewBag.datos = response;
ViewBag.departamento = dep.nombre;
return View();
}
return View();
}
#endregion
#region Cuestionario
[Authorize]
public ActionResult CreateQuestionnaire()
{
ViewBag.optionmenu = 2;
return View();
}
//MODIFICADO POR EDINSON
[Authorize]
[HttpPost]
public ActionResult CreateQuestionnaire(cuestionario miCuestionario)
{
ViewBag.optionmenu = 2;
int esta = 0;
if (ModelState.IsValid)
{
string nombre = miCuestionario.tipocuestionario;
if (nombre == null)
{
ViewBag.Error = "Debe ingresar un nombre para el cuestionario";
}
else
{
esta = yaEsta(nombre);
if (esta == 1)
{
ViewBag.Error = "Ya existe un cuestionario con el nombre ingresado";
}
else
{
dbEntity.cuestionario.AddObject(miCuestionario);
dbEntity.SaveChanges();
ViewBag.Message = "El cuestionario se creo correctamente";
}
}
return View();
}
return View(miCuestionario);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult UpdateQuestionnaire()
{
ViewBag.optionmenu = 2;
return View(dbEntity.cuestionario.ToList());
}
[Authorize]
[HttpPost]
//[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult EditQuestionnaire(cuestionario micuestionario)
{
if (ModelState.IsValid)
{
dbEntity.cuestionario.Attach(micuestionario);
dbEntity.ObjectStateManager.ChangeObjectState(micuestionario, EntityState.Modified);
dbEntity.SaveChanges();
return Json(micuestionario, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
//MODIFICADO POR EDINSON
[Authorize]
[HttpPost]
public ActionResult DeleteQuestionnaire(int id)
{
int id_borrar = id;
var asignaciones = dbEntity.asignarCuestionario.Where(q => q.idcuestionario == id);
foreach (asignarCuestionario aux in asignaciones)
{
dbEntity.asignarCuestionario.DeleteObject(aux);
}
var eliminar_grupos = dbEntity.grupo.Where(q => q.idcuestionario == id);
foreach (grupo aux1 in eliminar_grupos)
{
var eliminar_preguntas = dbEntity.pregunta.Where(q => q.idgrupo == aux1.idgrupo);
foreach (pregunta aux2 in eliminar_preguntas)
{
dbEntity.pregunta.DeleteObject(aux2);
}
dbEntity.grupo.DeleteObject(aux1);
}
cuestionario cuestionario = dbEntity.cuestionario.Single(c => c.idcuestionario == id);
dbEntity.cuestionario.DeleteObject(cuestionario);
dbEntity.SaveChanges();
return Json(cuestionario, JsonRequestBehavior.AllowGet);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchQuestionnaire(string term)
{
var response = dbEntity.cuestionario.Select(q => new { label = q.tipocuestionario, id = q.idcuestionario }).Where(q => q.label.ToUpper().Contains(term.ToUpper())).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
//MODIFICADO POR EDINSON
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult AjaxSetQuestionnaire(cuestionario miCuestionario)
{
int esta = 0;
if (ModelState.IsValid)
{
string nombre = miCuestionario.tipocuestionario;
esta = yaEsta(nombre);
if (esta == 1)
{
miCuestionario.idcuestionario = 0;
}
else
{
dbEntity.cuestionario.AddObject(miCuestionario);
dbEntity.SaveChanges();
}
return Json(miCuestionario, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
#endregion
// inicio cambio contraeña
public static string md5(string password)
{
// para probar pq hace falta
MD5 md5 = MD5CryptoServiceProvider.Create();
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] stream = null;
StringBuilder sb = new StringBuilder();
string br = "";
stream = md5.ComputeHash(encoding.GetBytes(password));
for (int i = 0; i < stream.Length; i++) sb.AppendFormat("{0:x2}", stream[i]);
br = sb.ToString();
return br;
}
[Authorize]
public ActionResult ChangePass()
{
int periodoActualSelec = 0;
periodoActualSelec = (int)SessionValue("periodoActual");;
if (periodoActualSelec == 1)
{
return RedirectPermanent("/Admin/Index");
}
ViewBag.optionmenu = 1;
return View();
}
[Authorize]
public ActionResult ChangePass1()
{
int periodoActualSelec = 0;
periodoActualSelec = (int)SessionValue("periodoActual");;
if (periodoActualSelec == 1)
{
return RedirectPermanent("/Admin/Index");
}
ViewBag.Value1 = "";
ViewBag.Value2 = "";
ViewBag.Value3 = "";
string anterior = "";
string nueva = "";
string repite = "";
string claveA = "";
int campo1 = 0;
int campo2 = 0;
int campo3 = 0;
//int entradas = 7;
//Boolean entro = false;
//Boolean error = false;
anterior = Request.Form["anterior"];
if (anterior == "")
{
campo1 = 1;
ViewBag.Error1 = "entro";
}
else
{
ViewBag.Value1 = anterior;
}
nueva = Request.Form["nueva"];
if (nueva == "")
{
campo2 = 1;
ViewBag.Error2 = "entro";
}
else
{
ViewBag.Value2 = nueva;
}
repite = Request.Form["repite"];
if (repite == "")
{
campo3 = 1;
ViewBag.Error3 = "entro";
}
else
{
ViewBag.Value3 = repite;
}
ViewBag.optionmenu = 1;
if (campo1 == 1 || campo2 == 1 || campo3 == 1)
{
ViewBag.Error = "Los campos con asterisco son obligatorios";
return View();
}
claveA = md5(anterior);
try
{
usuario NuevaContrasena = dbEntity.usuario.Single(u => u.emailinstitucional == "<EMAIL>" && u.password == claveA);
if (nueva != repite)
{
ViewBag.Error = "No coinciden la nueva contraseña con la anterior";
return View();
}
else
{
if (!ActualizarContrasenaUsuarioActual(nueva, anterior))
{
throw new Exception("Invalid Password");
}
nueva = md5(nueva);
NuevaContrasena.password = <PASSWORD>;
dbEntity.ObjectStateManager.ChangeObjectState(NuevaContrasena, EntityState.Modified);
dbEntity.SaveChanges();
ViewBag.Value1 = null;
ViewBag.Value2 = null;
ViewBag.Value3 = null;
ViewBag.Message = "La contraseña se cambio exitosamente";
return View();
}
}
catch
{
ViewBag.Error = "La contraseña anterior es incorrecta";
return View();
}
}
// fin cambios contraseña
#region Grupo
//MODIFICADO POR EDINSON
[Authorize]
public ActionResult CreateGroup()
{
ViewBag.optionmenu = 2;
ViewBag.Value1 = null;
ViewBag.Value2 = null;
ViewBag.Value3 = null;
return View();
}
//MODIFICADO POR EDINSON
[Authorize]
[HttpPost]
public ActionResult CreateGroupo()
{
string cuestionario = "";
string nombre = "";
string auxporcentaje = "";
double porcentaje = 0;
int campo1 = 0;
int campo2 = 0;
int campo3 = 0;
ViewBag.Value1 = "";
ViewBag.Value2 = "";
ViewBag.Value3 = "";
cuestionario = Request.Form["cuestionario"];
if (cuestionario == "")
{
campo1 = 1;
ViewBag.Error1 = "entro";
}
else
{
ViewBag.Value1 = cuestionario;
}
nombre = Request.Form["nombre"];
if (nombre == "")
{
campo2 = 1;
ViewBag.Error2 = "entro";
}
else
{
ViewBag.Value2 = nombre;
}
auxporcentaje = Request.Form["porcentaje"];
if (auxporcentaje == "")
{
campo3 = 1;
ViewBag.Error3 = "entro";
}
else
{
ViewBag.Value3 = auxporcentaje;
}
ViewBag.optionmenu = 1;
if (campo1 == 1 || campo2 == 1 || campo3 == 1)
{
ViewBag.Error = "Los campos con asterisco son obligatorios";
return View();
}
try
{
cuestionario existecuestionario = dbEntity.cuestionario.Single(q => q.tipocuestionario == cuestionario);
try
{
porcentaje = Convert.ToDouble(auxporcentaje);
}
catch
{
ViewBag.Error = "El campo porcentaje debe ser un numero";
return View();
}
int grupoExiste = yaEstaGrupo(nombre, (int)existecuestionario.idcuestionario);
if (grupoExiste == 1)
{
ViewBag.Error = "Ya existe un grupo de preguntas con el nombre " + nombre;
return View();
}
double porcentajes = 0;
double total_final = 0;
double aux_final = 0;
try
{
porcentajes = (double)dbEntity.grupo.Where(q => q.idcuestionario == existecuestionario.idcuestionario).Sum(q => q.porcentaje);
}
catch
{
porcentajes = 0;
}
total_final = porcentaje + porcentajes;
if (total_final > 100)
{
aux_final = 100 - porcentajes;
if (aux_final == 0)
{
ViewBag.Error = "No puedes agregar más grupos, la suma de los porcentajes es 100% ";
return View();
}
else
{
ViewBag.Error = "El máximo valor en la casilla porcentaje es: " + aux_final;
return View();
}
}
int maxorder;
try
{
maxorder = dbEntity.grupo.Where(q => q.idcuestionario == existecuestionario.idcuestionario).Max(q => q.orden);
}
catch (Exception)
{
maxorder = 0;
}
grupo miGrupo = new grupo();
ViewBag.optionmenu = 2;
miGrupo.orden = maxorder + 1;
miGrupo.idcuestionario = existecuestionario.idcuestionario;
miGrupo.nombre = nombre;
miGrupo.porcentaje = porcentaje;
dbEntity.grupo.AddObject(miGrupo);
dbEntity.SaveChanges();
ViewBag.Message = "El Grupo se creo correctamente";
return View();
}
catch
{
ViewBag.Error = "El campo tipo de cuestionario esta vacio o el cuestionario escrito no existe";
return View();
}
}
[Authorize]
public ActionResult UpdateGroup()
{
ViewBag.optionmenu = 2;
return View();
}
[Authorize]
[HttpPost]
public ActionResult EditGroup(grupo miGrupo)
{
if (ModelState.IsValid)
{
dbEntity.grupo.Attach(miGrupo);
dbEntity.ObjectStateManager.ChangeObjectState(miGrupo, EntityState.Modified);
dbEntity.SaveChanges();
return Json(miGrupo, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
public ActionResult DeleteGroup(int id)
{
grupo grupo = dbEntity.grupo.Single(c => c.idgrupo == id);
dbEntity.grupo.DeleteObject(grupo);
dbEntity.SaveChanges();
return Json(grupo, JsonRequestBehavior.AllowGet);
}
[Authorize]
public ActionResult SearchGroup(string idQuestionnarie, string term)
{
var response = dbEntity.grupo.Select(q => new { label = q.nombre, orden = q.orden, idq = q.idcuestionario, porcentaje = q.porcentaje, nombre = q.nombre, idgrupo = q.idgrupo }).Where(q => q.label.ToUpper().Contains(term.ToUpper())).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SortGroups(string stridq, intListing[] list_ids)
{
int idq = int.Parse(stridq);
int idg;
try
{
for (int i = 1; i <= list_ids.Count(); i++)
{
idg = list_ids[(i - 1)].id;
grupo miGrupo = dbEntity.grupo.Single(q => q.idgrupo == idg);
miGrupo.orden = i;
dbEntity.ObjectStateManager.ChangeObjectState(miGrupo, EntityState.Modified);
dbEntity.SaveChanges();
}
var response = dbEntity.grupo.Select(q => new { label = q.nombre, id = q.idgrupo, pos = q.orden, idc = q.idcuestionario, porc = q.porcentaje }).Where(q => q.idc == idq).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(null, JsonRequestBehavior.AllowGet);
}
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetQuestionnaireGroups(string term)
{
int idq = int.Parse(term);
var response = dbEntity.grupo.Select(q => new { label = q.nombre, id = q.idgrupo, pos = q.orden, idc = q.idcuestionario, porc = q.porcentaje }).Where(q => q.idc == idq).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
#endregion
#region Pregunta
[Authorize]
public ActionResult CreateQuestion()
{
ViewBag.optionmenu = 2;
return View();
}
[Authorize]
public ActionResult UpdateQuestion()
{
ViewBag.optionmenu = 2;
return View();
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult EditQuestion(pregunta pregunta)
{
if (ModelState.IsValid)
{
dbEntity.pregunta.Attach(pregunta);
dbEntity.ObjectStateManager.ChangeObjectState(pregunta, EntityState.Modified);
dbEntity.SaveChanges();
return Json(pregunta, JsonRequestBehavior.AllowGet);
}
return View(pregunta);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult DeleteQuestion(int id)
{
pregunta pregunta = dbEntity.pregunta.Single(c => c.idpregunta == id);
dbEntity.pregunta.DeleteObject(pregunta);
dbEntity.SaveChanges();
return Json(pregunta, JsonRequestBehavior.AllowGet);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetQuestionsFromGroup(string term)
{
int idgroup = int.Parse(term);
var response = dbEntity.pregunta.Select(q => new { label = q.pregunta1, id = q.idpregunta, idg = q.idgrupo }).Where(q => q.idg == idgroup).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult AjaxSetQuestion(pregunta miPregunta)
{
if (ModelState.IsValid)
{
dbEntity.pregunta.AddObject(miPregunta);
dbEntity.SaveChanges();
return Json(miPregunta, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
#endregion
#region Periodo Académico
[Authorize]
public ActionResult AcademicPeriods()
{
ViewBag.optionmenu = 7;
return View(dbEntity.periodo_academico.ToList());
}
[Authorize]
public ConsolidadoLabores crearReporte(int idUsuario)
{
int currentper = (int)SessionValue("currentAcadPeriod");
var docjefe = new docente();
var usujefe = new usuario();
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
var docente = dbEntity.docente.SingleOrDefault(q => q.idusuario == idUsuario);
var jefe = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == docente.iddepartamento && q.idperiodo == currentper);
if (jefe != null)
docjefe = dbEntity.docente.SingleOrDefault(q => q.iddocente == jefe.iddocente);
if (docjefe != null)
usujefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == docjefe.idusuario);
ConsolidadoLabores reporte = new ConsolidadoLabores();
List<int> labores = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper && u.idusuario == idUsuario
select l.idlabor).ToList();
reporte = setLabor(labores);
reporte.nombredocente = user.nombres + " " + user.apellidos;
if (usujefe != null)
{
reporte.nombrejefe = usujefe.nombres + " " + usujefe.apellidos;
}
else
{
reporte.nombrejefe = "SIN JEFE ASIGNADO";
}
reporte.periodoanio = (int)PeriodoSeleccionado.anio;
reporte.periodonum = (int)PeriodoSeleccionado.numeroperiodo;
reporte.fechaevaluacion = fecha_actual;
//reporte.totalhorassemana = (Double)labores.Sum(q => q.horasxsemana);
ReporteLabores = reporte;
return reporte;
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult CreateAcademicPeriod(periodo_academico periodo)
{
if (ModelState.IsValid)
{
dbEntity.periodo_academico.AddObject(periodo);
dbEntity.SaveChanges();
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
Session["currentAcadPeriod"] = ultimoPeriodo.idperiodo;
int currentper = (int)SessionValue("currentAcadPeriod");
return Json(periodo, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult EditAcademicPeriod(periodo_academico periodo)
{
if (ModelState.IsValid)
{
dbEntity.periodo_academico.Attach(periodo);
dbEntity.ObjectStateManager.ChangeObjectState(periodo, EntityState.Modified);
dbEntity.SaveChanges();
return Json(periodo, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult DeleteAcademicPeriod(int id)
{
if (dbEntity.labor.Count(q => q.idperiodo == id) == 0 && dbEntity.esjefe.Count(q => q.idperiodo == id) == 0)
{
periodo_academico periodo = dbEntity.periodo_academico.Single(c => c.idperiodo == id);
dbEntity.periodo_academico.DeleteObject(periodo);
dbEntity.SaveChanges();
return Json(periodo, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
#endregion
#region Jefe Departamento
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetCurrentDepartmentChief(int iddepartamento)
{
int currentper = (int)SessionValue("currentAcadPeriod");
esjefe response = null;
response = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == iddepartamento && q.idperiodo == currentper);
return Json(response, JsonRequestBehavior.AllowGet);
}
#endregion
#region Jefe Labor
//MODIFICADO POR EDINSON
[Authorize]
public ActionResult AssessLaborChief()
{
ViewBag.optionmenu = 6;
int currentper = (int)SessionValue("currentAcadPeriod");
var users = (from u in dbEntity.usuario
join d in dbEntity.dirige on u.idusuario equals d.idusuario
join l in dbEntity.labor on d.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
join ev in dbEntity.evaluacion on d.idevaluacion equals ev.idevaluacion
where l.idperiodo == currentper
//select new JefeLabor { idusuario = u.idusuario, idlabor = l.idlabor, idevaluacion = ev.idevaluacion, nombres = u.nombres, apellidos = u.apellidos, rol = u.rol, evaluacionJefe = (int)ev.evaluacionjefe }).Where(p => p.evaluacionJefe == -1).OrderBy(p => p.apellidos).ToList();
select new JefeLabor { idusuario = u.idusuario, idlabor = l.idlabor, idevaluacion = ev.idevaluacion, nombres = u.nombres, apellidos = u.apellidos, rol = u.rol, evaluacionJefe = (int)ev.evaluacionjefe }).OrderBy(p => p.apellidos).ToList();
users = setLaborChief(users);
ViewBag.lista = users;
return View();
}
/// <summary>
/// Actualiza el jefe actual para un departamento especifico
/// </summary>
/// <param name="idDepartamento"></param>
/// <param name="idDocentAct"></param>
/// <param name="idDocentNue"></param>
/// <param name="laboresCalc"></param>
/// <param name="currentper"></param>
/// <returns></returns>
public esjefe ProcessUpdateCurrentChief(int idDepartamento, int idDocentAct, int idDocentNue, int laboresCalc, int currentper)
{
if (idDocentAct != -1)
{
esjefe eliminar = dbEntity.esjefe.Single(q => q.iddepartamento == idDepartamento && q.iddocente == idDocentAct && q.idperiodo == currentper);
dbEntity.esjefe.DeleteObject(eliminar);
dbEntity.SaveChanges();
docente oDocente = dbEntity.docente.Single(q => q.iddocente == idDocentAct);
usuario oUsuario = dbEntity.usuario.Single(q => q.idusuario == oDocente.idusuario);
RemoverUsuarioDeRol(oUsuario.emailinstitucional, "DepartmentChief");
}
esjefe nuevo = new esjefe();
nuevo.idperiodo = currentper;
nuevo.iddepartamento = idDepartamento;
nuevo.iddocente = idDocentNue;
dbEntity.esjefe.AddObject(nuevo);
dbEntity.SaveChanges();
docente oNDoc = dbEntity.docente.Single(q => q.iddocente == idDocentNue);
usuario oNUser = dbEntity.usuario.Single(q => q.idusuario == oNDoc.idusuario);
RegistrarUsuarioEnRol(oNUser.emailinstitucional, "DepartmentChief");
if (laboresCalc > 1)
{
var value = dbEntity.docente.SingleOrDefault(q => q.iddocente == idDocentNue);
DepartmentChiefController oController = new DepartmentChiefController();
/// Docentes
if ((laboresCalc % 3) == 0)
{
var labores = (from p in dbEntity.labor
join per in dbEntity.periodo_academico on p.idperiodo equals per.idperiodo
join doc in dbEntity.docencia on p.idlabor equals doc.idlabor
select p.idlabor).ToList();
foreach (int idLabor in labores)
{
oController.SaveChiefAux(value.idusuario, idLabor, 1);
}
}
/// Desarrollo profesoral
if ((laboresCalc % 5) == 0)
{
var labores = (from p in dbEntity.labor
join per in dbEntity.periodo_academico on p.idperiodo equals per.idperiodo
join doc in dbEntity.desarrolloprofesoral on p.idlabor equals doc.idlabor
select p.idlabor).ToList();
foreach (int idLabor in labores)
{
oController.SaveChiefAux(value.idusuario, idLabor, 1);
}
}
/// Trabajo de grado de investigacion
if ((laboresCalc % 7) == 0)
{
var labores = (from p in dbEntity.labor
join per in dbEntity.periodo_academico on p.idperiodo equals per.idperiodo
join doc in dbEntity.trabajodegradoinvestigacion on p.idlabor equals doc.idlabor
select p.idlabor).ToList();
foreach (int idLabor in labores)
{
oController.SaveChiefAux(value.idusuario, idLabor, 1);
}
}
/// Trabajo de grado
if ((laboresCalc % 11) == 0)
{
var labores = (from p in dbEntity.labor
join per in dbEntity.periodo_academico on p.idperiodo equals per.idperiodo
join doc in dbEntity.trabajodegrado on p.idlabor equals doc.idlabor
select p.idlabor).ToList();
foreach (int idLabor in labores)
{
oController.SaveChiefAux(value.idusuario, idLabor, 1);
}
}
/// Investigacion
if ((laboresCalc % 13) == 0)
{
var labores = (from p in dbEntity.labor
join per in dbEntity.periodo_academico on p.idperiodo equals per.idperiodo
join doc in dbEntity.investigacion on p.idlabor equals doc.idlabor
select p.idlabor).ToList();
foreach (int idLabor in labores)
{
oController.SaveChiefAux(value.idusuario, idLabor, 1);
}
}
/// Gestion
if ((laboresCalc % 17) == 0)
{
var labores = (from p in dbEntity.labor
join per in dbEntity.periodo_academico on p.idperiodo equals per.idperiodo
join doc in dbEntity.gestion on p.idlabor equals doc.idlabor
select p.idlabor).ToList();
foreach (int idLabor in labores)
{
oController.SaveChiefAux(value.idusuario, idLabor, 1);
}
}
/// social
if ((laboresCalc % 19) == 0)
{
var labores = (from p in dbEntity.labor
join per in dbEntity.periodo_academico on p.idperiodo equals per.idperiodo
join doc in dbEntity.social on p.idlabor equals doc.idlabor
select p.idlabor).ToList();
foreach (int idLabor in labores)
{
oController.SaveChiefAux(value.idusuario, idLabor, 1);
}
}
/// otras
if ((laboresCalc % 23) == 0)
{
var labores = (from p in dbEntity.labor
join per in dbEntity.periodo_academico on p.idperiodo equals per.idperiodo
join doc in dbEntity.otras on p.idlabor equals doc.idlabor
select p.idlabor).ToList();
foreach (int idLabor in labores)
{
oController.SaveChiefAux(value.idusuario, idLabor, 1);
}
}
}
return nuevo;
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult UpdateCurrentChief(int idDepartamento, int idDocentAct, int idDocentNue, int laboresCalc)
{
int currentper = (int)SessionValue("currentAcadPeriod");
return Json(ProcessUpdateCurrentChief(idDepartamento, idDocentAct, idDocentNue, laboresCalc, currentper), JsonRequestBehavior.AllowGet);
}
//MODIFICADO POR CLARA
public List<JefeLabor> setLaborChief(List<JefeLabor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otra;
foreach (JefeLabor jefe in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (gestion != null)
{
jefe.tipoLabor = "Gestiónn";
jefe.descripcion = gestion.nombrecargo;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (social != null)
{
jefe.tipoLabor = "Social";
jefe.descripcion = social.nombreproyecto;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (investigacion != null)
{
jefe.tipoLabor = "Investigación";
jefe.descripcion = investigacion.nombreproyecto;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGrado != null)
{
jefe.tipoLabor = "Trabajo De Grado";
jefe.descripcion = trabajoDeGrado.titulotrabajo;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
jefe.tipoLabor = "Trabajo De Grado De Investigación";
jefe.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (desarrolloProfesoral != null)
{
jefe.tipoLabor = "Desarrollo Profesoral";
jefe.descripcion = desarrolloProfesoral.nombreactividad;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (docencia != null)
{
materia materia = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
jefe.tipoLabor = "Docencia";
jefe.descripcion = materia.nombremateria;
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (otra != null)
{
jefe.tipoLabor = "Otra";
jefe.descripcion = otra.descripcion;
continue;
}
}
return lista;
}
#endregion
#region Evaluación
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult UpdateEvaluacion(int idEvaluacion, int calificacion)
{
evaluacion eval = dbEntity.evaluacion.Single(q => q.idevaluacion == idEvaluacion);
eval.evaluacionjefe = calificacion;
dbEntity.SaveChanges();
return null;
}
#endregion
/****** INICIO ADICIONADO POR CLARA*******/
#region ADICIONADO POR CLARA
#region Facultad
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchFacultad()
{
var response = dbEntity.facultad.Select(q => new { label = q.fac_nombre, id = q.idfacultad }).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
public ActionResult ObtenerFacultadPrograma()
{
List<FacultadPrograma> Facultades = new List<FacultadPrograma>();
foreach (var fac in dbEntity.facultad)
Facultades.Add(
new FacultadPrograma()
{
codfacultad = fac.idfacultad,
nomfacultad = fac.fac_nombre.ToString()
});
ViewBag.Facultades = Facultades;
return View(ViewBag.Facultades);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchFacultad(string term)
{
var response = dbEntity.facultad.Select(q => new { label = q.fac_nombre, id = q.idfacultad }).Where(q => q.label.ToUpper().Contains(term.ToUpper())).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetFacultad(string term)
{
int idp = int.Parse(term);
var dp = dbEntity.departamento.SingleOrDefault(q => q.iddepartamento == idp);
var response = dbEntity.facultad.SingleOrDefault(q => q.idfacultad == dp.idfacultad);
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult AjaxSetFacultad(facultad miFacultad)
{
if (ModelState.IsValid)
{
dbEntity.facultad.AddObject(miFacultad);
dbEntity.SaveChanges();
return Json(miFacultad, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
#endregion
#region Departamento
[Authorize]
public ActionResult ListProgramas()
{
ViewBag.facultades = dbEntity.facultad.ToList();
return View();
}
[Authorize]
public ActionResult SearchPrograma(string idFacultad, string term)
{
var response = dbEntity.departamento.Select(q => new { label = q.nombre, idf = q.idfacultad, nombre = q.nombre, idp = q.iddepartamento }).Where(q => q.label.ToUpper().Contains(term.ToUpper())).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchDepartment(string term)
{
var response = dbEntity.departamento.Select(q => new { label = q.nombre, id = q.iddepartamento }).Where(q => q.label.ToUpper().Contains(term.ToUpper())).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SortProgramas(string stridf, intListing[] list_ids)
{
int idf = int.Parse(stridf);
int idp;
try
{
for (int i = 1; i <= list_ids.Count(); i++)
{
idp = list_ids[(i - 1)].id;
departamento miPrograma = dbEntity.departamento.Single(q => q.iddepartamento == idp);
dbEntity.ObjectStateManager.ChangeObjectState(miPrograma, EntityState.Modified);
dbEntity.SaveChanges();
}
var response = dbEntity.departamento.Select(q => new { label = q.nombre, id = q.iddepartamento, idfa = q.idfacultad }).Where(q => q.idfa == idf).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(null, JsonRequestBehavior.AllowGet);
}
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetFacultadPrograma(string term)
{
int idf = int.Parse(term);
var response = dbEntity.departamento.Select(q => new { label = q.nombre, id = q.iddepartamento, idfa = q.idfacultad }).Where(q => q.idfa == idf).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
#endregion
#region Docente
[Authorize]
public ActionResult ListDocente()
{
ViewBag.optionmenu = 1;
ViewBag.facultades = dbEntity.facultad.ToList();
return View();
}
[Authorize]
public ActionResult VerDocentes(int id)
{
ViewBag.optionmenu = 1;
if (ModelState.IsValid)
{
var dep = dbEntity.departamento.SingleOrDefault(q => q.iddepartamento == id);
var response = GetTeachersFromDepartment(id);
ViewBag.datos = response;
ViewBag.departamento = dep.nombre;
return View();
}
return View();
}
[Authorize]
public ActionResult VerMDocentes(int id)
{
ViewBag.optionmenu = 1;
if (ModelState.IsValid)
{
var dep = dbEntity.departamento.SingleOrDefault(q => q.iddepartamento == id);
var response = GetTeachersFromDepartment(id);
ViewBag.datos = response;
ViewBag.departamento = dep.nombre;
return View();
}
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public List<DocenteDepto> GetTeachersFromDepartment(int iddepartment)
{
int currentper = (int)SessionValue("currentAcadPeriod");
var doc_depto = dbEntity.usuario
.Join(dbEntity.docente,
usu => usu.idusuario,
doc => doc.idusuario,
(usu, doc) => new { usuario = usu, docente = doc })
.Where(usu_doc => usu_doc.docente.iddepartamento == iddepartment && usu_doc.docente.estado == "activo");
var response = doc_depto.Select(q => new DocenteDepto { idususaio = q.usuario.idusuario, iddetp = q.docente.iddepartamento, iddocente = q.docente.iddocente, nombre = q.usuario.nombres, apellido = q.usuario.apellidos, estado = q.docente.estado }).OrderBy(q => q.apellido).ToList();
esjefe jefe = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == iddepartment && q.idperiodo == currentper);
foreach (var d in response)
try
{
if (jefe != null && d.iddocente == jefe.iddocente)
d.jefe = "checked";
else
d.jefe = "";
}
catch { d.jefe = ""; }
return (response);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetDepartamentoProfesores(string term)
{
int idd = int.Parse(term);
var response = dbEntity.usuario.Select(q => new { label = q.nombres, id = q.idusuario }).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
#endregion
#region Materias
public ActionResult ListSemestre(int id)
{
ViewBag.optionmenu = 1;
if (ModelState.IsValid)
{
var dep = dbEntity.departamento.SingleOrDefault(q => q.iddepartamento == id);
ViewBag.iddepa = dep.iddepartamento;
ViewBag.nombredepa = dep.nombre;
return View();
}
return View();
}
[Authorize]
public ActionResult ListMateria()
{
ViewBag.optionmenu = 1;
ViewBag.facultades = dbEntity.facultad.ToList();
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowMaterias(int idusuario)
{
ViewBag.optionmenu = 1;
ViewBag.reporte = crearReporteMateria(idusuario);
return View();
}
public ConsolidadoDocencia crearReporteMateria(int idUsuario)
{
int currentper = (int)SessionValue("currentAcadPeriod");
var docjefe = new docente();
var usujefe = new usuario();
ConsolidadoDocencia reporte;
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
var docente = dbEntity.docente.SingleOrDefault(q => q.idusuario == idUsuario);
var jefe = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == docente.iddepartamento && q.idperiodo == currentper);
if (jefe != null)
docjefe = dbEntity.docente.SingleOrDefault(q => q.iddocente == jefe.iddocente);
if (docjefe != null)
usujefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == docjefe.idusuario);
if (usujefe != null)
reporte = new ConsolidadoDocencia() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = usujefe.nombres + " " + usujefe.apellidos, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
else
reporte = new ConsolidadoDocencia() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = " ", fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
List<DetalleDocencia> labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join ld in dbEntity.docencia on l.idlabor equals ld.idlabor
join m in dbEntity.materia on ld.idmateria equals m.idmateria
//join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join ae in dbEntity.autoevaluacion on p.idautoevaluacion equals ae.idautoevaluacion
//join pg in dbEntity.programa on m.idprograma equals pg.idprograma
join pr in dbEntity.problema on ae.idautoevaluacion equals pr.idautoevaluacion
join s in dbEntity.resultado on ae.idautoevaluacion equals s.idautoevaluacion
where l.idperiodo == currentper && p.iddocente == docente.iddocente
select new DetalleDocencia
{
idLabDoc = l.idlabor,
idmateria = m.idmateria,
nombremateria = m.nombremateria,//grupo = m.grupo,tipo = m.tipo,idprograma= pg.idprograma, nombreprograma= pg.nombreprograma,
//horassemana = (int)ld.horassemana, semanaslaborales = (int)ld.semanaslaborales, creditos = (int)m.creditos, semestre = (int)m.semestre,
//evaluacionjefe = (int)e.evaluacionjefe, evaluacionestudiante = (int)e.evaluacionestudiante,
evaluacionautoevaluacion = (int)ae.calificacion,
problemadescripcion = pr.descripcion,
problemasolucion = pr.solucion,
resultadodescripcion = s.descripcion,
resultadosolucion = s.ubicacion
}).ToList();
reporte.labDocencia = labores;
//reporte.nombredocente = user.nombres + " " + user.apellidos;
//reporte.nombrejefe = usujefe.nombres + " " + usujefe.apellidos;
//reporte.periodoanio = (int)PeriodoSeleccionado.anio;
//reporte.periodonum = (int)PeriodoSeleccionado.numeroperiodo;
//reporte.fechaevaluacion = fecha_actual;
//reporte.totalhorassemana = (Double)labores.Sum(q => q.horasxsemana);
Debug.WriteLine("# labores" + labores.Count);
foreach (var l in labores)
{
Debug.WriteLine("lab " + l.idLabDoc + "mat " + l.idmateria);
}
//Debug.WriteLine("user 1 " + reporte.nombredocente);
//Debug.WriteLine("periodo 1 " + reporte.periodoanio);
return reporte;
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetMateriasPrograma(string term, string depa)
{
int sem = int.Parse(term);
int dep = int.Parse(depa);
int currentper = (int)SessionValue("currentAcadPeriod");
var response = (from l in dbEntity.labor
join d in dbEntity.docencia on l.idlabor equals d.idlabor
join m in dbEntity.materia on d.idmateria equals m.idmateria
where m.semestre == sem && m.idprograma == dep && l.idperiodo == currentper
select new Asignatura { id = m.idmateria, nombre = m.nombremateria }).Distinct().ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowAutoScoresMateria(string depa, string tipo)
{
ViewBag.optionmenu = 1;
int idD = int.Parse(depa);
int id = int.Parse(tipo);
ViewBag.reporte = reporteEvaluacionesMateria(idD, id);
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowScoresMateria(string depa, string tipo)
{
ViewBag.optionmenu = 1;
int idD = int.Parse(depa);
int id = int.Parse(tipo);
Debug.WriteLine("idl 1 " + id);
Debug.WriteLine("idl 2 " + idD);
ViewBag.reporte = reporteEvaluacionesMateria(idD, id);
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public List<ConsolidadoDocencia> reporteEvaluacionesMateria(int idD, int idM)
{
ViewBag.optionmenu = 1;
int currentper = (int)SessionValue("currentAcadPeriod");
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
List<ConsolidadoDocencia> MateriaEvaluada = new List<ConsolidadoDocencia>();
List<int> labores = (from l in dbEntity.labor
join d in dbEntity.docencia on l.idlabor equals d.idlabor
where d.idmateria == idM && l.idperiodo == currentper
select d.idlabor).Distinct().ToList();
foreach (var lab in labores)
{
List<usuDoc> docentes = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
where p.idlabor == lab && d.iddepartamento == idD
select new usuDoc { id = p.iddocente, nombre = u.nombres + " " + u.apellidos, idlab = p.idlabor }).Distinct().ToList();
materia mat = dbEntity.materia.SingleOrDefault(q => q.idmateria == idM);
docencia labdoc = dbEntity.docencia.SingleOrDefault(q => q.idlabor == lab);
foreach (var doc in docentes)
{
ConsolidadoDocencia datos = new ConsolidadoDocencia() { nombredocente = doc.nombre, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
datos.labDocencia = new List<DetalleDocencia>();
List<DetalleDocencia> lista = (from p in dbEntity.participa
join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join aev in dbEntity.autoevaluacion on p.idautoevaluacion equals aev.idautoevaluacion
join pr in dbEntity.problema on aev.idautoevaluacion equals pr.idautoevaluacion
join re in dbEntity.resultado on aev.idautoevaluacion equals re.idautoevaluacion
where p.idlabor == doc.idlab && p.iddocente == doc.id
select new DetalleDocencia
{
nombremateria = mat.nombremateria,
grupo = mat.grupo,
codmateria = mat.codigomateria,
creditos = (int)mat.creditos,
horassemana = (int)labdoc.horassemana,
semanaslaborales = (int)labdoc.semanaslaborales,
idLabDoc = lab,
evaluacionautoevaluacion = (int)e.evaluacionautoevaluacion,
evaluacionestudiante = (int)e.evaluacionestudiante,
evaluacionjefe = (int)e.evaluacionjefe,
problemadescripcion = pr.descripcion,
problemasolucion = pr.solucion,
resultadodescripcion = re.descripcion,
resultadosolucion = re.ubicacion
}).Distinct().ToList();
datos.labDocencia.AddRange(lista);
MateriaEvaluada.Add(datos);
}
}
return MateriaEvaluada;
}
#endregion
#region Autoevaluacion
[Authorize]
public ActionResult Autoevaluacion()
{
ViewBag.optionmenu = 1;
ViewBag.facultades = dbEntity.facultad.ToList();
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowAutoDocentes(int idusuario)
{
ViewBag.optionmenu = 1;
var response = crearReporteAutoevaluacion(idusuario);
ViewBag.reporte = response;
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowAutoScores(string depa, string tipo)
{
ViewBag.optionmenu = 1;
departamento dep = dbEntity.departamento.SingleOrDefault(q => q.nombre == depa);
var response = GetAutoFromDepartment(dep.iddepartamento);
ViewBag.reporte = response;
ViewBag.tipo = tipo;
ViewBag.dep = dep.nombre;
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public List<AutoevaluacionDocente> GetAutoFromDepartment(int iddepartment)
{
int currentper = (int)SessionValue("currentAcadPeriod");
var docjefe = new docente();
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
var jefe = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == iddepartment && q.idperiodo == currentper);
if (jefe != null)
docjefe = dbEntity.docente.SingleOrDefault(q => q.iddocente == jefe.iddocente);
List<AutoevaluacionDocente> ReporteAutoLabores = new List<AutoevaluacionDocente>();
var docentes = GetTeachersFromDepartment(iddepartment);
foreach (var doc in docentes)
{
ReporteAutoLabores.Add(crearReporteAutoevaluacion(doc.idususaio));
}
return (ReporteAutoLabores);
}
#endregion
#region Labores
[Authorize]
public ActionResult VerLabores(int id)
{
ViewBag.optionmenu = 1;
if (ModelState.IsValid)
{
var dep = dbEntity.departamento.SingleOrDefault(q => q.iddepartamento == id);
var response = GetWorksFromDepartment(id);
List<string> lab = new List<string>();
foreach (var l in response)
{
foreach (var a in l.detalleslabores)
{
if (!lab.Contains(a))
lab.Add(a);
}
}
ViewBag.labores = lab;
ViewBag.datos = response;
ViewBag.departamento = dep.nombre;
return View();
}
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowDetallesLabores(string depa, string tipo)
{
ViewBag.optionmenu = 1;
departamento dep = dbEntity.departamento.SingleOrDefault(q => q.nombre == depa);
var response = GetWorksFromDepartment(dep.iddepartamento);
ViewBag.reporte = response;
ViewBag.tipo = tipo;
ViewBag.dep = dep.nombre;
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public List<ConsolidadoLabores> GetWorksFromDepartment(int iddepartment)
{
int currentper = (int)SessionValue("currentAcadPeriod");
var docjefe = new docente();
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
var jefe = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == iddepartment && q.idperiodo == currentper);
var docentes = GetTeachersFromDepartment(iddepartment);
if (jefe != null)
docjefe = dbEntity.docente.SingleOrDefault(q => q.iddocente == jefe.iddocente);
foreach (var doc in docentes)
{
ReporteLabores1.Add(crearReporte(doc.idususaio));
}
return (ReporteLabores1);
}
public AutoevaluacionDocente crearReporteAutoevaluacion(int idUsuario)
{
departamento departamento = (departamento)Session["depto"];
AutoevaluacionDocente AutoevaluacionDocenteReporte;
var docjefe = new docente();
var usujefe = new usuario();
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
var docente = dbEntity.docente.SingleOrDefault(q => q.idusuario == idUsuario);
var jefe = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == docente.iddepartamento && q.idperiodo == currentper);
if (jefe != null)
docjefe = dbEntity.docente.SingleOrDefault(q => q.iddocente == jefe.iddocente);
if (docjefe != null)
usujefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == docjefe.idusuario);
if (usujefe != null)
{
AutoevaluacionDocenteReporte = new AutoevaluacionDocente() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = usujefe.nombres + " " + usujefe.apellidos, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
}
else
{
AutoevaluacionDocenteReporte = new AutoevaluacionDocente() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = "SIN JEFE ASIGNADO", fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
}
List<ResAutoEvaluacionLabor> labores = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join aev in dbEntity.autoevaluacion on p.idautoevaluacion equals aev.idautoevaluacion
join pr in dbEntity.problema on aev.idautoevaluacion equals pr.idautoevaluacion
join re in dbEntity.resultado on aev.idautoevaluacion equals re.idautoevaluacion
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == PeriodoSeleccionado.idperiodo && u.idusuario == idUsuario
select new ResAutoEvaluacionLabor { idlabor = l.idlabor, nota = (int)aev.calificacion, problemadescripcion = pr.descripcion, problemasolucion = pr.solucion, resultadodescripcion = re.descripcion, resultadosolucion = re.ubicacion }).ToList();
labores = setAELabor(labores);
AutoevaluacionDocenteReporte.autoevaluacioneslabores = labores;
return AutoevaluacionDocenteReporte;
}
public List<ResAutoEvaluacionLabor> setAELabor(List<ResAutoEvaluacionLabor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otra;
foreach (ResAutoEvaluacionLabor labor in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (gestion != null)
{
labor.tipolabor = "Gestion";
labor.tipolaborcorto = "GES";
labor.descripcion = gestion.nombrecargo;
//labor.horasxsemana = (int)gestion.horassemana;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (social != null)
{
labor.tipolabor = "Social";
labor.tipolaborcorto = "SOC";
labor.descripcion = social.nombreproyecto;
//labor.horasxsemana = (int)social.horassemana;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (investigacion != null)
{
labor.tipolabor = "Investigación";
labor.tipolaborcorto = "INV";
labor.descripcion = investigacion.nombreproyecto;
//labor.horasxsemana = (int)investigacion.horassemana;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGrado != null)
{
labor.tipolabor = "Trabajo de Grado";
labor.tipolaborcorto = "TDG";
labor.descripcion = trabajoDeGrado.titulotrabajo;
// labor.horasxsemana = (int)trabajoDeGrado.horassemana;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
labor.tipolabor = "Trabajo de Grado Investigación";
labor.tipolaborcorto = "TDGI";
labor.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
// labor.horasxsemana = (int)trabajoDeGradoInvestigacion.horassemana;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (desarrolloProfesoral != null)
{
labor.tipolabor = "Desarrollo Profesoral";
labor.tipolaborcorto = "DP";
labor.descripcion = desarrolloProfesoral.nombreactividad;
//labor.horasxsemana = (int)desarrolloProfesoral.horassemana;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (docencia != null)
{
materia materia = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
labor.tipolabor = "Docencia Directa";
labor.tipolaborcorto = "DD";
labor.descripcion = materia.nombremateria;
//labor.horasxsemana = (int)docencia.horassemana;
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (otra != null)
{
labor.tipolabor = "Otra";
labor.tipolaborcorto = "OTR";
labor.descripcion = otra.descripcion;
//labor.horasxsemana = (int)docencia.horassemana;
continue;
}
}
return lista;
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowLabores(int idusuario)
{
ViewBag.optionmenu = 1;
ViewBag.reporte = crearReporte(idusuario);
return View();
}
public ConsolidadoLabores setLabor(List<int> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otra;
ConsolidadoLabores labores = new ConsolidadoLabores();
labores.detalleslabores = new List<String>();
labores.labSocial = new List<social>();
labores.labGestion = new List<gestion>();
labores.labDocencia = new List<DocenciaMateria>();
labores.labInvestigacion = new List<investigacion>();
labores.labTrabajoDeGrado = new List<trabajodegrado>();
labores.labTrabajoDegradoInvestigacion = new List<trabajodegradoinvestigacion>();
labores.labDesarrolloProfesoral = new List<desarrolloprofesoral>();
labores.labOtras = new List<otras>();
for (var i = 0; i < lista.Count; i++)
{
int id = lista[i];
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == id);
if (gestion != null)
{
labores.labGestion.Add(gestion);
if (!labores.detalleslabores.Contains("Gestion"))
labores.detalleslabores.Add("Gestion");
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == id);
if (social != null)
{
labores.labSocial.Add(social);
if (!labores.detalleslabores.Contains("Social"))
labores.detalleslabores.Add("Social");
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == id);
if (investigacion != null)
{
labores.labInvestigacion.Add(investigacion);
if (!labores.detalleslabores.Contains("Investigación"))
labores.detalleslabores.Add("Investigación");
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == id);
if (trabajoDeGrado != null)
{
labores.labTrabajoDeGrado.Add(trabajoDeGrado);
if (!labores.detalleslabores.Contains("Trabajo de Grado"))
labores.detalleslabores.Add("Trabajo de Grado");
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == id);
if (trabajoDeGradoInvestigacion != null)
{
labores.labTrabajoDegradoInvestigacion.Add(trabajoDeGradoInvestigacion);
if (!labores.detalleslabores.Contains("Trabajo de Grado Investigación"))
labores.detalleslabores.Add("Trabajo de Grado Investigación");
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == id);
if (desarrolloProfesoral != null)
{
labores.labDesarrolloProfesoral.Add(desarrolloProfesoral);
if (!labores.detalleslabores.Contains("Desarrollo Profesoral"))
labores.detalleslabores.Add("Desarrollo Profesoral");
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == id);
if (docencia != null)
{
DocenciaMateria aux = new DocenciaMateria();
aux.DocMateria = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
aux.MatPrograma = dbEntity.programa.SingleOrDefault(p => p.idprograma == aux.DocMateria.idprograma);
aux.labDoc = docencia;
labores.labDocencia.Add(aux);
if (!labores.detalleslabores.Contains("Docencia Directa"))
labores.detalleslabores.Add("Docencia Directa");
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == id);
if (otra != null)
{
labores.labOtras.Add(otra);
if (!labores.detalleslabores.Contains("Otra"))
labores.detalleslabores.Add("Otra");
continue;
}
}
return labores;
}
public ActionResult ExportToExcelLabores()
{
SpreadsheetModelLabores mySpreadsheetAE = new SpreadsheetModelLabores();
String[] datos = new String[32];
datos[0] = "Docente";
datos[1] = "ID Labor";
datos[2] = "Tipo Corto";
datos[3] = "Tipo";
datos[4] = "Labor";
datos[5] = "Nota";
datos[6] = "Descripción Problema";
datos[7] = "Solución Problema";
datos[8] = "Descripción Solucion";
datos[9] = "Ubicación Solucion";
//Gestion
datos[10] = "Nombre Cargo";
datos[11] = "Horas Semana";
datos[12] = "Semanas Laborales";
datos[13] = "Unidad";
//Social
datos[14] = "Resolución";
datos[15] = "Nombre Proyecto";
datos[16] = "Fecha Inicio";
datos[17] = "Fecha Fin";
//Desarrollo Profesoral
datos[18] = "Nombre Actividad";
//Docencia
datos[19] = "Grupo";
datos[20] = "ID Materia";
//Materia
datos[21] = "Código Materia";
datos[22] = "Nombre Materia";
datos[23] = "Créditos";
datos[24] = "Semestre";
datos[25] = "Intensidad Horaria";
datos[26] = "Tipo";
datos[27] = "Programa";
//Investigación
datos[28] = "Código VRI";
//Trabajo Grado
datos[29] = "Título De Trabajo";
datos[30] = "Código Estudiante";
//Otra
datos[31] = "Descripcion";
mySpreadsheetAE.fechaevaluacion = ReporteLabores.fechaevaluacion;
mySpreadsheetAE.periodo = "" + ReporteLabores.periodonum + " - " + ReporteLabores.periodoanio;
mySpreadsheetAE.nombrejefe = ReporteLabores.nombrejefe;
mySpreadsheetAE.datos = datos;
mySpreadsheetAE.detalleslabores = new List<string>();
mySpreadsheetAE.detalleslabores.AddRange(ReporteLabores.detalleslabores);
mySpreadsheetAE.labSocial = new List<social>();
mySpreadsheetAE.labDesarrolloProfesoral = new List<desarrolloprofesoral>();
mySpreadsheetAE.labGestion = new List<gestion>();
mySpreadsheetAE.labDocencia = new List<DocenciaMateria>();
mySpreadsheetAE.labInvestigacion = new List<investigacion>();
mySpreadsheetAE.labTrabajoDeGrado = new List<trabajodegrado>();
mySpreadsheetAE.labTrabajoDegradoInvestigacion = new List<trabajodegradoinvestigacion>();
mySpreadsheetAE.labOtras = new List<otras>();
foreach (string tipo in ReporteLabores.detalleslabores)
{
switch (tipo)
{
case "Gestion":
for (int j = 0; j < ReporteLabores.labGestion.Count(); j++)
{
gestion aux = new gestion();
aux.idlabor = ReporteLabores.labGestion.ElementAt(j).idlabor;
aux.nombrecargo = ReporteLabores.labGestion.ElementAt(j).nombrecargo;
aux.horassemana = ReporteLabores.labGestion.ElementAt(j).horassemana;
aux.semanaslaborales = ReporteLabores.labGestion.ElementAt(j).semanaslaborales;
aux.unidad = ReporteLabores.labGestion.ElementAt(j).unidad;
mySpreadsheetAE.labGestion.Add(aux);
}
break;
case "Social":
for (int j = 0; j < ReporteLabores.labSocial.Count(); j++)
{
social aux = new social();
aux.idlabor = ReporteLabores.labSocial.ElementAt(j).idlabor;
aux.nombreproyecto = ReporteLabores.labSocial.ElementAt(j).nombreproyecto;
aux.resolucion = ReporteLabores.labSocial.ElementAt(j).resolucion;
aux.horassemana = ReporteLabores.labSocial.ElementAt(j).horassemana;
aux.unidad = ReporteLabores.labSocial.ElementAt(j).unidad;
aux.semanaslaborales = ReporteLabores.labSocial.ElementAt(j).semanaslaborales;
aux.fechafin = ReporteLabores.labSocial.ElementAt(j).fechafin;
aux.fechainicio = ReporteLabores.labSocial.ElementAt(j).fechainicio;
mySpreadsheetAE.labSocial.Add(aux);
}
break;
case "Desarrollo Profesoral":
for (int j = 0; j < ReporteLabores.labDesarrolloProfesoral.Count(); j++)
{
desarrolloprofesoral aux = new desarrolloprofesoral();
aux.idlabor = ReporteLabores.labDesarrolloProfesoral.ElementAt(j).idlabor;
aux.nombreactividad = ReporteLabores.labDesarrolloProfesoral.ElementAt(j).nombreactividad;
aux.resolucion = ReporteLabores.labDesarrolloProfesoral.ElementAt(j).resolucion;
aux.horassemana = ReporteLabores.labDesarrolloProfesoral.ElementAt(j).horassemana;
aux.semanaslaborales = ReporteLabores.labDesarrolloProfesoral.ElementAt(j).semanaslaborales;
mySpreadsheetAE.labDesarrolloProfesoral.Add(aux);
}
break;
case "Docencia Directa":
for (int j = 0; j < ReporteLabores.labDocencia.Count(); j++)
{
DocenciaMateria aux = new DocenciaMateria();
aux.DocMateria = new materia();
aux.labDoc = new docencia();
aux.MatPrograma = new programa();
aux.labDoc.idlabor = ReporteLabores.labDocencia.ElementAt(j).labDoc.idlabor;
aux.labDoc.idmateria = ReporteLabores.labDocencia.ElementAt(j).labDoc.idmateria;
aux.labDoc.grupo = ReporteLabores.labDocencia.ElementAt(j).labDoc.grupo;
aux.labDoc.horassemana = ReporteLabores.labDocencia.ElementAt(j).labDoc.horassemana;
aux.labDoc.semanaslaborales = ReporteLabores.labDocencia.ElementAt(j).labDoc.semanaslaborales;
aux.MatPrograma.idprograma = ReporteLabores.labDocencia.ElementAt(j).MatPrograma.idprograma;
aux.MatPrograma.nombreprograma = ReporteLabores.labDocencia.ElementAt(j).MatPrograma.nombreprograma;
aux.DocMateria.idmateria = ReporteLabores.labDocencia.ElementAt(j).DocMateria.idmateria;
aux.DocMateria.nombremateria = ReporteLabores.labDocencia.ElementAt(j).DocMateria.nombremateria;
aux.DocMateria.codigomateria = ReporteLabores.labDocencia.ElementAt(j).DocMateria.codigomateria;
aux.DocMateria.creditos = ReporteLabores.labDocencia.ElementAt(j).DocMateria.creditos;
aux.DocMateria.grupo = ReporteLabores.labDocencia.ElementAt(j).DocMateria.grupo;
aux.DocMateria.intensidadhoraria = ReporteLabores.labDocencia.ElementAt(j).DocMateria.intensidadhoraria;
aux.DocMateria.semestre = ReporteLabores.labDocencia.ElementAt(j).DocMateria.semestre;
aux.DocMateria.tipo = ReporteLabores.labDocencia.ElementAt(j).DocMateria.tipo;
mySpreadsheetAE.labDocencia.Add(aux);
}
break;
case "Investigacion":
for (int j = 0; j < ReporteLabores.labInvestigacion.Count(); j++)
{
investigacion aux = new investigacion();
aux.idlabor = ReporteLabores.labInvestigacion.ElementAt(j).idlabor;
aux.nombreproyecto = ReporteLabores.labInvestigacion.ElementAt(j).nombreproyecto;
aux.codigovri = ReporteLabores.labInvestigacion.ElementAt(j).codigovri;
aux.horassemana = ReporteLabores.labInvestigacion.ElementAt(j).horassemana;
aux.semanaslaborales = ReporteLabores.labInvestigacion.ElementAt(j).semanaslaborales;
aux.fechafin = ReporteLabores.labInvestigacion.ElementAt(j).fechafin;
aux.fechainicio = ReporteLabores.labInvestigacion.ElementAt(j).fechainicio;
mySpreadsheetAE.labInvestigacion.Add(aux);
}
break;
case "Trabajo de Grado":
for (int j = 0; j < ReporteLabores.labTrabajoDeGrado.Count(); j++)
{
trabajodegrado aux = new trabajodegrado();
aux.idlabor = ReporteLabores.labTrabajoDeGrado.ElementAt(j).idlabor;
aux.titulotrabajo = ReporteLabores.labTrabajoDeGrado.ElementAt(j).titulotrabajo;
aux.resolucion = ReporteLabores.labTrabajoDeGrado.ElementAt(j).resolucion;
aux.horassemana = ReporteLabores.labTrabajoDeGrado.ElementAt(j).horassemana;
aux.semanaslaborales = ReporteLabores.labTrabajoDeGrado.ElementAt(j).semanaslaborales;
aux.fechafin = ReporteLabores.labTrabajoDeGrado.ElementAt(j).fechafin;
aux.fechainicio = ReporteLabores.labTrabajoDeGrado.ElementAt(j).fechainicio;
aux.codigoest = ReporteLabores.labTrabajoDeGrado.ElementAt(j).codigoest;
mySpreadsheetAE.labTrabajoDeGrado.Add(aux);
}
break;
case "Trabajo de Grado Investigación":
for (int j = 0; j < ReporteLabores.labTrabajoDegradoInvestigacion.Count(); j++)
{
trabajodegradoinvestigacion aux = new trabajodegradoinvestigacion();
aux.idlabor = ReporteLabores.labTrabajoDegradoInvestigacion.ElementAt(j).idlabor;
aux.titulotrabajo = ReporteLabores.labTrabajoDegradoInvestigacion.ElementAt(j).titulotrabajo;
aux.horassemana = ReporteLabores.labTrabajoDegradoInvestigacion.ElementAt(j).horassemana;
aux.semanaslaborales = ReporteLabores.labTrabajoDegradoInvestigacion.ElementAt(j).semanaslaborales;
aux.codigoest = ReporteLabores.labTrabajoDegradoInvestigacion.ElementAt(j).codigoest;
mySpreadsheetAE.labTrabajoDegradoInvestigacion.Add(aux);
}
break;
case "Otra":
for (int j = 0; j < ReporteLabores.labOtras.Count(); j++)
{
otras aux = new otras();
aux.idlabor = ReporteLabores.labOtras.ElementAt(j).idlabor;
aux.descripcion = ReporteLabores.labOtras.ElementAt(j).descripcion;
aux.horassemana = ReporteLabores.labOtras.ElementAt(j).horassemana;
mySpreadsheetAE.labOtras.Add(aux);
}
break;
}
}
periodo_academico lastAcademicPeriod = GetLastAcademicPeriod();
DateTime Hora = DateTime.Now;
DateTime Hoy = DateTime.Today;
string hora = Hora.ToString("HH:mm");
string hoy = Hoy.ToString("dd-MM");
mySpreadsheetAE.fileName = "Reporte" + lastAcademicPeriod.anio + "-" + lastAcademicPeriod.idperiodo + "_" + hoy + "_" + hora + ".xls";
return View(mySpreadsheetAE);
}
public int obtenerFilasRM()
{
int filasReporte = 0;
foreach (ConsolidadoDocencia filas in ReporteMaterias)
{
filasReporte = filasReporte + filas.labDocencia.Count() + 1;
}
return filasReporte;
}
#endregion
public class DocenteDepto
{
public String nombre;
public String apellido;
public String estado;
public int iddetp;
public int iddocente;
public int idususaio;
public String jefe;
}
public class Lab
{
public int id;
public String tipo;
}
public class evaluaciones
{
public int idevaluacion;
public int idautoevaluacion;
}
public class usuDoc
{
public int id;
public string nombre;
public int idlab;
}
#endregion
/******FIN ADICIONADO POR CLARA *******/
#region Importar Datos De SIMCA
[Authorize]
public ActionResult ImportDataSIMCA()
{
ViewBag.optionmenu = 3;
return View(new List<DocenteMateria>());
}
[Authorize]
[HttpPost]
public ActionResult ImportDataSIMCA(HttpPostedFileBase excelfile)
{
ViewBag.optionmenu = 3;
var guardados = new List<DocenteMateria>();
var noguardados = new List<DocenteMateria>();
var vistaDocenteMateria = new List<DocenteMateria>();
var tablaDatosSIMCA = new List<DocenteMateria>();
if (excelfile != null)
{
String extension = Path.GetExtension(excelfile.FileName);
String filename = Path.GetFileName(excelfile.FileName);
String filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(excelfile.FileName));
if (extension == ".xls" || extension == ".xlsx")
{
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
excelfile.SaveAs(filePath);
try
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Password=\"\";User ID=Admin;Data Source=" + filePath.ToString() + ";Mode=Share Deny Write;Extended Properties=\"HDR=YES;\";Jet OLEDB:Engine Type=37";
System.Data.OleDb.OleDbConnection oconn = new System.Data.OleDb.OleDbConnection(connectionString);
oconn.Open();
string sInvalidas;
bool valido = ExcelValidation(oconn, out sInvalidas, 1);
if (valido)
{
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("SELECT * FROM [Docentes$]", oconn);
DataSet myDataSet = new DataSet();
dataAdapter.Fill(myDataSet, "Docentes");
DataTable dataTable = myDataSet.Tables["Docentes"];
var rows = from p in dataTable.AsEnumerable()
select new
{
codMateria = p[0],
nombreMateria = p[1],
grupo = p[2],
identificacion = p[3],
total = p[4],
};
var id = new List<int>();
// modificado febrero 4
int currentper = (int)SessionValue("currentAcadPeriod");
vistaDocenteMateria = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join lab in dbEntity.labor on p.idlabor equals lab.idlabor
join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join doc in dbEntity.docencia on p.idlabor equals doc.idlabor
join mat in dbEntity.materia on doc.idmateria equals mat.idmateria
where lab.idperiodo.Equals(currentper)
select new DocenteMateria { identificacion = u.identificacion, nombres = u.nombres, apellidos = u.apellidos, email = u.emailinstitucional, nombremateria = mat.nombremateria, codigomateria = mat.codigomateria, grupo = mat.grupo, ideval = e.idevaluacion }).ToList();
Debug.WriteLine("filas " + rows.Count());
foreach (var row in rows)
{
DocenteMateria dm = new DocenteMateria();
string identificacion = row.identificacion.ToString();
string codigo = row.codMateria.ToString();
string nombre = row.nombreMateria.ToString();
string grupo = row.grupo.ToString();
string total = row.total.ToString();
if (identificacion != "" && codigo != "" && nombre != "" && grupo != "" && total != "")
{
dm.identificacion = identificacion;
dm.codigomateria = codigo;
dm.nombremateria = nombre;
dm.grupo = grupo;
try
{
dm.evalest = Convert.ToInt16(total);
}
catch(Exception ex)
{
Utilities.ManageException(ex, Server.MapPath(@"..\generalLog.txt"));
dm.evalest = 0;
}
dm.guardado = 0;
tablaDatosSIMCA.Add(dm);
}
}
int cont = 0;
foreach (DocenteMateria ds in tablaDatosSIMCA)
{
foreach (DocenteMateria dv in vistaDocenteMateria)
{
try
{
if (ds.identificacion == dv.identificacion)
{
if (ds.codigomateria == dv.codigomateria && ds.grupo == dv.grupo)
{
evaluacion eval = dbEntity.evaluacion.Single(q => q.idevaluacion == dv.ideval);
eval.evaluacionestudiante = ds.evalest;
dv.evalest = ds.evalest;
dbEntity.SaveChanges();
ds.grupo = dv.grupo;
ds.identificacion = dv.identificacion;
ds.nombres = dv.nombres;
ds.apellidos = dv.apellidos;
ds.nombremateria = dv.nombremateria;
ds.guardado = 1;
}
else
{
cont++;
}
}
}
catch { }
}
if (ds.guardado == 0)
{
cont++;
}
}
}
else
{
ViewBag.Error += "El formato de archivo no es valido";
}
oconn.Close();
System.IO.File.Delete(filePath);
}
catch (Exception ex)
{
Utilities.ManageException(ex, Server.MapPath(@"..\generalLog.txt"));
ViewBag.Error = "No se pudo abrir el archivo, consulte el formato del mismo";
}
}
else
{
ViewBag.Error = "Solo se admiten archivos excel .xls o .xlsx";
}
}
else
{
ViewBag.Error = "No Recibido";
}
return View(tablaDatosSIMCA);
}
#endregion
//#region Importar Datos de Evaluacion desde EXCEL
//[Authorize]
//public ActionResult ImportDataEvaluations()
//{
// ViewBag.optionmenu = 5;
// return View(new List<savedDataSIGELA>());
//}
//#endregion
#region Importar Datos De SIGELA MODIFICADO POR AMBOS
[Authorize]
public ActionResult ImportDataSIGELA()
{
ViewBag.optionmenu = 3;
return View(new List<savedDataSIGELA>());
}
public List<savedDataSIGELA> ProcessImportDataSIGELA(HttpPostedFileBase excelfile,
int periodId,ref string sError,ref string FileValid,ref int LabsReg, ref int TeacReg)
{
string connectionString = "";
System.Data.OleDb.OleDbConnection oconn = new OleDbConnection();
List<savedDataSIGELA> savedsigela = new List<savedDataSIGELA>();
if (excelfile != null)
{
String extension = Path.GetExtension(excelfile.FileName);
String filename = Path.GetFileName(excelfile.FileName);
String filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename);
if (extension == ".xls" || extension == ".xlsx")
{
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
excelfile.SaveAs(filePath);
try
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Password=\"\";User ID=Admin;Data Source=" + filePath.ToString() + ";Mode=Share Deny Write;Extended Properties=\"HDR=YES;\";Jet OLEDB:Engine Type=37";
oconn = new System.Data.OleDb.OleDbConnection(connectionString);
oconn.Open();
string sInvalidas = "";
bool valido = ExcelValidation(oconn, out sInvalidas);
if (valido)
{
int currentper = periodId;
List<docenteSIGELA> docs_sig = this.data_imports.getDocentes(); //Obtener la lista de docentes desde excel edv
List<docenteSIGELA> saveddtes = TeacherImportSave(docs_sig);
savedsigela = TeachingImportSave(this.data_imports.getDocencias(), currentper);
savedsigela = savedsigela.Concat(TeacherProfDevImportSave(this.data_imports.getDlloProfesoral(), currentper)).ToList();
savedsigela = savedsigela.Concat(ResearchGradeWorkImportSave(this.data_imports.getTrabajoGdoInv(), currentper)).ToList();
savedsigela = savedsigela.Concat(GradeWorkImportSave(this.data_imports.getTrabajoGdo(), currentper)).ToList();
savedsigela = savedsigela.Concat(ResearchImportSave(this.data_imports.getInvestigacion(), currentper)).ToList();
savedsigela = savedsigela.Concat(SocialImportSave(this.data_imports.getSocial(), currentper)).ToList();
savedsigela = savedsigela.Concat(ManagementImportSave(this.data_imports.getGestion(), currentper)).ToList();
// nuevo febrero 3
savedsigela = savedsigela.Concat(OtrasImportSave(this.data_imports.getOtras(), currentper)).ToList();
FileValid = "El archivo " + filename + " recibido es valido";
LabsReg = savedsigela.Count();
TeacReg = docs_sig.Count();
}
else
{
sError = "Excel no valido. Revise las hojas: " + sInvalidas;
}
oconn.Close();
System.IO.File.Delete(filePath);
}
catch (Exception ex)
{
if (oconn.State != ConnectionState.Closed)
{
oconn.Close();
}
sError = "No se pudo abrir el archivo de excel " + ex;
}
}
else
{
sError = "Solo se admiten archivos excel .xls o .xlsx";
}
}
else
{
sError = "Archivo no recibido";
}
return savedsigela;
}
// modificado 3 febrero
[Authorize]
[HttpPost]
public ActionResult ImportDataSIGELA(HttpPostedFileBase excelfile)
{
ViewBag.optionmenu = 5;
List<savedDataSIGELA> oResult;
string sError = "";
string sFileValid = "";
int LabsReg = 0;
int TeacReg = 0;
oResult = ProcessImportDataSIGELA(excelfile, (int)Session["currentAcadPeriod"], ref sError, ref sFileValid, ref LabsReg, ref TeacReg);
ViewBag.FileValid = sFileValid;
ViewBag.Labsreg = LabsReg;
ViewBag.Teacreg = TeacReg;
if (sError != "")
ViewBag.Error = sError;
return View(oResult);
}
// modificado febrero 3
[Authorize]
public List<savedDataSIGELA> ManagementImportSave(List<gestionSIGELA> list, int currentper)
{
List<savedDataSIGELA> savedManage = new List<savedDataSIGELA>();
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
foreach (gestionSIGELA man in list)
{
try
{
int iddoc = GetIdDocenteByIdentification(man.identificacion);
docente undocente = dbEntity.docente.SingleOrDefault(q => q.iddocente == iddoc);
usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.idusuario == undocente.idusuario);
var docenteGes = (from d in dbEntity.gestion
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
join usu in dbEntity.usuario on doc.idusuario equals usu.idusuario
where d.nombrecargo.Equals(man.nombrecargo)
where lab.idperiodo.Equals(currentper)
where usu.identificacion.Equals(man.identificacion)
where d.unidad.Equals(man.unidad)
select new gestionSIGELA { nombrecargo = d.nombrecargo }).Distinct().ToList();
//Para verificar que no ingresen una labor si esta ya existe
if (docenteGes.Count() == 0)
{
try
{
labor unalabor = new labor() { idperiodo = currentper };
dbEntity.labor.AddObject(unalabor);
dbEntity.SaveChanges();
gestion ungestion = new gestion() { idlabor = unalabor.idlabor, horassemana = man.horassemana, semanaslaborales = man.semanaslaborales, unidad = man.unidad, nombrecargo = man.nombrecargo };
dbEntity.gestion.AddObject(ungestion);
dbEntity.SaveChanges();
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
//INICO ADICIONADO POR CLARA
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
//FIN ADICIONADO POR CLARA
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedManage.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Gestion", nombrelabor = man.nombrecargo });
}
catch (Exception ex) { }
}
if (docenteGes.Count() > 0)
{
var docenteGesEsta = (from d in dbEntity.gestion
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
where d.nombrecargo.Equals(man.nombrecargo)
where lab.idperiodo.Equals(currentper)
where p.iddocente.Equals(iddoc)
select new gestionSIGELA { nombrecargo = d.nombrecargo }).Distinct().ToList();
if (docenteGesEsta.Count() == 0)
{
try
{
//labor unalabor = new labor() { idperiodo = currentper };
//dbEntity.labor.AddObject(unalabor);
//dbEntity.SaveChanges();
//gestion ungestion = new gestion() { idlabor = unalabor.idlabor, horassemana = man.horassemana, semanaslaborales = man.semanaslaborales, unidad = man.unidad, nombrecargo = man.nombrecargo };
//dbEntity.gestion.AddObject(ungestion);
//dbEntity.SaveChanges();
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
//INICO ADICIONADO POR CLARA
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
//FIN ADICIONADO POR CLARA
// nuevo febrero 3
var maxid = (from pa in dbEntity.gestion
where pa.nombrecargo.Equals(man.nombrecargo)
select pa.idlabor).Max();
gestion unalabor = dbEntity.gestion.FirstOrDefault(gt => gt.idlabor == maxid && gt.nombrecargo == man.nombrecargo);
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedManage.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Gestion", nombrelabor = man.nombrecargo });
}
catch (Exception ex) { }
}
}
}
catch { }
}
return savedManage;
}
// nuevo febrero 3
[Authorize]
public List<savedDataSIGELA> OtrasImportSave(List<otrasSIGELA> list, int currentper)
{
List<savedDataSIGELA> savedManage = new List<savedDataSIGELA>();
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
// aqui voy
foreach (otrasSIGELA man in list)
{
try
{
int iddoc = GetIdDocenteByIdentification(man.identificacion);
docente undocente = dbEntity.docente.SingleOrDefault(q => q.iddocente == iddoc);
usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.idusuario == undocente.idusuario);
var otrasVar = (from d in dbEntity.otras
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
join usu in dbEntity.usuario on doc.idusuario equals usu.idusuario
where usu.identificacion.Equals(man.identificacion)
where d.descripcion.Equals(man.descripcion)
where lab.idperiodo.Equals(currentper)
select new otrasSIGELA { descripcion = d.descripcion }).Distinct().ToList();
//Para verificar que no ingresen una labor si esta ya existe
if (otrasVar.Count() == 0)
{
try
{
labor unalabor = new labor() { idperiodo = currentper };
dbEntity.labor.AddObject(unalabor);
dbEntity.SaveChanges();
otras unOtra = new otras() { idlabor = unalabor.idlabor, descripcion = man.descripcion, horassemana = man.horassemana };
dbEntity.otras.AddObject(unOtra);
dbEntity.SaveChanges();
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedManage.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Otras", nombrelabor = man.descripcion });
}
catch (Exception ex) { }
}
if (otrasVar.Count() > 0)
{
var otrasVarEsta = (from d in dbEntity.otras
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
where d.descripcion.Equals(man.descripcion)
where lab.idperiodo.Equals(currentper)
where doc.iddocente.Equals(iddoc)
select new otrasSIGELA { descripcion = d.descripcion }).Distinct().ToList();
if (otrasVarEsta.Count() == 0)
{
try
{
//labor unalabor = new labor() { idperiodo = currentper };
//dbEntity.labor.AddObject(unalabor);
//dbEntity.SaveChanges();
//gestion ungestion = new gestion() { idlabor = unalabor.idlabor, horassemana = man.horassemana, semanaslaborales = man.semanaslaborales, unidad = man.unidad, nombrecargo = man.nombrecargo };
//dbEntity.gestion.AddObject(ungestion);
//dbEntity.SaveChanges();
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
//INICO ADICIONADO POR CLARA
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
//FIN ADICIONADO POR CLARA
// nuevo febrero 3
var maxid = (from pa in dbEntity.otras
where pa.descripcion.Equals(man.descripcion)
select pa.idlabor).Max();
otras unalabor = dbEntity.otras.FirstOrDefault(gt => gt.idlabor == maxid && gt.descripcion == man.descripcion);
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedManage.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Otras", nombrelabor = man.descripcion });
}
catch (Exception ex) { }
}
}
}
catch { }
}
return savedManage;
}
// modificado febrero 3
[Authorize]
public List<savedDataSIGELA> SocialImportSave(List<socialSIGELA> list, int currentper)
{
List<savedDataSIGELA> savedSocial = new List<savedDataSIGELA>();
foreach (socialSIGELA soc in list)
{
try
{
int iddoc = GetIdDocenteByIdentification(soc.identificacion);
docente undocente = dbEntity.docente.SingleOrDefault(q => q.iddocente == iddoc);
usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.idusuario == undocente.idusuario);
var docenteSoc = (from d in dbEntity.social
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
join usu in dbEntity.usuario on doc.idusuario equals usu.idusuario
where d.nombreproyecto.Equals(soc.nombreproyecto)
where lab.idperiodo.Equals(currentper)
where d.resolucion.Equals(soc.resolucion)
where usu.identificacion.Equals(soc.identificacion)
where d.unidad.Equals(soc.unidad)
select new socialSIGELA { nombreproyecto = d.nombreproyecto, resolucion = d.resolucion }).Distinct().ToList();
//Para verificar que no ingresen una labor si esta ya existe
if (docenteSoc.Count() == 0)
{
try
{
labor unalabor = new labor() { idperiodo = currentper };
dbEntity.labor.AddObject(unalabor);
dbEntity.SaveChanges();
social unsocial = new social() { idlabor = unalabor.idlabor, horassemana = soc.horassemana, semanaslaborales = soc.semanaslaborales, resolucion = soc.resolucion, unidad = soc.unidad, fechainicio = DateTime.Parse(soc.fechainicio), fechafin = DateTime.Parse(soc.fechafin), nombreproyecto = soc.nombreproyecto };
dbEntity.social.AddObject(unsocial);
dbEntity.SaveChanges();
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
//INICO ADICIONADO POR CLARA
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
//FIN ADICIONADO POR CLARA
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedSocial.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Social", nombrelabor = soc.nombreproyecto });
}
catch (Exception ex) { }
}
if (docenteSoc.Count() > 0)
{
var docenteSocEsta = (from d in dbEntity.social
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
where d.nombreproyecto.Equals(soc.nombreproyecto)
where lab.idperiodo.Equals(currentper)
where p.iddocente.Equals(iddoc)
select new socialSIGELA { nombreproyecto = d.nombreproyecto, resolucion = d.resolucion }).Distinct().ToList();
if (docenteSocEsta.Count() == 0)
{
try
{
//labor unalabor = new labor() { idperiodo = currentper };
//dbEntity.labor.AddObject(unalabor);
//dbEntity.SaveChanges();
//social unsocial = new social() { idlabor = unalabor.idlabor, horassemana = soc.horassemana, semanaslaborales = soc.semanaslaborales, resolucion = soc.resolucion, unidad = soc.unidad, fechainicio = DateTime.Parse(soc.fechainicio), fechafin = DateTime.Parse(soc.fechafin), nombreproyecto = soc.nombreproyecto };
//dbEntity.social.AddObject(unsocial);
//dbEntity.SaveChanges();
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
//INICO ADICIONADO POR CLARA
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
//FIN ADICIONADO POR CLARA
// nuevo febrero 3
var maxid = (from pa in dbEntity.social
where pa.nombreproyecto.Equals(soc.nombreproyecto)
select pa.idlabor).Max();
social unalabor = dbEntity.social.FirstOrDefault(sc => sc.idlabor == maxid && sc.nombreproyecto == soc.nombreproyecto);
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedSocial.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Social", nombrelabor = soc.nombreproyecto });
}
catch (Exception ex) { }
}
}
}
catch { }
}
return savedSocial;
}
// modificado febrero 3
[Authorize]
public List<savedDataSIGELA> ResearchImportSave(List<investigacionSIGELA> list, int currentper)
{
List<savedDataSIGELA> savedResearch = new List<savedDataSIGELA>();
foreach (investigacionSIGELA inv in list)
{
try
{
int iddoc = GetIdDocenteByIdentification(inv.identificacion);
docente undocente = dbEntity.docente.SingleOrDefault(q => q.iddocente == iddoc);
usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.idusuario == undocente.idusuario);
var docenteInv = (from d in dbEntity.investigacion
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
join usu in dbEntity.usuario on doc.idusuario equals usu.idusuario
where d.nombreproyecto.Equals(inv.nombreproyecto)
where lab.idperiodo.Equals(currentper)
where d.codigovri.Equals(inv.codigovri)
where usu.identificacion.Equals(inv.identificacion)
select new investigacionSIGELA { nombreproyecto = d.nombreproyecto, codigovri = d.codigovri }).Distinct().ToList();
//Para verificar que no ingresen una labor si esta ya existe
if (docenteInv.Count() == 0)
{
try
{
labor unalabor = new labor() { idperiodo = currentper };
dbEntity.labor.AddObject(unalabor);
dbEntity.SaveChanges();
investigacion untrabajo = new investigacion() { idlabor = unalabor.idlabor, codigovri = inv.codigovri, horassemana = inv.horassemana, semanaslaborales = inv.semanaslaborales, fechainicio = DateTime.Parse(inv.fechainicio), fechafin = DateTime.Parse(inv.fechafin), nombreproyecto = inv.nombreproyecto };
dbEntity.investigacion.AddObject(untrabajo);
dbEntity.SaveChanges();
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
//INICO ADICIONADO POR CLARA
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
//FIN ADICIONADO POR CLARA
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedResearch.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Investigación", nombrelabor = inv.nombreproyecto });
}
catch (Exception ex) { }
}
if (docenteInv.Count() > 0)
{
var docenteInvEsta = (from d in dbEntity.investigacion
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
where d.nombreproyecto.Equals(inv.nombreproyecto)
where lab.idperiodo.Equals(currentper)
where p.iddocente.Equals(iddoc)
select new investigacionSIGELA { nombreproyecto = d.nombreproyecto, codigovri = d.codigovri }).Distinct().ToList();
if (docenteInvEsta.Count() == 0)
{
try
{
//labor unalabor = new labor() { idperiodo = currentper };
//dbEntity.labor.AddObject(unalabor);
//dbEntity.SaveChanges();
//investigacion untrabajo = new investigacion() { idlabor = unalabor.idlabor, codigovri = inv.codigovri, horassemana = inv.horassemana, semanaslaborales = inv.semanaslaborales, fechainicio = DateTime.Parse(inv.fechainicio), fechafin = DateTime.Parse(inv.fechafin), nombreproyecto = inv.nombreproyecto };
//dbEntity.investigacion.AddObject(untrabajo);
//dbEntity.SaveChanges();
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
//INICO ADICIONADO POR CLARA
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
//FIN ADICIONADO POR CLARA
// nuevo febrero 3
var maxid = (from pa in dbEntity.investigacion
where pa.nombreproyecto.Equals(inv.nombreproyecto)
select pa.idlabor).Max();
investigacion unalabor = dbEntity.investigacion.FirstOrDefault(investig => investig.idlabor == maxid && investig.nombreproyecto == inv.nombreproyecto);
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedResearch.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Investigación", nombrelabor = inv.nombreproyecto });
}
catch (Exception ex) { }
}
}
}
catch { }
}
return savedResearch;
}
// modificado febrero 3
[Authorize]
public List<savedDataSIGELA> GradeWorkImportSave(List<trabajoGdoSIGELA> list, int currentper)
{
List<savedDataSIGELA> savedGradeWork = new List<savedDataSIGELA>();
foreach (trabajoGdoSIGELA tg in list)
{
try
{
int iddoc = GetIdDocenteByIdentification(tg.identificacion);
docente undocente = dbEntity.docente.SingleOrDefault(q => q.iddocente == iddoc);
usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.idusuario == undocente.idusuario);
var docenteTrabGrad = (from d in dbEntity.trabajodegrado
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
join usu in dbEntity.usuario on doc.idusuario equals usu.idusuario
where usu.identificacion.Equals(tg.identificacion)
where d.titulotrabajo.Equals(tg.titulotrabajo)
where lab.idperiodo.Equals(currentper)
where d.resolucion.Equals(tg.resolucion)
select new trabajoGdoSIGELA { titulotrabajo = d.titulotrabajo, resolucion = d.resolucion }).Distinct().ToList();
//Para verificar que no ingresen una labor si esta ya existe
if (docenteTrabGrad.Count() == 0)
{
try
{
labor unalabor = new labor() { idperiodo = currentper };
dbEntity.labor.AddObject(unalabor);
dbEntity.SaveChanges();
int idprog = GetIdProgramaByName(tg.programa);
trabajodegrado untrabajo = new trabajodegrado() { idlabor = unalabor.idlabor, idprograma = idprog, codigoest = tg.codigoest, horassemana = tg.horassemana, semanaslaborales = tg.semanaslaborales, resolucion = tg.resolucion, titulotrabajo = tg.titulotrabajo };
dbEntity.trabajodegrado.AddObject(untrabajo);
dbEntity.SaveChanges();
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
//INICO ADICIONADO POR CLARA
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
//FIN ADICIONADO POR CLARA
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedGradeWork.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Trabajo De Grado", nombrelabor = tg.titulotrabajo });
RegisterStudentForResearchGradeWork(untrabajo.codigoest, untrabajo.titulotrabajo);
}
catch (Exception ex) { }
}
if (docenteTrabGrad.Count() > 0)
{
var trabGradEsta = (from d in dbEntity.trabajodegrado
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
where d.titulotrabajo.Equals(tg.titulotrabajo)
where lab.idperiodo.Equals(currentper)
where p.iddocente.Equals(iddoc)
select new trabajoGdoSIGELA { titulotrabajo = d.titulotrabajo, resolucion = d.resolucion }).Distinct().ToList();
if (trabGradEsta.Count() == 0)
{
try
{
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
var maxid = (from pa in dbEntity.trabajodegrado
where pa.titulotrabajo.Equals(tg.titulotrabajo)
select pa.idlabor).Max();
trabajodegrado unalabor = dbEntity.trabajodegrado.FirstOrDefault(tr => tr.idlabor == maxid && tr.titulotrabajo == tg.titulotrabajo);
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedGradeWork.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Trabajo De Grado", nombrelabor = tg.titulotrabajo });
RegisterStudentForResearchGradeWork(unalabor.codigoest, unalabor.titulotrabajo);
}
catch (Exception ex) { }
}
}
}
catch { }
}
return savedGradeWork;
}
/// <summary>
/// Obtiene nombres y apellidos de un nombre completo
/// </summary>
/// <param name="fullName"></param>
/// <param name="?"></param>
/// <param name="?"></param>
public void SplitFullName(string fullName, ref string sNames, ref string sLastNames)
{
string[] lstNames = fullName.Trim().Split(' ');
switch (lstNames.Length)
{
case 1:
sNames = lstNames[0];
break;
case 2:
sNames = lstNames[0];
sLastNames = lstNames[1];
break;
case 3:
sNames = lstNames[0];
sLastNames = lstNames[1] + ' ' + lstNames[2];
break;
default:
sNames = lstNames[0] + ' ' + lstNames[1];
sLastNames = lstNames[2] + ' ' + lstNames[3];
break;
}
}
/// <summary>
/// Registra un estudiante para que sea el evaluador de la labor
/// </summary>
/// <param name="untrabajoinv"></param>
private void RegisterStudentForResearchGradeWork(long codigoest, string titulotrabajo)
{
string sCodigoEst = codigoest.ToString();
/// Ristrar usuarios para evaluacion de docentes
var lstEstudiantes = (from u in dbEntity.usuario
where u.identificacion.Equals(sCodigoEst)
select u.idusuario).ToList();
if (lstEstudiantes.Count == 0)
{
string snombres = "", sapellidos = "";
SplitFullName(titulotrabajo, ref snombres, ref sapellidos);
usuario oEstudiante = new usuario()
{
nombres = snombres,
apellidos = sapellidos,
rol = "Estudiante",
emailinstitucional = (codigoest.ToString().Trim() + <EMAIL>"),
password = md5(codigoest.ToString().Trim()),
identificacion = codigoest.ToString()
};
dbEntity.usuario.AddObject(oEstudiante);
dbEntity.SaveChanges();
}
RegistrarUsuarioConRol(codigoest.ToString().Trim() + <EMAIL>", codigoest.ToString().Trim(), "Student");
}
// nuevo febrero 3
[Authorize]
public List<savedDataSIGELA> ResearchGradeWorkImportSave(List<trabajoGdoInvSIGELA> list, int currentper)
{
List<savedDataSIGELA> savedResearchGradeWork = new List<savedDataSIGELA>();
foreach (trabajoGdoInvSIGELA tgi in list)
{
try
{
int iddoc = GetIdDocenteByIdentification(tgi.identificacion);
docente undocente = dbEntity.docente.SingleOrDefault(q => q.iddocente == iddoc);
usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.idusuario == undocente.idusuario);
var docenteDlloProf = (from d in dbEntity.trabajodegradoinvestigacion
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
join usu in dbEntity.usuario on doc.idusuario equals usu.idusuario
where usu.identificacion.Equals(tgi.identificacion)
where d.titulotrabajo.Equals(tgi.titulotrabajo)
where lab.idperiodo.Equals(currentper)
where d.codigoest.Equals(tgi.codigoest)
select new trabajoGdoInvSIGELA { titulotrabajo = d.titulotrabajo, codigoest = d.codigoest }).Distinct().ToList();
//Para verificar que no ingresen una labor si esta ya existe
if (docenteDlloProf.Count() == 0)
{
try
{
labor unalabor = new labor() { idperiodo = currentper };
dbEntity.labor.AddObject(unalabor);
dbEntity.SaveChanges();
int idprog = GetIdProgramaByName(tgi.programa);
trabajodegradoinvestigacion untrabajoinv = new trabajodegradoinvestigacion() { idlabor = unalabor.idlabor, idprograma = idprog, codigoest = tgi.codigoest, horassemana = tgi.horassemana, semanaslaborales = tgi.semanaslaborales, titulotrabajo = tgi.titulotrabajo };
dbEntity.trabajodegradoinvestigacion.AddObject(untrabajoinv);
dbEntity.SaveChanges();
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedResearchGradeWork.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Trabajo De Grado Investigacion", nombrelabor = tgi.titulotrabajo });
// Se llama al registro del estudiante
RegisterStudentForResearchGradeWork(untrabajoinv.codigoest, untrabajoinv.titulotrabajo);
}
catch (Exception ex)
{
}
}
if (docenteDlloProf.Count() > 0)
{
var trabajoInvEsta = (from d in dbEntity.trabajodegradoinvestigacion
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
where d.titulotrabajo.Equals(tgi.titulotrabajo)
where lab.idperiodo.Equals(currentper)
where p.iddocente.Equals(iddoc)
select new trabajoGdoInvSIGELA { titulotrabajo = d.titulotrabajo, codigoest = d.codigoest }).Distinct().ToList();
if (trabajoInvEsta.Count() == 0)
{
try
{
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
var maxid = (from pa in dbEntity.trabajodegradoinvestigacion
where pa.titulotrabajo.Equals(tgi.titulotrabajo)
select pa.idlabor).Max();
trabajodegradoinvestigacion unalabor = dbEntity.trabajodegradoinvestigacion.FirstOrDefault(t => t.idlabor == maxid && t.titulotrabajo == tgi.titulotrabajo);
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedResearchGradeWork.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Trabajo De Grado Investigacion", nombrelabor = tgi.titulotrabajo });
// Se llama al registro del estudiante
RegisterStudentForResearchGradeWork(unalabor.codigoest, unalabor.titulotrabajo);
}
catch (Exception ex) { }
}
}
}
catch (Exception ex) { }
}
return savedResearchGradeWork;
}
// modificado febrero 3
[Authorize]
public List<savedDataSIGELA> TeacherProfDevImportSave(List<dlloProfesoralSIGELA> list, int currentper)
{
List<savedDataSIGELA> savedTeacherProfDev = new List<savedDataSIGELA>();
foreach (dlloProfesoralSIGELA dllp in list)
{
try
{
int iddoc = GetIdDocenteByIdentification(dllp.identificacion);
docente undocente = dbEntity.docente.SingleOrDefault(q => q.iddocente == iddoc);
usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.idusuario == undocente.idusuario);
var docenteTrabGradInv = (from d in dbEntity.desarrolloprofesoral
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
join usu in dbEntity.usuario on doc.idusuario equals usu.idusuario
where usu.identificacion.Equals(dllp.identificacion)
where d.nombreactividad.Equals(dllp.nombreactividad)
where d.resolucion.Equals(dllp.resolucion)
where lab.idperiodo.Equals(currentper)
select new dlloProfesoralSIGELA { nombreactividad = d.nombreactividad, resolucion = d.resolucion }).Distinct().ToList();
//Para verificar que no ingresen una labor si esta ya existe
if (docenteTrabGradInv.Count() == 0)
{
try
{
labor unalabor = new labor() { idperiodo = currentper };
dbEntity.labor.AddObject(unalabor);
dbEntity.SaveChanges();
desarrolloprofesoral undesarrollo = new desarrolloprofesoral() { idlabor = unalabor.idlabor, resolucion = dllp.resolucion, horassemana = dllp.horassemana, semanaslaborales = dllp.semanaslaborales, nombreactividad = dllp.nombreactividad };
dbEntity.desarrolloprofesoral.AddObject(undesarrollo);
dbEntity.SaveChanges();
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
//INICO ADICIONADO POR CLARA
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
//FIN ADICIONADO POR CLARA
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedTeacherProfDev.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Desarrollo profesoral", nombrelabor = dllp.nombreactividad });
}
catch (Exception ex) { }
}
if (docenteTrabGradInv.Count() > 0)
{
var laborDesarrollo = (from d in dbEntity.desarrolloprofesoral
join p in dbEntity.participa on d.idlabor equals p.idlabor
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
where d.nombreactividad.Equals(dllp.nombreactividad)
where lab.idperiodo.Equals(currentper)
where p.iddocente.Equals(iddoc)
select new dlloProfesoralSIGELA { nombreactividad = d.nombreactividad, resolucion = d.resolucion }).Distinct().ToList();
if (laborDesarrollo.Count() == 0)
{
try
{
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
//INICO ADICIONADO POR CLARA
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
//FIN ADICIONADO POR CLARA
// nuevo 3 febrero
var maxid = (from pa in dbEntity.desarrolloprofesoral
where pa.nombreactividad.Equals(dllp.nombreactividad)
where pa.resolucion.Equals(dllp.resolucion)
select pa.idlabor).Max();
desarrolloprofesoral unalabor = dbEntity.desarrolloprofesoral.FirstOrDefault(d => d.idlabor == maxid && d.nombreactividad == dllp.nombreactividad && d.resolucion == dllp.resolucion);
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedTeacherProfDev.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Desarrollo profesoral", nombrelabor = dllp.nombreactividad });
}
catch { }
}
}
}
catch (Exception ex) { }
}
return savedTeacherProfDev;
}
// modificado 3 de febrero
[Authorize]
public List<savedDataSIGELA> TeachingImportSave(List<docenciaSIGELA> list, int currentper)
{
List<savedDataSIGELA> savedTeaching = new List<savedDataSIGELA>();
foreach (docenciaSIGELA dcia in list)
{
try
{
int iddoc = GetIdDocenteByIdentification(dcia.identificacion);
docente undocente = dbEntity.docente.SingleOrDefault(q => q.iddocente == iddoc);
usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.idusuario == undocente.idusuario);
var docenteDocencia = (from m in dbEntity.materia
join d in dbEntity.docencia on m.idmateria equals d.idmateria
join lab in dbEntity.labor on d.idlabor equals lab.idlabor
join p in dbEntity.participa on d.idlabor equals p.idlabor
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
join usu in dbEntity.usuario on doc.idusuario equals usu.idusuario
where m.codigomateria.Equals(dcia.codigomateria)
where m.grupo.Equals(dcia.grupo)
where usu.identificacion.Equals(dcia.identificacion)
where lab.idperiodo.Equals(currentper)
select new docenciaSIGELA
{
nombremateria = m.nombremateria,
grupo = m.grupo,
codigomateria = m.codigomateria
}).Distinct().ToList();
//Para verificar que no ingresen una labor si esta ya existe
if (docenteDocencia.Count() == 0)
{
try
{
labor unalabor = new labor() { idperiodo = currentper };
dbEntity.labor.AddObject(unalabor);
dbEntity.SaveChanges();
int idmateria = GetMateriaByImport(dcia);
docencia unadocencia = new docencia() { idlabor = unalabor.idlabor, idmateria = idmateria, horassemana = dcia.horassemana, semanaslaborales = dcia.semanaslaborales, grupo = dcia.grupo };
dbEntity.docencia.AddObject(unadocencia);
dbEntity.SaveChanges();
evaluacion unaevaluacion = new evaluacion() { evaluacionautoevaluacion = -1, evaluacionestudiante = -1, evaluacionjefe = -1 };
dbEntity.evaluacion.AddObject(unaevaluacion);
dbEntity.SaveChanges();
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
participa unparticipa = new participa() { iddocente = iddoc, idlabor = unalabor.idlabor, idevaluacion = unaevaluacion.idevaluacion, idautoevaluacion = unaautoevalaucion.idautoevaluacion };
dbEntity.participa.AddObject(unparticipa);
dbEntity.SaveChanges();
savedTeaching.Add(new savedDataSIGELA() { nombre = unusuario.nombres, apellido = unusuario.apellidos, email = unusuario.emailinstitucional, identificacion = unusuario.identificacion, tipolabor = "Docencia", nombrelabor = dcia.nombremateria });
// Se revisa si hay un jefe para la importacion
var JefesListId = (from j in dbEntity.esjefe
join d in dbEntity.docente on j.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where j.iddepartamento.Equals(undocente.iddepartamento)
where j.idperiodo.Equals(currentper)
select u.idusuario).ToList();
int iUsuarioJefe = -1;
foreach(int iValor in JefesListId)
{
iUsuarioJefe = iValor;
}
if (iUsuarioJefe != -1)
{
var labores = (from p in dbEntity.labor
join per in dbEntity.periodo_academico on p.idperiodo equals per.idperiodo
join doc in dbEntity.docencia on p.idlabor equals doc.idlabor
select p.idlabor).ToList();
DepartmentChiefController oController = new DepartmentChiefController();
foreach (int idLabor in labores)
{
oController.SaveChiefAux(iUsuarioJefe, idLabor, 1);
}
}
}
catch (Exception ex) { }
}
}
catch (Exception ex) { }
}
return savedTeaching;
}
[Authorize]
public int GetMateriaByImport(docenciaSIGELA dcia)
{
int idprograma = GetIdProgramaByName(dcia.programa);
materia unamateria = dbEntity.materia.SingleOrDefault(q => q.idprograma == idprograma && q.codigomateria == dcia.codigomateria);
if (unamateria == null)
{
unamateria = new materia() { nombremateria = dcia.nombremateria, codigomateria = dcia.codigomateria, idprograma = idprograma, grupo = dcia.grupo, creditos = null, intensidadhoraria = null, semestre = null, tipo = null };
dbEntity.materia.AddObject(unamateria);
dbEntity.SaveChanges();
return unamateria.idmateria;
}
else
{
return unamateria.idmateria;
}
}
// modificado 3 febrero
[Authorize]
public List<docenteSIGELA> TeacherImportSave(List<docenteSIGELA> sigela_docentes)
{
List<docenteSIGELA> savedTeachers = new List<docenteSIGELA>();
string claveEn = "";
foreach (docenteSIGELA dte in sigela_docentes)
{
try
{
String emailinst;
int idusu;
dte.email = dte.email.Trim();
if (!dte.email.EndsWith("@unicauca.edu.co"))
{
dte.email += "@unicauca.edu.co";
}
emailinst = dte.email;
usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.emailinstitucional == emailinst && q.identificacion == dte.identificacion);
if (unusuario == null) //no existe
{
// para contraseña md5
claveEn = md5(emailinst.Replace("@unicauca.edu.co", ""));
//
//Creamos el usuario
unusuario = new usuario() { emailinstitucional = emailinst, password = claveEn, rol = "Docente", nombres = dte.nombres, apellidos = dte.apellidos, identificacion = dte.identificacion };
//guardamos el usuario, ahora en unusuario debe existir el id asignado
dbEntity.usuario.AddObject(unusuario);
dbEntity.SaveChanges();
idusu = unusuario.idusuario;
//verificar el departamento
int iddepto = getIdDeptoByName(dte.departamento);
//creamos el docente
docente undocente = new docente() { iddepartamento = iddepto, idusuario = idusu, estado = "activo" };
dbEntity.docente.AddObject(undocente);
dbEntity.SaveChanges();
savedTeachers.Add(dte);
RegistrarUsuarioConRol(unusuario.emailinstitucional, emailinst.Replace("@un<EMAIL>", ""), "Teacher");
}
else
{//ya existe el usuario
idusu = unusuario.idusuario;
unusuario.nombres = dte.nombres;
unusuario.apellidos = dte.apellidos;
dbEntity.SaveChanges();
docente undocente = dbEntity.docente.SingleOrDefault(q => q.idusuario == idusu);
//verificar el departamento
int iddepto = getIdDeptoByName(dte.departamento);
RegistrarUsuarioConRol(unusuario.emailinstitucional, emailinst.Replace("@unicauca.edu.co", ""), "Teacher");
if (undocente == null)
{
//creamos el docente
undocente = new docente() { iddepartamento = iddepto, idusuario = idusu, estado = "activo" };
dbEntity.docente.AddObject(undocente);
dbEntity.SaveChanges();
savedTeachers.Add(dte);
}
else
{
undocente.estado = "activo";
dbEntity.SaveChanges();
}
}
}
catch { }
}
return savedTeachers;
}
// nuevo febrero 3
[Authorize]
public bool ExcelValidation(System.Data.OleDb.OleDbConnection oconn, out string oResult, int TipoImportacion = 0)
{
if (TipoImportacion == 0)
{
bool dtes_val, dcia_val, dllprof_val, trabGradInv_val, trabGrad_val, inv_val, soc_val, ges_val, otras_val;
this.data_imports.docentesTable = SheetValidation(oconn, "Docentes", new String[] { "identificacion", "emailinstitucional", "nombres", "apellidos", "departamento", "estado" }, out dtes_val);
this.data_imports.docenciaTable = SheetValidation(oconn, "Docencia", new String[] { "programa", "codigomateria", "nombremateria", "grupo", "identificacion", "horassemana", "semanaslaborales" }, out dcia_val);
this.data_imports.dlloProfesoralTable = SheetValidation(oconn, "DesarrolloProfesoral", new String[] { "identificacion", "resolucion", "horassemana", "semanaslaborales", "nombreactividad" }, out dllprof_val);
this.data_imports.trabajoGdoInvTable = SheetValidation(oconn, "TrabajoDeGradoInvestigacion", new String[] { "identificacion", "programa", "codigoest", "horassemana", "semanaslaborales", "titulotrabajo" }, out trabGradInv_val);
this.data_imports.trabajoGdoTable = SheetValidation(oconn, "TrabajoDeGrado", new String[] { "identificacion", "programa", "codigoest", "horassemana", "semanaslaborales", "resolucion", "titulotrabajo" }, out trabGrad_val);
this.data_imports.investigacionTable = SheetValidation(oconn, "Investigacion", new String[] { "identificacion", "codigovri", "horassemana", "fechainicio", "fechafin", "semanaslaborales", "nombreproyecto" }, out inv_val);
this.data_imports.socialTable = SheetValidation(oconn, "Social", new String[] { "identificacion", "horassemana", "resolucion", "unidad", "fechainicio", "fechafin", "semanaslaborales", "nombreproyecto" }, out soc_val);
this.data_imports.gestionTable = SheetValidation(oconn, "Gestion", new String[] { "identificacion", "horassemana", "unidad", "semanaslaborales", "nombrecargo" }, out ges_val);
this.data_imports.otrasTable = SheetValidation(oconn, "Otras", new String[] { "identificacion", "horassemana", "descripcion" }, out otras_val);
oResult = "";
if (!dtes_val) oResult += "Docentes,";
if (!dcia_val) oResult += "Docencia,";
if (!dllprof_val) oResult += "DesarrolloProfesoral,";
if (!trabGradInv_val) oResult += "TrabajoDeGradoInvestigacion,";
if (!trabGrad_val) oResult += "TrabajoDeGrado,";
if (!inv_val) oResult += "Investigacion,";
if (!soc_val) oResult += "Social,";
if (!ges_val) oResult += "Gestion,";
if (!otras_val) oResult += "Otras,";
if (oResult != "") oResult = oResult.Substring(0, oResult.Length - 1);
return dtes_val && dcia_val && dllprof_val && trabGradInv_val && trabGrad_val && inv_val && soc_val && ges_val && otras_val;
}
else if (TipoImportacion == 1)
{
bool dcia_val;
this.data_imports.docenciaTable = SheetValidation(oconn, "Docentes", new string[] { "CodigoMateria", "NombreMateria", "Grupo", "Identificacion", "Total" }, out dcia_val);
oResult = "";
if (!dcia_val) oResult += "Docentes,";
if (oResult != "") oResult = oResult.Substring(0, oResult.Length - 1);
return dcia_val;
}
oResult = "";
return true;
}
[Authorize]
public DataTable SheetValidation(System.Data.OleDb.OleDbConnection oconn, String sheetname, String[] columnas, out bool valid)
{
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("SELECT * FROM [" + sheetname + "$]", oconn);
DataSet myDataSet = new DataSet();
dataAdapter.Fill(myDataSet, sheetname);
DataTable dataTab;
dataTab = myDataSet.Tables[sheetname];
// Use a DataTable object's DataColumnCollection.
DataColumnCollection columns = dataTab.Columns;
// Print the ColumnName and DataType for each column.
valid = false;
if (columnas.Length == columns.Count)
{
int i = 0;
valid = true;
foreach (DataColumn column in columns)
{
valid = valid && (columnas[i] == column.ColumnName);
i++;
}
}
return dataTab;
}
#endregion
//INICIO ADICIONADO POR EDINSON
#region ADICIONADO POR EDINSON
public int yaEsta(string nombre)
{
try
{
cuestionario cuestionario1 = dbEntity.cuestionario.Single(c => c.tipocuestionario == nombre);
}
catch
{
return 0;
}
return 1;
}
public int yaEstaGrupo(string nombre, int Cuestionario)
{
try
{
grupo grupoExiste = dbEntity.grupo.Single(c => c.idcuestionario == Cuestionario && c.nombre == nombre);
}
catch
{
return 0;
}
return 1;
}
#region Asignar Cuestionario
[Authorize]
public ActionResult AssignQuestionnaire()
{
int contador = 0;
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
int idperiodoAc = ultimoPeriodo.idperiodo;
try
{
var asignacionesPeriodo = dbEntity.asignarCuestionario.ToList();
foreach (asignarCuestionario tempAsigancion in asignacionesPeriodo)
{
contador = contador + 1;
}
}
catch
{
}
if (contador == 8)
{
ViewBag.Message = "Todos los cuestionarios han sido asignados";
}
ViewBag.optionmenu = 1;
return View();
}
[Authorize]
public ActionResult EditarAssignQuestionnaire()
{
ViewBag.optionmenu = 1;
return View();
}
// NUEVO 28 ENERO
[Authorize]
public ActionResult AssignQuestionnaire1()
{
string socialVar = "";
string gestionVar = "";
string investigacionVar = "";
string trabajoGVar = "";
string desarrolloPVar = "";
string trabajoIVar = "";
string docenciaVar = "";
string otrasVar = "";
int vacio = 0;
int entradas = 8;
Boolean entro = false;
Boolean error = false;
socialVar = Request.Form["social"];
if (socialVar == null)
{
entradas = entradas - 1;
socialVar = "";
}
gestionVar = Request.Form["gestion"];
if (gestionVar == null)
{
entradas = entradas - 1;
gestionVar = "";
}
investigacionVar = Request.Form["investigacion"];
if (investigacionVar == null)
{
entradas = entradas - 1;
investigacionVar = "";
}
trabajoGVar = Request.Form["trabajoG"];
if (trabajoGVar == null)
{
entradas = entradas - 1;
trabajoGVar = "";
}
desarrolloPVar = Request.Form["desarrolloP"];
if (desarrolloPVar == null)
{
entradas = entradas - 1;
desarrolloPVar = "";
}
trabajoIVar = Request.Form["trabajoI"];
if (trabajoIVar == null)
{
entradas = entradas - 1;
trabajoIVar = "";
}
docenciaVar = Request.Form["docencia"];
if (docenciaVar == null)
{
entradas = entradas - 1;
docenciaVar = "";
}
otrasVar = Request.Form["otras"];
if (docenciaVar == null)
{
entradas = entradas - 1;
otrasVar = "";
}
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
if (socialVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == socialVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
nuevaAsigancion.idlabor = 1;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (gestionVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido1 = null;
asignarCuestionario nuevaAsigancion1 = new asignarCuestionario();
cuestionarioObtenido1 = dbEntity.cuestionario.Single(c => c.tipocuestionario == gestionVar);
nuevaAsigancion1.idcuestionario = cuestionarioObtenido1.idcuestionario;
nuevaAsigancion1.idlabor = 2;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion1);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (investigacionVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido2 = null;
asignarCuestionario nuevaAsigancion2 = new asignarCuestionario();
cuestionarioObtenido2 = dbEntity.cuestionario.Single(c => c.tipocuestionario == investigacionVar);
nuevaAsigancion2.idcuestionario = cuestionarioObtenido2.idcuestionario;
nuevaAsigancion2.idlabor = 3;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion2);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (trabajoGVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido3 = null;
asignarCuestionario nuevaAsigancion3 = new asignarCuestionario();
cuestionarioObtenido3 = dbEntity.cuestionario.Single(c => c.tipocuestionario == trabajoGVar);
nuevaAsigancion3.idcuestionario = cuestionarioObtenido3.idcuestionario;
nuevaAsigancion3.idlabor = 4;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion3);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (desarrolloPVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido4 = null;
asignarCuestionario nuevaAsigancion4 = new asignarCuestionario();
cuestionarioObtenido4 = dbEntity.cuestionario.Single(c => c.tipocuestionario == desarrolloPVar);
nuevaAsigancion4.idcuestionario = cuestionarioObtenido4.idcuestionario;
nuevaAsigancion4.idlabor = 5;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion4);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (trabajoIVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido5 = null;
asignarCuestionario nuevaAsigancion5 = new asignarCuestionario();
cuestionarioObtenido5 = dbEntity.cuestionario.Single(c => c.tipocuestionario == trabajoIVar);
nuevaAsigancion5.idcuestionario = cuestionarioObtenido5.idcuestionario;
nuevaAsigancion5.idlabor = 6;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion5);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (docenciaVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido6 = null;
asignarCuestionario nuevaAsigancion6 = new asignarCuestionario();
cuestionarioObtenido6 = dbEntity.cuestionario.Single(c => c.tipocuestionario == docenciaVar);
nuevaAsigancion6.idcuestionario = cuestionarioObtenido6.idcuestionario;
nuevaAsigancion6.idlabor = 7;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion6);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (otrasVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido6 = null;
asignarCuestionario nuevaAsigancion6 = new asignarCuestionario();
cuestionarioObtenido6 = dbEntity.cuestionario.Single(c => c.tipocuestionario == otrasVar);
nuevaAsigancion6.idcuestionario = cuestionarioObtenido6.idcuestionario;
nuevaAsigancion6.idlabor = 8;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion6);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
ViewBag.optionmenu = 1;
if (entradas == 0)
{
ViewBag.Message = "Todos los cuestionarios han sido asignados";
}
if (entro == true && error == false)
{
ViewBag.Message = "Se ejecutaron las asignaciones solicitadas correctamente";
}
else
{
if (entro == true && error == true)
{
ViewBag.Error = "Algunos cambios no se realizaron";
}
if (entro == false && error == true)
{
ViewBag.Error = "Algunos cambios no se realizaron";
}
}
return View();
}
// FIN NUEVO 29 NOCHE
// NUEVO 29 NOCHE
[Authorize]
public ActionResult EditarAssignQuestionnaire1()
{
string socialVar = "";
string gestionVar = "";
string investigacionVar = "";
string trabajoGVar = "";
string desarrolloPVar = "";
string trabajoIVar = "";
string docenciaVar = "";
string otrasVar = "";
int vacio = 0;
int entradas = 8;
Boolean entro = false;
Boolean error = false;
socialVar = Request.Form["social"];
if (socialVar == null)
{
entradas = entradas - 1;
socialVar = "";
}
gestionVar = Request.Form["gestion"];
if (gestionVar == null)
{
entradas = entradas - 1;
gestionVar = "";
}
investigacionVar = Request.Form["investigacion"];
if (investigacionVar == null)
{
entradas = entradas - 1;
investigacionVar = "";
}
trabajoGVar = Request.Form["trabajoG"];
if (trabajoGVar == null)
{
entradas = entradas - 1;
trabajoGVar = "";
}
desarrolloPVar = Request.Form["desarrolloP"];
if (desarrolloPVar == null)
{
entradas = entradas - 1;
desarrolloPVar = "";
}
trabajoIVar = Request.Form["trabajoI"];
if (trabajoIVar == null)
{
entradas = entradas - 1;
trabajoIVar = "";
}
docenciaVar = Request.Form["docencia"];
if (docenciaVar == null)
{
entradas = entradas - 1;
docenciaVar = "";
}
otrasVar = Request.Form["otras"];
if (otrasVar == null)
{
entradas = entradas - 1;
docenciaVar = "";
}
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
if (socialVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 1);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == socialVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (gestionVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 2);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == gestionVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (investigacionVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 3);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == investigacionVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (trabajoGVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 4);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == trabajoGVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (desarrolloPVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 5);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == desarrolloPVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (trabajoIVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 6);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == trabajoIVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (docenciaVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 7);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == docenciaVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (otrasVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 8);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == otrasVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
ViewBag.optionmenu = 1;
if (entro == true && error == false)
{
ViewBag.Message = "Se ejecutaron los cambios solicitados";
}
else
{
if (entro == true && error == true)
{
ViewBag.Error = "Algunos cambios no se realizaron";
}
if (entro == false && error == true)
{
ViewBag.Error = "Algunos cambios no se realizaron";
}
}
return View();
}
// FIN NUEVO 29 NOCHE
// NUEVO 29 NOCHE
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetAsiganacionPeriodo(string term)
{
int[] response;
response = new int[8];
response[0] = 0;
response[1] = 0;
response[2] = 0;
response[3] = 0;
response[4] = 0;
response[5] = 0;
response[6] = 0;
// NUEVO 29
response[7] = 0;
// FIN NUEVO 29
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
int currentper = (int)SessionValue("currentAcadPeriod");
//if (currentper == ultimoPeriodo.idperiodo) {
int idperiodoAc = ultimoPeriodo.idperiodo;
try
{
var asignacionesPeriodo = dbEntity.asignarCuestionario.ToList();
foreach (asignarCuestionario tempAsigancion in asignacionesPeriodo)
{
response[tempAsigancion.idlabor - 1] = 1;
}
}
catch
{
}
return Json(response, JsonRequestBehavior.AllowGet);
// }
// return Json(-1, JsonRequestBehavior.AllowGet);
}
// FIN NUEVO 29 NOCHE
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetTechingWork1(string term)
{
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
var asignados = (from p in dbEntity.asignarCuestionario
join l in dbEntity.cuestionario on p.idcuestionario equals l.idcuestionario
select new asignacionQ { custionario = l.tipocuestionario, idlabor = p.idlabor }).ToList();
return Json(asignados, JsonRequestBehavior.AllowGet);
}
#endregion
#region Evaluar Jefe
[Authorize]
public ActionResult EvaluateSubordinates2()
{
if (opcionError == 0)
{
ViewBag.Error = "No hay cuestionario asignado para la evaluación de esta labor";
}
else
{
ViewBag.Error = "La evaluacion de este docente ya se realizo";
}
return View();
}
[Authorize]
public ActionResult EvaluateSubordinates1()
{
string laborEntra = Request.Form["labor"];
string usuarioEntra1 = Request.Form["usuario"];
string evaluacionEntra = Request.Form["evaluacion"];
int labor = Convert.ToInt16(laborEntra);
int doce = Convert.ToInt16(usuarioEntra1);
int idE = Convert.ToInt16(evaluacionEntra);
// docente auxDocente = dbEntity.docente.Single(c => c.idusuario == doce);
int idlabor = labor;
//int iddoce = auxDocente.iddocente;
//doce = iddoce;
int idEva = idE;
int salir = 0;
evaluacion regevaluacion = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == idE);
if (regevaluacion.evaluacionjefe != -1)
{
salir = 1;
}
if (salir == 0)
{
ViewBag.SubByWork2 = idlabor;
ViewBag.SubByWork3 = doce;
ViewBag.SubByWork4 = idEva;
int currentper2 = (int)SessionValue("currentAcadPeriod");
asignarCuestionario realizada = null;
try
{
social socialVar = dbEntity.social.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 1);
}
catch
{
try
{
docencia docenciaVar = dbEntity.docencia.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 7);
}
catch
{
try
{
desarrolloprofesoral desarrolloVar = dbEntity.desarrolloprofesoral.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 5);
}
catch
{
try
{
gestion gestionVar = dbEntity.gestion.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 2);
}
catch
{
try
{
investigacion investigacionVar = dbEntity.investigacion.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 3);
}
catch
{
try
{
trabajodegrado trabajoGVar = dbEntity.trabajodegrado.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 4);
}
catch
{
try
{
trabajodegradoinvestigacion trabajoIVar = dbEntity.trabajodegradoinvestigacion.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 6);
}
catch
{
try
{
otras otrasVar = dbEntity.otras.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 8);
}
catch
{
}
}
}
}
}
}
}
}
if (realizada != null)
{
ViewBag.SubByWork5 = realizada.idcuestionario;
var grup_data = dbEntity.grupo
.Join(dbEntity.cuestionario,
grup => grup.idcuestionario,
cues => cues.idcuestionario,
(grup, cues) => new { grupo = grup, cuestionario = cues })
.OrderBy(grup_cues => grup_cues.grupo.orden)
.Where(grup_cues => grup_cues.cuestionario.idcuestionario == realizada.idcuestionario)
.Select(l => new { idCuestionario = l.cuestionario.idcuestionario, idGrupo = l.grupo.idgrupo, nombreGrupo = l.grupo.nombre, porcentaje = l.grupo.porcentaje }).ToList();
List<QuestionnaireGroup> l_quesgroup = new List<QuestionnaireGroup>();
for (int i = 0; i < grup_data.Count(); i++)
{
int idG = grup_data.ElementAt(i).idGrupo;
var temp_p = dbEntity.pregunta.Where(l => l.idgrupo == idG).ToList();
List<Question> l_ques = new List<Question>();
for (int j = 0; j < temp_p.Count(); j++)
{
l_ques.Add(new Question((int)temp_p.ElementAt(j).idpregunta, (string)temp_p.ElementAt(j).pregunta1));
}
l_quesgroup.Add(new QuestionnaireGroup((int)grup_data.ElementAt(i).idGrupo, (string)grup_data.ElementAt(i).nombreGrupo, (double)grup_data.ElementAt(i).porcentaje, l_ques));
}
CompleteQuestionnaire compQuest = new CompleteQuestionnaire(1, l_quesgroup);
// docente docenteEntra = dbEntity.docente.Single(c => c.iddocente == iddoce);
usuario usuarioEntra = dbEntity.usuario.Single(c => c.idusuario == doce);
ViewBag.SubByWork1 = usuarioEntra.nombres + " " + usuarioEntra.apellidos;
ViewBag.CompQuest = compQuest;
ViewBag.WorkDescription = TeacherController.getLaborDescripcion(idlabor);
return View();
}
else
{
opcionError = 0;
return RedirectPermanent("/sedoc/Admin/EvaluateSubordinates2");
}
}
opcionError = 1;
return RedirectPermanent("/sedoc/Admin/EvaluateSubordinates2");
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult UpdateEval(ChiefEval myEval)
{
var averages = myEval.calificaciones.GroupBy(l => l.idgrupo).Select(l => new { idgroup = l.Key, count = l.Count(), average = l.Average(r => r.calificacion) });
var percents = averages
.Join(dbEntity.grupo,
aver => aver.idgroup,
grup => grup.idgrupo,
(aver, grup) => new { grupo = grup, averages = aver })
.Select(l => new { idgrupo = l.grupo.idgrupo, promedio = l.averages.average, porcentaje = l.grupo.porcentaje, score = (l.averages.average * (l.grupo.porcentaje / 100)) });
var totalscore = (decimal)percents.Sum(c => c.score);
totalscore = System.Math.Round(totalscore, 0);
try
{
evaluacion regevaluacion = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == myEval.idevaluacion);
regevaluacion.evaluacionjefe = (int)totalscore; // aqui se supone que el total me da con decimales, pero tengo que redondear
WorkChiefController oController = new WorkChiefController();
oController.GeneratePdfFile(myEval, Server.MapPath("~/pdfsupport/"), (double)totalscore);
dbEntity.SaveChanges();
return Json((int)totalscore, JsonRequestBehavior.AllowGet);
}
catch
{
return Json(-1, JsonRequestBehavior.AllowGet);
}
}
#endregion
#endregion
//FIN ADICIONADO POR EDINSON
// NUEVO 28
[Authorize]
[HttpPost]
public ActionResult RestorePassword(UsuarioSimple Model)
{
try
{
string sName = Request.Form["txtUserName"];
if (!sName.EndsWith("@unicauca.edu.co"))
{
sName += "@unicauca.edu.co";
}
MembershipUser oUSer = Membership.GetUser(sName);
string sPassword = oUSer.ResetPassword();
string sUsuario = sName.Replace("@unicauca.edu.co","");
bool oResult = oUSer.ChangePassword(sPassword, sUsuario);
usuario oUsuario = dbEntity.usuario.SingleOrDefault(u => u.emailinstitucional == sName);
oUsuario.password = md5(<PASSWORD>);
dbEntity.ObjectStateManager.ChangeObjectState(oUsuario, EntityState.Modified);
dbEntity.SaveChanges();
return RedirectToAction("CreateUser", "Admin", new { Result = "Contraseña Restaurada! " });
}
catch
{
return RedirectToAction("CreateUser", "Admin", new { Result = "Error al actualizar la contraseña!! "});
}
}
[Authorize]
public ActionResult CreateUser(string Result = "")
{
ViewBag.sResult = Result;
ViewBag.optionmenu = 5;
List<SelectListItem> oRoles = new List<SelectListItem>();
oRoles.Add(new SelectListItem { Selected = true, Text = "Docente Evaluador", Value = "Coordinador" });
//oRoles.Add(new SelectListItem { Selected = true, Text = "Docente", Value = "Docente" });
oRoles.Add(new SelectListItem { Selected = false, Text = "Estudiante Evaluador", Value = "Estudiante" });
ViewBag.lstRoles = oRoles;
return View();
}
[Authorize]
[HttpPost]
public ActionResult CreateUser(UsuarioSimple Model)
{
string sResult = "";
try
{
usuario oUsuario = new usuario();
oUsuario.nombres = Request.Form["Nombres"];
oUsuario.apellidos = Request.Form["Apellidos"];
string sUserName = Request.Form["UserName"];
string sSimpleUser = "";
if (sUserName.EndsWith("@unicauca.edu.co"))
{
oUsuario.emailinstitucional = sUserName;
sSimpleUser = sUserName.Replace("@unicauca.edu.co", "");
oUsuario.password = md5(<PASSWORD>);
}
else
{
sSimpleUser = sUserName;
oUsuario.password = md5(sUserName);
oUsuario.emailinstitucional = sUserName + "@unicauca.edu.co";
}
oUsuario.identificacion = Request.Form["Identification"];
oUsuario.rol = Request.Form["Role"];
dbEntity.usuario.AddObject(oUsuario);
dbEntity.SaveChanges();
if (Membership.FindUsersByName(oUsuario.emailinstitucional).Count == 0)
{
Membership.CreateUser(oUsuario.emailinstitucional, sSimpleUser);
}
if (oUsuario.rol.Equals("Coordinador") || oUsuario.rol.Equals("Docente"))
{
Roles.AddUserToRole(oUsuario.emailinstitucional, "Teacher");
}
else if (oUsuario.rol.Equals("Estudiante"))
{
Roles.AddUserToRole(oUsuario.emailinstitucional, "Student");
}
sResult = "Usuario " + oUsuario.nombres + " creado satisfactoriamente!";
}
catch(Exception ex)
{
Utilities.ManageException(ex, Server.MapPath(@"..\generalLog.txt"));
sResult = "Error al intentar crear el usuario";
}
return RedirectToAction("CreateUser", "Admin", new { Result = sResult });
}
[Authorize]
public ActionResult ImportDataC()
{
ViewBag.optionmenu = 3;
return View(new List<savedDataSIGELA>());
}
[Authorize]
[HttpPost]
public ActionResult ImportDataC(HttpPostedFileBase excelfile)
{
ViewBag.optionmenu = 2;
string connectionString = "";
System.Data.OleDb.OleDbConnection oconn = new OleDbConnection();
List<savedDataSIGELA> savedsigela = new List<savedDataSIGELA>();
if (excelfile != null)
{
String extension = Path.GetExtension(excelfile.FileName);
String filename = Path.GetFileName(excelfile.FileName);
String filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename);
if (extension == ".xls" || extension == ".xlsx")
{
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
excelfile.SaveAs(filePath);
try
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Password=\"\";User ID=Admin;Data Source=" + filePath.ToString() + ";Mode=Share Deny Write;Extended Properties=\"HDR=YES;\";Jet OLEDB:Engine Type=37";
oconn = new System.Data.OleDb.OleDbConnection(connectionString);
oconn.Open();
bool valido = ExcelValidation1(oconn); /// edv
if (valido)
{
int currentper = (int)SessionValue("currentAcadPeriod");
List<coordinadorSIGELA> docs_sig = this.data_imports.getDocentes1(); //Obtener la lista de docentes desde excel
List<coordinadorSIGELA> saveddtes = CoordinatorImportSave1(docs_sig);
ViewBag.FileValid = "El archivo " + filename + " recibido es valido";
ViewBag.Labsreg = savedsigela.Count();
ViewBag.Teacreg = docs_sig.Count();
}
else
{
ViewBag.Error = "Excel no valido";
}
oconn.Close();
System.IO.File.Delete(filePath);
}
catch (Exception)
{
if (oconn.State != ConnectionState.Closed)
{
oconn.Close();
}
ViewBag.Error = "No se pudo abrir el archivo en Excel, consulte el formato del mismo";
}
}
else
{
ViewBag.Error = "Solo se admiten archivos Excel .xls o .xlsx";
}
}
else
{
ViewBag.Error = "No Recibido";
}
return View(savedsigela);
}
[Authorize]
public List<coordinadorSIGELA> CoordinatorImportSave1(List<coordinadorSIGELA> sigela_docentes)
{
List<coordinadorSIGELA> savedTeachers = new List<coordinadorSIGELA>();
string claveN = "";
foreach (coordinadorSIGELA dte in sigela_docentes)
{
claveN = "";
String emailinst;
int idusu;
if (!dte.email.EndsWith("@unicauca.edu.co"))
{
dte.email += "@unicauca.edu.co";
}
emailinst = dte.email;
usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.emailinstitucional == emailinst && q.identificacion == dte.identificacion);
//usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.emailinstitucional == emailinst);
if (emailinst != "@<EMAIL>")
{
if (unusuario == null) //no existe
{
try
{
departamento dpt = dbEntity.departamento.SingleOrDefault(dp => dp.nombre == dte.departamento);
if (dpt != null)
{
// para encriptar la clave
claveN = md5(emailinst.Replace("@<EMAIL>", ""));
// para encriptar la clave
//Creamos el usuario
unusuario = new usuario() { emailinstitucional = emailinst, password = <PASSWORD>, rol = "Coordinador", nombres = dte.nombres, apellidos = dte.apellidos, identificacion = dte.identificacion };
//guardamos el usuario, ahora en unusuario debe existir el id asignado
dbEntity.usuario.AddObject(unusuario);
dbEntity.SaveChanges();
usuario unusuarioCrd = dbEntity.usuario.SingleOrDefault(q => q.emailinstitucional == emailinst);
decanoCoordinador ingresa = new decanoCoordinador() { id = 9, idusuario = unusuarioCrd.idusuario, idfacultadDepto = dpt.iddepartamento };
dbEntity.decanoCoordinador.AddObject(ingresa);
dbEntity.SaveChanges();
}
}
catch { }
}
else
{//ya existe el usuario
idusu = unusuario.idusuario;
unusuario.nombres = dte.nombres;
unusuario.apellidos = dte.apellidos;
dbEntity.SaveChanges();
}
}
}
return savedTeachers;
}
public bool ExcelValidation1(System.Data.OleDb.OleDbConnection oconn)
{
bool dtes_val;
this.data_imports.docentesTable = SheetValidation(oconn, "Coordinadores", new String[] { "identificacion", "emailinstitucional", "nombres", "apellidos", "departamento" }, out dtes_val);
return dtes_val;
}
#region AdmnistrarMembresias
public void RegistrarUsuarioEnRol(string sUserName, string sRole)
{
if (!Roles.IsUserInRole(sUserName, sRole))
{
Roles.AddUserToRole(sUserName, sRole);
}
}
public void RemoverUsuarioDeRol(string sUserName, string sRole)
{
if (Roles.IsUserInRole(sUserName, sRole))
{
Roles.RemoveUserFromRole(sUserName, sRole);
}
}
public void RegistrarUsuarioConRol(string sUserName, string sPassword, string sRole)
{
MembershipUser oUSer;
if (Membership.GetUser(sUserName) != null)
{
oUSer = Membership.GetUser(sUserName);
}
else
{
oUSer = Membership.CreateUser(sUserName, sPassword);
}
RegistrarUsuarioEnRol(sUserName, sRole);
}
public bool ActualizarContrasenaUsuarioActual(string sNewPassword, string sOldPassword)
{
MembershipUser oUSer = Membership.GetUser();
return oUSer.ChangePassword(sOldPassword, sNewPassword);
}
#endregion
}
}
public class JefeLabor
{
public int idusuario;
public int idlabor;
public string nombres;
public string apellidos;
public string rol;
public string tipoLabor;
public string descripcion;
public int evaluacionJefe;
public int idevaluacion;
}
public class FacultadPrograma
{
public int codfacultad;
public string nomfacultad;
public int codprograma;
public string nomprograma;
}
public class Departamento
{
public int iddepartamento;
public string nombre;
}
public class asignacionQ
{
public string custionario;
public string asignacion;
public int idlabor;
}
public class Asignatura
{
public int id;
public string nombre;
}
public class UsuarioSimple
{
[Display(Name="Usuario Unicauca")]
[Required(ErrorMessage="Campo Requerido!")]
public string UserName;
[Display(Name="Nombres")]
[Required(ErrorMessage = "Campo Requerido!")]
public string Nombres;
[Display(Name = "Apellidos")]
[Required(ErrorMessage = "Campo Requerido!")]
public string Apellidos;
[Required(ErrorMessage = "Campo Requerido!")]
[Display(Name = "Identificación")]
public string Identification;
[Required(ErrorMessage = "Campo Requerido!")]
[Display(Name = "Rol")]
public string Role;
}<file_sep>
function loadDepartamentos(idF, route) {
$.getJSON(route, { term: idF }, function (data) {
// contenido de la tabla
$.each(data, function (key, val) {
$("#DepartamentFrom" + idF + " tbody").append("<tr>" +
"<td>" + val['label'] + "</td>" +
"<td><a class='edit' href='/sedoc/Admin/SetPrivileges/" + val['id'] + "'>Ver Docentes</a> </td>" +
"</tr>");
});
});
}
// carga la cabecera de la tabla
function loadTable(idFacultad) {
idfac = idFacultad;
if (idFacultad != 0) {
nameFac = $("#fac" + idfac).attr("facname");
$("#work-area").html("<table id='DepartamentFrom" + idfac + "' class='list' style='width:100%'>" +
"<thead><tr><th align='center' colspan=3>Programas De La Facultad De " + nameFac + "</th></tr></thead>" +
"<tbody></tbody>" +
"</table><br/>");
loadDepartamentos(idFacultad, "/sedoc/Admin/GetFacultadPrograma/");
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace MvcSEDOC.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
if (!Roles.RoleExists("Admin"))
{
ViewBag.StartScriptResult = FirstStartScript();
}
else
{
ViewBag.StartScriptResult = "";
}
ViewBag.menuOption = "Index";
return View();
}
public string FirstStartScript()
{
string sResult = "";
try
{
// Se adicionan los roles necesarios para la aplicacion
if (!Roles.RoleExists("Admin")) Roles.CreateRole("Admin");
if (!Roles.RoleExists("AdminFac")) Roles.CreateRole("AdminFac");
if (!Roles.RoleExists("DepartmentChief")) Roles.CreateRole("DepartmentChief");
if (!Roles.RoleExists("Student")) Roles.CreateRole("Student");
if (!Roles.RoleExists("Teacher")) Roles.CreateRole("Teacher");
if (!Roles.RoleExists("WorkChief")) Roles.CreateRole("WorkChief");
// Se adicionan los usuarios por defecto para la gestion de la aplicacion
Membership.CreateUser("<EMAIL>", "admin");
Membership.CreateUser("<EMAIL>", "admin");
Membership.CreateUser("<EMAIL>", "admin");
// Se adicionan los roles a los usuarios por defecto
Roles.AddUserToRole("<EMAIL>", "Admin");
Roles.AddUserToRole("<EMAIL>", "AdminFac");
Roles.AddUserToRole("<EMAIL>", "AdminFac");
Roles.AddUserToRole("<EMAIL>", "Teacher");
Roles.AddUserToRole("<EMAIL>", "Teacher");
}
catch (Exception ex)
{
sResult = "¡Error durante la ejecución de las acciones de configuración iniciales, mensaje del error: \n" + ex.Message;
}
if (sResult == "")
{
sResult = "¡Las acciones de configuración iniales se ejecutaron correctamente!";
}
return sResult;
}
public ActionResult ActionDenied()
{
return View();
}
public ActionResult About()
{
ViewBag.menuOption = "About";
return View();
}
public ActionResult Contact()
{
ViewBag.menuOption = "Contact";
return View();
}
public ActionResult Enlaces()
{
ViewBag.menuOption = "Enlaces";
return View();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MvcSEDOC.Models
{
public class SpreadsheetModelLabores
{
public String fileName { get; set; }
public String[] datos { get; set; }
public string nombredocente { get; set; }
public string nombrejefe { get; set; }
public string fechaevaluacion { get; set; }
public string periodo { get; set; }
public List<String> detalleslabores { get; set; }
public List<gestion> labGestion { get; set; }
public List<social> labSocial { get; set; }
public List<DocenciaMateria> labDocencia { get; set; }
public List<investigacion> labInvestigacion { get; set; }
public List<trabajodegrado> labTrabajoDeGrado { get; set; }
public List<trabajodegradoinvestigacion> labTrabajoDegradoInvestigacion { get; set; }
public List<otras> labOtras { get; set; }
public List<desarrolloprofesoral> labDesarrolloProfesoral { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcSEDOC.Models
{
public class DocenteMateria
{
public string identificacion;
public string nombres;
public string apellidos;
public string email;
public string nombremateria;
public string codigomateria;
public string grupo;
public int ideval;
public int evalest;
public int guardado;
}
}<file_sep>
$(function () {
$('#btnGuardar').click(function () {
if (validarEntero()) {
$('#dialogSaveConfirm').dialog("open");
} else {
$('#dialogError').dialog('open');
}
return false;
});
$('#dialogSaveConfirm').dialog({
autoOpen: false,
width: 400,
height: 200,
modal: true,
buttons: {
"Guardar": function () {
Save();
$(this).dialog("close");
},
"Cancelar": function () {
assessLaborChief();
$(this).dialog("close");
}
}
});
$('#dialogError').dialog({
autoOpen: false,
width: 400,
height: 200,
modal: true,
buttons: {
"Aceptar": function () {
$(this).dialog("close");
}
}
});
function validarEntero() {
var sonNumeros = true;
$("input.calif").each(function (index) {
// si el imput no esta vacio
if ($(this).val() != "") {
// recupero en valor del input
var numero = $(this).val();
//Compruebo si es un valor numérico
if (!/^([0-9])*$/.test(numero)) {
//entonces (no es numero) fijo la variable sonNumeros en falso y salgo del each
sonNumeros = false;
return;
} else {
if (numero < 0 || numero > 100) {
//entonces no es un valor valido, fijo la variable sonNumeros en falso y salgo del each
sonNumeros = false;
return;
}
}
}
});
return sonNumeros;
}
function Save() {
$("input.calif").each(function (index) {
if ($(this).val() != "") {
updateEvaluacion($(this).attr("ideval"), $(this).val());
}
});
}
function updateEvaluacion(idEvaluacion, calificacion) {
// almacena el valor de la calificacion
var strParametros = '{"idEvaluacion": ' + idEvaluacion + ', "calificacion": ' + calificacion + ' }';
$.ajax({
cache: false,
url: "/sedoc/AdminFac/UpdateEvaluacion/",
type: 'Post',
dataType: 'json',
data: strParametros,
contentType: 'application/json; charset=utf-8',
success: function (data) {
}
});
}
function assessLaborChief() {
// carga nuevamente la vista
$.ajax({
cache: false,
url: "/sedoc/AdminFac/AssessLaborChief/",
type: 'Post',
dataType: 'json',
data: null,
contentType: 'application/json; charset=utf-8',
success: function (data) { }
});
}
});
/*
function getLaborsId() {
// obtiene los ids de las labores del ultimo periodo academico
$.ajax({
cache: false,
url: "/sedoc/Admin/GetLaborsId/",
type: 'Post',
dataType: 'json',
data: null,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (validarEntero(data) == true) {
laboresId = data;
$('#dialogSaveConfirm').dialog("open");
} else {
$('#dialogError').dialog('open');
}
}
});
}
function assessLaborChief() {
// carga nuevamente la vista
$.ajax({
cache: false,
url: "/sedoc/Admin/AssessLaborChief/",
type: 'Post',
dataType: 'json',
data: null,
contentType: 'application/json; charset=utf-8',
success: function (data) { }
});
}
*/<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcSEDOC.Models
{
public class ConsolidadoLabores
{
public String nombredocente { get; set; }
public String nombrejefe { get; set; }
public String fechaevaluacion { get; set; }
public int notafinal { get; set; }
public int periodoanio { get; set; }
public int periodonum { get; set; }
public Double totalhorassemana { get; set; }
public int totalporcentajes { get; set; }
public String observaciones { get; set; }
public List<String> detalleslabores { get; set; }
public List<gestion> labGestion { get; set; }
public List<social> labSocial { get; set; }
//public List<docencia> labDocencia { get; set; }
public List<DocenciaMateria> labDocencia { get; set; }
public List<investigacion> labInvestigacion { get; set; }
public List<trabajodegrado> labTrabajoDeGrado { get; set; }
public List<trabajodegradoinvestigacion> labTrabajoDegradoInvestigacion { get; set; }
public List<otras> labOtras { get; set; }
public List<desarrolloprofesoral> labDesarrolloProfesoral { get; set; }
}
public class DocenciaMateria
{
public docencia labDoc { get; set; }
public materia DocMateria { get; set; }
public programa MatPrograma { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcSEDOC.Models;
using System.Data;
using System.Data.Entity;
using System.Diagnostics;
using System.IO;
namespace MvcSEDOC.Controllers
{
public class DepartmentChiefController : SEDOCController
{
//variable para almacenar el reporte
public static int noAlmaceno;
public static int siAlmaceno;
public static int rangoFuera;
public static List<DocenteReporte> listaReporte = new List<DocenteReporte>();
public static List<ConsolidadoDocente> consolidadoDocente = new List<ConsolidadoDocente>();
public static List<ConsolidadoDocente> consolidadoDocenteReporte;
//ADICIONADO AUTOEVALAUCION
public static List<AutoevaluacionDocente> AutoevaluacionDocenteReporte;
[Authorize]
public ActionResult Index()
{
departamento departamento = (departamento)Session["depto"];
return View(departamento);
}
[Authorize]
public ActionResult SetChief()
{
departamento depto = (departamento)Session["depto"];
return View(depto);
}
[Authorize]
// NUEVO 2 febrero MODIFICADO POR CLARA
public ActionResult AssignWork()
{
int currentper = (int)Session["currentAcadPeriod"];
periodo_academico per = GetLastAcademicPeriod();
if (noAlmaceno == 1 && siAlmaceno != 1)
{
ViewBag.Error = "No se realizo ninguna de las asignaciones";
}
if (noAlmaceno == 1 && siAlmaceno == 1)
{
ViewBag.Error = "Algunas asignaciones no se realizaron";
}
if (noAlmaceno != 1 && siAlmaceno == 1)
{
ViewBag.Message = "Se realizaron todas las asignaciones";
}
departamento depto = (departamento)Session["depto"];
noAlmaceno = 0;
siAlmaceno = 0;
ViewBag.datos = depto.nombre;
if (currentper != per.idperiodo)
ViewBag.periodo = 0;
else
ViewBag.periodo = 1;
return View();
}
// FIN NUEVO 2 febrero
public class UserDocente
{
public string nombres;
public string apellidos;
public int iddocente;
public int iddepartamento;
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchDepartament(string term)
{
var response = dbEntity.departamento.Select(d => new { label = d.nombre, id = d.iddepartamento }).Where(d => d.label.ToUpper().Contains(term.ToUpper())).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
// NUEVO 29
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetDepartamentTeaching(string term)
{
int iddept = int.Parse(term);
var dept_teach = dbEntity.usuario
.Join(dbEntity.docente,
usu => usu.idusuario,
doc => doc.idusuario,
(usu, doc) => new { usuario = usu, docente = doc })
.Where(usu_doc => usu_doc.docente.iddepartamento == iddept);
var response = dept_teach.Select(d => new { label = d.usuario.nombres, ape = d.usuario.apellidos, id = d.docente.iddocente, pos = d.docente.iddocente, iddepto = d.docente.iddepartamento }).OrderBy(d => d.ape).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
// FIN NUEVO 29
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetDepartamentFromTeaching(string term)
{
int idgroup = int.Parse(term);
var response = dbEntity.pregunta.Select(q => new { label = q.pregunta1, id = q.idpregunta, idg = q.idgrupo }).Where(q => q.idg == idgroup).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
//MODIFICADO POR CLARA
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetTechingWork(string term)
{
//int currentper = (int)Session["currentAcadPeriod"];
departamento depto = (departamento)Session["depto"];
periodo_academico currentper = GetLastAcademicPeriod();
var idlaborestotales = (from p in dbEntity.participa
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper.idperiodo && doc.iddepartamento == depto.iddepartamento
select new Labor { idlabor = l.idlabor }).Distinct().ToList();
var idlaboresjefe = (from d in dbEntity.dirige
select new Labor { idlabor = d.idlabor }).Distinct().ToList();
// var idlabores = new List<Labor>().ToList();
foreach (Labor labor in idlaboresjefe)
{
foreach (Labor laborj in idlaborestotales)
{
if (labor.idlabor == laborj.idlabor)
{
idlaborestotales.Remove(laborj);
break;
}
}
}
var response = getLabor(idlaborestotales);
return Json(response, JsonRequestBehavior.AllowGet);
}
public class Labor
{
public int idlabor;
public String tipoLabor;
public String descripcion;
public String nombres;
// nuevo 2 febrero
public int horasSemana;
// fin nuevo 2 febrero
}
public List<Labor> getLabor(List<Labor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
materia materia;
otras otrasLabores;
foreach (Labor jefe in lista)
{
string sSQL = " select usuario.nombres + ' ' + usuario.apellidos nombrecompleto from participa " +
" inner join docente on docente.iddocente = participa.iddocente " +
" inner join usuario on usuario.idusuario = docente.idusuario where participa.idlabor = " + jefe.idlabor.ToString();
jefe.nombres = (string)Models.Utilities.ExecuteScalar(sSQL);
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (gestion != null)
{
jefe.tipoLabor = "gestion";
jefe.descripcion = gestion.nombrecargo;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (social != null)
{
jefe.tipoLabor = "social";
jefe.descripcion = social.nombreproyecto;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (investigacion != null)
{
jefe.tipoLabor = "investigacion";
jefe.descripcion = investigacion.nombreproyecto;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGrado != null)
{
jefe.tipoLabor = "trabajo de grado";
jefe.descripcion = trabajoDeGrado.titulotrabajo;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
jefe.tipoLabor = "trabajo de grado investigacion";
jefe.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (desarrolloProfesoral != null)
{
jefe.tipoLabor = "desarrollo profesoral";
jefe.descripcion = desarrolloProfesoral.nombreactividad;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (docencia != null)
{
jefe.tipoLabor = "docencia";
materia = dbEntity.materia.SingleOrDefault(m => m.idmateria == docencia.idmateria);
jefe.descripcion = materia.nombremateria;
continue;
}
otrasLabores = dbEntity.otras.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (otrasLabores != null)
{
jefe.tipoLabor = "otras";
jefe.descripcion = otrasLabores.descripcion;
continue;
}
}
return lista.OrderBy(e => e.tipoLabor).ThenBy(d => d.descripcion).ToList();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult searchTeching(string term)
{
var response = dbEntity.usuario.Select(d => new { label = d.nombres + " " + d.apellidos, id = d.idusuario, rol = d.rol }).Where(d => d.label.ToUpper().Contains(term.ToUpper()) && d.rol != "Administrador").ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
#region Evaluación
public evaluacion GetLastEvaluacion()
{
evaluacion lastEvaluacion;
var maxId = (from ev in dbEntity.evaluacion
select ev.idevaluacion).Max();
lastEvaluacion = dbEntity.evaluacion.Single(q => q.idevaluacion == maxId);
return lastEvaluacion;
}
public void SaveChiefAux(int idJ, int idL, int horas)
{
dirige eliminar = dbEntity.dirige.SingleOrDefault(d => d.idlabor == idL);
dirige dirige = new dirige();
dirige.idusuario = idJ;
dirige.idlabor = idL;
dirige.horasSemana = horas;
if (eliminar != null)
{
if (eliminar.idevaluacion != null)
{
int idEvaluacion = (int)eliminar.idevaluacion;
dirige.idevaluacion = idEvaluacion;
}
else
{
//crea la nueva evaluación
evaluacion nuevaEvaluacion = new evaluacion();
nuevaEvaluacion.evaluacionautoevaluacion = -1;
nuevaEvaluacion.evaluacionjefe = -1;
nuevaEvaluacion.evaluacionestudiante = -1;
//agrega la nueva evaluación
dbEntity.evaluacion.AddObject(nuevaEvaluacion);
dbEntity.SaveChanges();
//obtiene el id de la evaluación creada
evaluacion evaluacionactual = GetLastEvaluacion();
dirige.idevaluacion = evaluacionactual.idevaluacion;
}
//INICO ADICIONADO POR CLARA
if (eliminar.idautoevaluacion != null)
{
int idAutoEvaluacion = (int)eliminar.idautoevaluacion;
dirige.idevaluacion = idAutoEvaluacion;
}
else
{
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
dirige.idautoevaluacion = unaautoevalaucion.idautoevaluacion;
}
//FIN ADICIONADO POR CLARA
dbEntity.dirige.DeleteObject(eliminar);
dbEntity.SaveChanges();
}
else
{
//crea la nueva evaluación
evaluacion nuevaEvaluacion = new evaluacion();
nuevaEvaluacion.evaluacionautoevaluacion = -1;
nuevaEvaluacion.evaluacionjefe = -1;
nuevaEvaluacion.evaluacionestudiante = -1;
//agrega la nueva evaluación
dbEntity.evaluacion.AddObject(nuevaEvaluacion);
dbEntity.SaveChanges();
//obtiene el id de la evaluación creada
evaluacion evaluacionactual = GetLastEvaluacion();
dirige.idevaluacion = evaluacionactual.idevaluacion;
//INICO ADICIONADO POR CLARA
autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
dbEntity.SaveChanges();
problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
dbEntity.problema.AddObject(unproblema);
dbEntity.SaveChanges();
resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
dbEntity.resultado.AddObject(unresultado);
dbEntity.SaveChanges();
dirige.idautoevaluacion = unaautoevalaucion.idautoevaluacion;
//FIN ADICIONADO POR CLARA
}
dbEntity.dirige.AddObject(dirige);
dbEntity.SaveChanges();
}
// nuevo 1 febrero
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult saveChief(int idL, int idJ)
{
try
{
int horas = 1;
if (horas > 0 && horas < 21)
{
SaveChiefAux(idJ, idL, horas);
//dirige eliminar = dbEntity.dirige.SingleOrDefault(d => d.idlabor == idL);
//dirige dirige = new dirige();
//dirige.idusuario = idJ;
//dirige.idlabor = idL;
//dirige.horasSemana = horas;
//if (eliminar != null)
//{
// if (eliminar.idevaluacion != null)
// {
// int idEvaluacion = (int)eliminar.idevaluacion;
// dirige.idevaluacion = idEvaluacion;
// }
// else
// {
// //crea la nueva evaluación
// evaluacion nuevaEvaluacion = new evaluacion();
// nuevaEvaluacion.evaluacionautoevaluacion = -1;
// nuevaEvaluacion.evaluacionjefe = -1;
// nuevaEvaluacion.evaluacionestudiante = -1;
// //agrega la nueva evaluación
// dbEntity.evaluacion.AddObject(nuevaEvaluacion);
// dbEntity.SaveChanges();
// //obtiene el id de la evaluación creada
// evaluacion evaluacionactual = GetLastEvaluacion();
// dirige.idevaluacion = evaluacionactual.idevaluacion;
// }
// //INICO ADICIONADO POR CLARA
// if (eliminar.idautoevaluacion != null)
// {
// int idAutoEvaluacion = (int)eliminar.idautoevaluacion;
// dirige.idevaluacion = idAutoEvaluacion;
// }
// else
// {
// autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
// dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
// dbEntity.SaveChanges();
// problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
// dbEntity.problema.AddObject(unproblema);
// dbEntity.SaveChanges();
// resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
// dbEntity.resultado.AddObject(unresultado);
// dbEntity.SaveChanges();
// dirige.idautoevaluacion = unaautoevalaucion.idautoevaluacion;
// }
// //FIN ADICIONADO POR CLARA
// dbEntity.dirige.DeleteObject(eliminar);
// dbEntity.SaveChanges();
//}
//else
//{
// //crea la nueva evaluación
// evaluacion nuevaEvaluacion = new evaluacion();
// nuevaEvaluacion.evaluacionautoevaluacion = -1;
// nuevaEvaluacion.evaluacionjefe = -1;
// nuevaEvaluacion.evaluacionestudiante = -1;
// //agrega la nueva evaluación
// dbEntity.evaluacion.AddObject(nuevaEvaluacion);
// dbEntity.SaveChanges();
// //obtiene el id de la evaluación creada
// evaluacion evaluacionactual = GetLastEvaluacion();
// dirige.idevaluacion = evaluacionactual.idevaluacion;
// //INICO ADICIONADO POR CLARA
// autoevaluacion unaautoevalaucion = new autoevaluacion() { calificacion = -1, fecha = null };
// dbEntity.autoevaluacion.AddObject(unaautoevalaucion);
// dbEntity.SaveChanges();
// problema unproblema = new problema() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", solucion = "Ninguna" };
// dbEntity.problema.AddObject(unproblema);
// dbEntity.SaveChanges();
// resultado unresultado = new resultado() { idautoevaluacion = unaautoevalaucion.idautoevaluacion, descripcion = "Ninguna", ubicacion = "Ninguna" };
// dbEntity.resultado.AddObject(unresultado);
// dbEntity.SaveChanges();
// dirige.idautoevaluacion = unaautoevalaucion.idautoevaluacion;
// //FIN ADICIONADO POR CLARA
//}
//dbEntity.dirige.AddObject(dirige);
//dbEntity.SaveChanges();
var tarea = new { respuesta = '1' };
siAlmaceno = 1;
return Json(tarea, JsonRequestBehavior.AllowGet);
}
else {
var tarea = new { respuesta = '0' };
noAlmaceno = 1;
return Json(tarea, JsonRequestBehavior.AllowGet);
}
}
catch
{
var tarea = new { respuesta = '0' };
noAlmaceno = 1;
return Json(tarea, JsonRequestBehavior.AllowGet);
}
}
// FIN 1 FEBRERO
public class DocenteReporte
{
public int iddocente;
public int idusuario;
public int idlabor;
public string nombres;
public string apellidos;
public double social;
public double gestion;
public double investigacion;
public double trabajoInvestigacion;
public double trabajoGrado;
public double dProfesoral;
public double docencia;
public double total;
}
public ActionResult CreateReport()
{
ViewBag.optionmenu = 3;
departamento departamento = (departamento)Session["depto"];
int currentper = (int)Session["currentAcadPeriod"];
consolidadoDocenteReporte = new List<ConsolidadoDocente>();
List<DocenteReporte> docentes = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento
select new DocenteReporte { iddocente = d.iddocente, idusuario = d.idusuario }).Distinct().ToList();
foreach (DocenteReporte doc in docentes)
{
consolidadoDocenteReporte.Add(crearReporte(doc.idusuario));
}
ViewBag.lista = consolidadoDocenteReporte;
ViewBag.departamento = departamento.nombre;
return View();
}
public int obtenerFilas()
{
int filasReporte = 0;
foreach (ConsolidadoDocente filas in consolidadoDocenteReporte)
{
filasReporte = filasReporte + filas.evaluacioneslabores.Count() + 2;
}
return filasReporte;
}
public ActionResult ExportToExcel()
{
SpreadsheetModel mySpreadsheet = new SpreadsheetModel();
int total_horas = 0;
double total_acumulado = 0;
int tam = obtenerFilas();
String[,] datos = new String[tam, 13];
datos[0, 0] = "Docente";
datos[0, 1] = "Jefe Departamento";
datos[0, 2] = "Fecha Evaluación";
datos[0, 3] = "Labor";
datos[0, 4] = "Tipo";
datos[0, 5] = "Periodo";
datos[0, 6] = "H/S";
datos[0, 7] = "%";
datos[0, 8] = "Est";
datos[0, 9] = "AutoEv";
datos[0, 10] = "JefeNota";
datos[0, 11] = "Total";
datos[0, 12] = "Acumulado";
int i = 1;
foreach (ConsolidadoDocente labor in consolidadoDocenteReporte)
{
for (int j = 0; j < labor.evaluacioneslabores.Count(); j++)
{
datos[i, 0] = labor.nombredocente;
datos[i, 1] = labor.nombrejefe;
datos[i, 2] = labor.fechaevaluacion;
datos[i, 3] = labor.evaluacioneslabores.ElementAt(j).descripcion;
datos[i, 4] = labor.evaluacioneslabores.ElementAt(j).tipolaborcorto;
datos[i, 5] = "" + labor.periodonum + " - " + labor.periodoanio;
datos[i, 6] = "" + labor.evaluacioneslabores.ElementAt(j).horasxsemana;
datos[i, 7] = "" + labor.evaluacioneslabores.ElementAt(j).porcentaje;
datos[i, 8] = "" + labor.evaluacioneslabores.ElementAt(j).evalest;
datos[i, 9] = "" + labor.evaluacioneslabores.ElementAt(j).evalauto;
datos[i, 10] = "" + labor.evaluacioneslabores.ElementAt(j).evaljefe;
datos[i, 11] = "" + labor.evaluacioneslabores.ElementAt(j).nota;
datos[i, 12] = "" + labor.evaluacioneslabores.ElementAt(j).acumula;
total_horas = total_horas + (int)labor.evaluacioneslabores.ElementAt(j).horasxsemana;
total_acumulado = total_acumulado + (double)labor.evaluacioneslabores.ElementAt(j).acumula;
i++;
}
datos[i, 0] = "";
datos[i, 1] = "";
datos[i, 2] = "";
datos[i, 3] = "";
datos[i, 4] = "";
datos[i, 5] = "Totales" ;
datos[i, 6] = "" + total_horas;
datos[i, 7] = "" ;
datos[i, 8] = "" ;
datos[i, 9] = "" ;
datos[i, 10] = "";
datos[i, 11] = "" ;
datos[i, 12] = "" + total_acumulado;
i++;
i++;
total_horas = 0;
total_acumulado = 0;
}
mySpreadsheet.contents = datos;
periodo_academico lastAcademicPeriod = GetLastAcademicPeriod();
DateTime Hora = DateTime.Now;
DateTime Hoy = DateTime.Today;
string hora = Hora.ToString("HH:mm");
string hoy = Hoy.ToString("dd-MM");
mySpreadsheet.fileName = "Reporte" + lastAcademicPeriod.anio + "-" + lastAcademicPeriod.idperiodo + "_" + hoy + "_" + hora + ".xls";
return View(mySpreadsheet);
}
[Authorize]
public ActionResult CreateQuery()
{
ViewBag.optionmenu = 1;
departamento departamento = (departamento)Session["depto"];
int currentper = (int)Session["currentAcadPeriod"];
var docentes = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento && l.idlabor == p.idlabor
select u).Distinct().OrderBy(u => u.apellidos).ToList();
ViewBag.lista = docentes;
ViewBag.departamento = departamento.nombre;
return View();
}
// NUEVO 2 FEBRERO
[Authorize]
public ActionResult CreateQuery1()
{
ViewBag.optionmenu = 1;
departamento departamento = (departamento)Session["depto"];
int currentper = (int)Session["currentAcadPeriod"];
var docentes = (from u in dbEntity.usuario
join d in dbEntity.decanoCoordinador on u.idusuario equals d.idusuario
join p in dbEntity.dirige on d.idusuario equals p.idusuario
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper && d.idfacultadDepto == departamento.iddepartamento && l.idlabor == p.idlabor
select u).Distinct().OrderBy(u => u.apellidos).ToList();
ViewBag.lista = docentes;
ViewBag.departamento = departamento.nombre;
return View();
}
// FIN NUEVO 2 FEBRERO
#endregion
//INICIO ADICIONADO POR CLARA
#region ADICIONADO POR CLARA
public class ProblemaLabor
{
public int idlabor;
public String tipoLabor;
public String descripcion;
public String problemadescripcion;
public String problemarespuesta;
public String soluciondescripcion;
public String solucionrespuesta;
}
#region Autoevaluación
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowAutoScores(int idusuario)
{
ViewBag.optionmenu = 1;
ViewBag.reporte = crearReporteAutoevaluacion(idusuario);
return View();
}
public AutoevaluacionDocente crearReporteAutoevaluacion(int idUsuario)
{
departamento departamento = (departamento)Session["depto"];
int currentper = (int)Session["currentAcadPeriod"];
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
docente docenteactual = (docente)Session["docente"];
int idjefe = docenteactual.idusuario;
usuario jefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idjefe);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
AutoevaluacionDocente AutoevaluacionDocenteReporte = new AutoevaluacionDocente() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = jefe.nombres + " " + jefe.apellidos, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
List<ResAutoEvaluacionLabor> labores = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join aev in dbEntity.autoevaluacion on p.idautoevaluacion equals aev.idautoevaluacion
join pr in dbEntity.problema on aev.idautoevaluacion equals pr.idautoevaluacion
join re in dbEntity.resultado on aev.idautoevaluacion equals re.idautoevaluacion
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == PeriodoSeleccionado.idperiodo && u.idusuario == idUsuario
select new ResAutoEvaluacionLabor { idlabor = l.idlabor, nota = (int)aev.calificacion, problemadescripcion = pr.descripcion, problemasolucion = pr.solucion, resultadodescripcion = re.descripcion, resultadosolucion = re.ubicacion }).ToList();
labores = setAELabor(labores);
AutoevaluacionDocenteReporte.autoevaluacioneslabores = labores;
return AutoevaluacionDocenteReporte;
}
public List<ResAutoEvaluacionLabor> setAELabor(List<ResAutoEvaluacionLabor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otra;
foreach (ResAutoEvaluacionLabor labor in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (gestion != null)
{
labor.tipolabor = "Gestion";
labor.tipolaborcorto = "GES";
labor.descripcion = gestion.nombrecargo;
//labor.horasxsemana = (int)gestion.horassemana;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (social != null)
{
labor.tipolabor = "Social";
labor.tipolaborcorto = "SOC";
labor.descripcion = social.nombreproyecto;
//labor.horasxsemana = (int)social.horassemana;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (investigacion != null)
{
labor.tipolabor = "Investigación";
labor.tipolaborcorto = "INV";
labor.descripcion = investigacion.nombreproyecto;
//labor.horasxsemana = (int)investigacion.horassemana;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGrado != null)
{
labor.tipolabor = "Trabajo de Grado";
labor.tipolaborcorto = "TDG";
labor.descripcion = trabajoDeGrado.titulotrabajo;
// labor.horasxsemana = (int)trabajoDeGrado.horassemana;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
labor.tipolabor = "Trabajo de Grado Investigación";
labor.tipolaborcorto = "TDGI";
labor.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
// labor.horasxsemana = (int)trabajoDeGradoInvestigacion.horassemana;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (desarrolloProfesoral != null)
{
labor.tipolabor = "Desarrollo Profesoral";
labor.tipolaborcorto = "DP";
labor.descripcion = desarrolloProfesoral.nombreactividad;
//labor.horasxsemana = (int)desarrolloProfesoral.horassemana;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (docencia != null)
{
materia materia = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
labor.tipolabor = "Docencia Directa";
labor.tipolaborcorto = "DD";
labor.descripcion = materia.nombremateria;
//labor.horasxsemana = (int)docencia.horassemana;
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (otra != null)
{
labor.tipolabor = "Otra";
labor.tipolaborcorto = "OTR";
labor.descripcion = otra.descripcion;
//labor.horasxsemana = (int)docencia.horassemana;
continue;
}
}
return lista;
}
public ActionResult CreateReportAE()
{
ViewBag.optionmenu = 3;
departamento departamento = (departamento)Session["depto"];
int currentper = (int)Session["currentAcadPeriod"];
AutoevaluacionDocenteReporte = new List<AutoevaluacionDocente>();
List<DocenteReporte> docentes = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento
select new DocenteReporte { iddocente = d.iddocente, idusuario = d.idusuario }).Distinct().ToList();
foreach (DocenteReporte doc in docentes)
{
AutoevaluacionDocenteReporte.Add(crearReporteAutoevaluacion(doc.idusuario));
}
ViewBag.lista = AutoevaluacionDocenteReporte;
ViewBag.departamento = departamento.nombre;
return View();
}
public int obtenerFilasAE()
{
int filasReporte = 0;
foreach (AutoevaluacionDocente filas in AutoevaluacionDocenteReporte)
{
filasReporte = filasReporte + filas.autoevaluacioneslabores.Count() + 1;
}
return filasReporte;
}
public ActionResult ExportToExcelAutoevaluacion()
{
SpreadsheetModelAE mySpreadsheetAE = new SpreadsheetModelAE();
int tam = obtenerFilasAE();
String[,] datos = new String[tam, 10];
datos[0, 0] = "Docente";
datos[0, 1] = "ID Labor";
datos[0, 2] = "Tipo Corto";
datos[0, 3] = "Tipo";
datos[0, 4] = "Labor";
datos[0, 5] = "Nota";
datos[0, 6] = "Descripción Problema";
datos[0, 7] = "Solución Problema";
datos[0, 8] = "Descripción Solucion";
datos[0, 9] = "Ubicación Solucion";
mySpreadsheetAE.fechaevaluacion = AutoevaluacionDocenteReporte[0].fechaevaluacion;
mySpreadsheetAE.periodo = "" + AutoevaluacionDocenteReporte[0].periodonum + " - " + AutoevaluacionDocenteReporte[0].periodoanio;
mySpreadsheetAE.nombrejefe = AutoevaluacionDocenteReporte[0].nombrejefe;
int i = 1;
foreach (AutoevaluacionDocente labor in AutoevaluacionDocenteReporte)
{
for (int j = 0; j < labor.autoevaluacioneslabores.Count(); j++)
{
datos[i, 0] = labor.nombredocente;
datos[i, 1] = "" + labor.autoevaluacioneslabores.ElementAt(j).idlabor;
datos[i, 2] = labor.autoevaluacioneslabores.ElementAt(j).tipolaborcorto;
datos[i, 3] = labor.autoevaluacioneslabores.ElementAt(j).tipolabor;
datos[i, 4] = labor.autoevaluacioneslabores.ElementAt(j).descripcion;
datos[i, 5] = "" + labor.autoevaluacioneslabores.ElementAt(j).nota;
datos[i, 6] = "" + labor.autoevaluacioneslabores.ElementAt(j).problemadescripcion;
datos[i, 7] = "" + labor.autoevaluacioneslabores.ElementAt(j).problemasolucion;
datos[i, 8] = "" + labor.autoevaluacioneslabores.ElementAt(j).resultadodescripcion;
datos[i, 9] = "" + labor.autoevaluacioneslabores.ElementAt(j).resultadosolucion;
i++;
}
i++;
}
mySpreadsheetAE.labores = datos;
periodo_academico lastAcademicPeriod = GetLastAcademicPeriod();
DateTime Hora = DateTime.Now;
DateTime Hoy = DateTime.Today;
string hora = Hora.ToString("HH:mm");
string hoy = Hoy.ToString("dd-MM");
mySpreadsheetAE.fileName = "Reporte" + lastAcademicPeriod.anio + "-" + lastAcademicPeriod.idperiodo + "_" + hoy + "_" + hora + ".xls";
return View(mySpreadsheetAE);
}
#endregion
#region Labores
[Authorize]
public ActionResult GetLaborType()
{
ViewBag.optionmenu = 1;
docente docente = (docente)Session["docente"];
int currentper = (int)Session["currentAcadPeriod"];
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
departamento departamento = (departamento)Session["depto"];
var GenreLst = new List<int>();
var NameLabor = new List<String>();
var tipolabor = from p in dbEntity.participa
join d in dbEntity.docente on p.iddocente equals d.iddocente
join aev in dbEntity.autoevaluacion on p.idautoevaluacion equals aev.idautoevaluacion
join l in dbEntity.labor on p.idlabor equals l.idlabor
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento
orderby l.idlabor
select p.idlabor;
GenreLst.AddRange(tipolabor.Distinct());
foreach (int id in GenreLst)
{
var gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == id);
if (gestion != null)
{
NameLabor.Add("Gestión");
continue;
}
var social = dbEntity.social.SingleOrDefault(g => g.idlabor == id);
if (social != null)
{
NameLabor.Add("Social");
continue;
}
var investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == id);
if (investigacion != null)
{
NameLabor.Add("Investigación");
continue;
}
var trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == id);
if (trabajoDeGrado != null)
{
NameLabor.Add("Trabajo de grado");
continue;
}
var trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == id);
if (trabajoDeGradoInvestigacion != null)
{
NameLabor.Add("Trabajo de grado investigacion");
continue;
}
var desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == id);
if (desarrolloProfesoral != null)
{
NameLabor.Add("Desarrollo profesoral");
continue;
}
var docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == id);
if (docencia != null)
{
NameLabor.Add("Docencia");
continue;
}
var otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == id);
if (otra != null)
{
NameLabor.Add("Otra");
continue;
}
}
if (NameLabor.Count > 0)
{
//funcion que envia los datos a la lista desplegable del docente
ViewBag.tipoLabor = new SelectList(NameLabor.Distinct());
ViewBag.datos = 1;
}
else
{
ViewBag.datos = 0;
}
ViewBag.departamento = departamento.nombre;
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchTipoLabor(string term)
{
docente docente = (docente)Session["docente"];
int currentper = (int)Session["currentAcadPeriod"];
departamento departamento = (departamento)Session["depto"];
var labores = new List<Labor>();
term = (term).ToLower();
if (term == "gestión")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join g in dbEntity.gestion on p.idlabor equals g.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = g.nombrecargo }).Distinct().ToList();
}
if (term == "social")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join s in dbEntity.social on p.idlabor equals s.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = s.nombreproyecto }).Distinct().ToList();
}
if (term == "investigación")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join i in dbEntity.investigacion on p.idlabor equals i.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = i.nombreproyecto }).Distinct().ToList();
}
if (term == "trabajo de grado")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join t in dbEntity.trabajodegrado on p.idlabor equals t.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = t.titulotrabajo }).Distinct().ToList();
}
if (term == "trabajo de grado investigacion")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join t in dbEntity.trabajodegradoinvestigacion on p.idlabor equals t.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = t.titulotrabajo }).Distinct().ToList();
}
if (term == "desarrollo profesoral")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join dp in dbEntity.desarrolloprofesoral on p.idlabor equals dp.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = dp.nombreactividad }).Distinct().ToList();
}
if (term == "docencia")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join t in dbEntity.docencia on p.idlabor equals t.idlabor
join m in dbEntity.materia on t.idmateria equals m.idmateria
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = m.nombremateria }).Distinct().ToList();
}
if (term == "otra")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join o in dbEntity.otras on p.idlabor equals o.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = o.descripcion }).Distinct().ToList();
}
return Json(labores, JsonRequestBehavior.AllowGet);
}
#endregion
#region Problemas Labor
public List<DepartamentoLabor> SearchProblemasLabor(int id, string term, int currentper, departamento departamento)
{
var labores = new List<DepartamentoLabor>();
term = (term).ToLower();
if (term == "gestion")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join g in dbEntity.gestion on p.idlabor equals g.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento && l.idlabor == id
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = g.nombrecargo, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "social")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join s in dbEntity.social on p.idlabor equals s.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento && l.idlabor == id
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = s.nombreproyecto, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "investigacion")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join i in dbEntity.investigacion on p.idlabor equals i.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento && l.idlabor == id
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = i.nombreproyecto, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "trabajo de grado")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join t in dbEntity.trabajodegrado on p.idlabor equals t.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento && l.idlabor == id
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = t.titulotrabajo, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "trabajo de grado investigacion")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join t in dbEntity.trabajodegradoinvestigacion on p.idlabor equals t.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento && l.idlabor == id
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = t.titulotrabajo, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "desarrollo profesoral")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join dp in dbEntity.desarrolloprofesoral on p.idlabor equals dp.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento && l.idlabor == id
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = dp.nombreactividad, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "docencia")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join t in dbEntity.docencia on p.idlabor equals t.idlabor
join m in dbEntity.materia on t.idmateria equals m.idmateria
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento && l.idlabor == id
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = m.nombremateria, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "otras")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join o in dbEntity.otras on p.idlabor equals o.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento && l.idlabor == id
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = o.descripcion, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
return labores;
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchProblemasLabor(int id, string term)
{
int currentper = (int)Session["currentAcadPeriod"];
departamento departamento = (departamento)Session["depto"];
var labores = SearchProblemasLabor(id, term, currentper, departamento);
return Json(labores, JsonRequestBehavior.AllowGet);
}
[Authorize]
public ActionResult ProblemasLabor(int id)
{
ViewBag.optionmenu = 1;
if (ModelState.IsValid)
{
var lista = new List<Labor>();
lista.Add(new Labor { idlabor = id });
var response = getLabor(lista);
ViewBag.datos = response;
return View();
}
return View();
}
#endregion
public class DepartamentoLabor
{
public int idlabor;
public string docente;
public string descripcion;
public string problemadescripcion;
public string problemarespuesta;
public string soluciondescripcion;
public string solucionrespuesta;
}
#endregion
//FIN ADICIONADO POR CLARA
#region Gestion Archivos
[Authorize]
public ActionResult ListPdfByUser(string UserId)
{
ViewBag.optionmenu = 3;
DirectoryInfo oInfo = new DirectoryInfo(Server.MapPath("~/pdfsupport/"));
var oFiles = oInfo.GetFiles();
List<BasicFileInfo> lstInfo = new List<BasicFileInfo>();
string sFind = UserId.ToString() + '_';
foreach (FileInfo oFile in oFiles)
{
if (oFile.Name.StartsWith(sFind))
{
string sFullName = oFile.Name;
string[] sSplit = sFullName.Split('_');
BasicFileInfo oNew = new BasicFileInfo();
oNew.sFullPath = sFullName;
oNew.sPeriod = sSplit[1];
oNew.sType = sSplit[2];
oNew.sName = sSplit[3] ;
oNew.sDateTime = sSplit[4].Substring(0, sSplit[4].Length - 4);
lstInfo.Add(oNew);
}
}
long lUserID = int.Parse(UserId);
var oUser = dbEntity.usuario.SingleOrDefault(q => q.idusuario == lUserID);
ViewBag.UserFullName = oUser.nombres + ' ' + oUser.apellidos;
lstInfo.Sort();
ViewBag.lstInfo = lstInfo;
return View();
}
[Authorize]
public ActionResult SearchPdfByUser()
{
ViewBag.optionmenu = 3;
DirectoryInfo oInfo = new DirectoryInfo(Server.MapPath("~/pdfsupport/"));
var oFiles = oInfo.GetFiles();
List<BasicUserInfo> lstInfo = new List<BasicUserInfo>();
foreach (FileInfo oFile in oFiles)
{
string sName = oFile.Name;
string[] oNameSplit = sName.Split('_');
BasicUserInfo oUserInfo = new BasicUserInfo();
oUserInfo.lId = long.Parse(oNameSplit[0]);
bool blnExist = false;
foreach (BasicUserInfo oItem in lstInfo)
{
if (oItem.lId == oUserInfo.lId)
blnExist = true;
}
if (!blnExist)
{
var usuario = dbEntity.usuario.SingleOrDefault(q => q.idusuario == oUserInfo.lId);
oUserInfo.sFullName = usuario.nombres + ' ' + usuario.apellidos;
lstInfo.Add(oUserInfo);
}
}
lstInfo.Sort();
ViewBag.lstInfo = lstInfo;
return View();
}
public class BasicUserInfo : IComparable
{
public long lId { set; get; }
public string sFullName { set; get; }
public int CompareTo(object obj)
{
return sFullName.CompareTo(((BasicUserInfo)obj).sFullName);
}
}
public class BasicFileInfo : IComparable
{
public string sName { set; get; }
public string sFullPath { set; get; }
public string sPeriod { set; get; }
public string sType { set; get; }
public string sDateTime { set; get; }
public int CompareTo(object obj)
{
return sFullPath.CompareTo(((BasicFileInfo)obj).sFullPath);
}
}
#endregion
#region Evaluación
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowScores(int idusuario)
{
//string usuarioEntra = Request.Form["usuario"];
//int idusuario = Convert.ToInt16(usuarioEntra);
ViewBag.optionmenu = 1;
ViewBag.reporte = crearReporte(idusuario);
return View();
}
/// nuevo 22 febero
public ActionResult ShowScores1(int idusuario)
{
//string usuarioEntra = Request.Form["usuario"];
//int idusuario = Convert.ToInt16(usuarioEntra);
ViewBag.optionmenu = 1;
ViewBag.reporte = crearReporte(idusuario);
return View();
}
public ConsolidadoDocente crearReporte1(int idUsuario)
{
departamento departamento = (departamento)Session["depto"];
int currentper = (int)Session["currentAcadPeriod"];
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
docente docenteactual = (docente)Session["docente"];
int idjefe = docenteactual.idusuario;
usuario jefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idjefe);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
ConsolidadoDocente reporte = new ConsolidadoDocente() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = jefe.nombres + " " + jefe.apellidos, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
//List<ResEvaluacionLabor> labores = (from u in dbEntity.usuario
// join d in dbEntity.decanoCoordinador on u.idusuario equals d.idusuario
// join p in dbEntity.dirige on d.idusuario equals p.idusuario
// join ev in dbEntity.evaluacion on p.idevaluacion equals ev.idevaluacion
// join l in dbEntity.labor on p.idlabor equals l.idlabor
// join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
// where l.idperiodo == currentper && u.idusuario == idUsuario
// select new ResEvaluacionLabor { idlabor = l.idlabor, evalest = (int)ev.evaluacionestudiante, evalauto = (int)ev.evaluacionautoevaluacion, evaljefe = (int)ev.evaluacionjefe }).ToList();
//// NUEVO 1 FEBRERO
List<ResEvaluacionLabor> labores = (from u in dbEntity.usuario
// join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.dirige on u.idusuario equals p.idusuario
join ev in dbEntity.evaluacion on p.idevaluacion equals ev.idevaluacion
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper && u.idusuario == idUsuario
select new ResEvaluacionLabor { idlabor = l.idlabor, evalest = (int)ev.evaluacionestudiante, evalauto = (int)ev.evaluacionautoevaluacion, evaljefe = (int)ev.evaluacionjefe }).ToList();
labores = setLabor(labores, 0);
// FIN NUEVO 1 FEBRERO
// labores = setLabor(labores, 1);
// INICIO NUEVO 1 FEBRERO
//foreach (ResEvaluacionLabor lab in OtrasLabores)
//{
// labores.Add(lab);
//}
// FIN NUEVO 1 FEBRERO
reporte.totalhorassemana = (Double)labores.Sum(q => q.horasxsemana);
reporte.evaluacioneslabores = calcularPonderados(labores);
reporte.totalporcentajes = (Double)reporte.evaluacioneslabores.Sum(q => q.porcentaje);
reporte.notafinal = (Double)reporte.evaluacioneslabores.Sum(q => q.acumula);
return reporte;
}
/// fin nuevo febrero 2
// NUEVO 29
public ConsolidadoDocente crearReporte(int idUsuario)
{
departamento departamento = (departamento)Session["depto"];
int currentper = (int)Session["currentAcadPeriod"];
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
docente docenteactual = (docente)Session["docente"];
int idjefe = docenteactual.idusuario;
usuario jefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idjefe);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
ConsolidadoDocente reporte = new ConsolidadoDocente() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = jefe.nombres + " " + jefe.apellidos, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
List<ResEvaluacionLabor> labores = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join ev in dbEntity.evaluacion on p.idevaluacion equals ev.idevaluacion
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper && u.idusuario == idUsuario
select new ResEvaluacionLabor { idlabor = l.idlabor, evalest = (int)ev.evaluacionestudiante, evalauto = (int)ev.evaluacionautoevaluacion, evaljefe = (int)ev.evaluacionjefe }).ToList();
labores = setLabor(labores, 1);
reporte.totalhorassemana = (Double)labores.Sum(q => q.horasxsemana);
reporte.evaluacioneslabores = calcularPonderados(labores);
reporte.totalporcentajes = (Double)reporte.evaluacioneslabores.Sum(q => q.porcentaje);
reporte.notafinal = (Double)reporte.evaluacioneslabores.Sum(q => q.acumula);
return reporte;
}
public List<ResEvaluacionLabor> setLabor(List<ResEvaluacionLabor> lista,int opcion)
{
gestion gestion;
dirige dirige;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otra;
foreach (ResEvaluacionLabor labor in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (gestion != null)
{
labor.tipolabor = "Gestión";
labor.tipolaborcorto = "GES";
if (opcion == 1)
{
labor.descripcion = gestion.nombrecargo;
labor.horasxsemana = (int)gestion.horassemana;
}
else {
dirige = dbEntity.dirige.SingleOrDefault(g => g.idlabor == labor.idlabor);
labor.horasxsemana = (int)dirige.horasSemana;
labor.descripcion = "Dirige " + gestion.nombrecargo;
}
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (social != null)
{
labor.tipolabor = "Social";
labor.tipolaborcorto = "SOC";
if (opcion == 1)
{
labor.descripcion = social.nombreproyecto;
labor.horasxsemana = (int)social.horassemana;
}
else {
dirige = dbEntity.dirige.SingleOrDefault(g => g.idlabor == labor.idlabor);
labor.horasxsemana = (int)dirige.horasSemana;
labor.descripcion = "Dirige " + social.nombreproyecto;
}
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (investigacion != null)
{
labor.tipolabor = "Investigación";
labor.tipolaborcorto = "INV";
if (opcion == 1)
{
labor.descripcion = investigacion.nombreproyecto;
labor.horasxsemana = (int)investigacion.horassemana;
}
else {
dirige = dbEntity.dirige.SingleOrDefault(g => g.idlabor == labor.idlabor);
labor.horasxsemana = (int)dirige.horasSemana;
labor.descripcion = "Dirige " + investigacion.nombreproyecto;
}
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGrado != null)
{
labor.tipolabor = "Trabajo de Grado";
labor.tipolaborcorto = "TDG";
if (opcion == 1)
{
labor.descripcion = trabajoDeGrado.titulotrabajo;
labor.horasxsemana = (int)trabajoDeGrado.horassemana;
}
else {
dirige = dbEntity.dirige.SingleOrDefault(g => g.idlabor == labor.idlabor);
labor.horasxsemana = (int)dirige.horasSemana;
labor.descripcion = "Dirige " + trabajoDeGrado.titulotrabajo;
}
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
labor.tipolabor = "Trabajo de Grado Investigación";
labor.tipolaborcorto = "TDGI";
if (opcion == 1)
{
labor.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
labor.horasxsemana = (int)trabajoDeGradoInvestigacion.horassemana;
}
else {
dirige = dbEntity.dirige.SingleOrDefault(g => g.idlabor == labor.idlabor);
labor.horasxsemana = (int)dirige.horasSemana;
labor.descripcion = "Dirige " + trabajoDeGradoInvestigacion.titulotrabajo;
}
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (desarrolloProfesoral != null)
{
labor.tipolabor = "Desarrollo Profesoral";
labor.tipolaborcorto = "DP";
if (opcion == 1)
{
labor.descripcion = desarrolloProfesoral.nombreactividad;
labor.horasxsemana = (int)desarrolloProfesoral.horassemana;
}
else {
dirige = dbEntity.dirige.SingleOrDefault(g => g.idlabor == labor.idlabor);
labor.horasxsemana = (int)dirige.horasSemana;
labor.descripcion = "Dirige "+ desarrolloProfesoral.nombreactividad;
}
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (docencia != null)
{
materia materia = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
labor.tipolabor = "Docencia Directa";
labor.tipolaborcorto = "DD";
if (opcion == 1)
{
labor.descripcion = materia.nombremateria;
labor.horasxsemana = (int)docencia.horassemana;
}
else {
dirige = dbEntity.dirige.SingleOrDefault(g => g.idlabor == labor.idlabor);
labor.horasxsemana = (int)dirige.horasSemana;
labor.descripcion = "Dirige " + materia.nombremateria;
}
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (otra != null)
{
labor.tipolabor = "OTRA";
labor.tipolaborcorto = "OT";
if (opcion == 1)
{
labor.descripcion = otra.descripcion;
labor.horasxsemana = (int)otra.horassemana;
}
else {
dirige = dbEntity.dirige.SingleOrDefault(g => g.idlabor == labor.idlabor);
labor.horasxsemana = (int)dirige.horasSemana;
labor.descripcion = "Dirige " + otra.descripcion;
}
continue;
}
}
return lista;
}
/// fin 1 febrero
// NUEVO 29
public static List<ResEvaluacionLabor> calcularPonderados(List<ResEvaluacionLabor> lista)
{
Double totalHoras = lista.Sum(q => q.horasxsemana);
foreach (ResEvaluacionLabor labor in lista)
{
Double porc = (labor.horasxsemana * 100) / totalHoras;
labor.porcentaje = (Double)System.Math.Round(porc, 2);
labor.nota = (Double)calculaNotaPromedio(labor.evalest, labor.evalauto, labor.evaljefe);
Double acum = System.Math.Round((porc * labor.nota) / 100, 2);
labor.acumula = (Double)acum;
}
return lista;
}
// FIN NUEVO 29
public static Double calculaNotaPromedio(Double n1, Double n2, Double n3)
{
if (n1 == -1 && n2 == -1 && n3 == -1)
{
return 0;
}
int divisor = 3;
if (n1 == -1) { n1 = 0; divisor--; }
if (n2 == -1) { n2 = 0; divisor--; }
if (n3 == -1) { n3 = 0; divisor--; }
return System.Math.Round(((n1 + n2 + n3) / divisor), 2);
}
#endregion
//INICIO ADICIONADO POR EDINSON
#region ADICIONADO POR EDINSON
[Authorize]
// NUEVO 29
public ActionResult AssignWork1()
{
int currentper = (int)Session["currentAcadPeriod"];
periodo_academico per = GetLastAcademicPeriod();
if (noAlmaceno == 1 && siAlmaceno != 1)
{
ViewBag.Error = "No se realizo ninguna de las asignaciones";
}
if (noAlmaceno == 1 && siAlmaceno == 1)
{
ViewBag.Error = "Algunas asignaciones o se realizaron";
}
if (noAlmaceno != 1 && siAlmaceno == 1)
{
ViewBag.Message = "Se realizaron todas las asignaciones";
}
departamento depto = (departamento)Session["depto"];
noAlmaceno = 0;
siAlmaceno = 0;
ViewBag.datos = depto.nombre;
if (currentper != per.idperiodo)
ViewBag.periodo = 0;
else
ViewBag.periodo = 1;
return View();
}
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetTechingWork1(string term) // aqui toca comparar de alguna forma sacar el titulo, el nombre de la materia, etc de cada labor
{
int idD = int.Parse(term);
departamento depto = (departamento)Session["depto"];
int currentper = (int)Session["currentAcadPeriod"];
var idlaborestotales = (from p in dbEntity.participa
join doc in dbEntity.docente on p.iddocente equals doc.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
join dir in dbEntity.dirige on l.idlabor equals dir.idlabor
where l.idperiodo == currentper && doc.iddepartamento == depto.iddepartamento
select new Labor { idlabor = l.idlabor, horasSemana = (int)dir.horasSemana }).Distinct().ToList();
var response = getLabor1(idlaborestotales);
return Json(response, JsonRequestBehavior.AllowGet);
}
// FIN NUEVO 29
public List<Labor> getLabor1(List<Labor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otrasLabores;
materia materia;
usuario usuarioDirige;
dirige jefeDirige;
foreach (Labor jefe in lista)
{
int idlabor = (int)jefe.idlabor;
jefeDirige = dbEntity.dirige.SingleOrDefault(t => t.idlabor == idlabor);
usuarioDirige = dbEntity.usuario.SingleOrDefault(u => u.idusuario == jefeDirige.idusuario);
jefe.nombres = usuarioDirige.nombres + " " + usuarioDirige.apellidos;
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (gestion != null)
{
jefe.tipoLabor = "gestion";
jefe.descripcion = gestion.nombrecargo;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (social != null)
{
jefe.tipoLabor = "social";
jefe.descripcion = social.nombreproyecto;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (investigacion != null)
{
jefe.tipoLabor = "investigacion";
jefe.descripcion = investigacion.nombreproyecto;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGrado != null)
{
jefe.tipoLabor = "trabajo de grado";
jefe.descripcion = trabajoDeGrado.titulotrabajo;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
jefe.tipoLabor = "trabajo de grado investigacion";
jefe.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (desarrolloProfesoral != null)
{
jefe.tipoLabor = "desarrollo profesoral";
jefe.descripcion = desarrolloProfesoral.nombreactividad;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (docencia != null)
{
jefe.tipoLabor = "docencia";
materia = dbEntity.materia.SingleOrDefault(m => m.idmateria == docencia.idmateria);
jefe.descripcion = materia.nombremateria;
continue;
}
otrasLabores = dbEntity.otras.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (otrasLabores != null)
{
jefe.tipoLabor = "otras";
jefe.descripcion = otrasLabores.descripcion;
continue;
}
}
return lista.OrderBy(d => d.tipoLabor).ThenBy(e => e.descripcion).ToList();
}
#endregion
//FIN ADICIONADO POR EDINSON
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
namespace MvcSEDOC.Models
{
public class Utilities
{
public static void ManageException(Exception ex, string path = "")
{
string strConfigValue = System.Configuration.ConfigurationManager.AppSettings.Get("RegisterOnLog");
if (strConfigValue == "true")
{
if (path == "") path = @"\generalLog.log";
System.IO.StreamWriter oLog = new System.IO.StreamWriter(path, true);
oLog.WriteLine("----------------------------------------------------------------");
oLog.WriteLine(string.Format("Message: {0}", ex.Message));
oLog.WriteLine(string.Format("Source: {0}", ex.Source));
oLog.WriteLine(string.Format("StackTrace: {0}", ex.StackTrace));
oLog.Close();
}
}
public static object ExecuteScalar(string sSQL)
{
string sConString = System.Configuration.ConfigurationManager.ConnectionStrings["SEDOCConection"].ConnectionString;
SqlConnection oConection = new SqlConnection(sConString);
SqlCommand oComando = new SqlCommand(sSQL,oConection);
oConection.Open();
object oResult = oComando.ExecuteScalar();
oConection.Close();
return oResult;
}
public iTextSharp.text.Document StartPdfWriter(string sUserId, string sEvalType, string sPeriod, string sWorkDescription, string sMapPath)
{
try
{
Document oDocument = new iTextSharp.text.Document();
string sDescription = sWorkDescription;
if (sDescription.Length > 40)
{
sDescription = sDescription.Substring(0, 40);
}
string sPath = sMapPath
+ sUserId + "_" + sPeriod + "_" + sEvalType + "_" + sDescription.Replace("_"," ") + "_"
+ DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
System.IO.FileStream file =
new System.IO.FileStream(sPath,
System.IO.FileMode.OpenOrCreate);
PdfWriter oWriter = PdfWriter.GetInstance(oDocument, file);
oDocument.AddTitle("SEDOC - Reporte Evaluación");
oDocument.AddAuthor("FIET - Universidad del Cauca");
oDocument.SetMargins(40, 40, 35, 35);
oDocument.Open();
Font oHeaderFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
Paragraph oUcauca = new Paragraph("Universidad del Cauca\nFacultad de Ingeniería Electrónica y Telecomunicaciones\nSistema de Evaluación Docente");
oUcauca.Font = oHeaderFont;
oUcauca.Alignment = Element.ALIGN_CENTER;
oDocument.Add(oUcauca);
return oDocument;
}
catch
{
return null;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MvcSEDOC.Models;
using System.IO;
using System.Data.OleDb;
using System.Data;
using System.Data.Entity;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace MvcSEDOC.Controllers
{
public class WorkChiefController : SEDOCController
{
//variable para almacenar el reporte
public static int opcionError;
public static List<DocenteReporte> listaReporte = new List<DocenteReporte>();
public static List<ConsolidadoDocente> consolidadoDocente = new List<ConsolidadoDocente>();
public static List<ConsolidadoDocente> consolidadoDocenteReporte;
public static List<AutoevaluacionDocente> AutoevaluacionDocenteReporte;
[Authorize]
public ActionResult Index()
{
return View();
}
public object SessionValue(string keyValue)
{
try
{
return Session[keyValue];
}
catch
{
return RedirectPermanent("/sedoc");
}
}
[Authorize]
public ActionResult ChangePass()
{
int periodoActualSelec = 0;
periodoActualSelec = (int)SessionValue("periodoActual");
if (periodoActualSelec == 1)
{
return RedirectPermanent("/WorkChief/Index1");
}
ViewBag.optionmenu = 1;
return View();
}
[Authorize]
public ActionResult ChangePass1()
{
int periodoActualSelec = 0;
periodoActualSelec = (int)SessionValue("periodoActual");
if (periodoActualSelec == 1)
{
return RedirectPermanent("/WorkChief/Index1");
}
ViewBag.Value1 = "";
ViewBag.Value2 = "";
ViewBag.Value3 = "";
string anterior = "";
string nueva = "";
string repite = "";
string claveA = "";
int campo1 = 0;
int campo2 = 0;
int campo3 = 0;
//int entradas = 7;
//Boolean entro = false;
//Boolean error = false;
anterior = Request.Form["anterior"];
if (anterior == "")
{
campo1 = 1;
ViewBag.Error1 = "entro";
}
else
{
ViewBag.Value1 = anterior;
}
nueva = Request.Form["nueva"];
if (nueva == "")
{
campo2 = 1;
ViewBag.Error2 = "entro";
}
else
{
ViewBag.Value2 = nueva;
}
repite = Request.Form["repite"];
if (repite == "")
{
campo3 = 1;
ViewBag.Error3 = "entro";
}
else
{
ViewBag.Value3 = repite;
}
ViewBag.optionmenu = 1;
if (campo1 == 1 || campo2 == 1 || campo3 == 1)
{
ViewBag.Error = "Los campos con asterisco son obligatorios";
return View();
}
claveA = AdminController.md5(anterior);
try
{
int usuarioAux = (int)SessionValue("docenteId");
usuario NuevaContrasena = dbEntity.usuario.Single(u => u.idusuario == usuarioAux && u.password == claveA);
if (nueva != repite)
{
ViewBag.Error = "No coinciden la nueva contraseña con la anterior";
return View();
}
else
{
AdminController oControl = new AdminController();
if (!oControl.ActualizarContrasenaUsuarioActual(nueva, anterior))
{
throw new Exception("Invalid Password");
}
nueva = AdminController.md5(nueva);
NuevaContrasena.password = <PASSWORD>;
// dbEntity.usuario.Attach(NuevaContrasena);
dbEntity.ObjectStateManager.ChangeObjectState(NuevaContrasena, EntityState.Modified);
dbEntity.SaveChanges();
ViewBag.Value1 = null;
ViewBag.Value2 = null;
ViewBag.Value3 = null;
ViewBag.Message = "La contraseña se cambio exitosamente";
return View();
}
}
catch
{
ViewBag.Error = "La contraseña anterior es incorrecta";
return View();
}
}
// fin cambiar contraseña
[Authorize]
public ActionResult Index1()
{
return View();
}
[Authorize]
public ActionResult AssessLaborChief()
{
int id = (int)SessionValue("docenteId");
ViewBag.optionmenu = 3;
int currentper = (int)SessionValue("currentAcadPeriod");
var users = (from u in dbEntity.usuario
join d in dbEntity.dirige on u.idusuario equals d.idusuario
join l in dbEntity.labor on d.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
join ev in dbEntity.evaluacion on d.idevaluacion equals ev.idevaluacion
where l.idperiodo == currentper
where u.idusuario == id
select new JefeLabor { idusuario = u.idusuario, idlabor = l.idlabor, idevaluacion = ev.idevaluacion, nombres = u.nombres, apellidos = u.apellidos, rol = u.rol, evaluacionJefe = (int)ev.evaluacionjefe }).OrderBy(p => p.apellidos).ToList();
if (users.Count == 0) {
ViewBag.Error = "No tiene labores asignadas para para este periodo";
}
users = setLaborChief(users);
ViewBag.lista = users;
return View();
}
public List<JefeLabor> setLaborChief(List<JefeLabor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otrasVar;
foreach (JefeLabor jefe in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (gestion != null)
{
jefe.tipoLabor = "gestion";
jefe.descripcion = gestion.nombrecargo;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (social != null)
{
jefe.tipoLabor = "social";
jefe.descripcion = social.nombreproyecto;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (investigacion != null)
{
jefe.tipoLabor = "investigacion";
jefe.descripcion = investigacion.nombreproyecto;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGrado != null)
{
jefe.tipoLabor = "trabajo de grado";
jefe.descripcion = trabajoDeGrado.titulotrabajo;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
jefe.tipoLabor = "trabajo de grado investigacion";
jefe.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (desarrolloProfesoral != null)
{
jefe.tipoLabor = "desarrollo profesoral";
jefe.descripcion = desarrolloProfesoral.nombreactividad;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (docencia != null)
{
materia materia = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
jefe.tipoLabor = "docencia";
jefe.descripcion = materia.nombremateria;
continue;
}
otrasVar = dbEntity.otras.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (otrasVar != null)
{
jefe.tipoLabor = "Otras";
jefe.descripcion = otrasVar.descripcion;
continue;
}
}
return lista;
}
public ActionResult evaluateSubordinates2()
{
if (opcionError == 0)
{
ViewBag.Error = "No hay cuestionario asignado para la evaluación de esta labor";
}
else
{
ViewBag.Error = "La evaluacion de este docente ya se realizo";
}
return View();
}
[Authorize]
public ActionResult evaluateSubordinates1()
{
string laborEntra = Request.Form["labor"];
string usuarioEntra1 = Request.Form["usuario"];
string evaluacionEntra = Request.Form["evaluacion"];
int labor = Convert.ToInt16(laborEntra);
int doce = Convert.ToInt16(usuarioEntra1);
int idE = Convert.ToInt16(evaluacionEntra);
int idlabor = labor;
int iddoce = doce;
int idEva = idE;
int salir = 0;
participa regparticipa = dbEntity.participa.SingleOrDefault(c => c.iddocente == iddoce && c.idlabor == idlabor);
if (regparticipa != null)
{
evaluacion regevaluacion = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == regparticipa.idevaluacion);
if (regevaluacion.evaluacionjefe != -1)
{
salir = 1;
}
}
if (salir == 0)
{
ViewBag.SubByWork2 = idlabor;
ViewBag.SubByWork3 = iddoce;
ViewBag.SubByWork4 = idEva;
int currentper2 = (int)SessionValue("currentAcadPeriod");
asignarCuestionario realizada = null;
try
{
social socialVar = dbEntity.social.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 1);
}
catch
{
try
{
docencia docenciaVar = dbEntity.docencia.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 7);
}
catch
{
try
{
desarrolloprofesoral desarrolloVar = dbEntity.desarrolloprofesoral.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 5);
}
catch
{
try
{
gestion gestionVar = dbEntity.gestion.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 2);
}
catch
{
try
{
investigacion investigacionVar = dbEntity.investigacion.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 3);
}
catch
{
try
{
trabajodegrado trabajoGVar = dbEntity.trabajodegrado.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 4);
}
catch
{
try
{
trabajodegradoinvestigacion trabajoIVar = dbEntity.trabajodegradoinvestigacion.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 6);
}
catch
{
try
{
otras otrasVar = dbEntity.otras.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 8);
}
catch
{
}
}
}
}
}
}
}
}
if (realizada != null)
{
ViewBag.SubByWork5 = realizada.idcuestionario;
// Obtener Cuestionariodocen
var grup_data = dbEntity.grupo
.Join(dbEntity.cuestionario,
grup => grup.idcuestionario,
cues => cues.idcuestionario,
(grup, cues) => new { grupo = grup, cuestionario = cues })
.OrderBy(grup_cues => grup_cues.grupo.orden)
.Where(grup_cues => grup_cues.cuestionario.idcuestionario == realizada.idcuestionario)
.Select(l => new { idCuestionario = l.cuestionario.idcuestionario, idGrupo = l.grupo.idgrupo, nombreGrupo = l.grupo.nombre, porcentaje = l.grupo.porcentaje }).ToList();
List<QuestionnaireGroup> l_quesgroup = new List<QuestionnaireGroup>();
for (int i = 0; i < grup_data.Count(); i++)
{
int idG = grup_data.ElementAt(i).idGrupo;
var temp_p = dbEntity.pregunta.Where(l => l.idgrupo == idG).ToList();
List<Question> l_ques = new List<Question>();
for (int j = 0; j < temp_p.Count(); j++)
{
l_ques.Add(new Question((int)temp_p.ElementAt(j).idpregunta, (string)temp_p.ElementAt(j).pregunta1));
}
l_quesgroup.Add(new QuestionnaireGroup((int)grup_data.ElementAt(i).idGrupo, (string)grup_data.ElementAt(i).nombreGrupo, (double)grup_data.ElementAt(i).porcentaje, l_ques));
}
CompleteQuestionnaire compQuest = new CompleteQuestionnaire(1, l_quesgroup);
docente docenteEntra = dbEntity.docente.Single(c => c.iddocente == iddoce);
usuario usuarioEntra = dbEntity.usuario.Single(c => c.idusuario == docenteEntra.idusuario);
ViewBag.SubByWork1 = usuarioEntra.nombres + " " + usuarioEntra.apellidos;
ViewBag.WorkDescription = TeacherController.getLaborDescripcion(idlabor);
ViewBag.CompQuest = compQuest;
return View();
}
else
{
opcionError = 0;
return RedirectPermanent("/sedoc/WorkChief/evaluateSubordinates2");
}
}
opcionError = 1;
return RedirectPermanent("/sedoc/WorkChief/evaluateSubordinates2");
}
public void GeneratePdfFile(ChiefEval oEval, string MapPath, double totalScore, string sEvalType = "chief", string sObservations = "")
{
Models.Utilities oUtil = new Models.Utilities();
docente oDocente = dbEntity.docente.SingleOrDefault(q => q.iddocente == oEval.iddocente);
labor oLabor = dbEntity.labor.SingleOrDefault(q => q.idlabor == oEval.idlabor);
periodo_academico oPeriodo = dbEntity.periodo_academico.SingleOrDefault(p => p.idperiodo == oLabor.idperiodo);
string sDescription = TeacherController.getLaborDescripcion(oEval.idlabor);
usuario oUsuario = dbEntity.usuario.SingleOrDefault(q => q.idusuario == oDocente.idusuario);
Document oDocument = oUtil.StartPdfWriter(oDocente.idusuario.ToString(), sEvalType,
oPeriodo.anio.ToString() + "-" + oPeriodo.numeroperiodo.ToString(), sDescription, MapPath);
Font oContentFont = new Font(Font.FontFamily.TIMES_ROMAN, 11, Font.NORMAL);
System.Text.StringBuilder oBuilder = new System.Text.StringBuilder();
oBuilder.Append("\n\nDocente: " + oUsuario.nombres + " " + oUsuario.apellidos);
oBuilder.Append("\nPeriodo: " + oPeriodo.anio.ToString() + "-" + oPeriodo.numeroperiodo.ToString());
oBuilder.Append("\nNombre de Labor: " + sDescription);
if (sEvalType.Equals("chief"))
oBuilder.Append("\nTipo de Evaluación: Jefe");
else if (sEvalType.Equals("student"))
oBuilder.Append("\nTipo de Evaluación: Estudiante");
oBuilder.Append("\nFecha y hora: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
oBuilder.Append("\nCALIFICACIÓN: " + totalScore.ToString() + "\n\n");
Paragraph oContent = new Paragraph(oBuilder.ToString());
oContent.Font = oContentFont;
oContent.Alignment = Element.ALIGN_JUSTIFIED;
oDocument.Add(oContent);
int idGrupo = -1;
oEval.calificaciones.Sort();
PdfPTable oTable = new PdfPTable(2);
oTable.WidthPercentage = 100;
Rectangle rect = new Rectangle(100, 1000);
oTable.SetWidthPercentage(new float[] { 95, 5 }, rect);
foreach (CE_Question oPregunta in oEval.calificaciones)
{
if (idGrupo != oPregunta.idgrupo)
{
grupo oGrupo = dbEntity.grupo.SingleOrDefault(g => g.idgrupo == oPregunta.idgrupo);
idGrupo = oPregunta.idgrupo;
PdfPCell oCell = new PdfPCell(new Phrase("\n" + oGrupo.nombre.ToUpper() + " (" + oGrupo.porcentaje + "%)"));
oCell.Colspan = 2;
oCell.BorderWidth = 0;
oTable.AddCell(oCell);
}
pregunta oPreg = dbEntity.pregunta.SingleOrDefault(p => p.idpregunta == oPregunta.idpregunta);
PdfPCell oCellQ = new PdfPCell(new Phrase(oPreg.pregunta1));
oCellQ.BorderWidth = 0;
PdfPCell oCellC = new PdfPCell(new Phrase(oPregunta.calificacion.ToString()));
oCellC.BorderWidth = 0;
oTable.AddCell(oCellQ);
oTable.AddCell(oCellC);
}
oDocument.Add(oTable);
sObservations = sObservations.Trim();
if (sObservations != "")
{
Paragraph oContent1 = new Paragraph("\nOBSERVACIONES: " + sObservations);
oContent1.Font = oContentFont;
oContent1.Alignment = Element.ALIGN_JUSTIFIED;
oDocument.Add(oContent1);
}
oDocument.Close();
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult UpdateEval(StudentEval myEval)
{
try
{
var averages = myEval.calificaciones.GroupBy(l => l.idgrupo).Select(l => new { idgroup = l.Key, count = l.Count(), average = l.Average(r => r.calificacion) });
var percents = averages
.Join(dbEntity.grupo,
aver => aver.idgroup,
grup => grup.idgrupo,
(aver, grup) => new { grupo = grup, averages = aver })
.Select(l => new { idgrupo = l.grupo.idgrupo, promedio = l.averages.average, porcentaje = l.grupo.porcentaje, score = (l.averages.average * (l.grupo.porcentaje / 100)) });
var totalscore = percents.Sum(c => c.score);
totalscore = System.Math.Round(totalscore, 0);
//verificamos la participacion y q existe la evaluación
participa regparticipa = dbEntity.participa.SingleOrDefault(c => c.iddocente == myEval.iddocente && c.idlabor == myEval.idlabor);
if (regparticipa != null)
{
evaluacion regevaluacion = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == regparticipa.idevaluacion);
regevaluacion.evaluacionjefe = (int)totalscore; // aqui se supone que el total me da con decimales, pero tengo que redondear
//regevaluacion.evaluacionestudiante = (int)myEval.EvalEst; /***COMENTADO POR EDINSON ****/
//regevaluacion.evaluacionautoevaluacion = (int)myEval.EvalAut; /***COMENTADO POR EDINSON ****/
dbEntity.SaveChanges();
GeneratePdfFile(myEval, Server.MapPath("~/pdfsupport/"), totalscore, sObservations: myEval.observaciones);
return Json((int)totalscore, JsonRequestBehavior.AllowGet);
}
else
{
return Json(-1, JsonRequestBehavior.AllowGet);
}
}
catch
{
return Json(-1, JsonRequestBehavior.AllowGet);
}
}
//MODIFICADO POR EDINSON
[Authorize]
public ActionResult evaluateSubordinates()
{
usuario usu = (usuario)SessionValue("logedUser");
int idUsr = usu.idusuario;
int currentper = (int)SessionValue("currentAcadPeriod");
List<SubordinatesByWork> mySubordinates = new List<SubordinatesByWork>();
var dir_ids = dbEntity.dirige
.Join(dbEntity.labor,
dir => dir.idlabor,
lab => lab.idlabor,
(dir, lab) => new { dirige = dir, labor = lab })
.Where(dir_lab => dir_lab.dirige.idusuario == idUsr && dir_lab.labor.idperiodo == currentper);
var part_idds = dbEntity.participa
.Join(dir_ids,
part => part.idlabor,
d_ids => d_ids.labor.idlabor,
(part, d_ids) => new { participa = part, dirige = d_ids });
var datos_doc = dbEntity.docente
.Join(part_idds,
doc => doc.iddocente,
part_ids => part_ids.participa.iddocente,
(doc, part_ids) => new { docente = doc, part_idds = part_ids });
var datos_usr = dbEntity.usuario
.Join(datos_doc,
usr => usr.idusuario,
dat_d => dat_d.docente.idusuario,
(usr, dat_d) => new { persona = usr, dato_doc = dat_d })
.Select(c => new { idDocente = c.dato_doc.docente.iddocente, idLabor = c.dato_doc.part_idds.participa.idlabor, idEvaluacion = c.dato_doc.part_idds.participa.idevaluacion, nombres = c.persona.nombres, apellidos = c.persona.apellidos }).ToList();
var gestion_works = dbEntity.gestion
.Join(dir_ids,
gest => gest.idlabor,
d_ids => d_ids.labor.idlabor,
(gest, d_ids) => new { gestion = gest, dir_ids = d_ids })
.Select(c => new { txtLabor = c.gestion.nombrecargo, idLabor = c.gestion.idlabor })
.OrderBy(e => e.txtLabor)
.ToList();
if (gestion_works.Count() > 0)
{
for (int i = 0; i < gestion_works.Count(); i++)
{
var temp_ls = datos_usr.Where(du => du.idLabor == gestion_works.ElementAt(i).idLabor).ToList();
List<Subordinate> l_sub = new List<Subordinate>();
for (int j = 0; j < temp_ls.Count(); j++)
{
int ideval = (int)temp_ls.ElementAt(j).idEvaluacion;
var puntaje = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == ideval);
if (puntaje.evaluacionjefe <= 1)
{
l_sub.Add(new Subordinate((int)temp_ls.ElementAt(j).idDocente, (int)temp_ls.ElementAt(j).idLabor, (int)temp_ls.ElementAt(j).idEvaluacion, (int)puntaje.evaluacionjefe, (int)puntaje.evaluacionestudiante, (int)puntaje.evaluacionautoevaluacion, (string)temp_ls.ElementAt(j).nombres, (string)temp_ls.ElementAt(j).apellidos));
}
}
if (l_sub.Count > 0)
{
mySubordinates.Add(new SubordinatesByWork(gestion_works.ElementAt(i).idLabor, gestion_works.ElementAt(i).txtLabor, "Gestion", l_sub));
}
}
}
var social_works = dbEntity.social
.Join(dir_ids,
soc => soc.idlabor,
d_ids => d_ids.labor.idlabor,
(soc, d_ids) => new { social = soc, dir_ids = d_ids })
.Select(c => new { txtLabor = c.social.nombreproyecto, idLabor = c.social.idlabor })
.OrderBy(e => e.txtLabor)
.ToList();
if (social_works.Count() > 0)
{
for (int i = 0; i < social_works.Count(); i++)
{
var temp_ls = datos_usr.Where(du => du.idLabor == social_works.ElementAt(i).idLabor).ToList();
List<Subordinate> l_sub = new List<Subordinate>();
for (int j = 0; j < temp_ls.Count(); j++)
{
int ideval = (int)temp_ls.ElementAt(j).idEvaluacion;
var puntaje = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == ideval);
if (puntaje.evaluacionjefe <= 1)
l_sub.Add(new Subordinate((int)temp_ls.ElementAt(j).idDocente, (int)temp_ls.ElementAt(j).idLabor, (int)temp_ls.ElementAt(j).idEvaluacion, (int)puntaje.evaluacionjefe, (int)puntaje.evaluacionestudiante, (int)puntaje.evaluacionautoevaluacion, (string)temp_ls.ElementAt(j).nombres, (string)temp_ls.ElementAt(j).apellidos));
}
if (l_sub.Count > 0)
mySubordinates.Add(new SubordinatesByWork(social_works.ElementAt(i).idLabor, social_works.ElementAt(i).txtLabor, "Social", l_sub));
}
}
var investigacion_works = dbEntity.investigacion
.Join(dir_ids,
inv => inv.idlabor,
d_ids => d_ids.labor.idlabor,
(inv, d_ids) => new { investigacion = inv, dir_ids = d_ids })
.Select(c => new { txtLabor = c.investigacion.nombreproyecto, idLabor = c.investigacion.idlabor })
.OrderBy(e => e.txtLabor)
.ToList();
if (investigacion_works.Count() > 0)
{
for (int i = 0; i < investigacion_works.Count(); i++)
{
var temp_ls = datos_usr.Where(du => du.idLabor == investigacion_works.ElementAt(i).idLabor).ToList();
List<Subordinate> l_sub = new List<Subordinate>();
for (int j = 0; j < temp_ls.Count(); j++)
{
int ideval = (int)temp_ls.ElementAt(j).idEvaluacion;
var puntaje = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == ideval);
if (puntaje.evaluacionjefe <= 1)
l_sub.Add(new Subordinate((int)temp_ls.ElementAt(j).idDocente, (int)temp_ls.ElementAt(j).idLabor, (int)temp_ls.ElementAt(j).idEvaluacion, (int)puntaje.evaluacionjefe, (int)puntaje.evaluacionestudiante, (int)puntaje.evaluacionautoevaluacion, (string)temp_ls.ElementAt(j).nombres, (string)temp_ls.ElementAt(j).apellidos));
}
if (l_sub.Count > 0)
mySubordinates.Add(new SubordinatesByWork(investigacion_works.ElementAt(i).idLabor, investigacion_works.ElementAt(i).txtLabor, "Investigacion", l_sub));
}
}
var trabajodegrado_works = dbEntity.trabajodegrado
.Join(dir_ids,
tdg => tdg.idlabor,
d_ids => d_ids.labor.idlabor,
(tdg, d_ids) => new { trabajodegrado = tdg, dir_ids = d_ids })
.Select(c => new { txtLabor = c.trabajodegrado.titulotrabajo, idLabor = c.trabajodegrado.idlabor })
.OrderBy(e => e.txtLabor)
.ToList();
if (trabajodegrado_works.Count() > 0)
{
for (int i = 0; i < trabajodegrado_works.Count(); i++)
{
var temp_ls = datos_usr.Where(du => du.idLabor == trabajodegrado_works.ElementAt(i).idLabor).ToList();
List<Subordinate> l_sub = new List<Subordinate>();
for (int j = 0; j < temp_ls.Count(); j++)
{
int ideval = (int)temp_ls.ElementAt(j).idEvaluacion;
var puntaje = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == ideval);
if (puntaje.evaluacionjefe <= 1)
l_sub.Add(new Subordinate((int)temp_ls.ElementAt(j).idDocente, (int)temp_ls.ElementAt(j).idLabor, (int)temp_ls.ElementAt(j).idEvaluacion, (int)puntaje.evaluacionjefe, (int)puntaje.evaluacionestudiante, (int)puntaje.evaluacionautoevaluacion, (string)temp_ls.ElementAt(j).nombres, (string)temp_ls.ElementAt(j).apellidos));
}
if (l_sub.Count > 0)
mySubordinates.Add(new SubordinatesByWork(trabajodegrado_works.ElementAt(i).idLabor, trabajodegrado_works.ElementAt(i).txtLabor, "Trabajo de grado", l_sub));
}
}
var trabajodegradoinv_works = dbEntity.trabajodegradoinvestigacion
.Join(dir_ids,
tdgi => tdgi.idlabor,
d_ids => d_ids.labor.idlabor,
(tdgi, d_ids) => new { trabajodegradoinvestigacion = tdgi, dir_ids = d_ids })
.Select(c => new { txtLabor = c.trabajodegradoinvestigacion.titulotrabajo, idLabor = c.trabajodegradoinvestigacion.idlabor })
.OrderBy(e => e.txtLabor)
.ToList();
if (trabajodegradoinv_works.Count() > 0)
{
for (int i = 0; i < trabajodegradoinv_works.Count(); i++)
{
var temp_ls = datos_usr.Where(du => du.idLabor == trabajodegradoinv_works.ElementAt(i).idLabor).ToList();
List<Subordinate> l_sub = new List<Subordinate>();
for (int j = 0; j < temp_ls.Count(); j++)
{
int ideval = (int)temp_ls.ElementAt(j).idEvaluacion;
var puntaje = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == ideval);
if (puntaje.evaluacionjefe <= 1)
l_sub.Add(new Subordinate((int)temp_ls.ElementAt(j).idDocente, (int)temp_ls.ElementAt(j).idLabor, (int)temp_ls.ElementAt(j).idEvaluacion, (int)puntaje.evaluacionjefe, (int)puntaje.evaluacionestudiante, (int)puntaje.evaluacionautoevaluacion, (string)temp_ls.ElementAt(j).nombres, (string)temp_ls.ElementAt(j).apellidos));
}
if (l_sub.Count > 0)
mySubordinates.Add(new SubordinatesByWork(trabajodegradoinv_works.ElementAt(i).idLabor, trabajodegradoinv_works.ElementAt(i).txtLabor, "Trabajo de grado Inv", l_sub));
}
}
var desarrolloprof_works = dbEntity.desarrolloprofesoral
.Join(dir_ids,
dprof => dprof.idlabor,
d_ids => d_ids.labor.idlabor,
(dprof, d_ids) => new { desarrolloprofesoral = dprof, dir_ids = d_ids })
.Select(c => new { txtLabor = c.desarrolloprofesoral.nombreactividad, idLabor = c.desarrolloprofesoral.idlabor })
.OrderBy(e => e.txtLabor)
.ToList();
if (desarrolloprof_works.Count() > 0)
{
for (int i = 0; i < desarrolloprof_works.Count(); i++)
{
var temp_ls = datos_usr.Where(du => du.idLabor == desarrolloprof_works.ElementAt(i).idLabor).ToList();
List<Subordinate> l_sub = new List<Subordinate>();
for (int j = 0; j < temp_ls.Count(); j++)
{
int ideval = (int)temp_ls.ElementAt(j).idEvaluacion;
var puntaje = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == ideval);
if (puntaje.evaluacionjefe <= 1)
l_sub.Add(new Subordinate((int)temp_ls.ElementAt(j).idDocente, (int)temp_ls.ElementAt(j).idLabor, (int)temp_ls.ElementAt(j).idEvaluacion, (int)puntaje.evaluacionjefe, (int)puntaje.evaluacionestudiante, (int)puntaje.evaluacionautoevaluacion, (string)temp_ls.ElementAt(j).nombres, (string)temp_ls.ElementAt(j).apellidos));
}
if (l_sub.Count > 0)
mySubordinates.Add(new SubordinatesByWork(desarrolloprof_works.ElementAt(i).idLabor, desarrolloprof_works.ElementAt(i).txtLabor, "Desarrollo profesional", l_sub));
}
}
var docencias = dbEntity.docencia
.Join(dir_ids,
docs => docs.idlabor,
d_ids => d_ids.labor.idlabor,
(docs, d_ids) => new { docencia = docs, dir_ids = d_ids });
var docencia_works = docencias
.Join(dbEntity.materia,
doc => doc.docencia.idmateria,
mat => mat.idmateria,
(doc, mat) => new { docencia = doc, materia = mat })
.Select(c => new { txtLabor = c.materia.nombremateria, idLabor = c.docencia.docencia.idlabor }).OrderBy(e => e.txtLabor).ToList();
if (docencia_works.Count() > 0)
{
string strTitle = "";
List<Subordinate> l_sub = new List<Subordinate>();
for (int i = 0; i < docencia_works.Count(); i++)
{
if(strTitle != docencia_works.ElementAt(i).txtLabor && l_sub.Count > 0 )
{
mySubordinates.Add(new SubordinatesByWork(docencia_works.ElementAt(i).idLabor, strTitle, "Docencia", l_sub));
l_sub = new List<Subordinate>();
}
strTitle = docencia_works.ElementAt(i).txtLabor;
var temp_ls = datos_usr.Where(du => du.idLabor == docencia_works.ElementAt(i).idLabor).ToList();
for (int j = 0; j < temp_ls.Count(); j++)
{
int ideval = (int)temp_ls.ElementAt(j).idEvaluacion;
var puntaje = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == ideval);
if (puntaje.evaluacionjefe <= 1)
l_sub.Add(new Subordinate((int)temp_ls.ElementAt(j).idDocente, (int)temp_ls.ElementAt(j).idLabor, (int)temp_ls.ElementAt(j).idEvaluacion, (int)puntaje.evaluacionjefe, (int)puntaje.evaluacionestudiante, (int)puntaje.evaluacionautoevaluacion, (string)temp_ls.ElementAt(j).nombres, (string)temp_ls.ElementAt(j).apellidos));
}
//mySubordinates.Add(new SubordinatesByWork(docencia_works.ElementAt(i).idLabor, docencia_works.ElementAt(i).txtLabor, "Docencia", l_sub));
}
if (l_sub.Count > 0)
{
mySubordinates.Add(new SubordinatesByWork(docencia_works.ElementAt(docencia_works.Count() - 1).idLabor, strTitle, "Docencia", l_sub));
}
}
// NUEVO 29 NOCHE
var otras_works = dbEntity.otras
.Join(dir_ids,
soc => soc.idlabor,
d_ids => d_ids.labor.idlabor,
(soc, d_ids) => new { social = soc, dir_ids = d_ids })
.Select(c => new { txtLabor = c.social.descripcion, idLabor = c.social.idlabor })
.OrderBy(e => e.txtLabor)
.ToList();
if (otras_works.Count() > 0)
{
for (int i = 0; i < otras_works.Count(); i++)
{
var temp_ls = datos_usr.Where(du => du.idLabor == otras_works.ElementAt(i).idLabor).ToList();
List<Subordinate> l_sub = new List<Subordinate>();
for (int j = 0; j < temp_ls.Count(); j++)
{
int ideval = (int)temp_ls.ElementAt(j).idEvaluacion;
var puntaje = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == ideval);
if (puntaje.evaluacionjefe <= 1)
l_sub.Add(new Subordinate((int)temp_ls.ElementAt(j).idDocente, (int)temp_ls.ElementAt(j).idLabor, (int)temp_ls.ElementAt(j).idEvaluacion, (int)puntaje.evaluacionjefe, (int)puntaje.evaluacionestudiante, (int)puntaje.evaluacionautoevaluacion, (string)temp_ls.ElementAt(j).nombres, (string)temp_ls.ElementAt(j).apellidos));
}
if (l_sub.Count > 0)
mySubordinates.Add(new SubordinatesByWork(otras_works.ElementAt(i).idLabor, otras_works.ElementAt(i).txtLabor, "Otras", l_sub));
}
}
// FIN NUEVO 29
if (mySubordinates.Count == 0)
{
ViewBag.Message = "No le han sido asignados docentes para este periodo ";
}
ViewBag.SubByWork = mySubordinates;
return View();
}
//INICIO ADICIONADO POR CLARA
#region Adicionado Por Clara
#region Docentes
// NUEVO 30
[Authorize]
public ActionResult CreateQuery()
{
int tipo = 0;
var lista_roles = (System.Collections.ArrayList)SessionValue("roles");
int currentper = (int)SessionValue("currentAcadPeriod");
for (int i = 0; i < lista_roles.Count; i++)
{
if (lista_roles[i].Equals("Decano"))
{
tipo = 1;
}
if (lista_roles[i].Equals("Coordinador"))
{
tipo = 2;
}
}
if (tipo == 0)
{
ViewBag.optionmenu = 1;
docente docente = (docente)SessionValue("docente");
departamento departamento = (departamento)SessionValue("depto");
usuario user = (usuario)SessionValue("logedUser");
// NUEVO 28
try
{
var docentes = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
join di in dbEntity.dirige on p.idlabor equals di.idlabor
where l.idperiodo == currentper && di.idusuario == docente.idusuario && d.iddepartamento == departamento.iddepartamento
select u).Distinct().OrderBy(u => u.apellidos).ToList();
ViewBag.lista = docentes;
if (docentes.Count > 0)
ViewBag.datos = 1;
else
ViewBag.datos = 0;
if (departamento != null)
{
ViewBag.departamento = departamento.nombre;
}
return View();
}
catch
{
ViewBag.Error = "No hay ";
return View();
}
// FIN NUEVO 28
}
if (tipo == 2 || tipo == 1)
{
int idCoordinador = (int)SessionValue("docenteId");
decanoCoordinador FacCoordinador = dbEntity.decanoCoordinador.Single(d => d.idusuario == idCoordinador);
ViewBag.optionmenu = 1;
//docente docente = (docente)SessionValue("docente"];
departamento departamento = (departamento)SessionValue("depto");
usuario user = (usuario)SessionValue("logedUser");
// NUEVO 28
try
{
var docentes = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
join di in dbEntity.dirige on p.idlabor equals di.idlabor
where l.idperiodo == currentper && di.idusuario == idCoordinador
select u).Distinct().OrderBy(u => u.apellidos).ToList();
ViewBag.lista = docentes;
if (departamento != null)
{
ViewBag.departamento = "";
}
return View();
}
catch
{
ViewBag.Error = "No le han sido asignados docentes para evaluar";
return View();
}
// FIN NUEVO 28
}
return View();
}
// FIN NUEVO 30
#endregion
#region Evaluación
public class DocenteReporte
{
public int iddocente;
public int idusuario;
public int idlabor;
public string nombres;
public string apellidos;
public double social;
public double gestion;
public double investigacion;
public double trabajoInvestigacion;
public double trabajoGrado;
public double dProfesoral;
public double docencia;
public double total;
}
public List<ResEvaluacionLabor> calcularPonderados(List<ResEvaluacionLabor> lista)
{
Double totalHoras = lista.Sum(q => q.horasxsemana);
foreach (ResEvaluacionLabor labor in lista)
{
Double porc = (labor.horasxsemana * 100) / totalHoras;
labor.porcentaje = (int)System.Math.Round(porc, 0);
labor.nota = (int)calculaNotaPromedio(labor.evalest, labor.evalauto, labor.evaljefe);
Double acum = System.Math.Round((porc * labor.nota) / 100, 2);
labor.acumula = (int)acum;
}
return lista;
}
public Double calculaNotaPromedio(Double n1, Double n2, Double n3)
{
if (n1 == -1 && n2 == -1 && n3 == -1)
{
return 0;
}
int divisor = 3;
if (n1 == -1) { n1 = 0; divisor--; }
if (n2 == -1) { n2 = 0; divisor--; }
if (n3 == -1) { n3 = 0; divisor--; }
return System.Math.Round(((n1 + n2 + n3) / divisor), 0);
}
//edinsonV
public ActionResult CreateReport()
{
int tipo = 0;
var lista_roles = (System.Collections.ArrayList)SessionValue("roles");
for (int i = 0; i < lista_roles.Count; i++)
{
if (lista_roles[i].Equals("Decano"))
{
tipo = 1;
}
if (lista_roles[i].Equals("Coordinador"))
{
tipo = 2;
}
}
if (tipo == 0)
{
ViewBag.optionmenu = 3;
usuario user = (usuario)SessionValue("logedUser");
departamento departamento = (departamento)SessionValue("depto");
int currentper = (int)SessionValue("currentAcadPeriod");
consolidadoDocenteReporte = new List<ConsolidadoDocente>();
// NUEVO 28
try
{
List<DocenteReporte> docentes = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
join di in dbEntity.dirige on p.idlabor equals di.idlabor
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento && di.idusuario == user.idusuario
select new DocenteReporte { iddocente = d.iddocente, idusuario = d.idusuario }).Distinct().ToList();
foreach (DocenteReporte doc in docentes)
{
consolidadoDocenteReporte.Add(crearReporte(doc.idusuario));
}
ViewBag.lista = consolidadoDocenteReporte;
if (consolidadoDocenteReporte.Count > 0)
ViewBag.datos = 1;
else
ViewBag.datos = 0;
if (departamento != null)
{
ViewBag.departamento = departamento.nombre;
}
return View();
}
catch
{
ViewBag.Error = "No hay";
return View();
}
// FIN NUEVO 28
}
if (tipo == 2 || tipo == 1)
{
int idCoordinador = (int)SessionValue("docenteId");
decanoCoordinador FacCoordinador = dbEntity.decanoCoordinador.Single(d => d.idusuario == idCoordinador);
departamento departamento = (departamento)SessionValue("depto");
int currentper = (int)SessionValue("currentAcadPeriod");
usuario user = (usuario)SessionValue("logedUser");
ViewBag.optionmenu = 3;
consolidadoDocenteReporte = new List<ConsolidadoDocente>();
// NUEVO 28
try
{
List<DocenteReporte> docentes = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
join di in dbEntity.dirige on p.idlabor equals di.idlabor
where l.idperiodo == currentper && di.idusuario == user.idusuario
select new DocenteReporte { iddocente = d.iddocente, idusuario = d.idusuario }).Distinct().ToList();
foreach (DocenteReporte doc in docentes)
{
consolidadoDocenteReporte.Add(crearReporte(doc.idusuario));
}
ViewBag.lista = consolidadoDocenteReporte;
if (consolidadoDocenteReporte.Count > 0)
ViewBag.datos = 1;
else
ViewBag.datos = 0;
if (departamento != null)
{
ViewBag.departamento = departamento.nombre;
}
return View();
}
catch
{
ViewBag.Error = "No hay";
return View();
}
// FIN NUEVO 28
}
return View();
}
public int obtenerFilas()
{
int filasReporte = 0;
foreach (ConsolidadoDocente filas in consolidadoDocenteReporte)
{
filasReporte = filasReporte + filas.evaluacioneslabores.Count();
}
return filasReporte;
}
// NUEVO 31 EDINSON
public ActionResult ExportToExcel()
{
SpreadsheetModel mySpreadsheet = new SpreadsheetModel();
int tam = obtenerFilas();
String[,] datos = new String[tam + 1, 11];
datos[0, 0] = "<NAME>";
datos[0, 1] = "<NAME>";
datos[0, 2] = "Fecha Evaluación";
datos[0, 3] = "Labor";
datos[0, 4] = "Tipo";
datos[0, 5] = "Periodo";
datos[0, 6] = "H/S";
//datos[0, 7] = "%";
datos[0, 7] = "Est";
datos[0, 8] = "AutoEv";
datos[0, 9] = "JefeNota";
//datos[0, 11] = "Acumulado";
datos[0, 10] = "Total";
int i = 1;
foreach (ConsolidadoDocente labor in consolidadoDocenteReporte)
{
for (int j = 0; j < labor.evaluacioneslabores.Count(); j++)
{
datos[i, 0] = labor.nombredocente;
datos[i, 1] = labor.nombrejefe;
datos[i, 2] = labor.fechaevaluacion;
datos[i, 3] = labor.evaluacioneslabores.ElementAt(j).descripcion;
datos[i, 4] = labor.evaluacioneslabores.ElementAt(j).tipolaborcorto;
datos[i, 5] = "" + labor.periodonum + " - " + labor.periodoanio;
datos[i, 6] = "" + labor.evaluacioneslabores.ElementAt(j).horasxsemana;
//datos[i, 7] = "" + labor.evaluacioneslabores.ElementAt(j).porcentaje;
datos[i, 7] = "" + labor.evaluacioneslabores.ElementAt(j).evalest;
datos[i, 8] = "" + labor.evaluacioneslabores.ElementAt(j).evalauto;
datos[i, 9] = "" + labor.evaluacioneslabores.ElementAt(j).evaljefe;
//datos[i, 11] = "" + labor.evaluacioneslabores.ElementAt(j).acumula;
datos[i, 10] = "" + labor.evaluacioneslabores.ElementAt(j).nota;
//i++;
}
i++;
}
mySpreadsheet.contents = datos;
periodo_academico lastAcademicPeriod = GetLastAcademicPeriod();
DateTime Hora = DateTime.Now;
DateTime Hoy = DateTime.Today;
string hora = Hora.ToString("HH:mm");
string hoy = Hoy.ToString("dd-MM");
mySpreadsheet.fileName = "Reporte" + lastAcademicPeriod.anio + "-" + lastAcademicPeriod.idperiodo + "_" + hoy + "_" + hora + ".xls";
return View(mySpreadsheet);
}
// FIN NUEVO 31 EDINSON
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowScores(int idusuario)
{
//string usuarioEntra = Request.Form["usuario"];
//int idusuario = Convert.ToInt16(usuarioEntra);
ViewBag.optionmenu = 1;
ViewBag.reporte = crearReporte(idusuario);
return View();
}
public ConsolidadoDocente crearReporte(int idUsuario)
{
departamento departamento = (departamento)SessionValue("depto");
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
usuario usuarioActual = (usuario)SessionValue("logedUser");
int idjefe = usuarioActual.idusuario;
usuario jefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idjefe);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
ConsolidadoDocente reporte = new ConsolidadoDocente() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = jefe.nombres + " " + jefe.apellidos, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
List<ResEvaluacionLabor> labores = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join ev in dbEntity.evaluacion on p.idevaluacion equals ev.idevaluacion
join l in dbEntity.labor on p.idlabor equals l.idlabor
join di in dbEntity.dirige on p.idlabor equals di.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper && u.idusuario == idUsuario && di.idusuario == usuarioActual.idusuario
select new ResEvaluacionLabor { idlabor = l.idlabor, evalest = (int)ev.evaluacionestudiante, evalauto = (int)ev.evaluacionautoevaluacion, evaljefe = (int)ev.evaluacionjefe }).ToList();
labores = setLabor(labores);
reporte.totalhorassemana = (Double)labores.Sum(q => q.horasxsemana);
reporte.evaluacioneslabores = calcularPonderados(labores);
reporte.totalporcentajes = (int)reporte.evaluacioneslabores.Sum(q => q.porcentaje);
reporte.notafinal = (int)reporte.evaluacioneslabores.Sum(q => q.acumula);
return reporte;
}
public List<ResEvaluacionLabor> setLabor(List<ResEvaluacionLabor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otra;
foreach (ResEvaluacionLabor labor in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (gestion != null)
{
labor.tipolabor = "Gestion";
labor.tipolaborcorto = "GES";
labor.descripcion = gestion.nombrecargo;
labor.horasxsemana = (int)gestion.horassemana;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (social != null)
{
labor.tipolabor = "Social";
labor.tipolaborcorto = "SOC";
labor.descripcion = social.nombreproyecto;
labor.horasxsemana = (int)social.horassemana;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (investigacion != null)
{
labor.tipolabor = "Investigación";
labor.tipolaborcorto = "INV";
labor.descripcion = investigacion.nombreproyecto;
labor.horasxsemana = (int)investigacion.horassemana;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGrado != null)
{
labor.tipolabor = "Trabajo de Grado";
labor.tipolaborcorto = "TDG";
labor.descripcion = trabajoDeGrado.titulotrabajo;
labor.horasxsemana = (int)trabajoDeGrado.horassemana;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
labor.tipolabor = "Trabajo de Grado Investigación";
labor.tipolaborcorto = "TDGI";
labor.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
labor.horasxsemana = (int)trabajoDeGradoInvestigacion.horassemana;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (desarrolloProfesoral != null)
{
labor.tipolabor = "Desarrollo Profesoral";
labor.tipolaborcorto = "DP";
labor.descripcion = desarrolloProfesoral.nombreactividad;
labor.horasxsemana = (int)desarrolloProfesoral.horassemana;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (docencia != null)
{
materia materia = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
labor.tipolabor = "Docencia Directa";
labor.tipolaborcorto = "DD";
labor.descripcion = materia.nombremateria;
labor.horasxsemana = (int)docencia.horassemana;
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (otra != null)
{
labor.tipolabor = "Otra";
labor.tipolaborcorto = "OT";
labor.descripcion = otra.descripcion;
labor.horasxsemana = (int)otra.horassemana;
continue;
}
}
return lista;
}
#endregion
#region Autoevaluación
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult VerAutoevaluaciones()
{
ViewBag.optionmenu = 1;
usuario user = (usuario)SessionValue("logedUser");
int currentper = (int)SessionValue("currentAcadPeriod");
ViewBag.reporte = crearReporteAutoevaluacion(user.idusuario);
return View();
}
public AutoevaluacionDocente crearReporteAutoevaluacion(int idUsuario)
{
departamento departamento = (departamento)SessionValue("depto");
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
usuario usuarioActual = (usuario)SessionValue("logedUser");
int idjefe = usuarioActual.idusuario;
usuario jefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idjefe);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
AutoevaluacionDocente AutoevaluacionDocenteReporte = new AutoevaluacionDocente() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = jefe.nombres + " " + jefe.apellidos, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
List<ResAutoEvaluacionLabor> labores = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join aev in dbEntity.autoevaluacion on p.idautoevaluacion equals aev.idautoevaluacion
join pr in dbEntity.problema on aev.idautoevaluacion equals pr.idautoevaluacion
join re in dbEntity.resultado on aev.idautoevaluacion equals re.idautoevaluacion
join l in dbEntity.labor on p.idlabor equals l.idlabor
join di in dbEntity.dirige on p.idlabor equals di.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper && u.idusuario == idUsuario && di.idusuario == usuarioActual.idusuario
select new ResAutoEvaluacionLabor { idlabor = l.idlabor, nota = (int)aev.calificacion, problemadescripcion = pr.descripcion, problemasolucion = pr.solucion, resultadodescripcion = re.descripcion, resultadosolucion = re.ubicacion }).ToList();
labores = setAELabor(labores);
AutoevaluacionDocenteReporte.autoevaluacioneslabores = labores;
return AutoevaluacionDocenteReporte;
}
public List<ResAutoEvaluacionLabor> setAELabor(List<ResAutoEvaluacionLabor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otra;
foreach (ResAutoEvaluacionLabor labor in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (gestion != null)
{
labor.tipolabor = "Gestión";
labor.tipolaborcorto = "GES";
labor.descripcion = gestion.nombrecargo;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (social != null)
{
labor.tipolabor = "Social";
labor.tipolaborcorto = "SOC";
labor.descripcion = social.nombreproyecto;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (investigacion != null)
{
labor.tipolabor = "Investigación";
labor.tipolaborcorto = "INV";
labor.descripcion = investigacion.nombreproyecto;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGrado != null)
{
labor.tipolabor = "Trabajo de Grado";
labor.tipolaborcorto = "TDG";
labor.descripcion = trabajoDeGrado.titulotrabajo;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
labor.tipolabor = "Trabajo de Grado Investigación";
labor.tipolaborcorto = "TDGI";
labor.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (desarrolloProfesoral != null)
{
labor.tipolabor = "Desarrollo Profesoral";
labor.tipolaborcorto = "DP";
labor.descripcion = desarrolloProfesoral.nombreactividad;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (docencia != null)
{
materia materia = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
labor.tipolabor = "Docencia Directa";
labor.tipolaborcorto = "DD";
labor.descripcion = materia.nombremateria;
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (otra != null)
{
labor.tipolabor = "Otra";
labor.tipolaborcorto = "OTR";
labor.descripcion = otra.descripcion;
continue;
}
}
return lista;
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowAutoScores(int idusuario)
{
ViewBag.optionmenu = 1;
ViewBag.reporte = crearReporteAutoevaluacion(idusuario);
if (ViewBag.reporte != null)
ViewBag.datos = 1;
else
ViewBag.datos = 0;
return View();
}
// NUEVO 31 EDINSONb
public ActionResult CreateReportAE()
{
int tipo = 0;
var lista_roles = (System.Collections.ArrayList)SessionValue("roles");
for (int i = 0; i < lista_roles.Count; i++)
{
if (lista_roles[i].Equals("Decano"))
{
tipo = 1;
}
if (lista_roles[i].Equals("Coordinador"))
{
tipo = 2;
}
}
if (tipo == 0)
{
ViewBag.optionmenu = 3;
departamento departamento = (departamento)SessionValue("depto");
usuario user = (usuario)SessionValue("logedUser");
int currentper = (int)SessionValue("currentAcadPeriod");
AutoevaluacionDocenteReporte = new List<AutoevaluacionDocente>();
try
{
List<DocenteReporte> docentes = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
join di in dbEntity.dirige on p.idlabor equals di.idlabor
where l.idperiodo == currentper && d.iddepartamento == departamento.iddepartamento && di.idusuario == user.idusuario
select new DocenteReporte { iddocente = d.iddocente, idusuario = d.idusuario }).Distinct().ToList();
foreach (DocenteReporte doc in docentes)
{
AutoevaluacionDocenteReporte.Add(crearReporteAutoevaluacion(doc.idusuario));
}
ViewBag.lista = AutoevaluacionDocenteReporte;
if (AutoevaluacionDocenteReporte.Count > 0)
ViewBag.datos = 1;
else
ViewBag.datos = 0;
if (departamento != null)
{
ViewBag.departamento = departamento.nombre;
}
return View();
}
catch
{
ViewBag.Error = "No tiene docentes asignados ";
return View();
}
}
if (tipo == 2 || tipo == 1)
{
int idCoordinador = (int)SessionValue("docenteId");
decanoCoordinador FacCoordinador = dbEntity.decanoCoordinador.Single(d => d.idusuario == idCoordinador);
departamento departamento = (departamento)SessionValue("depto");
int currentper = (int)SessionValue("currentAcadPeriod");
ViewBag.optionmenu = 3;
usuario user = (usuario)SessionValue("logedUser");
AutoevaluacionDocenteReporte = new List<AutoevaluacionDocente>();
try
{
List<DocenteReporte> docentes = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
join di in dbEntity.dirige on p.idlabor equals di.idlabor
where l.idperiodo == currentper && di.idusuario == user.idusuario
select new DocenteReporte { iddocente = d.iddocente, idusuario = d.idusuario }).Distinct().ToList();
foreach (DocenteReporte doc in docentes)
{
AutoevaluacionDocenteReporte.Add(crearReporteAutoevaluacion(doc.idusuario));
}
ViewBag.lista = AutoevaluacionDocenteReporte;
if (AutoevaluacionDocenteReporte.Count > 0)
ViewBag.datos = 1;
else
ViewBag.datos = 0;
if (departamento != null)
{
ViewBag.departamento = departamento.nombre;
}
return View();
}
catch
{
ViewBag.Error = "No tiene docentes asignados";
return View();
}
}
return View();
}
// FIN NUEVO 31 EDINSON
public int obtenerFilasAE()
{
int filasReporte = 0;
foreach (AutoevaluacionDocente filas in AutoevaluacionDocenteReporte)
{
filasReporte = filasReporte + filas.autoevaluacioneslabores.Count() + 1;
}
return filasReporte;
}
public ActionResult ExportToExcelAutoevaluacion()
{
SpreadsheetModelAE mySpreadsheetAE = new SpreadsheetModelAE();
int tam = obtenerFilasAE();
String[,] datos = new String[tam, 10];
datos[0, 0] = "<NAME>";
datos[0, 1] = "ID Labor";
datos[0, 2] = "Tipo Corto";
datos[0, 3] = "Tipo";
datos[0, 4] = "Labor";
datos[0, 5] = "Nota";
datos[0, 6] = "Descripcion Problema";
datos[0, 7] = "Respuesta Problema";
datos[0, 8] = "Descripcion Solucion";
datos[0, 9] = "Respuesta Solucion";
mySpreadsheetAE.fechaevaluacion = AutoevaluacionDocenteReporte[0].fechaevaluacion;
mySpreadsheetAE.periodo = "" + AutoevaluacionDocenteReporte[0].periodonum + " - " + AutoevaluacionDocenteReporte[0].periodoanio;
mySpreadsheetAE.nombrejefe = AutoevaluacionDocenteReporte[0].nombrejefe;
int i = 1;
foreach (AutoevaluacionDocente labor in AutoevaluacionDocenteReporte)
{
for (int j = 0; j < labor.autoevaluacioneslabores.Count(); j++)
{
datos[i, 0] = labor.nombredocente;
datos[i, 1] = "" + labor.autoevaluacioneslabores.ElementAt(j).idlabor;
datos[i, 2] = labor.autoevaluacioneslabores.ElementAt(j).tipolaborcorto;
datos[i, 3] = labor.autoevaluacioneslabores.ElementAt(j).tipolabor;
datos[i, 4] = labor.autoevaluacioneslabores.ElementAt(j).descripcion;
datos[i, 5] = "" + labor.autoevaluacioneslabores.ElementAt(j).nota;
datos[i, 6] = "" + labor.autoevaluacioneslabores.ElementAt(j).problemadescripcion;
datos[i, 7] = "" + labor.autoevaluacioneslabores.ElementAt(j).problemasolucion;
datos[i, 8] = "" + labor.autoevaluacioneslabores.ElementAt(j).resultadodescripcion;
datos[i, 9] = "" + labor.autoevaluacioneslabores.ElementAt(j).resultadosolucion;
i++;
}
i++;
}
mySpreadsheetAE.labores = datos;
periodo_academico lastAcademicPeriod = GetLastAcademicPeriod();
DateTime Hora = DateTime.Now;
DateTime Hoy = DateTime.Today;
string hora = Hora.ToString("HH:mm");
string hoy = Hoy.ToString("dd-MM");
mySpreadsheetAE.fileName = "Reporte" + lastAcademicPeriod.anio + "-" + lastAcademicPeriod.idperiodo + "_" + hoy + "_" + hora + ".xls";
return View(mySpreadsheetAE);
}
#endregion
#region Labores
public class Labor
{
public int idlabor;
public String tipoLabor;
public String descripcion;
}
[Authorize]
public ActionResult GetLaborType()
{
ViewBag.optionmenu = 1;
int currentper = (int)SessionValue("currentAcadPeriod");
departamento departamento = (departamento)SessionValue("depto");
usuario user = (usuario)SessionValue("logedUser");
var GenreLst = new List<int>();
var NameLabor = new List<String>();
var tipolabor = from p in dbEntity.participa
join aev in dbEntity.autoevaluacion on p.idautoevaluacion equals aev.idautoevaluacion
join l in dbEntity.labor on p.idlabor equals l.idlabor
join d in dbEntity.dirige on l.idlabor equals d.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper && d.idusuario == user.idusuario
orderby l.idlabor
select p.idlabor;
GenreLst.AddRange(tipolabor.Distinct());
foreach (int id in GenreLst)
{
var gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == id);
if (gestion != null)
{
NameLabor.Add("Gestión");
continue;
}
var social = dbEntity.social.SingleOrDefault(g => g.idlabor == id);
if (social != null)
{
NameLabor.Add("Social");
continue;
}
var investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == id);
if (investigacion != null)
{
NameLabor.Add("Investigación");
continue;
}
var trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == id);
if (trabajoDeGrado != null)
{
NameLabor.Add("Trabajo de grado");
continue;
}
var trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == id);
if (trabajoDeGradoInvestigacion != null)
{
NameLabor.Add("Trabajo de grado investigacion");
continue;
}
var desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == id);
if (desarrolloProfesoral != null)
{
NameLabor.Add("Desarrollo profesoral");
continue;
}
var docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == id);
if (docencia != null)
{
NameLabor.Add("Docencia");
continue;
}
var otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == id);
if (otra != null)
{
NameLabor.Add("Otra");
continue;
}
}
if (NameLabor.Count > 0)
{
//funcion que envia los datos a la lista desplegable del docente
ViewBag.tipoLabor = new SelectList(NameLabor.Distinct());
ViewBag.datos = 1;
}
else
{
ViewBag.datos = 0;
}
ViewBag.nombre = user.nombres + " " + user.apellidos;
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchTipoLabor(string term)
{
int currentper = (int)SessionValue("currentAcadPeriod");
departamento departamento = (departamento)SessionValue("depto");
usuario user = (usuario)SessionValue("logedUser");
var labores = new List<Labor>();
term = (term).ToLower();
if (term == "gestión")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join g in dbEntity.gestion on p.idlabor equals g.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.dirige on l.idlabor equals d.idlabor
where l.idperiodo == currentper && d.idusuario == user.idusuario
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = g.nombrecargo }).Distinct().ToList();
}
if (term == "social")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join s in dbEntity.social on p.idlabor equals s.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.dirige on l.idlabor equals d.idlabor
where l.idperiodo == currentper && d.idusuario == user.idusuario
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = s.nombreproyecto }).Distinct().ToList();
}
if (term == "investigación")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join i in dbEntity.investigacion on p.idlabor equals i.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.dirige on l.idlabor equals d.idlabor
where l.idperiodo == currentper && d.idusuario == user.idusuario
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = i.nombreproyecto }).Distinct().ToList();
}
if (term == "trabajo de grado")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join t in dbEntity.trabajodegrado on p.idlabor equals t.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.dirige on l.idlabor equals d.idlabor
where l.idperiodo ==currentper && d.idusuario == user.idusuario
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = t.titulotrabajo }).Distinct().ToList();
}
if (term == "trabajo de grado investigacion")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join t in dbEntity.trabajodegradoinvestigacion on p.idlabor equals t.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.dirige on l.idlabor equals d.idlabor
where l.idperiodo == currentper && d.idusuario == user.idusuario
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = t.titulotrabajo }).Distinct().ToList();
}
if (term == "desarrollo profesoral")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join dp in dbEntity.desarrolloprofesoral on p.idlabor equals dp.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.dirige on l.idlabor equals d.idlabor
where l.idperiodo == currentper && d.idusuario == user.idusuario
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = dp.nombreactividad }).Distinct().ToList();
}
if (term == "docencia")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join t in dbEntity.docencia on p.idlabor equals t.idlabor
join m in dbEntity.materia on t.idmateria equals m.idmateria
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.dirige on l.idlabor equals d.idlabor
where l.idperiodo == currentper && d.idusuario == user.idusuario
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = m.nombremateria }).Distinct().ToList();
}
if (term == "otra")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join o in dbEntity.otras on p.idlabor equals o.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join d in dbEntity.dirige on l.idlabor equals d.idlabor
where l.idperiodo == currentper && d.idusuario == user.idusuario
orderby p.idlabor
select new Labor { idlabor = p.idlabor, descripcion = o.descripcion }).Distinct().ToList();
}
return Json(labores, JsonRequestBehavior.AllowGet);
}
[Authorize]
public ActionResult ProblemasLabor(int id)
{
ViewBag.optionmenu = 1;
int currentper = (int)SessionValue("currentAcadPeriod");
labor lab = dbEntity.labor.SingleOrDefault(q => q.idlabor == id);
if (lab.idperiodo == currentper)
{
if (ModelState.IsValid)
{
var lista = new List<Labor>();
lista.Add(new Labor { idlabor = id });
var response = getLabor(lista);
ViewBag.datos = response;
ViewBag.mensaje = 1;
return View();
}
}
else
{
ViewBag.mensaje = 0;
}
return View();
}
public List<Labor> getLabor(List<Labor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otrasVar;
materia materia;
foreach (Labor jefe in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (gestion != null)
{
jefe.tipoLabor = "gestion";
jefe.descripcion = gestion.nombrecargo;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (social != null)
{
jefe.tipoLabor = "social";
jefe.descripcion = social.nombreproyecto;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (investigacion != null)
{
jefe.tipoLabor = "investigacion";
jefe.descripcion = investigacion.nombreproyecto;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGrado != null)
{
jefe.tipoLabor = "trabajo de grado";
jefe.descripcion = trabajoDeGrado.titulotrabajo;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
jefe.tipoLabor = "trabajo de grado investigacion";
jefe.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (desarrolloProfesoral != null)
{
jefe.tipoLabor = "desarrollo profesoral";
jefe.descripcion = desarrolloProfesoral.nombreactividad;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (docencia != null)
{
jefe.tipoLabor = "docencia";
materia = dbEntity.materia.SingleOrDefault(m => m.idmateria == docencia.idmateria);
jefe.descripcion = materia.nombremateria;
continue;
}
// NUEVO 30 ENERO
otrasVar = dbEntity.otras.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (otrasVar != null)
{
jefe.tipoLabor = "Otras";
jefe.descripcion = otrasVar.descripcion;
continue;
}
// FIN NUEVO 30 ENERO
}
return lista;
}
public class DepartamentoLabor
{
public int idlabor;
public string docente;
public string descripcion;
public string problemadescripcion;
public string problemarespuesta;
public string soluciondescripcion;
public string solucionrespuesta;
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchProblemasLabor(int id, string term)
{
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
departamento departamento = (departamento)SessionValue("depto");
var labores = new List<DepartamentoLabor>();
usuario user = (usuario)SessionValue("logedUser");
term = (term).ToLower();
if (term == "gestión")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join g in dbEntity.gestion on p.idlabor equals g.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join di in dbEntity.dirige on p.idlabor equals di.idlabor
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == ultimoPeriodo.idperiodo && l.idlabor == id && di.idusuario == user.idusuario
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = g.nombrecargo, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "social")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join s in dbEntity.social on p.idlabor equals s.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join di in dbEntity.dirige on p.idlabor equals di.idlabor
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == ultimoPeriodo.idperiodo && l.idlabor == id && di.idusuario == user.idusuario
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = s.nombreproyecto, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "investigación")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join i in dbEntity.investigacion on p.idlabor equals i.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join di in dbEntity.dirige on p.idlabor equals di.idlabor
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == ultimoPeriodo.idperiodo && l.idlabor == id && di.idusuario == user.idusuario
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = i.nombreproyecto, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "trabajo de grado")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join t in dbEntity.trabajodegrado on p.idlabor equals t.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join di in dbEntity.dirige on p.idlabor equals di.idlabor
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == ultimoPeriodo.idperiodo && l.idlabor == id && di.idusuario == user.idusuario
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = t.titulotrabajo, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "trabajo de grado investigacion")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join t in dbEntity.trabajodegradoinvestigacion on p.idlabor equals t.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join di in dbEntity.dirige on p.idlabor equals di.idlabor
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == ultimoPeriodo.idperiodo && l.idlabor == id && di.idusuario == user.idusuario
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = t.titulotrabajo, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "desarrollo profesoral")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join dp in dbEntity.desarrolloprofesoral on p.idlabor equals dp.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join di in dbEntity.dirige on p.idlabor equals di.idlabor
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == ultimoPeriodo.idperiodo && l.idlabor == id && di.idusuario == user.idusuario
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = dp.nombreactividad, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "docencia")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join t in dbEntity.docencia on p.idlabor equals t.idlabor
join m in dbEntity.materia on t.idmateria equals m.idmateria
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join di in dbEntity.dirige on p.idlabor equals di.idlabor
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == ultimoPeriodo.idperiodo && l.idlabor == id && di.idusuario == user.idusuario
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = m.nombremateria, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
if (term == "otra")
{
labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join o in dbEntity.otras on p.idlabor equals o.idlabor
join e in dbEntity.autoevaluacion on p.idautoevaluacion equals e.idautoevaluacion
join pr in dbEntity.problema on e.idautoevaluacion equals pr.idautoevaluacion
join sol in dbEntity.resultado on e.idautoevaluacion equals sol.idautoevaluacion
join di in dbEntity.dirige on p.idlabor equals di.idlabor
join d in dbEntity.docente on p.iddocente equals d.iddocente
join u in dbEntity.usuario on d.idusuario equals u.idusuario
where l.idperiodo == ultimoPeriodo.idperiodo && l.idlabor == id && di.idusuario == user.idusuario
orderby p.idlabor
select new DepartamentoLabor { idlabor = p.idlabor, docente = u.nombres + " " + u.apellidos, descripcion = o.descripcion, problemadescripcion = pr.descripcion, problemarespuesta = pr.solucion, soluciondescripcion = sol.descripcion, solucionrespuesta = sol.ubicacion }).Distinct().ToList();
}
return Json(labores, JsonRequestBehavior.AllowGet);
}
#endregion
#endregion
//FIN ADICIONADO POR CLARA
}
}
<file_sep>$(function () {
var questions = $("input.calif"),
evalest = $("#calif_est"),
evalauto = $("#calif_auto"),
allFields = $([]).add(questions).add(evalest).add(evalauto),
tips = $("#validation-messages");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("El tamaño de " + n + " debe estar entre " +
min + " y " + max + ".");
return false;
} else {
return true;
}
}
function checkDigits(o) { //retorna true si solo tiene digitos
solodigitos = true;
for (i = 0; i < o.val().length; i++) {
solodigitos = solodigitos && (o.val().charAt(i) >= '0' && o.val().charAt(i) <= '9');
}
return solodigitos;
}
function checkRange(o, n, min, max) {
if (!isNaN(parseInt(o.val())) && checkDigits(o)) {
var num = parseInt(o.val());
if (num < min || num > max) {
o.addClass("ui-state-error");
updateTips("El rango de la " + n + " debe estar entre " +
min + " y " + max + ".");
return false;
} else {
return true;
}
} else {
o.addClass("ui-state-error");
updateTips("El valor de la " + n + " debe ser un numero entre " +
min + " y " + max + ".");
return false;
}
}
var confirmdialog = true;
$('#dialogEvalSubordinate').dialog({
autoOpen: false,
width: 500,
height: 600,
modal: true,
buttons: {
"Guardar Evaluación": function () {
confirmdialog = false;
var bValid = true;
allFields.removeClass("ui-state-error");
bValid = bValid && checkRange(evalest, "evaluación de estudiantes", 1, 100);
bValid = bValid && checkRange(evalauto, "autoevaluación", 1, 100);
questions.each(function (index) {
bValid = bValid && checkRange($(this), "evaluacion", 1, 100);
});
if (bValid) {
allFields.removeClass("ui-state-error");
SaveEval("/sedoc/WorkChief/UpdateEval/", $(this));
$(this).dialog("close");
}
},
"Cancelar": function () {
confirmdialog = true;
$(this).dialog("close");
}
},
beforeClose: function (event, ui) {
if (confirmdialog) {
if (!confirm("¿Seguro desea Cancelar sin guardar ningun cambio?")) {
confirmdialog = true;
return false;
}
}
}
});
function SaveEval(route, jquerydialog) {
var evaluacion = getEval();
if (evaluacion != null) {
var request = $.ajax({
cache: false,
url: route,
type: 'POST',
dataType: 'json',
data: evaluacion,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.toString() != "-1") {
$("#" + $('#idEvaluacion').val()).html(data.toString());
$("#Est_" + $('#idEvaluacion').val()).html($("#calif_est").val());
$("#Auto_" + $('#idEvaluacion').val()).html($("#calif_auto").val());
alert("Evaluación grabada éxitosamente");
} else {
alert("Lo siento no pude grabar la evaluación, comunicate con el administrador");
}
}
});
}
}
function getEval() {
var idL = $("#idLaborEvaluar").val();
var idD = $("#idDocenteEvaluado").val();
var idE = $("#idEvaluacion").val();
var idC = $("#idCuestionario").val();
var EvEst = $("#calif_est").val();
var EvAut = $("#calif_auto").val();
var cal = '[ ';
$("input.calif").each(function (index) {
cal += '{ "idgrupo": "' + $(this).attr("idgrupo") + '", "idpregunta": "' + $(this).attr("idpregunta") + '", "calificacion": "' + $(this).val() + '" },';
});
cal = cal.substring(0, cal.length - 1) + ' ]';
return (idL == "" || idD == "" || idE == "" || idC == "" || EvEst == "" || EvAut == "") ? null : '{ "idlabor": "' + idL + '", "iddocente": "' + idD + '","idevaluacion": "' + idE + '", "EvalEst":"' + EvEst + '", "EvalAut":"' + EvAut + '", "idcuestionario": "' + idC + '","calificaciones": ' + cal + ' }';
}
$('a.edit').click(function () {
var ideval = $(this).attr("ideval");
$("input.calif").val("");
$('#dialogEvalSubordinate').dialog('open');
$('#idLaborEvaluar').val($(this).attr("idlabeval"));
$('#idDocenteEvaluado').val($(this).attr("iddoc"));
$('#idEvaluacion').val(ideval);
if ($('#Est_' + ideval).text() != "No tiene") {
$('#calif_est').val($('#Est_' + ideval).text());
} else {
$('#calif_est').val("1");
}
if ($('#Auto_' + ideval).text() != "No tiene") {
$('#calif_auto').val($('#Auto_' + ideval).text());
} else {
$('#calif_auto').val("1");
}
$('#DocName').html($(this).attr("docname"));
return false;
});
});<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcSEDOC.Models;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Data.OleDb;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
namespace MvcSEDOC.Controllers
{
public class AdminFacController : SEDOCController
{
public static int opcionError;
public ImportDataSheets data_imports = new ImportDataSheets();
public static ConsolidadoLabores ReporteLabores = new ConsolidadoLabores();
List<ConsolidadoDocencia> ReporteMaterias = new List<ConsolidadoDocencia>();
List<ConsolidadoLabores> ReporteLabores1 = new List<ConsolidadoLabores>();
[Authorize]
public ActionResult Index()
{
facultad facultad = (facultad)SessionValue("fac");
return View(facultad);
}
public object SessionValue(string keyValue)
{
object oValue = null;
try
{
oValue = Session[keyValue];
}
catch
{
return RedirectPermanent("/sedoc");
}
return oValue;
}
#region Privilegios
// MODIFICADO 1 - FEB
[Authorize]
public ActionResult SetPrivileges()
{
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
int currentper = (int)SessionValue("currentAcadPeriod");
if (currentper == ultimoPeriodo.idperiodo)
{
facultad fac = (facultad)SessionValue("fac");
var response = (from d in dbEntity.departamento
where d.idfacultad == fac.idfacultad
select new Departamento { iddepartamento = d.iddepartamento, nombre = d.nombre }).Distinct().ToList();
ViewBag.departamentos = response;
}
else {
ViewBag.Error = " No puede realizar esta acción en periodos anteriores";
}
return View();
}
// FIN MODIFICADO 1 - FEB
#endregion
#region Cuestionario
[Authorize]
public ActionResult CreateQuestionnaire()
{
ViewBag.optionmenu = 2;
return View();
}
//MODIFICADO POR EDINSON
[Authorize]
[HttpPost]
public ActionResult CreateQuestionnaire(cuestionario miCuestionario)
{
ViewBag.optionmenu = 2;
int esta = 0;
if (ModelState.IsValid)
{
string nombre = miCuestionario.tipocuestionario;
if (nombre == null)
{
ViewBag.Error = "Debe ingresar un nombre para el cuestionario";
}
else
{
esta = yaEsta(nombre);
if (esta == 1)
{
ViewBag.Error = "Ya existe un cuestionario con el nombre ingresado";
}
else
{
dbEntity.cuestionario.AddObject(miCuestionario);
dbEntity.SaveChanges();
ViewBag.Message = "El cuestionario se creo correctamente";
}
}
return View();
}
return View(miCuestionario);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult UpdateQuestionnaire()
{
ViewBag.optionmenu = 2;
return View(dbEntity.cuestionario.ToList());
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult EditQuestionnaire(cuestionario micuestionario)
{
if (ModelState.IsValid)
{
dbEntity.cuestionario.Attach(micuestionario);
dbEntity.ObjectStateManager.ChangeObjectState(micuestionario, EntityState.Modified);
dbEntity.SaveChanges();
return Json(micuestionario, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
//MODIFICADO POR EDINSON
[Authorize]
[HttpPost]
public ActionResult DeleteQuestionnaire(int id)
{
int id_borrar = id;
var asignaciones = dbEntity.asignarCuestionario.Where(q => q.idcuestionario == id);
foreach (asignarCuestionario aux in asignaciones)
{
dbEntity.asignarCuestionario.DeleteObject(aux);
}
var eliminar_grupos = dbEntity.grupo.Where(q => q.idcuestionario == id);
foreach (grupo aux1 in eliminar_grupos)
{
var eliminar_preguntas = dbEntity.pregunta.Where(q => q.idgrupo == aux1.idgrupo);
foreach (pregunta aux2 in eliminar_preguntas)
{
dbEntity.pregunta.DeleteObject(aux2);
}
dbEntity.grupo.DeleteObject(aux1);
}
cuestionario cuestionario = dbEntity.cuestionario.Single(c => c.idcuestionario == id);
dbEntity.cuestionario.DeleteObject(cuestionario);
dbEntity.SaveChanges();
return Json(cuestionario, JsonRequestBehavior.AllowGet);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchQuestionnaire(string term)
{
var response = dbEntity.cuestionario.Select(q => new { label = q.tipocuestionario, id = q.idcuestionario }).Where(q => q.label.ToUpper().Contains(term.ToUpper())).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
//MODIFICADO POR EDINSON
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult AjaxSetQuestionnaire(cuestionario miCuestionario)
{
int esta = 0;
if (ModelState.IsValid)
{
string nombre = miCuestionario.tipocuestionario;
esta = yaEsta(nombre);
if (esta == 1)
{
miCuestionario.idcuestionario = 0;
}
else
{
dbEntity.cuestionario.AddObject(miCuestionario);
dbEntity.SaveChanges();
}
return Json(miCuestionario, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
#endregion
#region Grupo
//MODIFICADO POR EDINSON
[Authorize]
public ActionResult CreateGroup()
{
ViewBag.optionmenu = 2;
ViewBag.Value1 = null;
ViewBag.Value2 = null;
ViewBag.Value3 = null;
return View();
}
//MODIFICADO POR EDINSON
[Authorize]
[HttpPost]
public ActionResult CreateGroupo()
{
string cuestionario = "";
string nombre = "";
string auxporcentaje = "";
double porcentaje = 0;
int campo1 = 0;
int campo2 = 0;
int campo3 = 0;
ViewBag.Value1 = "";
ViewBag.Value2 = "";
ViewBag.Value3 = "";
cuestionario = Request.Form["cuestionario"];
if (cuestionario == "")
{
campo1 = 1;
ViewBag.Error1 = "entro";
}
else
{
ViewBag.Value1 = cuestionario;
}
nombre = Request.Form["nombre"];
if (nombre == "")
{
campo2 = 1;
ViewBag.Error2 = "entro";
}
else
{
ViewBag.Value2 = nombre;
}
auxporcentaje = Request.Form["porcentaje"];
if (auxporcentaje == "")
{
campo3 = 1;
ViewBag.Error3 = "entro";
}
else
{
ViewBag.Value3 = auxporcentaje;
}
ViewBag.optionmenu = 1;
if (campo1 == 1 || campo2 == 1 || campo3 == 1)
{
ViewBag.Error = "Los campos con asterisco son obligatorios";
return View();
}
try
{
cuestionario existecuestionario = dbEntity.cuestionario.Single(q => q.tipocuestionario == cuestionario);
try
{
porcentaje = Convert.ToDouble(auxporcentaje);
}
catch
{
ViewBag.Error = "El campo porcentaje debe ser un numero";
return View();
}
int grupoExiste = yaEstaGrupo(nombre, (int)existecuestionario.idcuestionario);
if (grupoExiste == 1)
{
ViewBag.Error = "Ya existe un grupo de preguntas con el nombre " + nombre;
return View();
}
double porcentajes = 0;
double total_final = 0;
double aux_final = 0;
try
{
porcentajes = (double)dbEntity.grupo.Where(q => q.idcuestionario == existecuestionario.idcuestionario).Sum(q => q.porcentaje);
}
catch
{
porcentajes = 0;
}
total_final = porcentaje + porcentajes;
if (total_final > 100)
{
aux_final = 100 - porcentajes;
if (aux_final == 0)
{
ViewBag.Error = "No puedes agregar más grupos, la suma de los porcentajes es 100% ";
return View();
}
else
{
ViewBag.Error = "El máximo valor en la casilla porcentaje es: " + aux_final;
return View();
}
}
int maxorder;
try
{
maxorder = dbEntity.grupo.Where(q => q.idcuestionario == existecuestionario.idcuestionario).Max(q => q.orden);
}
catch (Exception)
{
maxorder = 0;
}
grupo miGrupo = new grupo();
ViewBag.optionmenu = 2;
miGrupo.orden = maxorder + 1;
miGrupo.idcuestionario = existecuestionario.idcuestionario;
miGrupo.nombre = nombre;
miGrupo.porcentaje = porcentaje;
dbEntity.grupo.AddObject(miGrupo);
dbEntity.SaveChanges();
ViewBag.Message = "El Grupo se creo correctamente";
return View();
}
catch
{
ViewBag.Error = "El campo tipo de cuestionario esta vacio o el cuestionario escrito no existe";
return View();
}
}
[Authorize]
public ActionResult UpdateGroup()
{
ViewBag.optionmenu = 2;
return View();
}
[Authorize]
[HttpPost]
public ActionResult EditGroup(grupo miGrupo)
{
if (ModelState.IsValid)
{
dbEntity.grupo.Attach(miGrupo);
dbEntity.ObjectStateManager.ChangeObjectState(miGrupo, EntityState.Modified);
dbEntity.SaveChanges();
return Json(miGrupo, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
public ActionResult DeleteGroup(int id)
{
grupo grupo = dbEntity.grupo.Single(c => c.idgrupo == id);
dbEntity.grupo.DeleteObject(grupo);
dbEntity.SaveChanges();
return Json(grupo, JsonRequestBehavior.AllowGet);
}
[Authorize]
public ActionResult SearchGroup(string idQuestionnarie, string term)
{
var response = dbEntity.grupo.Select(q => new { label = q.nombre, orden = q.orden, idq = q.idcuestionario, porcentaje = q.porcentaje, nombre = q.nombre, idgrupo = q.idgrupo }).Where(q => q.label.ToUpper().Contains(term.ToUpper())).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SortGroups(string stridq, intListing[] list_ids)
{
int idq = int.Parse(stridq);
int idg;
try
{
for (int i = 1; i <= list_ids.Count(); i++)
{
idg = list_ids[(i - 1)].id;
grupo miGrupo = dbEntity.grupo.Single(q => q.idgrupo == idg);
miGrupo.orden = i;
dbEntity.ObjectStateManager.ChangeObjectState(miGrupo, EntityState.Modified);
dbEntity.SaveChanges();
}
var response = dbEntity.grupo.Select(q => new { label = q.nombre, id = q.idgrupo, pos = q.orden, idc = q.idcuestionario, porc = q.porcentaje }).Where(q => q.idc == idq).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(null, JsonRequestBehavior.AllowGet);
}
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetQuestionnaireGroups(string term)
{
int idq = int.Parse(term);
var response = dbEntity.grupo.Select(q => new { label = q.nombre, id = q.idgrupo, pos = q.orden, idc = q.idcuestionario, porc = q.porcentaje }).Where(q => q.idc == idq).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
#endregion
#region Pregunta
[Authorize]
public ActionResult CreateQuestion()
{
ViewBag.optionmenu = 2;
return View();
}
[Authorize]
public ActionResult UpdateQuestion()
{
ViewBag.optionmenu = 2;
return View();
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult EditQuestion(pregunta pregunta)
{
if (ModelState.IsValid)
{
dbEntity.pregunta.Attach(pregunta);
dbEntity.ObjectStateManager.ChangeObjectState(pregunta, EntityState.Modified);
dbEntity.SaveChanges();
return Json(pregunta, JsonRequestBehavior.AllowGet);
}
return View(pregunta);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult DeleteQuestion(int id)
{
pregunta pregunta = dbEntity.pregunta.Single(c => c.idpregunta == id);
dbEntity.pregunta.DeleteObject(pregunta);
dbEntity.SaveChanges();
return Json(pregunta, JsonRequestBehavior.AllowGet);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetQuestionsFromGroup(string term)
{
int idgroup = int.Parse(term);
var response = dbEntity.pregunta.Select(q => new { label = q.pregunta1, id = q.idpregunta, idg = q.idgrupo }).Where(q => q.idg == idgroup).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult AjaxSetQuestion(pregunta miPregunta)
{
if (ModelState.IsValid)
{
dbEntity.pregunta.AddObject(miPregunta);
dbEntity.SaveChanges();
return Json(miPregunta, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
#endregion
#region Periodo Académico
[Authorize]
public ActionResult AcademicPeriods()
{
ViewBag.optionmenu = 7;
return View(dbEntity.periodo_academico.ToList());
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult CreateAcademicPeriod(periodo_academico periodo)
{
if (ModelState.IsValid)
{
dbEntity.periodo_academico.AddObject(periodo);
dbEntity.SaveChanges();
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
Session["currentAcadPeriod"] = ultimoPeriodo.idperiodo;
int currentper = (int)SessionValue("currentAcadPeriod");
return Json(periodo, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult EditAcademicPeriod(periodo_academico periodo)
{
if (ModelState.IsValid)
{
dbEntity.periodo_academico.Attach(periodo);
dbEntity.ObjectStateManager.ChangeObjectState(periodo, EntityState.Modified);
dbEntity.SaveChanges();
return Json(periodo, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult DeleteAcademicPeriod(int id)
{
if (dbEntity.labor.Count(q => q.idperiodo == id) == 0 && dbEntity.esjefe.Count(q => q.idperiodo == id) == 0)
{
periodo_academico periodo = dbEntity.periodo_academico.Single(c => c.idperiodo == id);
dbEntity.periodo_academico.DeleteObject(periodo);
dbEntity.SaveChanges();
return Json(periodo, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
#endregion
#region Jefe Departamento
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetCurrentDepartmentChief(int iddepartamento)
{
int currentper = (int)SessionValue("currentAcadPeriod");
esjefe response = null;
response = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == iddepartamento && q.idperiodo == currentper);
//Debug.WriteLine("jefe " + response.iddocente);
return Json(response, JsonRequestBehavior.AllowGet);
}
#endregion
#region Jefe Labor
//<NAME>
[Authorize]
public ActionResult ListJefeLabor()
{
ViewBag.optionmenu = 6;
facultad fac = (facultad)SessionValue("fac");
var response = (from d in dbEntity.departamento
where d.idfacultad == fac.idfacultad
select new Departamento { iddepartamento = d.iddepartamento, nombre = d.nombre }).Distinct().ToList();
foreach (var i in response)
Debug.WriteLine("dep " + i.nombre);
ViewBag.departamentos = response;
ViewBag.facultad = fac;
return View();
}
//MODIFICADO POR CLARA
[Authorize]
public ActionResult AssessLaborChief(int id)
{
ViewBag.optionmenu = 6;
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico ultimoperiodo = GetLastAcademicPeriod();
List<JefeLabor> users = (from u in dbEntity.usuario
join doc in dbEntity.docente on u.idusuario equals doc.idusuario
join d in dbEntity.dirige on u.idusuario equals d.idusuario
join l in dbEntity.labor on d.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
join ev in dbEntity.evaluacion on d.idevaluacion equals ev.idevaluacion
where l.idperiodo == ultimoperiodo.idperiodo && doc.iddepartamento == id
//select new JefeLabor { idusuario = u.idusuario, idlabor = l.idlabor, idevaluacion = ev.idevaluacion, nombres = u.nombres, apellidos = u.apellidos, rol = u.rol, evaluacionJefe = (int)ev.evaluacionjefe }).Where(p => p.evaluacionJefe == -1).OrderBy(p => p.apellidos).ToList();
select new JefeLabor { idusuario = u.idusuario, idlabor = l.idlabor, idevaluacion = ev.idevaluacion, nombres = u.nombres, apellidos = u.apellidos, rol = u.rol, evaluacionJefe = (int)ev.evaluacionjefe }).OrderBy(p => p.apellidos).ToList();
// NUEVO 1 FEBRERO
List<JefeLabor> otrosUsers = (from u in dbEntity.usuario
join d in dbEntity.dirige on u.idusuario equals d.idusuario
join dec in dbEntity.decanoCoordinador on u.idusuario equals dec.idusuario
join l in dbEntity.labor on d.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
join ev in dbEntity.evaluacion on d.idevaluacion equals ev.idevaluacion
where l.idperiodo == ultimoperiodo.idperiodo && dec.idfacultadDepto == id
//select new JefeLabor { idusuario = u.idusuario, idlabor = l.idlabor, idevaluacion = ev.idevaluacion, nombres = u.nombres, apellidos = u.apellidos, rol = u.rol, evaluacionJefe = (int)ev.evaluacionjefe }).Where(p => p.evaluacionJefe == -1).OrderBy(p => p.apellidos).ToList();
select new JefeLabor { idusuario = u.idusuario, idlabor = l.idlabor, idevaluacion = ev.idevaluacion, nombres = u.nombres, apellidos = u.apellidos, rol = u.rol, evaluacionJefe = (int)ev.evaluacionjefe }).OrderBy(p => p.apellidos).ToList();
foreach(JefeLabor unoMas in otrosUsers){
users.Add(unoMas);
}
// FIN NUEVO 1 FEBRERO
if (currentper != ultimoperiodo.idperiodo)
ViewBag.periodo = 0;
else
ViewBag.periodo = 1;
users = setLaborChief(users);
ViewBag.lista = users;
return View();
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult UpdateCurrentChief(int idDepartamento, int idDocentAct, int idDocentNue, int laboresCalc)
{
int currentper = (int)SessionValue("currentAcadPeriod");
AdminController oController = new AdminController();
return Json(oController.ProcessUpdateCurrentChief(idDepartamento, idDocentAct, idDocentNue, laboresCalc, currentper), JsonRequestBehavior.AllowGet);
}
//MODIFICADO POR CLARA
public List<JefeLabor> setLaborChief(List<JefeLabor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otra;
foreach (JefeLabor jefe in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (gestion != null)
{
jefe.tipoLabor = "Gestiónn";
jefe.descripcion = gestion.nombrecargo;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (social != null)
{
jefe.tipoLabor = "Social";
jefe.descripcion = social.nombreproyecto;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (investigacion != null)
{
jefe.tipoLabor = "Investigación";
jefe.descripcion = investigacion.nombreproyecto;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGrado != null)
{
jefe.tipoLabor = "Trabajo De Grado";
jefe.descripcion = trabajoDeGrado.titulotrabajo;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
jefe.tipoLabor = "Trabajo De Grado De Investigación";
jefe.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (desarrolloProfesoral != null)
{
jefe.tipoLabor = "Desarrollo Profesoral";
jefe.descripcion = desarrolloProfesoral.nombreactividad;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (docencia != null)
{
materia materia = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
jefe.tipoLabor = "Docencia";
jefe.descripcion = materia.nombremateria;
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == jefe.idlabor);
if (otra != null)
{
jefe.tipoLabor = "Otra";
jefe.descripcion = otra.descripcion;
continue;
}
}
return lista;
}
#endregion
#region Evaluación
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult UpdateEvaluacion(int idEvaluacion, int calificacion)
{
evaluacion eval = dbEntity.evaluacion.Single(q => q.idevaluacion == idEvaluacion);
eval.evaluacionjefe = calificacion;
dbEntity.SaveChanges();
return null;
}
#endregion
/****** INICIO ADICIONADO POR CLARA*******/
#region ADICIONADO POR CLARA
#region Asignar Administrador Facultad
[Authorize]
public ActionResult SetAdminFac()
{
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
int currentper = (int)SessionValue("currentAcadPeriod");
facultad fac = (facultad)SessionValue("fac");
if (currentper == ultimoPeriodo.idperiodo)
{
var response = (from d in dbEntity.departamento
where d.idfacultad == fac.idfacultad
select new Departamento { iddepartamento = d.iddepartamento, nombre = d.nombre }).Distinct().ToList();
ViewBag.departamentos = response;
}
else
{
ViewBag.Error = " No puede realizar esta acción en periodos anteriores";
}
ViewBag.facultad = fac;
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public docente GetCurrentAdminFac(int iddepartamento)
{
int currentper = (int)SessionValue("currentAcadPeriod");
facultad fac = (facultad)SessionValue("fac");
adminfacultad admin = dbEntity.adminfacultad.SingleOrDefault(q => q.idfacultad == fac.idfacultad);
docente response = dbEntity.docente.SingleOrDefault(q => q.idusuario == admin.idusuario);
return (response);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetTeachersFromDepartment2(string term)
{
int iddepartment = int.Parse(term);
var doc_depto = dbEntity.usuario
.Join(dbEntity.docente,
usu => usu.idusuario,
doc => doc.idusuario,
(usu, doc) => new { usuario = usu, docente = doc })
.Where(usu_doc => usu_doc.docente.iddepartamento == iddepartment && usu_doc.docente.estado == "activo");
docente admin = GetCurrentAdminFac(iddepartment);
var response = doc_depto.Select(q => new doc_usu { iddepartamento = q.docente.iddepartamento, idusuario = q.usuario.idusuario, iddocente = q.docente.iddocente, nombre = q.usuario.nombres + " " + q.usuario.apellidos, chiefId = -1 }).OrderBy(q => q.nombre).ToList();
foreach (var i in response)
{
if (i.idusuario == admin.idusuario)
i.chiefId = admin.idusuario;
}
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult UpdateAdminFac(int idDepartamento, int idDocentAct, int idDocentNue)
{
int currentper = (int)SessionValue("currentAcadPeriod");
departamento dep = dbEntity.departamento.Single(q => q.iddepartamento == idDepartamento);
if (idDocentAct != -1)
{
adminfacultad eliminar = dbEntity.adminfacultad.Single(q => q.idfacultad == dep.idfacultad);
dbEntity.adminfacultad.DeleteObject(eliminar);
dbEntity.SaveChanges();
}
adminfacultad nuevo = new adminfacultad();
nuevo.idfacultad = dep.idfacultad;
nuevo.idusuario = idDocentNue;
dbEntity.adminfacultad.AddObject(nuevo);
dbEntity.SaveChanges();
return Json(nuevo, JsonRequestBehavior.AllowGet);
}
public class doc_usu
{
public int iddocente;
public int idusuario;
public string nombre;
public int iddepartamento;
public int chiefId;
}
#endregion
#region Facultad
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchFacultad()
{
var response = dbEntity.facultad.Select(q => new { label = q.fac_nombre, id = q.idfacultad }).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
public ActionResult ObtenerFacultadPrograma()
{
List<FacultadPrograma> Facultades = new List<FacultadPrograma>();
foreach (var fac in dbEntity.facultad)
Facultades.Add(
new FacultadPrograma()
{
codfacultad = fac.idfacultad,
nomfacultad = fac.fac_nombre.ToString()
});
ViewBag.Facultades = Facultades;
return View(ViewBag.Facultades);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchFacultad(string term)
{
var response = dbEntity.facultad.Select(q => new { label = q.fac_nombre, id = q.idfacultad }).Where(q => q.label.ToUpper().Contains(term.ToUpper())).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetFacultad(string term)
{
int idp = int.Parse(term);
var dp = dbEntity.departamento.SingleOrDefault(q => q.iddepartamento == idp);
var response = dbEntity.facultad.SingleOrDefault(q => q.idfacultad == dp.idfacultad);
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult AjaxSetFacultad(facultad miFacultad)
{
if (ModelState.IsValid)
{
dbEntity.facultad.AddObject(miFacultad);
dbEntity.SaveChanges();
return Json(miFacultad, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
#endregion
#region Departamento
[Authorize]
public ActionResult ListProgramas()
{
ViewBag.facultades = dbEntity.facultad.ToList();
return View();
}
[Authorize]
public ActionResult SearchPrograma(string idFacultad, string term)
{
var response = dbEntity.departamento.Select(q => new { label = q.nombre, idf = q.idfacultad, nombre = q.nombre, idp = q.iddepartamento }).Where(q => q.label.ToUpper().Contains(term.ToUpper())).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SearchDepartment(string term)
{
var response = dbEntity.departamento.Select(q => new { label = q.nombre, id = q.iddepartamento }).Where(q => q.label.ToUpper().Contains(term.ToUpper())).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult SortProgramas(string stridf, intListing[] list_ids)
{
int idf = int.Parse(stridf);
int idp;
try
{
for (int i = 1; i <= list_ids.Count(); i++)
{
idp = list_ids[(i - 1)].id;
departamento miPrograma = dbEntity.departamento.Single(q => q.iddepartamento == idp);
dbEntity.ObjectStateManager.ChangeObjectState(miPrograma, EntityState.Modified);
dbEntity.SaveChanges();
}
var response = dbEntity.departamento.Select(q => new { label = q.nombre, id = q.iddepartamento, idfa = q.idfacultad }).Where(q => q.idfa == idf).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(null, JsonRequestBehavior.AllowGet);
}
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetFacultadPrograma(string term)
{
int idf = int.Parse(term);
var response = dbEntity.departamento.Select(q => new { label = q.nombre, id = q.iddepartamento, idfa = q.idfacultad }).Where(q => q.idfa == idf).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
#endregion
#region Docente
//MODIFICADO POR CLARA
[Authorize]
public ActionResult ListDocente()
{
ViewBag.optionmenu = 1;
facultad fac = (facultad)SessionValue("fac");
var response = (from d in dbEntity.departamento
where d.idfacultad == fac.idfacultad
select new Departamento { iddepartamento = d.iddepartamento, nombre = d.nombre }).Distinct().ToList();
foreach (var i in response)
Debug.WriteLine("dep "+i.nombre);
ViewBag.departamentos = response;
ViewBag.facultad = fac;
return View();
}
[Authorize]
public ActionResult VerDocentes(int id)
{
ViewBag.optionmenu = 1;
if (ModelState.IsValid)
{
var dep = dbEntity.departamento.SingleOrDefault(q => q.iddepartamento == id);
var response = GetTeachersFromDepartment(id);
ViewBag.datos = response;
ViewBag.departamento = dep.nombre;
return View();
}
return View();
}
[Authorize]
public ActionResult VerMDocentes(int id)
{
ViewBag.optionmenu = 1;
if (ModelState.IsValid)
{
var dep = dbEntity.departamento.SingleOrDefault(q => q.iddepartamento == id);
var response = GetTeachersFromDepartment(id);
ViewBag.datos = response;
ViewBag.departamento = dep.nombre;
return View();
}
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetTeachersFromDepartment1(string term)
{
int iddepartment = int.Parse(term);
var doc_depto = dbEntity.usuario
.Join(dbEntity.docente,
usu => usu.idusuario,
doc => doc.idusuario,
(usu, doc) => new { usuario = usu, docente = doc })
.Where(usu_doc => usu_doc.docente.iddepartamento == iddepartment && usu_doc.docente.estado == "activo");
var response = doc_depto.Select(q => new { label = q.docente.iddepartamento, id = q.docente.iddocente, nombres = q.usuario.nombres, apellidos = q.usuario.apellidos, estado = q.docente.estado }).OrderBy(q => q.apellidos).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public List<DocenteDepto> GetTeachersFromDepartment(int iddepartment)
{
var doc_depto = dbEntity.usuario
.Join(dbEntity.docente,
usu => usu.idusuario,
doc => doc.idusuario,
(usu, doc) => new { usuario = usu, docente = doc })
.Where(usu_doc => usu_doc.docente.iddepartamento == iddepartment && usu_doc.docente.estado == "activo");
var response = doc_depto.Select(q => new DocenteDepto { idususaio = q.usuario.idusuario, iddetp = q.docente.iddepartamento, iddocente = q.docente.iddocente, nombre = q.usuario.nombres, apellido = q.usuario.apellidos, estado = q.docente.estado }).OrderBy(q => q.apellido).ToList();
return (response);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetDepartamentoProfesores(string term)
{
int idd = int.Parse(term);
var response = dbEntity.usuario.Select(q => new { label = q.nombres, id = q.idusuario}).OrderBy(q => q.label).ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
#endregion
#region Materias
public ActionResult ListSemestre(int id)
{
ViewBag.optionmenu = 1;
if (ModelState.IsValid)
{
var dep = dbEntity.departamento.SingleOrDefault(q => q.iddepartamento == id);
ViewBag.iddepa = dep.iddepartamento;
ViewBag.nombredepa = dep.nombre;
return View();
}
return View();
}
//MODIFICADO POR CLARA
[Authorize]
public ActionResult ListMateria()
{
ViewBag.optionmenu = 1;
facultad fac = (facultad)SessionValue("fac");
var response = (from d in dbEntity.departamento
where d.idfacultad == fac.idfacultad
select new Departamento { iddepartamento = d.iddepartamento, nombre = d.nombre }).Distinct().ToList();
foreach (var i in response)
Debug.WriteLine("dep " + i.nombre);
ViewBag.departamentos = response;
ViewBag.facultad = fac;
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowMaterias(int idusuario)
{
ViewBag.optionmenu = 1;
ViewBag.reporte = crearReporteMateria(idusuario);
return View();
}
public ConsolidadoDocencia crearReporteMateria(int idUsuario)
{
var docjefe = new docente();
var usujefe = new usuario();
ConsolidadoDocencia reporte;
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
var docente = dbEntity.docente.SingleOrDefault(q => q.idusuario == idUsuario);
var jefe = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == docente.iddepartamento && q.idperiodo == currentper);
if (jefe != null)
docjefe = dbEntity.docente.SingleOrDefault(q => q.iddocente == jefe.iddocente);
if (docjefe != null)
usujefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == docjefe.idusuario);
if (usujefe != null)
reporte = new ConsolidadoDocencia() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = usujefe.nombres + " " + usujefe.apellidos, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
else
reporte = new ConsolidadoDocencia() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = " ", fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
List<DetalleDocencia> labores = (from p in dbEntity.participa
join l in dbEntity.labor on p.idlabor equals l.idlabor
join ld in dbEntity.docencia on l.idlabor equals ld.idlabor
join m in dbEntity.materia on ld.idmateria equals m.idmateria
//join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join ae in dbEntity.autoevaluacion on p.idautoevaluacion equals ae.idautoevaluacion
//join pg in dbEntity.programa on m.idprograma equals pg.idprograma
join pr in dbEntity.problema on ae.idautoevaluacion equals pr.idautoevaluacion
join s in dbEntity.resultado on ae.idautoevaluacion equals s.idautoevaluacion
where l.idperiodo == currentper && p.iddocente == docente.iddocente
select new DetalleDocencia {idLabDoc = l.idlabor, idmateria = m.idmateria, nombremateria = m.nombremateria,//grupo = m.grupo,tipo = m.tipo,idprograma= pg.idprograma, nombreprograma= pg.nombreprograma,
//horassemana = (int)ld.horassemana, semanaslaborales = (int)ld.semanaslaborales, creditos = (int)m.creditos, semestre = (int)m.semestre,
//evaluacionjefe = (int)e.evaluacionjefe, evaluacionestudiante = (int)e.evaluacionestudiante,
evaluacionautoevaluacion= (int)ae.calificacion,
problemadescripcion = pr.descripcion, problemasolucion = pr.solucion, resultadodescripcion= s.descripcion, resultadosolucion = s.ubicacion
}).ToList();
reporte.labDocencia = labores;
//reporte.nombredocente = user.nombres + " " + user.apellidos;
//reporte.nombrejefe = usujefe.nombres + " " + usujefe.apellidos;
//reporte.periodoanio = (int)PeriodoSeleccionado.anio;
//reporte.periodonum = (int)PeriodoSeleccionado.numeroperiodo;
//reporte.fechaevaluacion = fecha_actual;
//reporte.totalhorassemana = (Double)labores.Sum(q => q.horasxsemana);
Debug.WriteLine("# labores" + labores.Count);
foreach (var l in labores)
{
Debug.WriteLine("lab "+l.idLabDoc + "mat " + l.idmateria );
}
//Debug.WriteLine("user 1 " + reporte.nombredocente);
//Debug.WriteLine("periodo 1 " + reporte.periodoanio);
return reporte;
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetMateriasPrograma(string term, string depa)
{
int sem = int.Parse(term);
int dep = int.Parse(depa);
int currentper = (int)SessionValue("currentAcadPeriod");
var response = (from l in dbEntity.labor
join d in dbEntity.docencia on l.idlabor equals d.idlabor
join m in dbEntity.materia on d.idmateria equals m.idmateria
where m.semestre == sem && m.idprograma == dep && l.idperiodo == currentper
select new Asignatura { id = m.idmateria, nombre = m.nombremateria }).Distinct().ToList();
return Json(response, JsonRequestBehavior.AllowGet);
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowAutoScoresMateria(string depa, string tipo)
{
ViewBag.optionmenu = 1;
int idD = int.Parse(depa);
int id = int.Parse(tipo);
ViewBag.reporte = reporteEvaluacionesMateria(idD, id);
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowScoresMateria(string depa, string tipo)
{
ViewBag.optionmenu = 1;
int idD = int.Parse(depa);
int id = int.Parse(tipo);
Debug.WriteLine("idl 1 " + id);
Debug.WriteLine("idl 2 " + idD);
ViewBag.reporte = reporteEvaluacionesMateria(idD, id);
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public List<ConsolidadoDocencia> reporteEvaluacionesMateria(int idD, int idM)
{
ViewBag.optionmenu = 1;
int currentper = (int)SessionValue("currentAcadPeriod");
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
List<ConsolidadoDocencia> MateriaEvaluada = new List<ConsolidadoDocencia>();
List<int> labores = (from l in dbEntity.labor
join d in dbEntity.docencia on l.idlabor equals d.idlabor
where d.idmateria == idM && l.idperiodo == currentper
select d.idlabor).Distinct().ToList();
foreach (var lab in labores)
{
List<usuDoc> docentes = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
where p.idlabor == lab && d.iddepartamento == idD
select new usuDoc { id = p.iddocente, nombre = u.nombres + " " + u.apellidos, idlab = p.idlabor }).Distinct().ToList();
materia mat = dbEntity.materia.SingleOrDefault(q => q.idmateria == idM);
docencia labdoc = dbEntity.docencia.SingleOrDefault(q => q.idlabor == lab);
foreach (var doc in docentes)
{
ConsolidadoDocencia datos = new ConsolidadoDocencia() { nombredocente = doc.nombre, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
datos.labDocencia = new List<DetalleDocencia>();
List<DetalleDocencia> lista = (from p in dbEntity.participa
join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join aev in dbEntity.autoevaluacion on p.idautoevaluacion equals aev.idautoevaluacion
join pr in dbEntity.problema on aev.idautoevaluacion equals pr.idautoevaluacion
join re in dbEntity.resultado on aev.idautoevaluacion equals re.idautoevaluacion
where p.idlabor == doc.idlab && p.iddocente == doc.id
select new DetalleDocencia
{
nombremateria = mat.nombremateria,
grupo = mat.grupo,
codmateria = mat.codigomateria,
creditos = (int)mat.creditos,
horassemana = (int)labdoc.horassemana,
semanaslaborales = (int)labdoc.semanaslaborales,
idLabDoc = lab,
evaluacionautoevaluacion = (int)e.evaluacionautoevaluacion,
evaluacionestudiante = (int)e.evaluacionestudiante,
evaluacionjefe = (int)e.evaluacionjefe,
problemadescripcion = pr.descripcion,
problemasolucion = pr.solucion,
resultadodescripcion = re.descripcion,
resultadosolucion = re.ubicacion
}).Distinct().ToList();
datos.labDocencia.AddRange(lista);
MateriaEvaluada.Add(datos);
}
}
return MateriaEvaluada;
}
#endregion
#region Autoevaluacion
[Authorize]
public ActionResult Autoevaluacion()
{
ViewBag.optionmenu = 1;
ViewBag.facultades = dbEntity.facultad.ToList();
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowAutoDocentes(int idusuario)
{
ViewBag.optionmenu = 1;
var response = crearReporteAutoevaluacion(idusuario);
ViewBag.reporte = response;
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowAutoScores(string depa, string tipo)
{
ViewBag.optionmenu = 1;
departamento dep = dbEntity.departamento.SingleOrDefault(q => q.nombre == depa);
var response = GetAutoFromDepartment(dep.iddepartamento);
ViewBag.reporte = response;
ViewBag.tipo = tipo;
ViewBag.dep = dep.nombre;
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public List<AutoevaluacionDocente> GetAutoFromDepartment(int iddepartment)
{
int currentper = (int)SessionValue("currentAcadPeriod");
var docjefe = new docente();
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
var jefe = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == iddepartment && q.idperiodo == currentper);
if (jefe != null)
docjefe = dbEntity.docente.SingleOrDefault(q => q.iddocente == jefe.iddocente);
List<AutoevaluacionDocente> ReporteAutoLabores = new List<AutoevaluacionDocente>();
var docentes = GetTeachersFromDepartment(iddepartment);
foreach (var doc in docentes)
{
ReporteAutoLabores.Add(crearReporteAutoevaluacion(doc.idususaio));
}
return (ReporteAutoLabores);
}
public ConsolidadoLabores crearReporte(int idUsuario)
{
var docjefe = new docente();
var usujefe = new usuario();
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
var docente = dbEntity.docente.SingleOrDefault(q => q.idusuario == idUsuario);
var jefe = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == docente.iddepartamento && q.idperiodo == currentper);
if (jefe != null)
docjefe = dbEntity.docente.SingleOrDefault(q => q.iddocente == jefe.iddocente);
if (docjefe != null)
usujefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == docjefe.idusuario);
ConsolidadoLabores reporte = new ConsolidadoLabores();
List<int> labores = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == currentper && u.idusuario == idUsuario
select l.idlabor).ToList();
reporte = setLabor(labores);
if (user != null)
reporte.nombredocente = user.nombres + " " + user.apellidos;
if (usujefe != null)
reporte.nombrejefe = usujefe.nombres + " " + usujefe.apellidos;
reporte.periodoanio = (int)PeriodoSeleccionado.anio;
reporte.periodonum = (int)PeriodoSeleccionado.numeroperiodo;
reporte.fechaevaluacion = fecha_actual;
//reporte.totalhorassemana = (Double)labores.Sum(q => q.horasxsemana);
ReporteLabores = reporte;
return ReporteLabores;
}
#endregion
#region Labores
[Authorize]
public ActionResult VerLabores(int id)
{
ViewBag.optionmenu = 1;
if (ModelState.IsValid)
{
var dep = dbEntity.departamento.SingleOrDefault(q => q.iddepartamento == id);
var response = GetWorksFromDepartment(id);
List<string> lab = new List<string>();
foreach (var l in response)
{
foreach (var a in l.detalleslabores)
{
if (!lab.Contains(a))
lab.Add(a);
}
}
ViewBag.labores = lab;
ViewBag.datos = response;
ViewBag.departamento = dep.nombre;
return View();
}
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowDetallesLabores(string depa, string tipo)
{
ViewBag.optionmenu = 1;
departamento dep = dbEntity.departamento.SingleOrDefault(q => q.nombre == depa);
var response = GetWorksFromDepartment(dep.iddepartamento);
ViewBag.reporte = response;
ViewBag.tipo = tipo;
ViewBag.dep = dep.nombre;
return View();
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public List<ConsolidadoLabores> GetWorksFromDepartment(int iddepartment)
{
int currentper = (int)SessionValue("currentAcadPeriod");
var docjefe = new docente();
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
var jefe = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == iddepartment && q.idperiodo == currentper);
var docentes = GetTeachersFromDepartment(iddepartment);
if (jefe != null)
docjefe = dbEntity.docente.SingleOrDefault(q => q.iddocente == jefe.iddocente);
foreach (var doc in docentes)
{
ReporteLabores1.Add(crearReporte(doc.idususaio));
}
return (ReporteLabores1);
}
public AutoevaluacionDocente crearReporteAutoevaluacion(int idUsuario)
{
departamento departamento = (departamento)SessionValue("depto");
var docjefe = new docente();
var usujefe = new usuario();
AutoevaluacionDocente AutoevaluacionDocenteReporte;
int currentper = (int)SessionValue("currentAcadPeriod");
periodo_academico PeriodoSeleccionado = dbEntity.periodo_academico.Single(q => q.idperiodo == currentper);
usuario user = dbEntity.usuario.SingleOrDefault(q => q.idusuario == idUsuario);
DateTime Hoy = DateTime.Today;
string fecha_actual = Hoy.ToString("MMMM dd") + " de " + Hoy.ToString("yyyy");
fecha_actual = fecha_actual.ToUpper();
var docente = dbEntity.docente.SingleOrDefault(q => q.idusuario == idUsuario);
var jefe = dbEntity.esjefe.SingleOrDefault(q => q.iddepartamento == docente.iddepartamento && q.idperiodo == currentper);
if (jefe != null)
docjefe = dbEntity.docente.SingleOrDefault(q => q.iddocente == jefe.iddocente);
if (docjefe != null)
usujefe = dbEntity.usuario.SingleOrDefault(q => q.idusuario == docjefe.idusuario);
if (usujefe != null)
{
AutoevaluacionDocenteReporte = new AutoevaluacionDocente() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = usujefe.nombres + " " + usujefe.apellidos, fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
}
else
{
AutoevaluacionDocenteReporte = new AutoevaluacionDocente() { nombredocente = user.nombres + " " + user.apellidos, nombrejefe = " ", fechaevaluacion = fecha_actual, periodoanio = (int)PeriodoSeleccionado.anio, periodonum = (int)PeriodoSeleccionado.numeroperiodo };
}
List<ResAutoEvaluacionLabor> labores = (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join aev in dbEntity.autoevaluacion on p.idautoevaluacion equals aev.idautoevaluacion
join pr in dbEntity.problema on aev.idautoevaluacion equals pr.idautoevaluacion
join re in dbEntity.resultado on aev.idautoevaluacion equals re.idautoevaluacion
join l in dbEntity.labor on p.idlabor equals l.idlabor
join pa in dbEntity.periodo_academico on l.idperiodo equals pa.idperiodo
where l.idperiodo == PeriodoSeleccionado.idperiodo && u.idusuario == idUsuario
select new ResAutoEvaluacionLabor { idlabor = l.idlabor, nota = (int)aev.calificacion, problemadescripcion = pr.descripcion, problemasolucion = pr.solucion, resultadodescripcion = re.descripcion, resultadosolucion = re.ubicacion }).ToList();
labores = setAELabor(labores);
AutoevaluacionDocenteReporte.autoevaluacioneslabores = labores;
return AutoevaluacionDocenteReporte;
}
public List<ResAutoEvaluacionLabor> setAELabor(List<ResAutoEvaluacionLabor> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otra;
foreach (ResAutoEvaluacionLabor labor in lista)
{
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (gestion != null)
{
labor.tipolabor = "Gestion";
labor.tipolaborcorto = "GES";
labor.descripcion = gestion.nombrecargo;
//labor.horasxsemana = (int)gestion.horassemana;
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (social != null)
{
labor.tipolabor = "Social";
labor.tipolaborcorto = "SOC";
labor.descripcion = social.nombreproyecto;
//labor.horasxsemana = (int)social.horassemana;
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (investigacion != null)
{
labor.tipolabor = "Investigación";
labor.tipolaborcorto = "INV";
labor.descripcion = investigacion.nombreproyecto;
//labor.horasxsemana = (int)investigacion.horassemana;
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGrado != null)
{
labor.tipolabor = "Trabajo de Grado";
labor.tipolaborcorto = "TDG";
labor.descripcion = trabajoDeGrado.titulotrabajo;
// labor.horasxsemana = (int)trabajoDeGrado.horassemana;
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (trabajoDeGradoInvestigacion != null)
{
labor.tipolabor = "Trabajo de Grado Investigación";
labor.tipolaborcorto = "TDGI";
labor.descripcion = trabajoDeGradoInvestigacion.titulotrabajo;
// labor.horasxsemana = (int)trabajoDeGradoInvestigacion.horassemana;
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (desarrolloProfesoral != null)
{
labor.tipolabor = "Desarrollo Profesoral";
labor.tipolaborcorto = "DP";
labor.descripcion = desarrolloProfesoral.nombreactividad;
//labor.horasxsemana = (int)desarrolloProfesoral.horassemana;
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (docencia != null)
{
materia materia = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
labor.tipolabor = "Docencia Directa";
labor.tipolaborcorto = "DD";
labor.descripcion = materia.nombremateria;
//labor.horasxsemana = (int)docencia.horassemana;
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == labor.idlabor);
if (otra != null)
{
labor.tipolabor = "Otra";
labor.tipolaborcorto = "OTR";
labor.descripcion = otra.descripcion;
//labor.horasxsemana = (int)docencia.horassemana;
continue;
}
}
return lista;
}
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ShowLabores(int idusuario)
{
ViewBag.optionmenu = 1;
ViewBag.reporte = crearReporte(idusuario);
return View();
}
public ConsolidadoLabores setLabor(List<int> lista)
{
gestion gestion;
social social;
investigacion investigacion;
trabajodegrado trabajoDeGrado;
trabajodegradoinvestigacion trabajoDeGradoInvestigacion;
desarrolloprofesoral desarrolloProfesoral;
docencia docencia;
otras otra;
ConsolidadoLabores labores= new ConsolidadoLabores();
labores.detalleslabores = new List<String>();
labores.labSocial = new List<social>();
labores.labGestion = new List<gestion>();
labores.labDocencia = new List<DocenciaMateria>();
labores.labInvestigacion = new List<investigacion>();
labores.labTrabajoDeGrado = new List<trabajodegrado>();
labores.labTrabajoDegradoInvestigacion = new List<trabajodegradoinvestigacion>();
labores.labDesarrolloProfesoral = new List<desarrolloprofesoral>();
labores.labOtras = new List<otras>();
for (var i = 0; i < lista.Count;i++ )
{
int id = lista[i];
gestion = dbEntity.gestion.SingleOrDefault(g => g.idlabor == id);
if (gestion != null)
{
labores.labGestion.Add(gestion);
if (!labores.detalleslabores.Contains("Gestion"))
labores.detalleslabores.Add("Gestion");
continue;
}
social = dbEntity.social.SingleOrDefault(g => g.idlabor == id);
if (social != null)
{
labores.labSocial.Add(social);
if (!labores.detalleslabores.Contains("Social"))
labores.detalleslabores.Add("Social");
continue;
}
investigacion = dbEntity.investigacion.SingleOrDefault(g => g.idlabor == id);
if (investigacion != null)
{
labores.labInvestigacion.Add(investigacion);
if (!labores.detalleslabores.Contains("Investigación"))
labores.detalleslabores.Add("Investigación");
continue;
}
trabajoDeGrado = dbEntity.trabajodegrado.SingleOrDefault(g => g.idlabor == id);
if (trabajoDeGrado != null)
{
labores.labTrabajoDeGrado.Add(trabajoDeGrado);
if (!labores.detalleslabores.Contains("Trabajo de Grado"))
labores.detalleslabores.Add("Trabajo de Grado");
continue;
}
trabajoDeGradoInvestigacion = dbEntity.trabajodegradoinvestigacion.SingleOrDefault(g => g.idlabor == id);
if (trabajoDeGradoInvestigacion != null)
{
labores.labTrabajoDegradoInvestigacion.Add(trabajoDeGradoInvestigacion);
if (!labores.detalleslabores.Contains("Trabajo de Grado Investigación"))
labores.detalleslabores.Add("Trabajo de Grado Investigación");
continue;
}
desarrolloProfesoral = dbEntity.desarrolloprofesoral.SingleOrDefault(g => g.idlabor == id);
if (desarrolloProfesoral != null)
{
labores.labDesarrolloProfesoral.Add(desarrolloProfesoral);
if (!labores.detalleslabores.Contains("Desarrollo Profesoral"))
labores.detalleslabores.Add("Desarrollo Profesoral");
continue;
}
docencia = dbEntity.docencia.SingleOrDefault(g => g.idlabor == id);
if (docencia != null)
{
DocenciaMateria aux = new DocenciaMateria();
aux.DocMateria = dbEntity.materia.SingleOrDefault(g => g.idmateria == docencia.idmateria);
aux.MatPrograma = dbEntity.programa.SingleOrDefault(p=> p.idprograma == aux.DocMateria.idprograma);
aux.labDoc = docencia;
labores.labDocencia.Add(aux);
if (!labores.detalleslabores.Contains("Docencia Directa"))
labores.detalleslabores.Add("Docencia Directa");
continue;
}
otra = dbEntity.otras.SingleOrDefault(g => g.idlabor == id);
if (otra != null)
{
labores.labOtras.Add(otra);
if (!labores.detalleslabores.Contains("Otra"))
labores.detalleslabores.Add("Otra");
continue;
}
}
return labores;
}
public ActionResult ExportToExcelLabores()
{
SpreadsheetModelLabores mySpreadsheetAE = new SpreadsheetModelLabores();
String[] datos = new String[32];
datos[0] = "Docente";
datos[1] = "ID Labor";
datos[2] = "Tipo Corto";
datos[3] = "Tipo";
datos[4] = "Labor";
datos[5] = "Nota";
datos[6] = "Descripción Problema";
datos[7] = "Solución Problema";
datos[8] = "Descripción Solucion";
datos[9] = "Ubicación Solucion";
//Gestion
datos[10] = "Nombre Cargo";
datos[11] = "Horas Semana";
datos[12] = "Semanas Laborales";
datos[13] = "Unidad";
//Social
datos[14] = "Resolución";
datos[15] = "Nombre Proyecto";
datos[16] = "Fecha Inicio";
datos[17] = "Fehca Fin";
//Desarrollo Profesoral
datos[18] = "Nombre Actividad";
//Docencia
datos[19] = "Grupo";
datos[20] = "ID Materia";
//Materia
datos[21] = "Código Materia";
datos[22] = "Nombre Materia";
datos[23] = "Créditos";
datos[24] = "Semestre";
datos[25] = "Intensidad Horaria";
datos[26] = "Tipo";
datos[27] = "Programa";
//Investigación
datos[28] = "Código VRI";
//Trabajo Grado
datos[29] = "Título De Trabajo";
datos[30] = "Código Estudiante";
//Otra
datos[31] = "Descripcion";
mySpreadsheetAE.fechaevaluacion = ReporteLabores.fechaevaluacion;
mySpreadsheetAE.periodo = "" + ReporteLabores.periodonum + " - " + ReporteLabores.periodoanio;
mySpreadsheetAE.nombrejefe = ReporteLabores.nombrejefe;
mySpreadsheetAE.datos = datos;
mySpreadsheetAE.detalleslabores = new List<string>();
mySpreadsheetAE.detalleslabores.AddRange(ReporteLabores.detalleslabores);
mySpreadsheetAE.labSocial = new List<social>();
mySpreadsheetAE.labDesarrolloProfesoral = new List<desarrolloprofesoral>();
mySpreadsheetAE.labGestion = new List<gestion>();
mySpreadsheetAE.labDocencia = new List<DocenciaMateria>();
mySpreadsheetAE.labInvestigacion = new List<investigacion>();
mySpreadsheetAE.labTrabajoDeGrado = new List<trabajodegrado>();
mySpreadsheetAE.labTrabajoDegradoInvestigacion = new List<trabajodegradoinvestigacion>();
mySpreadsheetAE.labOtras = new List<otras>();
foreach (string tipo in ReporteLabores.detalleslabores)
{
switch (tipo)
{
case "Gestion":
for (int j = 0; j < ReporteLabores.labGestion.Count(); j++)
{
gestion aux = new gestion();
aux.idlabor = ReporteLabores.labGestion.ElementAt(j).idlabor;
aux.nombrecargo = ReporteLabores.labGestion.ElementAt(j).nombrecargo;
aux.horassemana = ReporteLabores.labGestion.ElementAt(j).horassemana;
aux.unidad = ReporteLabores.labGestion.ElementAt(j).unidad;
mySpreadsheetAE.labGestion.Add(aux);
}
break;
case "Social":
for (int j = 0; j < ReporteLabores.labSocial.Count(); j++)
{
social aux = new social();
aux.idlabor = ReporteLabores.labSocial.ElementAt(j).idlabor;
aux.nombreproyecto = ReporteLabores.labSocial.ElementAt(j).nombreproyecto;
aux.resolucion = ReporteLabores.labSocial.ElementAt(j).resolucion;
aux.horassemana = ReporteLabores.labSocial.ElementAt(j).horassemana;
aux.unidad = ReporteLabores.labSocial.ElementAt(j).unidad;
aux.semanaslaborales = ReporteLabores.labSocial.ElementAt(j).semanaslaborales;
aux.fechafin = ReporteLabores.labSocial.ElementAt(j).fechafin;
aux.fechainicio = ReporteLabores.labSocial.ElementAt(j).fechainicio;
mySpreadsheetAE.labSocial.Add(aux);
}
break;
case "Desarrollo Profesoral":
for (int j = 0; j < ReporteLabores.labDesarrolloProfesoral.Count(); j++)
{
desarrolloprofesoral aux = new desarrolloprofesoral();
aux.idlabor = ReporteLabores.labDesarrolloProfesoral.ElementAt(j).idlabor;
aux.nombreactividad = ReporteLabores.labDesarrolloProfesoral.ElementAt(j).nombreactividad;
aux.resolucion = ReporteLabores.labDesarrolloProfesoral.ElementAt(j).resolucion;
aux.horassemana = ReporteLabores.labDesarrolloProfesoral.ElementAt(j).horassemana;
aux.semanaslaborales = ReporteLabores.labDesarrolloProfesoral.ElementAt(j).semanaslaborales;
mySpreadsheetAE.labDesarrolloProfesoral.Add(aux);
}
break;
case "Docencia Directa":
for (int j = 0; j < ReporteLabores.labDocencia.Count(); j++)
{
DocenciaMateria aux = new DocenciaMateria();
aux.DocMateria = new materia();
aux.labDoc = new docencia();
aux.MatPrograma = new programa();
aux.labDoc.idlabor = ReporteLabores.labDocencia.ElementAt(j).labDoc.idlabor;
aux.labDoc.idmateria = ReporteLabores.labDocencia.ElementAt(j).labDoc.idmateria;
aux.labDoc.grupo = ReporteLabores.labDocencia.ElementAt(j).labDoc.grupo;
aux.labDoc.horassemana = ReporteLabores.labDocencia.ElementAt(j).labDoc.horassemana;
aux.labDoc.semanaslaborales = ReporteLabores.labDocencia.ElementAt(j).labDoc.semanaslaborales;
aux.MatPrograma.idprograma = ReporteLabores.labDocencia.ElementAt(j).MatPrograma.idprograma;
aux.MatPrograma.nombreprograma = ReporteLabores.labDocencia.ElementAt(j).MatPrograma.nombreprograma;
aux.DocMateria.idmateria = ReporteLabores.labDocencia.ElementAt(j).DocMateria.idmateria;
aux.DocMateria.nombremateria = ReporteLabores.labDocencia.ElementAt(j).DocMateria.nombremateria;
aux.DocMateria.codigomateria = ReporteLabores.labDocencia.ElementAt(j).DocMateria.codigomateria;
aux.DocMateria.creditos = ReporteLabores.labDocencia.ElementAt(j).DocMateria.creditos;
aux.DocMateria.grupo = ReporteLabores.labDocencia.ElementAt(j).DocMateria.grupo;
aux.DocMateria.intensidadhoraria = ReporteLabores.labDocencia.ElementAt(j).DocMateria.intensidadhoraria;
aux.DocMateria.semestre = ReporteLabores.labDocencia.ElementAt(j).DocMateria.semestre;
aux.DocMateria.tipo = ReporteLabores.labDocencia.ElementAt(j).DocMateria.tipo;
mySpreadsheetAE.labDocencia.Add(aux);
}
break;
case "Investigacion":
for (int j = 0; j < ReporteLabores.labInvestigacion.Count(); j++)
{
investigacion aux = new investigacion();
aux.idlabor = ReporteLabores.labInvestigacion.ElementAt(j).idlabor;
aux.nombreproyecto = ReporteLabores.labInvestigacion.ElementAt(j).nombreproyecto;
aux.codigovri = ReporteLabores.labInvestigacion.ElementAt(j).codigovri;
aux.horassemana = ReporteLabores.labInvestigacion.ElementAt(j).horassemana;
aux.semanaslaborales = ReporteLabores.labInvestigacion.ElementAt(j).semanaslaborales;
aux.fechafin = ReporteLabores.labInvestigacion.ElementAt(j).fechafin;
aux.fechainicio = ReporteLabores.labInvestigacion.ElementAt(j).fechainicio;
mySpreadsheetAE.labInvestigacion.Add(aux);
}
break;
case "Trabajo de Grado":
for (int j = 0; j < ReporteLabores.labTrabajoDeGrado.Count(); j++)
{
trabajodegrado aux = new trabajodegrado();
aux.idlabor = ReporteLabores.labTrabajoDeGrado.ElementAt(j).idlabor;
aux.titulotrabajo = ReporteLabores.labTrabajoDeGrado.ElementAt(j).titulotrabajo;
aux.resolucion = ReporteLabores.labTrabajoDeGrado.ElementAt(j).resolucion;
aux.horassemana = ReporteLabores.labTrabajoDeGrado.ElementAt(j).horassemana;
aux.semanaslaborales = ReporteLabores.labTrabajoDeGrado.ElementAt(j).semanaslaborales;
aux.fechafin = ReporteLabores.labTrabajoDeGrado.ElementAt(j).fechafin;
aux.fechainicio = ReporteLabores.labTrabajoDeGrado.ElementAt(j).fechainicio;
aux.codigoest = ReporteLabores.labTrabajoDeGrado.ElementAt(j).codigoest;
mySpreadsheetAE.labTrabajoDeGrado.Add(aux);
}
break;
case "Trabajo de Grado Investigación":
for (int j = 0; j < ReporteLabores.labTrabajoDegradoInvestigacion.Count(); j++)
{
trabajodegradoinvestigacion aux = new trabajodegradoinvestigacion();
aux.idlabor = ReporteLabores.labTrabajoDegradoInvestigacion.ElementAt(j).idlabor;
aux.titulotrabajo = ReporteLabores.labTrabajoDegradoInvestigacion.ElementAt(j).titulotrabajo;
aux.horassemana = ReporteLabores.labTrabajoDegradoInvestigacion.ElementAt(j).horassemana;
aux.semanaslaborales = ReporteLabores.labTrabajoDegradoInvestigacion.ElementAt(j).semanaslaborales;
aux.codigoest = ReporteLabores.labTrabajoDegradoInvestigacion.ElementAt(j).codigoest;
mySpreadsheetAE.labTrabajoDegradoInvestigacion.Add(aux);
}
break;
case "Otra":
for (int j = 0; j < ReporteLabores.labOtras.Count(); j++)
{
otras aux = new otras();
aux.idlabor = ReporteLabores.labOtras.ElementAt(j).idlabor;
aux.descripcion = ReporteLabores.labOtras.ElementAt(j).descripcion;
aux.horassemana = ReporteLabores.labOtras.ElementAt(j).horassemana;
mySpreadsheetAE.labOtras.Add(aux);
}
break;
}
}
periodo_academico lastAcademicPeriod = GetLastAcademicPeriod();
DateTime Hora = DateTime.Now;
DateTime Hoy = DateTime.Today;
string hora = Hora.ToString("HH:mm");
string hoy = Hoy.ToString("dd-MM");
mySpreadsheetAE.fileName = "Reporte" + lastAcademicPeriod.anio + "-" + lastAcademicPeriod.idperiodo + "_" + hoy + "_" + hora + ".xls";
return View(mySpreadsheetAE);
}
public int obtenerFilasRM()
{
int filasReporte = 0;
foreach (ConsolidadoDocencia filas in ReporteMaterias)
{
filasReporte = filasReporte + filas.labDocencia.Count() + 1;
}
return filasReporte;
}
#endregion
public class DocenteDepto
{
public String nombre;
public String apellido;
public String estado;
public int iddetp;
public int iddocente;
public int idususaio;
public String jefe;
}
public class Lab
{
public int id;
public String tipo;
}
public class evaluaciones
{
public int idevaluacion;
public int idautoevaluacion;
}
public class usuDoc
{
public int id;
public string nombre;
public int idlab;
}
#endregion
/******FIN ADICIONADO POR CLARA *******/
#region Importar Datos De SIMCA
[Authorize]
public ActionResult ImportDataSIMCA()
{
ViewBag.optionmenu = 5;
return View(new List<DocenteMateria>());
}
[Authorize]
[HttpPost]
public ActionResult ImportDataSIMCA(HttpPostedFileBase excelfile)
{
ViewBag.optionmenu = 5;
var guardados = new List<DocenteMateria>();
var noguardados = new List<DocenteMateria>();
var vistaDocenteMateria = new List<DocenteMateria>();
var tablaDatosSIMCA = new List<DocenteMateria>();
if (excelfile != null)
{
String extension = Path.GetExtension(excelfile.FileName);
String filename = Path.GetFileName(excelfile.FileName);
String filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(excelfile.FileName));
if (extension == ".xls" || extension == ".xlsx")
{
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
excelfile.SaveAs(filePath);
try
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Password=\"\";User ID=Admin;Data Source=" + filePath.ToString() + ";Mode=Share Deny Write;Extended Properties=\"HDR=YES;\";Jet OLEDB:Engine Type=37";
System.Data.OleDb.OleDbConnection oconn = new System.Data.OleDb.OleDbConnection(connectionString);
oconn.Open();
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("SELECT * FROM [Docentes$]", oconn);
DataSet myDataSet = new DataSet();
dataAdapter.Fill(myDataSet, "Docentes");
DataTable dataTable = myDataSet.Tables["Docentes"];
// Use a DataTable object's DataColumnCollection.
DataColumnCollection columns = dataTable.Columns;
String[] columnas = { "CodigoMateria", "NombreMateria", "Grupo", "Identificacion", "Total" };
// Print the ColumnName and DataType for each column.
Boolean valido = false;
if (columnas.Length == columns.Count)
{
int i = 0;
valido = true;
foreach (DataColumn column in columns)
{
valido = valido && (columnas[i] == column.ColumnName);
i++;
}
}
if (valido)
{
var rows = from p in dataTable.AsEnumerable()
select new
{
codMateria = p[0],
nombreMateria = p[1],
grupo = p[2],
identificacion = p[3],
total = p[4],
};
var id = new List<int>();
// modificado febrero 4
int currentper = (int)SessionValue("currentAcadPeriod");
vistaDocenteMateria= (from u in dbEntity.usuario
join d in dbEntity.docente on u.idusuario equals d.idusuario
join p in dbEntity.participa on d.iddocente equals p.iddocente
join lab in dbEntity.labor on p.idlabor equals lab.idlabor
join e in dbEntity.evaluacion on p.idevaluacion equals e.idevaluacion
join doc in dbEntity.docencia on p.idlabor equals doc.idlabor
join mat in dbEntity.materia on doc.idmateria equals mat.idmateria
where lab.idperiodo.Equals(currentper)
select new DocenteMateria { identificacion = u.identificacion, nombres = u.nombres, apellidos = u.apellidos, email = u.emailinstitucional, nombremateria = mat.nombremateria, codigomateria = mat.codigomateria, grupo = mat.grupo, ideval = e.idevaluacion }).ToList();
Debug.WriteLine("filas " + rows.Count());
foreach (var row in rows)
{
DocenteMateria dm = new DocenteMateria();
string identificacion=row.identificacion.ToString();
string codigo = row.codMateria.ToString();
string nombre = row.nombreMateria.ToString();
string grupo = row.grupo.ToString();
string total = row.total.ToString();
if (identificacion != "" && codigo != "" && nombre != "" && grupo != "" && total != "")
{
dm.identificacion = identificacion;
dm.codigomateria = codigo;
dm.nombremateria = nombre;
dm.grupo = grupo;
try
{
dm.evalest = Int32.Parse(total);
}
catch
{
break;
}
dm.guardado = 0;
tablaDatosSIMCA.Add(dm);
}
}
foreach (DocenteMateria ds in tablaDatosSIMCA)
{
foreach (DocenteMateria dv in vistaDocenteMateria)
{
try
{
if (ds.identificacion == dv.identificacion)
{
if (ds.codigomateria == dv.codigomateria && ds.grupo == dv.grupo)
{
evaluacion eval = dbEntity.evaluacion.Single(q => q.idevaluacion == dv.ideval);
eval.evaluacionestudiante = ds.evalest;
dv.evalest = ds.evalest;
dbEntity.SaveChanges();
ds.grupo = dv.grupo;
ds.identificacion = dv.identificacion;
ds.nombres = dv.nombres;
ds.apellidos = dv.apellidos;
ds.nombremateria = dv.nombremateria;
ds.guardado = 1;
}
}
}
catch { }
}
}
}
else
{
ViewBag.Error += "El formato de archivo no es valido";
}
oconn.Close();
System.IO.File.Delete(filePath);
}
catch (Exception)
{
ViewBag.Error = "No se pudo abrir el archivo, consulte el formato del mismo";
}
}
else
{
ViewBag.Error = "Solo se admiten archivos excel .xls o .xlsx";
}
}
else
{
ViewBag.Error = "No Recibido";
}
return View(tablaDatosSIMCA);
}
#endregion
#region Importar Datos De SIGELA MODIFICADO POR AMBOS
[Authorize]
public ActionResult ImportDataSIGELA()
{
ViewBag.optionmenu = 5;
return View(new List<savedDataSIGELA>());
}
// modificado 3 febrero
[Authorize]
[HttpPost]
public ActionResult ImportDataSIGELA(HttpPostedFileBase excelfile)
{
ViewBag.optionmenu = 5;
ViewBag.optionmenu = 5;
List<savedDataSIGELA> oResult;
string sError = "";
string sFileValid = "";
int LabsReg = 0;
int TeacReg = 0;
AdminController oController = new AdminController();
oResult = oController.ProcessImportDataSIGELA(excelfile, (int)SessionValue("currentAcadPeriod"), ref sError, ref sFileValid, ref LabsReg, ref TeacReg);
ViewBag.FileValid = sFileValid;
ViewBag.Labsreg = LabsReg;
ViewBag.Teacreg = TeacReg;
if (sError != "")
ViewBag.Error = sError;
return View(oResult);
}
#endregion
//INICIO ADICIONADO POR EDINSON
#region ADICIONADO POR EDINSON
public int yaEsta(string nombre)
{
try
{
cuestionario cuestionario1 = dbEntity.cuestionario.Single(c => c.tipocuestionario == nombre);
}
catch
{
return 0;
}
return 1;
}
public int yaEstaGrupo(string nombre, int Cuestionario)
{
try
{
grupo grupoExiste = dbEntity.grupo.Single(c => c.idcuestionario == Cuestionario && c.nombre == nombre);
}
catch
{
return 0;
}
return 1;
}
#region Asignar Cuestionario
[Authorize]
public ActionResult AssignQuestionnaire()
{
int contador = 0;
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
int idperiodoAc = ultimoPeriodo.idperiodo;
try
{
var asignacionesPeriodo = dbEntity.asignarCuestionario.ToList();
foreach (asignarCuestionario tempAsigancion in asignacionesPeriodo)
{
contador = contador + 1;
}
}
catch
{
}
if (contador == 8)
{
ViewBag.Message = "Todos los cuestionarios han sido asignados";
}
ViewBag.optionmenu = 1;
return View();
}
[Authorize]
public ActionResult EditarAssignQuestionnaire()
{
ViewBag.optionmenu = 1;
return View();
}
// NUEVO 28 ENERO
[Authorize]
public ActionResult AssignQuestionnaire1()
{
string socialVar = "";
string gestionVar = "";
string investigacionVar = "";
string trabajoGVar = "";
string desarrolloPVar = "";
string trabajoIVar = "";
string docenciaVar = "";
string otrasVar = "";
int vacio = 0;
int entradas = 8;
Boolean entro = false;
Boolean error = false;
socialVar = Request.Form["social"];
if (socialVar == null)
{
entradas = entradas - 1;
socialVar = "";
}
gestionVar = Request.Form["gestion"];
if (gestionVar == null)
{
entradas = entradas - 1;
gestionVar = "";
}
investigacionVar = Request.Form["investigacion"];
if (investigacionVar == null)
{
entradas = entradas - 1;
investigacionVar = "";
}
trabajoGVar = Request.Form["trabajoG"];
if (trabajoGVar == null)
{
entradas = entradas - 1;
trabajoGVar = "";
}
desarrolloPVar = Request.Form["desarrolloP"];
if (desarrolloPVar == null)
{
entradas = entradas - 1;
desarrolloPVar = "";
}
trabajoIVar = Request.Form["trabajoI"];
if (trabajoIVar == null)
{
entradas = entradas - 1;
trabajoIVar = "";
}
docenciaVar = Request.Form["docencia"];
if (docenciaVar == null)
{
entradas = entradas - 1;
docenciaVar = "";
}
otrasVar = Request.Form["otras"];
if (docenciaVar == null)
{
entradas = entradas - 1;
otrasVar = "";
}
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
if (socialVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == socialVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
nuevaAsigancion.idlabor = 1;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (gestionVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido1 = null;
asignarCuestionario nuevaAsigancion1 = new asignarCuestionario();
cuestionarioObtenido1 = dbEntity.cuestionario.Single(c => c.tipocuestionario == gestionVar);
nuevaAsigancion1.idcuestionario = cuestionarioObtenido1.idcuestionario;
nuevaAsigancion1.idlabor = 2;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion1);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (investigacionVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido2 = null;
asignarCuestionario nuevaAsigancion2 = new asignarCuestionario();
cuestionarioObtenido2 = dbEntity.cuestionario.Single(c => c.tipocuestionario == investigacionVar);
nuevaAsigancion2.idcuestionario = cuestionarioObtenido2.idcuestionario;
nuevaAsigancion2.idlabor = 3;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion2);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (trabajoGVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido3 = null;
asignarCuestionario nuevaAsigancion3 = new asignarCuestionario();
cuestionarioObtenido3 = dbEntity.cuestionario.Single(c => c.tipocuestionario == trabajoGVar);
nuevaAsigancion3.idcuestionario = cuestionarioObtenido3.idcuestionario;
nuevaAsigancion3.idlabor = 4;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion3);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (desarrolloPVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido4 = null;
asignarCuestionario nuevaAsigancion4 = new asignarCuestionario();
cuestionarioObtenido4 = dbEntity.cuestionario.Single(c => c.tipocuestionario == desarrolloPVar);
nuevaAsigancion4.idcuestionario = cuestionarioObtenido4.idcuestionario;
nuevaAsigancion4.idlabor = 5;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion4);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (trabajoIVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido5 = null;
asignarCuestionario nuevaAsigancion5 = new asignarCuestionario();
cuestionarioObtenido5 = dbEntity.cuestionario.Single(c => c.tipocuestionario == trabajoIVar);
nuevaAsigancion5.idcuestionario = cuestionarioObtenido5.idcuestionario;
nuevaAsigancion5.idlabor = 6;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion5);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (docenciaVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido6 = null;
asignarCuestionario nuevaAsigancion6 = new asignarCuestionario();
cuestionarioObtenido6 = dbEntity.cuestionario.Single(c => c.tipocuestionario == docenciaVar);
nuevaAsigancion6.idcuestionario = cuestionarioObtenido6.idcuestionario;
nuevaAsigancion6.idlabor = 7;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion6);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (otrasVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido6 = null;
asignarCuestionario nuevaAsigancion6 = new asignarCuestionario();
cuestionarioObtenido6 = dbEntity.cuestionario.Single(c => c.tipocuestionario == otrasVar);
nuevaAsigancion6.idcuestionario = cuestionarioObtenido6.idcuestionario;
nuevaAsigancion6.idlabor = 8;
dbEntity.asignarCuestionario.AddObject(nuevaAsigancion6);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
ViewBag.optionmenu = 1;
if (entradas == 0)
{
ViewBag.Message = "Todos los cuestionarios han sido asignados";
}
if (entro == true && error == false)
{
ViewBag.Message = "Se ejecutaron las asignaciones solicitadas correctamente";
}
else
{
if (entro == true && error == true)
{
ViewBag.Error = "Algunos cambios no se realizaron";
}
if (entro == false && error == true)
{
ViewBag.Error = "Algunos cambios no se realizaron";
}
}
return View();
}
// FIN NUEVO 29 NOCHE
// NUEVO 29 NOCHE
[Authorize]
public ActionResult EditarAssignQuestionnaire1()
{
string socialVar = "";
string gestionVar = "";
string investigacionVar = "";
string trabajoGVar = "";
string desarrolloPVar = "";
string trabajoIVar = "";
string docenciaVar = "";
string otrasVar = "";
int vacio = 0;
int entradas = 8;
Boolean entro = false;
Boolean error = false;
socialVar = Request.Form["social"];
if (socialVar == null)
{
entradas = entradas - 1;
socialVar = "";
}
gestionVar = Request.Form["gestion"];
if (gestionVar == null)
{
entradas = entradas - 1;
gestionVar = "";
}
investigacionVar = Request.Form["investigacion"];
if (investigacionVar == null)
{
entradas = entradas - 1;
investigacionVar = "";
}
trabajoGVar = Request.Form["trabajoG"];
if (trabajoGVar == null)
{
entradas = entradas - 1;
trabajoGVar = "";
}
desarrolloPVar = Request.Form["desarrolloP"];
if (desarrolloPVar == null)
{
entradas = entradas - 1;
desarrolloPVar = "";
}
trabajoIVar = Request.Form["trabajoI"];
if (trabajoIVar == null)
{
entradas = entradas - 1;
trabajoIVar = "";
}
docenciaVar = Request.Form["docencia"];
if (docenciaVar == null)
{
entradas = entradas - 1;
docenciaVar = "";
}
otrasVar = Request.Form["otras"];
if (otrasVar == null)
{
entradas = entradas - 1;
docenciaVar = "";
}
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
if (socialVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 1);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == socialVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (gestionVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 2);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == gestionVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (investigacionVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 3);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == investigacionVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (trabajoGVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 4);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == trabajoGVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (desarrolloPVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 5);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == desarrolloPVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (trabajoIVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 6);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == trabajoIVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (docenciaVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 7);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == docenciaVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
if (otrasVar.Length != 0)
{
try
{
cuestionario cuestionarioObtenido = null;
asignarCuestionario nuevaAsigancion = new asignarCuestionario();
nuevaAsigancion = dbEntity.asignarCuestionario.Single(c => c.idlabor == 8);
cuestionarioObtenido = dbEntity.cuestionario.Single(c => c.tipocuestionario == otrasVar);
nuevaAsigancion.idcuestionario = cuestionarioObtenido.idcuestionario;
dbEntity.ObjectStateManager.ChangeObjectState(nuevaAsigancion, EntityState.Modified);
dbEntity.SaveChanges();
entro = true;
entradas = entradas - 1;
}
catch
{
vacio = 2;
error = true;
}
}
ViewBag.optionmenu = 1;
if (entro == true && error == false)
{
ViewBag.Message = "Se ejecutaron los cambios solicitados";
}
else
{
if (entro == true && error == true)
{
ViewBag.Error = "Algunos cambios no se realizaron";
}
if (entro == false && error == true)
{
ViewBag.Error = "Algunos cambios no se realizaron";
}
}
return View();
}
// FIN NUEVO 29 NOCHE
// NUEVO 29 NOCHE
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetAsiganacionPeriodo(string term)
{
int[] response;
response = new int[8];
response[0] = 0;
response[1] = 0;
response[2] = 0;
response[3] = 0;
response[4] = 0;
response[5] = 0;
response[6] = 0;
// NUEVO 29
response[7] = 0;
// FIN NUEVO 29
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
int currentper = (int)SessionValue("currentAcadPeriod");
//if (currentper == ultimoPeriodo.idperiodo) {
int idperiodoAc = ultimoPeriodo.idperiodo;
try
{
var asignacionesPeriodo = dbEntity.asignarCuestionario.ToList();
foreach (asignarCuestionario tempAsigancion in asignacionesPeriodo)
{
response[tempAsigancion.idlabor - 1] = 1;
}
}
catch
{
}
return Json(response, JsonRequestBehavior.AllowGet);
// }
// return Json(-1, JsonRequestBehavior.AllowGet);
}
// FIN NUEVO 29 NOCHE
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetTechingWork1(string term)
{
periodo_academico ultimoPeriodo = GetLastAcademicPeriod();
var asignados = (from p in dbEntity.asignarCuestionario
join l in dbEntity.cuestionario on p.idcuestionario equals l.idcuestionario
select new asignacionQ { custionario = l.tipocuestionario, idlabor = p.idlabor }).ToList();
return Json(asignados, JsonRequestBehavior.AllowGet);
}
#endregion
#region Evaluar Jefe
[Authorize]
public ActionResult EvaluateSubordinates2()
{
if (opcionError == 0)
{
ViewBag.Error = "No hay cuestionario asignado para la evaluación de esta labor";
}
else
{
ViewBag.Error = "La evaluacion de este docente ya se realizo";
}
return View();
}
[Authorize]
public ActionResult EvaluateSubordinates1()
{
string laborEntra = Request.Form["labor"];
string usuarioEntra1 = Request.Form["usuario"];
string evaluacionEntra = Request.Form["evaluacion"];
int labor = Convert.ToInt16(laborEntra);
int doce = Convert.ToInt16(usuarioEntra1);
int idE = Convert.ToInt16(evaluacionEntra);
// docente auxDocente = dbEntity.docente.Single(c => c.idusuario == doce);
int idlabor = labor;
// int iddoce = auxDocente.iddocente;
// doce = iddoce;
int idEva = idE;
int salir = 0;
evaluacion regevaluacion = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == idE);
if (regevaluacion.evaluacionjefe != -1)
{
salir = 1;
}
if (salir == 0)
{
ViewBag.SubByWork2 = idlabor;
ViewBag.SubByWork3 = doce;
ViewBag.SubByWork4 = idEva;
int currentper2 = (int)SessionValue("currentAcadPeriod");
asignarCuestionario realizada = null;
try
{
social socialVar = dbEntity.social.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 1);
}
catch
{
try
{
docencia docenciaVar = dbEntity.docencia.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 7);
}
catch
{
try
{
desarrolloprofesoral desarrolloVar = dbEntity.desarrolloprofesoral.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 5);
}
catch
{
try
{
gestion gestionVar = dbEntity.gestion.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 2);
}
catch
{
try
{
investigacion investigacionVar = dbEntity.investigacion.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 3);
}
catch
{
try
{
trabajodegrado trabajoGVar = dbEntity.trabajodegrado.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 4);
}
catch
{
try
{
trabajodegradoinvestigacion trabajoIVar = dbEntity.trabajodegradoinvestigacion.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 6);
}
catch
{
try
{
otras otrasVar = dbEntity.otras.Single(c => c.idlabor == idlabor);
realizada = dbEntity.asignarCuestionario.Single(c => c.idlabor == 8);
}
catch
{
}
}
}
}
}
}
}
}
if (realizada != null)
{
ViewBag.SubByWork5 = realizada.idcuestionario;
var grup_data = dbEntity.grupo
.Join(dbEntity.cuestionario,
grup => grup.idcuestionario,
cues => cues.idcuestionario,
(grup, cues) => new { grupo = grup, cuestionario = cues })
.OrderBy(grup_cues => grup_cues.grupo.orden)
.Where(grup_cues => grup_cues.cuestionario.idcuestionario == realizada.idcuestionario)
.Select(l => new { idCuestionario = l.cuestionario.idcuestionario, idGrupo = l.grupo.idgrupo, nombreGrupo = l.grupo.nombre, porcentaje = l.grupo.porcentaje }).ToList();
List<QuestionnaireGroup> l_quesgroup = new List<QuestionnaireGroup>();
for (int i = 0; i < grup_data.Count(); i++)
{
int idG = grup_data.ElementAt(i).idGrupo;
var temp_p = dbEntity.pregunta.Where(l => l.idgrupo == idG).ToList();
List<Question> l_ques = new List<Question>();
for (int j = 0; j < temp_p.Count(); j++)
{
l_ques.Add(new Question((int)temp_p.ElementAt(j).idpregunta, (string)temp_p.ElementAt(j).pregunta1));
}
l_quesgroup.Add(new QuestionnaireGroup((int)grup_data.ElementAt(i).idGrupo, (string)grup_data.ElementAt(i).nombreGrupo, (double)grup_data.ElementAt(i).porcentaje, l_ques));
}
CompleteQuestionnaire compQuest = new CompleteQuestionnaire(1, l_quesgroup);
//docente docenteEntra = dbEntity.docente.Single(c => c.iddocente == iddoce);
usuario usuarioEntra = dbEntity.usuario.Single(c => c.idusuario == doce);
ViewBag.SubByWork1 = usuarioEntra.nombres + " " + usuarioEntra.apellidos;
ViewBag.CompQuest = compQuest;
ViewBag.WorkDescription = TeacherController.getLaborDescripcion(idlabor);
return View();
}
else
{
opcionError = 0;
return RedirectPermanent("/sedoc/AdminFac/EvaluateSubordinates2");
}
}
opcionError = 1;
return RedirectPermanent("/sedoc/AdminFac/EvaluateSubordinates2");
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult UpdateEval(ChiefEval myEval)
{
var averages = myEval.calificaciones.GroupBy(l => l.idgrupo).Select(l => new { idgroup = l.Key, count = l.Count(), average = l.Average(r => r.calificacion) });
var percents = averages
.Join(dbEntity.grupo,
aver => aver.idgroup,
grup => grup.idgrupo,
(aver, grup) => new { grupo = grup, averages = aver })
.Select(l => new { idgrupo = l.grupo.idgrupo, promedio = l.averages.average, porcentaje = l.grupo.porcentaje, score = (l.averages.average * (l.grupo.porcentaje / 100)) });
var totalscore = (decimal)percents.Sum(c => c.score);
totalscore = System.Math.Round(totalscore, 0);
try
{
evaluacion regevaluacion = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == myEval.idevaluacion);
regevaluacion.evaluacionjefe = (int)totalscore; // aqui se supone que el total me da con decimales, pero tengo que redondear
dbEntity.SaveChanges();
WorkChiefController oController = new WorkChiefController();
oController.GeneratePdfFile(myEval, Server.MapPath("~/pdfsupport/"), (double)totalscore);
return Json((int)totalscore, JsonRequestBehavior.AllowGet);
}
catch
{
return Json(-1, JsonRequestBehavior.AllowGet);
}
}
#endregion
#endregion
//FIN ADICIONADO POR EDINSON
// NUEVO 28
[Authorize]
public ActionResult ImportDataC()
{
ViewBag.optionmenu = 2;
return View(new List<savedDataSIGELA>());
}
[Authorize]
[HttpPost]
public ActionResult ImportDataC(HttpPostedFileBase excelfile)
{
ViewBag.optionmenu = 2;
string connectionString = "";
System.Data.OleDb.OleDbConnection oconn = new OleDbConnection();
List<savedDataSIGELA> savedsigela = new List<savedDataSIGELA>();
if (excelfile != null)
{
String extension = Path.GetExtension(excelfile.FileName);
String filename = Path.GetFileName(excelfile.FileName);
String filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename);
if (extension == ".xls" || extension == ".xlsx")
{
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
excelfile.SaveAs(filePath);
try
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Password=\"\";User ID=Admin;Data Source=" + filePath.ToString() + ";Mode=Share Deny Write;Extended Properties=\"HDR=YES;\";Jet OLEDB:Engine Type=37";
oconn = new System.Data.OleDb.OleDbConnection(connectionString);
oconn.Open();
bool valido = ExcelValidation1(oconn);
if (valido)
{
int currentper = (int)SessionValue("currentAcadPeriod");
List<coordinadorSIGELA> docs_sig = this.data_imports.getDocentes1(); //Obtener la lista de docentes desde excel
List<coordinadorSIGELA> saveddtes = CoordinatorImportSave1(docs_sig);
ViewBag.FileValid = "El archivo " + filename + " recibido es valido";
ViewBag.Labsreg = savedsigela.Count();
ViewBag.Teacreg = docs_sig.Count();
}
else
{
ViewBag.Error = "Excel no valido";
}
oconn.Close();
System.IO.File.Delete(filePath);
}
catch (Exception)
{
if (oconn.State != ConnectionState.Closed)
{
oconn.Close();
}
ViewBag.Error = "No se pudo abrir el archivo en Excel, consulte el formato del mismo";
}
}
else
{
ViewBag.Error = "Solo se admiten archivos Excel .xls o .xlsx";
}
}
else
{
ViewBag.Error = "No Recibido";
}
return View(savedsigela);
}
[Authorize]
public List<coordinadorSIGELA> CoordinatorImportSave1(List<coordinadorSIGELA> sigela_docentes)
{
List<coordinadorSIGELA> savedTeachers = new List<coordinadorSIGELA>();
string claveN = "";
foreach (coordinadorSIGELA dte in sigela_docentes)
{
claveN = "";
String emailinst;
int idusu;
if (!dte.email.EndsWith("@unicauca.edu.co"))
{
dte.email += "@unicauca.edu.co";
}
emailinst = dte.email;
usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.emailinstitucional == emailinst && q.identificacion == dte.identificacion);
//usuario unusuario = dbEntity.usuario.SingleOrDefault(q => q.emailinstitucional == emailinst);
if (emailinst != "@unicauca.edu.co")
{
if (unusuario == null) //no existe
{
try
{
departamento dpt = dbEntity.departamento.SingleOrDefault(dp => dp.nombre == dte.departamento);
if (dpt != null)
{
// para encriptar la clave
claveN = AdminController.md5(emailinst.Replace("@unicauca.edu.co", ""));
//claveN = emailinst.Replace("@unicauca.edu.co", "");
// para encriptar la clave
//Creamos el usuario
unusuario = new usuario() { emailinstitucional = emailinst, password = <PASSWORD>, rol = "Coordinador", nombres = dte.nombres, apellidos = dte.apellidos, identificacion = dte.identificacion };
//guardamos el usuario, ahora en unusuario debe existir el id asignado
dbEntity.usuario.AddObject(unusuario);
dbEntity.SaveChanges();
usuario unusuarioCrd = dbEntity.usuario.SingleOrDefault(q => q.emailinstitucional == emailinst);
decanoCoordinador ingresa = new decanoCoordinador() { id = 9, idusuario = unusuarioCrd.idusuario, idfacultadDepto = dpt.iddepartamento };
dbEntity.decanoCoordinador.AddObject(ingresa);
dbEntity.SaveChanges();
}
}
catch { }
}
else
{//ya existe el usuario
idusu = unusuario.idusuario;
unusuario.nombres = dte.nombres;
unusuario.apellidos = dte.apellidos;
dbEntity.SaveChanges();
}
}
}
return savedTeachers;
}
public bool ExcelValidation1(System.Data.OleDb.OleDbConnection oconn)
{
bool dtes_val;
AdminController oControlador = new AdminController();
this.data_imports.docentesTable = oControlador.SheetValidation(oconn, "Coordinadores", new String[] { "identificacion", "emailinstitucional", "nombres", "apellidos", "departamento" }, out dtes_val);
return dtes_val;
}
// FIN NUEVO 28
}
}
<file_sep>using System;
using System.Linq;
using System.Web;
using System.Data;
using System.Collections.Generic;
namespace MvcSEDOC.Models
{
public class ImportDataSheets
{
public DataTable docentesTable { get; set; }
public DataTable docenciaTable { get; set; }
public DataTable dlloProfesoralTable { get; set; }
public DataTable trabajoGdoInvTable { get; set; }
public DataTable trabajoGdoTable { get; set; }
public DataTable investigacionTable { get; set; }
public DataTable socialTable { get; set; }
public DataTable gestionTable { get; set; }
public DataTable otrasTable { get; set; }
// NUEVO 28
public List<coordinadorSIGELA> getDocentes1()
{
List<coordinadorSIGELA> data = new List<coordinadorSIGELA>();
try
{
foreach (var row in this.docentesTable.AsEnumerable())
{
coordinadorSIGELA nuevo = new coordinadorSIGELA()
{
identificacion = row[0].ToString().Trim(),
email = row[1].ToString().Trim(),
nombres = row[2].ToString().Trim(),
apellidos = row[3].ToString().Trim(),
departamento = row[4].ToString().Trim(),
};
if (nuevo.identificacion != "" && nuevo.email != "" && nuevo.nombres != "" && nuevo.apellidos != "" && nuevo.departamento != "")
{
data.Add(nuevo);
}
}
}
catch
{
}
return data;
}
// FIN NUEVO 28
public List<docenteSIGELA> getDocentes()
{
List<docenteSIGELA> data = new List<docenteSIGELA>();
try {
foreach (var row in this.docentesTable.AsEnumerable()) {
// MODIFICADO 1 FEB
docenteSIGELA docente = new docenteSIGELA()
{
identificacion = row[0].ToString().Trim(),
email = row[1].ToString().Trim(),
nombres = row[2].ToString().Trim(),
apellidos = row[3].ToString().Trim(),
departamento = row[4].ToString().Trim(),
estado = row[5].ToString().Trim(),
};
if (docente.identificacion != "" && docente.email != "" && docente.nombres != "" && docente.apellidos != "" && docente.departamento != "" && docente.estado != "")
{
data.Add(docente);
}
// FIN MODIFICADO 1 FEB
}
}
catch (Exception ex) {
}
return data;
}
public List<docenciaSIGELA> getDocencias()
{
List<docenciaSIGELA> data = new List<docenciaSIGELA>();
try {
foreach (var row in this.docenciaTable.AsEnumerable()) {
data.Add(
new docenciaSIGELA()
{
programa = row[0].ToString().Trim(),
codigomateria = row[1].ToString().Trim(),
nombremateria = row[2].ToString().Trim(),
grupo = row[3].ToString().Trim(),
identificacion = row[4].ToString().Trim(),
horassemana = decimal.Parse(row[5].ToString().Trim()),
semanaslaborales = int.Parse(row[6].ToString().Trim())
});
}
}
catch (Exception ex) {
}
return data;
}
public List<dlloProfesoralSIGELA> getDlloProfesoral()
{
List<dlloProfesoralSIGELA> data = new List<dlloProfesoralSIGELA>();
try {
foreach (var row in this.dlloProfesoralTable.AsEnumerable()) {
data.Add(
new dlloProfesoralSIGELA()
{
identificacion = row[0].ToString().Trim(),
resolucion = row[1].ToString().Trim(),
horassemana = decimal.Parse(row[2].ToString().Trim()),
semanaslaborales = int.Parse(row[3].ToString().Trim()),
nombreactividad = row[4].ToString().Trim()
});
}
}
catch (Exception ex)
{
}
return data;
}
public List<trabajoGdoInvSIGELA> getTrabajoGdoInv()
{
List<trabajoGdoInvSIGELA> data = new List<trabajoGdoInvSIGELA>();
try {
foreach (var row in this.trabajoGdoInvTable.AsEnumerable()) {
data.Add(
new trabajoGdoInvSIGELA()
{
identificacion = row[0].ToString().Trim(),
programa = row[1].ToString().Trim(),
codigoest = Int64.Parse(row[2].ToString().Trim()),
horassemana = decimal.Parse(row[3].ToString().Trim()),
semanaslaborales = int.Parse(row[4].ToString().Trim()),
titulotrabajo = row[5].ToString().Trim()
});
}
}
catch (Exception ex) {
}
return data;
}
public List<trabajoGdoSIGELA> getTrabajoGdo()
{
List<trabajoGdoSIGELA> data = new List<trabajoGdoSIGELA>();
try {
foreach (var row in this.trabajoGdoTable.AsEnumerable()) {
data.Add(
new trabajoGdoSIGELA() {
identificacion = row[0].ToString().Trim(),
programa = row[1].ToString().Trim(),
codigoest = Int64.Parse(row[2].ToString().Trim()),
horassemana = decimal.Parse(row[3].ToString().Trim()),
semanaslaborales = int.Parse(row[4].ToString().Trim()),
resolucion = row[5].ToString().Trim(),
titulotrabajo = row[6].ToString().Trim()
});
}
}
catch (Exception ex) {
}
return data;
}
public List<investigacionSIGELA> getInvestigacion()
{
List<investigacionSIGELA> data = new List<investigacionSIGELA>();
try {
foreach (var row in this.investigacionTable.AsEnumerable()) {
data.Add(
new investigacionSIGELA() {
identificacion = row[0].ToString().Trim(),
codigovri = row[1].ToString().Trim(),
horassemana = decimal.Parse(row[2].ToString().Trim()),
fechainicio = row[3].ToString().Trim(),
fechafin = row[4].ToString().Trim(),
semanaslaborales = int.Parse(row[5].ToString().Trim()),
nombreproyecto = row[6].ToString().Trim()
});
}
}
catch (Exception ex) {
}
return data;
}
public List<socialSIGELA> getSocial()
{
List<socialSIGELA> data = new List<socialSIGELA>();
try {
foreach (var row in this.socialTable.AsEnumerable()) {
data.Add(
new socialSIGELA() {
identificacion = row[0].ToString().Trim(),
horassemana = decimal.Parse(row[1].ToString().Trim()),
resolucion = row[2].ToString().Trim(),
unidad = row[3].ToString().Trim(),
fechainicio = row[4].ToString().Trim(),
fechafin = row[5].ToString().Trim(),
semanaslaborales = int.Parse(row[6].ToString().Trim()),
nombreproyecto = row[7].ToString().Trim()
});
}
}
catch (Exception ex) {
}
return data;
}
public List<gestionSIGELA> getGestion()
{
List<gestionSIGELA> data = new List<gestionSIGELA>();
try {
foreach (var row in this.gestionTable.AsEnumerable()) {
data.Add(
new gestionSIGELA() {
identificacion = row[0].ToString().Trim(),
horassemana = decimal.Parse(row[1].ToString().Trim()),
unidad = row[2].ToString().Trim(),
semanaslaborales = int.Parse(row[3].ToString().Trim()),
nombrecargo = row[4].ToString().Trim()
});
}
}
catch (Exception ex) {
}
return data;
}
// nuevo febrero 3
public List<otrasSIGELA> getOtras()
{
List<otrasSIGELA> data = new List<otrasSIGELA>();
try
{
foreach (var row in this.otrasTable.AsEnumerable())
{
data.Add(
new otrasSIGELA()
{
identificacion = row[0].ToString().Trim(),
horassemana = decimal.Parse(row[1].ToString().Trim()),
descripcion = row[2].ToString().Trim(),
});
}
}
catch
{
}
return data;
}
}
// Clases para importar de Excel
// NUEVO 28
public class coordinadorSIGELA
{
public String identificacion { get; set; }
public String email { get; set; }
public String nombres { get; set; }
public String apellidos { get; set; }
public String departamento { get; set; }
}
// FIN NUEVO 28
public class docenteSIGELA {
public String identificacion { get; set; }
public String email { get; set; }
public String nombres { get; set; }
public String apellidos { get; set; }
public String departamento { get; set; }
public String estado { get; set; }
}
public class docenciaSIGELA {
public String programa { get; set; }
public String codigomateria { get; set; }
public String nombremateria { get; set; }
public String grupo { get; set; }
public String identificacion { get; set; }
public decimal horassemana { get; set; }
public int semanaslaborales { get; set; }
//public int creditos { get; set; }
//public int semestre { get; set; }
//public int intensidadhoraria { get; set; }
//public String tipo { get; set; }
}
public class dlloProfesoralSIGELA {
public String identificacion { get; set; }
public String resolucion { get; set; }
public decimal horassemana { get; set; }
public int semanaslaborales { get; set; }
public String nombreactividad { get; set; }
}
public class trabajoGdoInvSIGELA {
public String identificacion { get; set; }
public String programa { get; set; }
public Int64 codigoest { get; set; }
public decimal horassemana { get; set; }
public int semanaslaborales { get; set; }
public String titulotrabajo { get; set; }
}
public class trabajoGdoSIGELA {
public String identificacion { get; set; }
public String programa { get; set; }
public Int64 codigoest { get; set; }
public decimal horassemana { get; set; }
public int semanaslaborales { get; set; }
public String resolucion { get; set; }
public String titulotrabajo { get; set; }
}
public class investigacionSIGELA {
public String identificacion { get; set; }
public String codigovri { get; set; }
public decimal horassemana { get; set; }
public String fechainicio { get; set; }
public String fechafin { get; set; }
public int semanaslaborales { get; set; }
public String nombreproyecto { get; set; }
}
public class socialSIGELA {
public String identificacion { get; set; }
public decimal horassemana { get; set; }
public String resolucion { get; set; }
public String unidad { get; set; }
public String fechainicio { get; set; }
public String fechafin { get; set; }
public int semanaslaborales { get; set; }
public String nombreproyecto { get; set; }
}
public class gestionSIGELA {
public String identificacion { get; set; }
public decimal horassemana { get; set; }
public String unidad { get; set; }
public int semanaslaborales { get; set; }
public String nombrecargo { get; set; }
}
public class savedDataSIGELA {
public String identificacion { get; set; }
public String nombre { get; set; }
public String apellido { get; set; }
public String email { get; set; }
public String tipolabor { get; set; }
public String nombrelabor { get; set; }
}
// nuevo feberro 3
public class otrasSIGELA
{
public String identificacion { get; set; }
public String descripcion { get; set; }
public decimal horassemana { get; set; }
}
}<file_sep>$(function () {
$("#accordionMenu").accordion({ active: parseInt($("#accordionMenu").attr("optionselected")) });
});<file_sep>function setEditAction(idQ, tipQ) {
$('#btnEdit' + idQ).click(function () {
$("#idcuestionario").val(idQ);
$("#tipocuestionario").val(entitiesDecode(tipQ));
$('#dialogEditQuestionnaire').dialog('open');
return false;
});
$('#btnDel' + idQ).click(function () {
$('#idcuestionario').val(idQ);
$('#dialogDeleteQuestionnaireConfirm').dialog('open');
return false;
});
}
function entitiesDecode(Str) {
var decoded = $("<div/>").html(Str).text();
return decoded;
}
$(function () {
var searchVar = "/sedoc/Admin/SearchQuestionnaire/";
var questionnairetype = $("#tipocuestionario"),
idquestionnaire = $("#idcuestionario"),
allFields = $([]).add(questionnairetype).add(idquestionnaire),
tips = $(".field-validation-valid");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("El tamaño de " + n + " debe estar entre " +
min + " y " + max + ".");
return false;
} else {
return true;
}
}
$('#dialogEditQuestionnaire').dialog({
autoOpen: false,
width: 400,
height: 200,
modal: true,
buttons: {
"Guardar": function () {
var bValid = true;
allFields.removeClass("ui-state-error");
bValid = bValid && checkLength(questionnairetype, "tipo de cuestionario", 3, 30);
if (bValid) {
SaveQuestionnaire("/sedoc/Admin/EditQuestionnaire/", $(this))
}
},
"Cancelar": function () {
allFields.val("").removeClass("ui-state-error");
updateTips("");
$(this).dialog("close");
}
}
});
$("#dialogDeleteQuestionnaireConfirm").dialog({
resizable: false,
autoOpen: false,
height: 140,
modal: true,
buttons: {
"Eliminar": function () {
DeleteQuestionnaire("/sedoc/Admin/DeleteQuestionnaire/", $(this));
},
"Cancelar": function () {
allFields.val("").removeClass("ui-state-error");
updateTips("");
$(this).dialog("close");
}
}
});
function DeleteQuestionnaire(route, jquerydialog) {
var idQ = $('#idcuestionario').val();
if (idQ == "") {
alert("El cuestionario no puede ser eliminado");
} else {
var quest = '{ "id": ' + idQ + ' }';
var request = $.ajax({
cache: false,
url: route,
type: 'POST',
dataType: 'json',
data: quest,
contentType: 'application/json; charset=utf-8',
success: function (data) {
deletedResponse(data, jquerydialog);
}
});
}
}
function SaveQuestionnaire(route, jquerydialog) {
var questionnaire = getQuestionnaire();
if (questionnaire == null) {
updateTips("El cuestionario no debe ser vacío");
} else {
var request = $.ajax({
cache: false,
url: route,
type: 'POST',
dataType: 'json',
data: questionnaire,
contentType: 'application/json; charset=utf-8',
success: function (data) {
savedResponse(data, jquerydialog);
}
});
}
}
function savedResponse(data, jquerydialog) {
if (data.idcuestionario != 0) {
$("#work-area").html("");
$('#lblEd' + data.idcuestionario).html(data.tipocuestionario);
allFields.val("").removeClass("ui-state-error");
updateTips("");
setEditAction(data.idcuestionario, data.tipocuestionario);
jquerydialog.dialog("close");
} else {
updateTips("Lo siento!, el registro no se pudo efectuar ... disculpame");
}
}
function deletedResponse(data, jquerydialog) {
if (data.idcuestionario != 0) {
$("#work-area").html("");
$('#btnDel' + data.idcuestionario).parent().parent().remove();
jquerydialog.dialog("close");
} else {
alert("Lo siento!, la eliminación no se pudo efectuar ... disculpame");
}
}
function getQuestionnaire() {
var idq = $("#idcuestionario").val();
var tip = $("#tipocuestionario").val();
return (idq == "" || tip == "") ? null : '{ "idcuestionario": "' + idq + '", "tipocuestionario": "' + tip + '" }';
}
});<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcSEDOC.Models
{
public class AutoevaluacionDocente
{
public String nombredocente { get; set; }
public String nombrejefe { get; set; }
public String fechaevaluacion { get; set; }
public int periodoanio { get; set; }
public int periodonum { get; set; }
public Double totalhorassemana { get; set; }
public List<ResAutoEvaluacionLabor> autoevaluacioneslabores { get; set; }
}
public class ResAutoEvaluacionLabor
{
public int idlabor { get; set; }
public String descripcion { get; set; }
public String tipolabor { get; set; }
public String tipolaborcorto { get; set; }
public int nota { get; set; }
public String problemadescripcion { get; set; }
public String problemasolucion { get; set; }
public String resultadodescripcion { get; set; }
public String resultadosolucion { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcSEDOC.Views.Admin
{
public class IndexViewModel
{
// Stores the selected value from the drop down box.
public int FacultadID { get; set; }
// Contains the list of countries.
public SelectList Facultades { get; set; }
}
}<file_sep>var departamentoSelected;
function openDialog(valor) {
departamentoSelected = valor;
$("#dialogListDepartment").dialog('open');
}
function prueba(id) {
alert(id);
}
var searchVarFac = "/sedoc/Admin/SearchFacultad/";
var searchVar = "/sedoc/Admin/SearchDepartment/";
var nameFac, idfac, nameDep, iddep;
// fija el id y el nombre de la facultad
function setFacultad(ui) {
nameFac = ui.item.label; // nombre de la facultad
idfac = ui.item.id; // id de la facultad
}
// fija el id y el nombre del departamento
function setDepartamento(ui) {
nameDep = ui.item.label; // nombre de la departamento
iddep = ui.item.id; // id de la departamento
}
function loadDepartamentos(idF, route) {
$.getJSON(route, { term: idF }, function (data) {
// contenido de la tabla
$.each(data, function (key, val) {
$("#DepartamentFrom" + idF).append("<option value='" + val['id'] + "'>" + val['label'] + "</option>");
});
});
}
function loadDept(idFacultad) {
idfac = idFacultad;
if (idFacultad != 0) {
//nameFac = $("#fac" + idfac).attr("facname");
$("TextBox").html("<select name='departamentos' id='DepartamentFrom" + idfac + "'>" +
"<option value='0'>Seleccione El Programa</option>" +
"</select>");
loadDepartamentos(idFacultad, "/sedoc/Admin/GetFacultadPrograma/");
}
}
//function loadProfesores(idD, route) {
// $.getJSON(route, { term: idD }, function (data) {
// // contenido de la tabla
// $.each(data, function (key, val) {
// $("#ProfesoresFrom" + idD).append("<option value='" + val['id'] + "'>" + val['label'] + "</option>");
// });
// });
//}
//function loadProf(idDepartamento) {
// iddep = idDepartamento;
// if (idDepartamento != 0) {
// //nameDep = $("#fac" + iddep).attr("facname");
// $("TextBox").html("<select name='profesores' id='ProfesoresFrom" + iddep + "'>" +
// "<option value='0'>Seleccione El Profesor</option>" +
// "</select>");
// loadProfesores(idDepartamento, "/sedoc/Admin/GetDepartamentoProfesores/");
// }
//}
function loadDocentes(idD, route) {
$.getJSON(route, { term: idD }, function (data) {
// contenido de la tabla
$.each(data, function (key, val) {
$("#ProfesoresFrom" + idD + " tbody").append("<tr>" +
"<td>" + val['label'] + "</td></tr>");
});
});
}
// carga la cabecera de la tabla
function loadTable(idDepartamento) {
iddep = idDepartamento;
if (idDepartamento != 0) {
//nameDep = $("#dep" + iddep).attr("depname");
$("#work-area").html("<table id='ProfesoresFrom" + iddep + "' class='list' style='width:100%'>" +
"<thead><tr><th align='center' colspan=3>Programas De La Facultad De </th></tr></thead>" +
"<tbody></tbody>" +
"</table><br/>");
loadDocentes(idDepartamento, "/sedoc/Admin/GetDepartamentoProfesores/");
}
}
$(function () {
/* Buscar facultad*/
$("#search_facultad").autocomplete({
source: searchVarFac,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setFacultad(ui);
loadTable(ui.item.id);
}
}
});
});<file_sep>$(function () {
var iddepto = document.getElementById("search_term").value;
setDepartament();
loadTeaching(iddepto, "/sedoc/DepartmentChief/GetDepartamentTeaching/");
function setDepartament() {
$("#work-area").html("");
$("#work-area").append("<table id='TableidTeaching' class='list' style='width:100%'>" +
"<thead><tr><th colspan='4'>Miembros</th></tr>" +
"<tr class='sub'>" +
"<th>Apellidos</th>"+
"<th>Nombres</th>"+
"<th colspan='2' style='width:130px;'>Acciones</th>" +
"</tr></thead>" +
"<tbody></tbody>" +
"</table><br/>");
}
function loadTeaching(idD, route) {
$.getJSON(route, { term: idD }, function (data) {
$.each(data, function (key, val) {
$("#TableidTeaching tbody").append("<tr>" +
"<td>" + val['ape'] + "</td>" +
"<td>" + val['label'] + "</td>" +
"<td><a class='edit' href='/sedoc/DepartmentChief/AssignWork/" + val['id'] + "'>Asignar Jefe</a> </td>" +
"<td><a class='edit' href='/sedoc/DepartmentChief/AssignWork1/" + val['id'] + "'>Editar Jefe</a> </td>" +
"</tr>");
});
});
}
});<file_sep>$(document).ready(function () {
$("#cal").change(function () {
valor = $(this).val();
if (isNaN(valor)) {
$('#dialogErrorRango').dialog("open");
}
else if(valor < 0 || valor > 100) {
$('#dialogErrorRango').dialog("open");
}
});
});
$(function () {
save();
//Cuando el evento click es capturado en el enlace guardar abre el dialogo
function save() {
$('#save').click(function () {
if (validarEntero()) {
$('#dialogSaveAutoEvalaucionConfirm').dialog('open');
}
return false;
});
}
function validarEntero() {
var sonNumeros = true;
$("input.calif").each(function (index) {
var valor = $("#cal").val();
// si el imput no esta vacio
if (valor != "") {
// recupero en valor del input
var numero = parseInt(valor);
//Compruebo si es un valor numérico
if (isNaN(numero)) {
//entonces (no es numero) fijo la variable sonNumeros en falso y salgo del each
sonNumeros = false;
$('#dialogErrorTexto').dialog("open");
return;
} else {
if (numero < 0 || numero > 100) {
//entonces no es un valor valido fijo la variable sonNumeros en falso y salgo del each
sonNumeros = false;
$('#dialogErrorRango').dialog("open");
return;
}
}
}
else {
sonNumeros = false;
$('#dialogValorNulo').dialog("open");
return;
}
});
return sonNumeros;
}
$(function () {
//adiciona los botones en la ventana del diajogo guardar
$("#dialogSaveAutoEvalaucionConfirm").dialog({
resizable: false,
autoOpen: false,
height: 140,
modal: true,
buttons: {
"Guardar": function () {
loadDateTable();
$(this).dialog("close");
},
"Cancelar": function () {
confirmdialog = true;
$(this).dialog("close");
}
}
});
$('#dialogErrorRango').dialog({
autoOpen: false,
width: 400,
height: 200,
modal: true,
buttons: {
"Aceptar": function () {
$(this).dialog("close");
}
}
});
$('#dialogErrorTexto').dialog({
autoOpen: false,
width: 400,
height: 200,
modal: true,
buttons: {
"Aceptar": function () {
$(this).dialog("close");
}
}
});
$('#dialogValorNulo').dialog({
autoOpen: false,
width: 400,
height: 200,
modal: true,
buttons: {
"Aceptar": function () {
$(this).dialog("close");
}
}
});
});
function loadDateTable() {
var iddocente = document.getElementById("search_term").value;
var idlabor = document.getElementById("idLabor").value;
var tipolabor = document.getElementById("tipoLabor").value;
var cal = $("#cal").val();
var PDesc = $("#PDescripcion").val();
var PSol = $("#PSolucion").val();
var RDesc = $("#RDescripcion").val();
var RSol = $("#RSolucion").val();
// //metodo que guarde los datos en la BD
$.getJSON("/sedoc/Teacher/saveAutoevaluacion/",
{ idL: idlabor, idD: iddocente, val: cal, pdes: PDesc, psol: PSol, rdes: RDesc, rsol: RSol },
function (data) {
});
setTimeout(redireccionar, 1000);
}
function resultado(data) {
if (data.respuesta == 0) {
alert("Lo siento!, los datos no se pueden guardar... disculpame");
}
}
function redireccionar() {
var pagina = "/sedoc/Teacher/EvaluarLabor/";
location.href = pagina;
}
});
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcSEDOC.Models
{
public class SubordinatesByWork
{
public int idLabor { get; set; }
public string txtLabor { get; set; }
public string tipoLabor { get; set; }
public List<Subordinate> subordinateList;
public SubordinatesByWork(int idL, string txtL, string tipL, List<Subordinate> sl)
{
this.idLabor = idL;
this.txtLabor = txtL;
this.tipoLabor = tipL;
this.subordinateList = sl;
}
}
public class Subordinate
{
public int idDocente { get; set; }
public int idLabor { get; set; }
public int idEvaluacion { get; set; }
public int puntajeActual { get; set; }
public int evalEstudiante { get; set; }
public int autoEval { get; set; }
public string nombres { get; set; }
public string apellidos { get; set; }
public Subordinate(int idD, int idL, int idE, int punt, int evalE, int autoE, string nom, string ape)
{
this.idDocente = idD;
this.idLabor = idL;
this.idEvaluacion = idE;
this.puntajeActual = punt;
this.evalEstudiante = evalE;
this.autoEval = autoE;
this.nombres = nom;
this.apellidos = ape;
}
}
}<file_sep>$(function () {
var searchVar = "/sedoc/Admin/SearchQuestionnaire/";
var question = $("#pregunta1"),
idgroup = $("#idgrupo"),
allFields = $([]).add(question).add(idgroup),
tips = $(".field-validation-valid");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("El tamaño de " + n + " debe estar entre " +
min + " y " + max + ".");
return false;
} else {
return true;
}
}
$('#dialogEditQuestion').dialog({
autoOpen: false,
width: 400,
height: 300,
modal: true,
buttons: {
"Guardar": function () {
var bValid = true;
allFields.removeClass("ui-state-error");
bValid = bValid && checkLength(question, "pregunta", 3, 150);
if (bValid) {
SaveQuestion("/sedoc/Admin/EditQuestion/", $(this))
}
updateTips("");
$(this).dialog("close");
},
"Cancelar": function () {
allFields.val("").removeClass("ui-state-error");
updateTips("");
$(this).dialog("close");
}
}
});
$("#dialogDeleteQuestionConfirm").dialog({
resizable: false,
autoOpen: false,
height: 140,
modal: true,
buttons: {
"Eliminar": function () {
DeleteQuestion("/sedoc/Admin/DeleteQuestion/", $(this));
},
Cancelar: function () {
allFields.val("").removeClass("ui-state-error");
updateTips("");
$(this).dialog("close");
}
}
});
function DeleteQuestion(route, jquerydialog) {
var idp = $('#idpregunta').val();
if (idp == "") {
alert("La pregunta no puede ser eliminada.");
} else {
var preg = '{ "id": ' + idp + ' }';
var request = $.ajax({
cache: false,
url: route,
type: 'POST',
dataType: 'json',
data: preg,
contentType: 'application/json; charset=utf-8',
success: function (data) {
deletedResponse(data, jquerydialog);
}
});
}
}
function SaveQuestion(route, jquerydialog) {
var question = getQuestion();
if (question == null) {
updateTips("La pregunta no debe ser vacía");
} else {
var request = $.ajax({
cache: false,
url: route,
type: 'POST',
dataType: 'json',
data: question,
contentType: 'application/json; charset=utf-8',
success: function (data) {
savedResponse(data, jquerydialog);
}
});
}
}
function savedResponse(data, jquerydialog) {
if (data.idpregunta != 0) {
$('#lblEdt' + data.idpregunta).html(data.pregunta1);
allFields.val("").removeClass("ui-state-error");
updateTips("");
jquerydialog.dialog("close");
} else {
updateTips("Lo siento!, el registro no se pudo efectuar ... disculpame");
}
}
function deletedResponse(data, jquerydialog) {
if (data.idpregunta != 0) {
$('#btnDel' + data.idpregunta).parent().parent().remove();
jquerydialog.dialog("close");
} else {
alert("Lo siento!, la eliminación no se pudo efectuar ... disculpame");
}
}
function getQuestion() {
var idp = $("#idpregunta").val();
var preg = $("#pregunta1").val();
var idg = $("#idgrupo").val();
return (preg == "" || idp == "" || idg == "") ? null : '{ "idpregunta": "' + idp + '", "pregunta1": "' + preg + '","idgrupo": "' + idg + '" }';
}
function setEditAction(idP, txtP, idG) {
$('#btnEdt' + idP).click(function () {
$('#dialogEditQuestion').dialog('open');
$("#idgrupo").val(idG);
$('#idpregunta').val(idP);
$("#pregunta1").text($('#lblEdt' + idP).html());
return false;
});
$('#btnDel' + idP).click(function () {
$('#dialogDeleteQuestionConfirm').dialog('open');
$('#idpregunta').val(idP);
return false;
});
}
function setQuestionnaireId(ui) {
$("#idQuestionnaire").val(ui.item.id);
$("#work-area").html("");
}
function loadGroups(idQ, route) {
$.getJSON(route, { term: idQ }, function (data) {
$.each(data, function (key, val) {
$("#work-area").append("<table id='TableidGroup" + val['id'] + "' class='list' style='width:100%'>" +
"<thead><tr><th colspan=2>" + val['label'] + "</th></tr>" +
"<tr class='sub'><th>Pregunta</th><th style='width:130px;'>Acción</th></tr></thead>" +
"<tbody></tbody>" +
"</table><br/>");
loadQuestionsFromGroup(val["id"], "/sedoc/Admin/GetQuestionsFromGroup/");
});
});
}
function loadQuestionsFromGroup(idG, route) {
$.getJSON(route, { term: idG }, function (data) {
$.each(data, function (key, val) {
$("#TableidGroup" + idG + " tbody").append("<tr>" +
"<td id='lblEdt" + val['id']+"' >" + val['label'] + "</td>" +
"<td><a href='#' class='edit' id='btnEdt" + val['id'] + "'>Editar</a> |" +
" <a class='delete' href='#' id='btnDel" + val["id"] + "'>Eliminar</a>" +
"</td>" +
"</tr>");
setEditAction(val['id'], val['label'], val['idg']);
});
});
}
$("#search_term").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setQuestionnaireId(ui);
loadGroups(ui.item.id, "/sedoc/Admin/GetQuestionnaireGroups/");
}
}
});
});<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcSEDOC.Models
{
public class Departamento
{
public int iddepartamento;
public string nombre;
public int idfacultad;
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcSEDOC.Models
{
// NUEVO 29
public class ConsolidadoDocente
{
public String nombredocente { get; set; }
public String nombrejefe { get; set; }
public String fechaevaluacion { get; set; }
public Double notafinal { get; set; }
public int periodoanio { get; set; }
public int periodonum { get; set; }
public Double totalhorassemana { get; set; }
public Double totalporcentajes { get; set; }
public String observaciones { get; set; }
public List<ResEvaluacionLabor> evaluacioneslabores { get; set; }
}
public class ResEvaluacionLabor
{
public int idlabor { get; set; }
public String descripcion { get; set; }
public String tipolabor { get; set; }
public String tipolaborcorto { get; set; }
public Double horasxsemana { get; set; }
public Double porcentaje { get; set; }
public Double evalest { get; set; }
public Double evalauto { get; set; }
public Double evaljefe { get; set; }
public Double nota { get; set; }
public Double acumula { get; set; }
}
// FIN NUEVO 29
}<file_sep>$(function () {
/************* VARIABLES *********************/
var searchVar = "/sedoc/Admin/SearchQuestionnaire/";
var iddepto = "search_term";
setAsignacion();
loadTeaching2(iddepto, "/sedoc/Admin/GetAsiganacionPeriodo/");
function setAsignacion() {
$("#work-area").html("");
$("#work-area").append("<form action='/sedoc/Admin/AssignQuestionnaire1' method='post'> <fieldset>" +
"<table id='TableidTeaching' class='list' style='width:100%'>" +
"<thead><tr><th colspan=3 >Labores - Cuestionarios</th></tr>" +
"<tr class='sub'><th ALIGN='CENTER' style='width:30px;'>id</th><th ALIGN='CENTER'>Labor</th><th ALIGN='CENTER'>Cuestionario</th></tr></thead>" +
"<tbody></tbody>" +
"</table><br/>" +
"<p>" +
"<input type='submit' value='Guardar'/>" +
"</p>" +
"</fieldset>");
}
function loadTeaching2(idD, route) {
var cont = -1;
$.getJSON(route, { term: idD }, function (data) {
$.each(data, function (key, val) {
cont = cont + 1;
if (cont == 0 && val == 0) {
$("#TableidTeaching tbody").append("<tr>" +
"<td ALIGN='CENTER' >1 </td>" +
"<td ALIGN='CENTER'>Social</td>" +
"<td ALIGN='CENTER'><input type='hidden' id='idJL1' /><input name='social' id='search_term' /></td>" +
"</tr>");
}
if (cont == 1 && val == 0) {
$("#TableidTeaching tbody").append("<tr>" +
"<td ALIGN='CENTER' >2</td>" +
"<td ALIGN='CENTER'>Gestion</td>" +
"<td ALIGN='CENTER'>" +
"<input name='gestion' id='uno' />" +
"</tr>");
}
if (cont == 2 && val == 0) {
$("#TableidTeaching tbody").append("<tr>" +
"<td ALIGN='CENTER' >3</td>" +
"<td ALIGN='CENTER'>Investigacion</td>" +
"<td ALIGN='CENTER'>" +
"<input name='investigacion' id='cinco' />" +
"</tr>");
}
if (cont == 3 && val == 0) {
$("#TableidTeaching tbody").append("<tr>" +
"<td ALIGN='CENTER' >4</td>" +
"<td ALIGN='CENTER'>Trabajo de Grado</td>" +
"<td ALIGN='CENTER'>" +
"<input name='trabajoG' id='tres' />" +
"</tr>");
}
if (cont == 4 && val == 0) {
$("#TableidTeaching tbody").append("<tr>" +
"<td ALIGN='CENTER' >5</td>" +
"<td ALIGN='CENTER'>Desarrollo Profesoral</td>" +
"<td ALIGN='CENTER'>" +
"<input name='desarrolloP' id='cuatro' />" +
"</tr>");
}
if (cont == 5 && val == 0) {
$("#TableidTeaching tbody").append("<tr>" +
"<td ALIGN='CENTER' >6</td>" +
"<td ALIGN='CENTER'>Trabajo de investigacion</td>" +
"<td ALIGN='CENTER'>" +
"<input name='trabajoI' id='dos' />" +
"</tr>");
}
if (cont == 6 && val == 0) {
$("#TableidTeaching tbody").append("<tr>" +
"<td ALIGN='CENTER' >7</td>" +
"<td ALIGN='CENTER'>Docencia</td>" +
"<td ALIGN='CENTER'>" +
"<input name='docencia' id='siete' />" +
"</tr>");
}
});
autocompleteTeching();
});
}
function autocompleteTeching() {
$("#search_term").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setQuestionnaireId(ui);
}
}
});
$("#uno").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setQuestionnaireId(ui);
}
}
});
$("#dos").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setQuestionnaireId(ui);
}
}
});
$("#tres").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setQuestionnaireId(ui);
}
}
});
$("#cuatro").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setQuestionnaireId(ui);
}
}
});
$("#cinco").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setQuestionnaireId(ui);
}
}
});
$("#seis").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setQuestionnaireId(ui);
}
}
});
$("#siete").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setQuestionnaireId(ui);
}
}
});
}
function setQuestionnaireId(ui) {
$("#idcuestionario").val(ui.item.id);
}
});<file_sep>$(function () {
/************* VARIABLES *********************/
var searchVar = "/sedoc/Admin/SearchQuestionnaire/";
var questionnaireVar = "/sedoc/Admin/GetQuestionnaireGroups/";
var saveVar = "/sedoc/Admin/CreateQuestionnaire/";
var typeQuestionnaire = $("#tipoCuestionario"),
allFields = $([]).add(typeQuestionnaire),
tips = $("#dialog_validation_msg");
/****** Inicializaciones JQuery *******/
$('#dialogCreateQuestionnaire').dialog({
autoOpen: false,
width: 400,
height: 200,
modal: true,
buttons: {
"Crear": function () {
var bValid = true;
allFields.removeClass("ui-state-error");
bValid = bValid && checkLength(typeQuestionnaire, "tipo de Cuestionario", 3, 30);
if (bValid) {
SaveQuestionnaire("/sedoc/Admin/AjaxSetQuestionnaire/", $(this))
}
},
"Cancelar": function () {
allFields.val("").removeClass("ui-state-error");
updateTips("");
$(this).dialog("close");
}
}
});
$('#btnAddQuestionnaire').click(function () {
$('#dialogCreateQuestionnaire').dialog('open');
return false;
});
$("#search_term").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setQuestionnaireId(ui);
}
}
});
/**************** FUNCIONES AUXILIARES *****************/
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("El tamaño de " + n + " debe estar entre " +
min + " y " + max + ".");
return false;
} else {
return true;
}
}
function SaveQuestionnaire(route, jquerydialog) {
var typeQuestionnaire = getQuestionnaire();
if (typeQuestionnaire == null) {
updateTips("El tipo de cuestionario no debe ser vacio");
}
else {
var request = $.ajax({
cache: false,
url: route,
type: 'POST',
dataType: 'json',
data: typeQuestionnaire,
contentType: 'application/json; charset=utf-8',
success: function (data) {
savedResponse(data, jquerydialog);
}
});
}
}
function savedResponse(data, jquerydialog) {
if (data.idcuestionario != 0) {
alert("El cuestionario fue creado con exito");
jquerydialog.dialog("close");
}
else {
updateTips("Ya existe un cuestionario con ese nombre");
}
}
function getQuestionnaire() {
var typeq = $("#tipoCuestionario").val();
return (typeq == "") ? null : '{ "tipocuestionario" : "' + typeq + '"}';
}
function setQuestionnaireId(ui) {
$("#idcuestionario").val(ui.item.id);
}
function loadGroups(idQ, route) {
$.getJSON(route, { term: idQ }, function (data) {
$.each(data, function (key, val) {
$("#work-area").append("<table id='TableidGroup" + val['id'] + "' class='list' style='width:100%'>" +
"<thead><tr><th colspan=3>" + val['label'] + "</th></tr>" +
"<tr class='sub'><th style='width:30px;'>id</th><th>Pregunta</th><th style='width:130px;'>Acción</th></tr></thead>" +
"<tbody></tbody>" +
"</table><br/>");
loadQuestionsFromGroup(val["id"], "/sedoc/Admin/GetQuestionsFromGroup/");
});
});
}
});<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcSEDOC.Models;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Data.OleDb;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
namespace MvcSEDOC.Controllers
{
public class StudentController : Controller
{
// Entidad de acceso a datos (Modelos)
protected SEDOCEntities dbEntity = new SEDOCEntities();
//
// GET: /Student/
public ActionResult Index()
{
return View();
}
public object SessionValue(string keyValue)
{
try
{
return Session[keyValue];
}
catch
{
return RedirectPermanent("/sedoc");
}
}
[Authorize]
public ActionResult listEvaluations()
{
ViewBag.optionmenu = 0;
var usuario = dbEntity.usuario.SingleOrDefault(q => q.emailinstitucional == User.Identity.Name);
int iNumeroEvals = 0;
if (usuario != null)
{
long idUsuario = long.Parse(usuario.identificacion);
int currentper = (int)SessionValue("currentAcadPeriod");
var lstDocentes = (from tr in dbEntity.trabajodegradoinvestigacion
join lab in dbEntity.labor on tr.idlabor equals lab.idlabor
join par in dbEntity.participa on lab.idlabor equals par.idlabor
join eval in dbEntity.evaluacion on par.idevaluacion equals eval.idevaluacion
join doc in dbEntity.docente on par.iddocente equals doc.iddocente
join us in dbEntity.usuario on doc.idusuario equals us.idusuario
where tr.codigoest == idUsuario && lab.idperiodo == currentper
select new DocenteDirector
{
iddocente = doc.iddocente,
idevaluacion = eval.idevaluacion,
idusuario = us.idusuario,
nombres = us.nombres,
apellidos = us.apellidos,
idlabor = lab.idlabor
}).ToList();
ViewBag.Docentes = lstDocentes;
iNumeroEvals = lstDocentes.Count;
}
ViewBag.NumeroEvals = iNumeroEvals;
return View();
}
[Authorize]
public ActionResult ChangePass()
{
int periodoActualSelec = 0;
periodoActualSelec = (int)SessionValue("periodoActual");
if (periodoActualSelec == 1)
{
return RedirectPermanent("/Student/Index");
}
ViewBag.optionmenu = 1;
return View();
}
[Authorize]
public ActionResult ChangePass1()
{
int periodoActualSelec = 0;
periodoActualSelec = (int)SessionValue("periodoActual");
if (periodoActualSelec == 1)
{
return RedirectPermanent("/Student/Index");
}
ViewBag.Value1 = "";
ViewBag.Value2 = "";
ViewBag.Value3 = "";
string anterior = "";
string nueva = "";
string repite = "";
string claveA = "";
int campo1 = 0;
int campo2 = 0;
int campo3 = 0;
//int entradas = 7;
//Boolean entro = false;
//Boolean error = false;
anterior = Request.Form["anterior"];
if (anterior == "")
{
campo1 = 1;
ViewBag.Error1 = "entro";
}
else
{
ViewBag.Value1 = anterior;
}
nueva = Request.Form["nueva"];
if (nueva == "")
{
campo2 = 1;
ViewBag.Error2 = "entro";
}
else
{
ViewBag.Value2 = nueva;
}
repite = Request.Form["repite"];
if (repite == "")
{
campo3 = 1;
ViewBag.Error3 = "entro";
}
else
{
ViewBag.Value3 = repite;
}
ViewBag.optionmenu = 1;
if (campo1 == 1 || campo2 == 1 || campo3 == 1)
{
ViewBag.Error = "Los campos con asterisco son obligatorios";
return View();
}
claveA = AdminController.md5(anterior);
try
{
usuario NuevaContrasena = dbEntity.usuario.Single(u => u.emailinstitucional == User.Identity.Name && u.password == claveA);
if (nueva != repite)
{
ViewBag.Error = "No coinciden la nueva contraseña con la anterior";
return View();
}
else
{
AdminController oControl = new AdminController();
if (!oControl.ActualizarContrasenaUsuarioActual(nueva, anterior))
{
throw new Exception("Invalid Password");
}
nueva = AdminController.md5(nueva);
NuevaContrasena.password = <PASSWORD>;
// dbEntity.usuario.Attach(NuevaContrasena);
dbEntity.ObjectStateManager.ChangeObjectState(NuevaContrasena, EntityState.Modified);
dbEntity.SaveChanges();
ViewBag.Value1 = null;
ViewBag.Value2 = null;
ViewBag.Value3 = null;
ViewBag.Message = "La contraseña se cambio exitosamente";
return View();
}
}
catch
{
ViewBag.Error = "La contraseña anterior es incorrecta";
return View();
}
}
public static int opcionError;
public ActionResult evaluateSubordinates2()
{
if (opcionError == 0)
{
ViewBag.Error = "No hay cuestionario asignado para la evaluación de esta labor";
}
else
{
ViewBag.Error = "La evaluacion de este docente ya se realizo";
}
return View();
}
[Authorize]
public ActionResult evaluateSubordinates1()
{
string laborEntra = Request.Form["labor"];
string usuarioEntra1 = Request.Form["usuario"];
string evaluacionEntra = Request.Form["evaluacion"];
int labor = Convert.ToInt16(laborEntra);
int doce = Convert.ToInt16(usuarioEntra1);
int idE = Convert.ToInt16(evaluacionEntra);
int idlabor = labor;
int iddoce = doce;
int idEva = idE;
int salir = 0;
participa regparticipa = dbEntity.participa.SingleOrDefault(c => c.iddocente == iddoce && c.idlabor == idlabor);
if (regparticipa != null)
{
evaluacion regevaluacion = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == regparticipa.idevaluacion);
if (regevaluacion.evaluacionjefe != -1)
{
salir = 1;
}
}
if (salir == 0)
{
ViewBag.SubByWork2 = idlabor;
ViewBag.SubByWork3 = iddoce;
ViewBag.SubByWork4 = idEva;
int currentper2 = (int)SessionValue("currentAcadPeriod");
var evalDirector = dbEntity.cuestionario.SingleOrDefault(q => q.tipocuestionario == "EvaluacionDirector");
if (evalDirector != null)
{
ViewBag.SubByWork5 = evalDirector.idcuestionario;
// Obtener Cuestionariodocen
var grup_data = dbEntity.grupo
.Join(dbEntity.cuestionario,
grup => grup.idcuestionario,
cues => cues.idcuestionario,
(grup, cues) => new { grupo = grup, cuestionario = cues })
.OrderBy(grup_cues => grup_cues.grupo.orden)
.Where(grup_cues => grup_cues.cuestionario.idcuestionario == evalDirector.idcuestionario)
.Select(l => new { idCuestionario = l.cuestionario.idcuestionario, idGrupo = l.grupo.idgrupo, nombreGrupo = l.grupo.nombre, porcentaje = l.grupo.porcentaje }).ToList();
List<QuestionnaireGroup> l_quesgroup = new List<QuestionnaireGroup>();
for (int i = 0; i < grup_data.Count(); i++)
{
int idG = grup_data.ElementAt(i).idGrupo;
var temp_p = dbEntity.pregunta.Where(l => l.idgrupo == idG).ToList();
List<Question> l_ques = new List<Question>();
for (int j = 0; j < temp_p.Count(); j++)
{
l_ques.Add(new Question((int)temp_p.ElementAt(j).idpregunta, (string)temp_p.ElementAt(j).pregunta1));
}
l_quesgroup.Add(new QuestionnaireGroup((int)grup_data.ElementAt(i).idGrupo, (string)grup_data.ElementAt(i).nombreGrupo, (double)grup_data.ElementAt(i).porcentaje, l_ques));
}
CompleteQuestionnaire compQuest = new CompleteQuestionnaire(1, l_quesgroup);
docente docenteEntra = dbEntity.docente.Single(c => c.iddocente == iddoce);
usuario usuarioEntra = dbEntity.usuario.Single(c => c.idusuario == docenteEntra.idusuario);
ViewBag.SubByWork1 = usuarioEntra.nombres + " " + usuarioEntra.apellidos;
ViewBag.CompQuest = compQuest;
ViewBag.WorkDescription = TeacherController.getLaborDescripcion(idlabor);
return View();
}
else
{
opcionError = 0;
return RedirectPermanent("/sedoc/Student/evaluateSubordinates2");
}
}
opcionError = 1;
return RedirectPermanent("/sedoc/Student/evaluateSubordinates2");
}
[Authorize]
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult UpdateEval(StudentEval myEval)
{
try
{
var averages = myEval.calificaciones.GroupBy(l => l.idgrupo).Select(l => new { idgroup = l.Key, count = l.Count(), average = l.Average(r => r.calificacion) });
var percents = averages
.Join(dbEntity.grupo,
aver => aver.idgroup,
grup => grup.idgrupo,
(aver, grup) => new { grupo = grup, averages = aver })
.Select(l => new { idgrupo = l.grupo.idgrupo, promedio = l.averages.average, porcentaje = l.grupo.porcentaje, score = (l.averages.average * (l.grupo.porcentaje / 100)) });
var totalscore = percents.Sum(c => c.score);
totalscore = System.Math.Round(totalscore, 0);
//verificamos la participacion y q existe la evaluación
participa regparticipa = dbEntity.participa.SingleOrDefault(c => c.iddocente == myEval.iddocente && c.idlabor == myEval.idlabor);
if (regparticipa != null)
{
evaluacion regevaluacion = dbEntity.evaluacion.SingleOrDefault(c => c.idevaluacion == regparticipa.idevaluacion);
regevaluacion.evaluacionestudiante = (int)totalscore; // aqui se supone que el total me da con decimales, pero tengo que redondear
regevaluacion.observaciones += myEval.observaciones + "\n";
dbEntity.SaveChanges();
WorkChiefController oController = new WorkChiefController();
oController.GeneratePdfFile(myEval, Server.MapPath("~/pdfsupport/"), (double)totalscore, "student", myEval.observaciones);
return Json((int)totalscore, JsonRequestBehavior.AllowGet);
}
else
{
return Json(-1, JsonRequestBehavior.AllowGet);
}
}
catch
{
return Json(-1, JsonRequestBehavior.AllowGet);
}
}
}
public class DocenteDirector
{
public string nombres;
public string apellidos;
public long idusuario;
public long iddocente;
public long idevaluacion;
public long idlabor;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcSEDOC.Models
{
public class DocenteDepto
{
public String nombre { get; set; }
public String apellido { get; set; }
public String estado { get; set; }
public int iddetp { get; set; }
public int iddocente { get; set; }
public int idususaio { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcSEDOC.Models
{
public class FacultadPrograma
{
public int codfacultad;
public string nomfacultad;
public int codprograma;
public string nomprograma;
}
}<file_sep>
function loadMaterias(idS, idD, route) {
$.getJSON(route, { term: idS, depa: idD }, function (data) {
// contenido de la tabla
$.each(data, function (key, val) {
$("#Materias" + idS + " tbody").append("<tr>" +
"<td colspan=3>" + val['nombre'] + "</td>" +
"<td><a class='edit' href='/sedoc/Admin/ShowScoresMateria?depa=" + idD + "&tipo=" + val['id'] + "'>Evaluación</a></td>" +
"<td><a class='edit' href='/sedoc/Admin/ShowAutoScoresMateria?depa="+ idD+"&tipo=" + val['id'] + "'>Autoevaluación</a></td>" +
"</tr>");
});
});
}
// carga la cabecera de la tabla
function loadTable(idSemestre, idD) {
ids = idSemestre;
if (idSemestre != 0) {
$("#work-area").html("<table id='Materias" + ids + "' class='list' style='width:100%'>" +
"<thead><tr><th align='center' colspan='3'>Materias Del Semestre " + idSemestre + "</th><th colspan='3'>Acciones</th></tr></thead>" +
"<tbody></tbody>" +
"</table><br/>");
loadMaterias(idSemestre, idD, "/sedoc/Admin/GetMateriasPrograma/");
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcSEDOC.Models
{
public class CompleteQuestionnaire
{
public int idCuestionario { get; set; }
public List<QuestionnaireGroup> listaGrupos { get; set; }
public CompleteQuestionnaire(int idq, List<QuestionnaireGroup> lqg)
{
this.idCuestionario = idq;
this.listaGrupos = lqg;
}
}
public class QuestionnaireGroup
{
public int idGrupo { get; set; }
public string nombre { get; set; }
public double porcentaje { get; set; }
public List<Question> listaPregs { get; set; }
public QuestionnaireGroup(int idg, string nom, double porc, List<Question> lp)
{
this.idGrupo = idg;
this.nombre = nom;
this.porcentaje = porc;
this.listaPregs = lp;
}
}
public class Question
{
public int idPregunta { get; set; }
public string txtPregunta { get; set; }
public Question(int idp, string txtp)
{
this.idPregunta = idp;
this.txtPregunta = txtp;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcSEDOC.Models
{
public class ConsolidadoDocencia
{
public String nombredocente { get; set; }
public String nombrejefe { get; set; }
public String fechaevaluacion { get; set; }
public int periodoanio { get; set; }
public int periodonum { get; set; }
public String observaciones { get; set; }
public List<DetalleDocencia> labDocencia { get; set; }
}
public class DetalleDocencia
{
public int idLabDoc { get; set; }
public String grupo { get; set; }
public String tipo { get; set; }
public int semestre { get; set; }
public int creditos { get; set; }
public int idmateria { get; set; }
public int horassemana { get; set; }
public int semanaslaborales { get; set; }
public String codmateria { get; set; }
public String nombremateria { get; set; }
public int idprograma { get; set; }
public String nombreprograma { get; set; }
public int evaluacionestudiante { get; set; }
public int evaluacionjefe { get; set; }
public int evaluacionautoevaluacion { get; set; }
public String problemadescripcion { get; set; }
public String problemasolucion { get; set; }
public String resultadodescripcion { get; set; }
public String resultadosolucion { get; set; }
}
}<file_sep>$(function () {
var iddepto = document.getElementById("search_term").value;
setDepartament();
loadTeaching(iddepto, "/sedoc/DepartmentChief/GetValueWork/");
function setDepartament() {
$("#work-area").html("");
$("#work-area").append("<table id='TableidTeaching' class='list' style='width:100%'>" +
"<thead><tr align='center'><th colspan=10>Docentes </th></tr>" +
"<tr class='sub'>" +
"<th>Apellidos</th><th>Nombres</th><th>Social</th><th>Gestión</th><th>Inv</th><th>Des. Prof.</th><th>Docencia</th><th>Trabajo Grado</th><th>Trabajo Inv.</th><th>Total</th>" +
"</tr></thead>" +
"<tbody></tbody>" +
"</table><br/>");
}
function loadTeaching(idD, route) {
//si el valor que llega es -1 entonces las siguientes variables toman el valor 'no tiene' para mostrar en pantalla
var social = "";
var gestion = "";
var investigacion = "";
var dProfesoral = "";
var docencia = "";
var trabajoGrado = "";
var total = "";
var trabajoInvestigacion = "";
$.getJSON(route, { term: idD }, function (data) {
$.each(data, function (key, val) {
if (val['social'] == null) { social = "-" } else if (val['social'] == "0") { social = "NC" } else { social = val['social'] }
if (val['gestion'] == null) { gestion = "-" } else if (val['gestion'] == "0") { gestion = "NC" } else { gestion = val['gestion'] }
if (val['investigacion'] == null) { investigacion = "-" } else if (val['investigacion'] == "0") { investigacion = "NC" } else { investigacion = val['investigacion'] }
if (val['dProfesoral'] == "-1") { dProfesoral = "-" } else if (val['dProfesoral'] == "0") { dProfesoral = "NC" } else { dProfesoral = val['dProfesoral'] }
if (val['docencia'] == null) { docencia = "-" } else if (val['docencia'] == "0") { docencia = "NC" } else { docencia = val['docencia'] }
if (val['trabajoGrado'] == "-1") { trabajoGrado = "-" } else if (val['trabajoGrado'] == "0") { trabajoGrado = "NC" } else { trabajoGrado = val['trabajoGrado'] }
if (val['trabajoInvestigacion'] == "-1") { trabajoInvestigacion = "-" } else if (val['trabajoInvestigacion'] == "0") { trabajoInvestigacion = "NC" } else { trabajoInvestigacion = val['trabajoInvestigacion'] }
if (val['total'] == "-1") { total = "-" } else { total = val['total'] }
$("#TableidTeaching tbody").append("<tr>" +
"<td>" + val['apellidos'] + "</td>" +
"<td>" + val['nombres'] + "</td>" +
"<td>" + social + "</td>" +
"<td>" + gestion + "</td>" +
"<td>" + investigacion + "</td>" +
"<td>" + dProfesoral + "</td>" +
"<td>" + docencia + "</td>" +
"<td>" + trabajoGrado + "</td>" +
"<td>" + trabajoInvestigacion + "</td>" +
"<td>" + total + "</td>" +
"</tr>");
});
});
}
});<file_sep>var laboresId;
var idLab;
function setEvaluations() {
if (validarEntero()) {
$('#dialogSaveConfirm').dialog("open");
}
}
function validarEntero() {
var sonNumeros = true;
$("input.calif").each(function (index) {
var valor = $(this).attr("value");
idLab = $(this).attr("idlabor");
// si el imput no esta vacio
if (valor != "") {
// recupero en valor del input
var numero = parseInt(valor);
//Compruebo si es un valor numérico
if (isNaN(numero)) {
//entonces (no es numero) fijo la variable sonNumeros en falso y salgo del each
sonNumeros = false;
$('#dialogErrorTexto').dialog("open");
return;
} else {
if (numero < 0 || numero > 100) {
//entonces no es un valor valido fijo la variable sonNumeros en falso y salgo del each
sonNumeros = false;
$('#dialogErrorRango').dialog("open");
return;
}
}
}
});
return sonNumeros;
}
$(function () {
$('#dialogSaveConfirm').dialog({
autoOpen: false,
width: 400,
height: 200,
modal: true,
buttons: {
"Guardar": function () {
loadDateTable();
$(this).dialog("close");
},
"Cancelar": function () {
$(this).dialog("close");
}
}
});
$('#dialogErrorRango').dialog({
autoOpen: false,
width: 400,
height: 200,
modal: true,
buttons: {
"Aceptar": function () {
$(this).dialog("close");
}
}
});
$('#dialogErrorTexto').dialog({
autoOpen: false,
width: 400,
height: 200,
modal: true,
buttons: {
"Aceptar": function () {
$(this).dialog("close");
}
}
});
});
function loadDateTable() {
var tabla = document.getElementById("LaborTeach");
var numFilas = tabla.rows.length;
for (i = 0; i < numFilas - 2; i++) {
var idLabor = idLab;
var idDocente = document.getElementById("iddocente").value;
var valor = document.getElementById("input" + idLabor).value;
//metodo que guarde los datos en la BD
$.getJSON("/sedoc/Teacher/saveEval/", { idL: idLabor, idD: idDocente, val: valor }, function (data) {
if (i == numFilas - 2) {
setTimeout(redireccionar, 1000);
}
});
}
}
function redireccionar() {
//var iddocente = document.getElementById("search_term").value;
var pagina = "/sedoc/Teacher/index/";
location.href = pagina;
}
<file_sep>var docenteSelected;
function openDialog(valor) {
docenteSelected = valor;
$("#dialogUpDateDepartmentChief").dialog('open');
}
function prueba(id) {
alert(id);
}
var searchVar = "/sedoc/AdminFac/SearchDepartment/";
var nameDept, iddept, idCurrentPeriod, chiefId;
// fija el id y el nombre del departamento
function setDepartment(ui) {
nameDept = ui.item.label; // nombre del departamento
iddept = ui.item.id; // id del departamento
}
function loadTeachers(idD, route) {
$.getJSON(route, { term: idD }, function (data) {
// contenido de la tabla
$.each(data, function (key, val) {
var checked = "";
if (val["id"] == chiefId) {
checked = "checked";
}
$("#TeachersFrom" + idD + " tbody").append("<tr>" +
"<td>" + val['apellidos'] + "</td>" +
"<td>" + val['nombres'] + "</td>" +
"<td align='center'> <input type= 'radio' name='group1' id='" + val['id'] + "' " + checked + " onClick='openDialog(this.id)' /></td>" +
"</tr>");
});
});
}
// obtiene el actual jefe de ese departamento
function getCurrentDepartmentChief(route) {
var strDepto = '{"iddepartamento": ' + iddept + ' }';
$.ajax({
cache: false,
url: route,
type: 'Post',
dataType: 'json',
data: strDepto,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data == null) {
chiefId = -1;
} else {
chiefId = data.iddocente;
}
loadTeachers(iddept, "/sedoc/AdminFac/GetTeachersFromDepartment1/");
}
});
}
// carga la cabecera de la tabla
function loadTable(idDepartamento) {
iddept = idDepartamento;
if (idDepartamento != 0) {
nameDept = $("#dep" + iddept).attr("depname");
$("#work-area").html("<table id='TeachersFrom" + iddept + "' class='list' style='width:100%'>" +
"<thead><tr><th align='center' colspan=3>Docentes del departamento de " + nameDept + "</th></tr>" +
"<tr class='sub'><th>Apellidos</th><th>Nombres</th><th align='center' style='width:160px;'>Jefe de Departamento</th></tr></thead>" +
"<tbody></tbody>" +
"</table><br/>");
getCurrentDepartmentChief("/sedoc/AdminFac/GetCurrentDepartmentChief/");
}
}
// obtiene el ultimo periodo academico
function getLastAcademicPeriod(route) {
$.ajax({
cache: false,
url: route,
type: 'Post',
dataType: 'json',
data: null,
contentType: 'application/json; charset=utf-8',
success: function (data) {
idCurrentPeriod = data.idperiodo;
getCurrentDepartmentChief("/sedoc/AdminFac/GetCurrentDepartmentChief/");
}
});
}
// actualiza el jefe del departamento
function updateCurrentChief(route) {
var worksValue = 1;
if ($('input[id$="chkDocencia"]').is(':checked')) worksValue = worksValue * 3;
if ($('input[id$="chkDesarrollo"]').is(':checked')) worksValue = worksValue * 5;
if ($('input[id$="chkTrabajoGradoInv"]').is(':checked')) worksValue = worksValue * 7;
if ($('input[id$="chkTrabajoGrado"]').is(':checked')) worksValue = worksValue * 11;
if ($('input[id$="chkInvestigacion"]').is(':checked')) worksValue = worksValue * 13;
if ($('input[id$="chkGestion"]').is(':checked')) worksValue = worksValue * 17;
if ($('input[id$="chkSocial"]').is(':checked')) worksValue = worksValue * 19;
if ($('input[id$="chkOtras"]').is(':checked')) worksValue = worksValue * 23;
var param = '{ "idDepartamento": ' + iddept + ', "idDocentAct": ' + chiefId + ', "idDocentNue": ' + docenteSelected + ', "laboresCalc": ' + worksValue + '}';
$.ajax({
cache: false,
url: route,
type: 'POST',
dataType: 'json',
data: param,
contentType: 'application/json; charset=utf-8',
success: function (data) {
iddept = data.iddepartamento;
chiefId = data.iddocente;
idCurrentPeriod = data.idperiodo;
}
});
}
$(function () {
/* Buscar departamento*/
$("#search_department").autocomplete({
source: searchVar,
minLength: 1,
select: function (event, ui) {
if (ui.item) {
setDepartment(ui);
loadTable(ui.item.id);
}
}
});
// dialogo para confirmar el cambio de jefe de departamento
$("#dialogUpDateDepartmentChief").dialog({
resizable: false,
autoOpen: false,
height: 140,
modal: true,
buttons: {
"Cambiar": function () {
updateCurrentChief("/sedoc/AdminFac/UpdateCurrentChief/");
$(this).dialog("close");
},
"Cancelar": function () {
if (chiefId == -1) {
document.getElementById(docenteSelected).checked = false;
} else {
document.getElementById(chiefId).checked = true;
}
$(this).dialog("close");
}
}
});
});<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MvcSEDOC.Models
{
public class SpreadsheetModelAE
{
public String fileName { get; set; }
public String[,] labores { get; set; }
public string nombredocente { get; set; }
public string nombrejefe { get; set; }
public string fechaevaluacion { get; set; }
public string periodo { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcSEDOC.Models;
namespace MvcSEDOC.Controllers
{
public class SEDOCController : Controller
{
// Entidad de acceso a datos (Modelos)
protected SEDOCEntities dbEntity = new SEDOCEntities();
[Authorize]
public ActionResult JsonGetLastAcademicPeriod()
{
var maxYear = (from pa in dbEntity.periodo_academico
select pa.anio).Max();
var maxPeriodNumber = (from pa in dbEntity.periodo_academico
where pa.anio == maxYear
select pa.numeroperiodo).Max();
var response = dbEntity.periodo_academico.Single(q => q.anio == maxYear && q.numeroperiodo == maxPeriodNumber);
return Json(response, JsonRequestBehavior.AllowGet);
}
public periodo_academico GetLastAcademicPeriod()
{
var maxYear = (from pa in dbEntity.periodo_academico
select pa.anio).Max();
var maxPeriodNumber = (from pa in dbEntity.periodo_academico
where pa.anio == maxYear
select pa.numeroperiodo).Max();
periodo_academico lastper = dbEntity.periodo_academico.Single(q => q.anio == maxYear && q.numeroperiodo == maxPeriodNumber);
return lastper;
}
//ADICIONADO
public periodo_academico GetAcademicPeriod(int id)
{
periodo_academico lastper = dbEntity.periodo_academico.Single(q => q.idperiodo == id );
return lastper;
}
public int get_id_from_identification(string identification) {
var response = dbEntity.usuario.SingleOrDefault(l => l.identificacion == identification);
if (response != null) {
return response.idusuario;
}
else {
return 0;
}
}
public int GetIdDocenteByIdentification(string identification) {
int idusu = get_id_from_identification(identification);
docente undocente = dbEntity.docente.SingleOrDefault(q => q.idusuario == idusu);
return undocente.iddocente;
}
public usuario get_user_by_email(string email)
{
usuario response = dbEntity.usuario.SingleOrDefault(l => l.emailinstitucional == email);
return response;
}
// TODO: retorna el id del departamento segun el nombre, sino existe crea uno nuevo
public int getIdDeptoByName(string p)
{
departamento undepto = dbEntity.departamento.SingleOrDefault(q => q.nombre.ToLower() == p.ToLower());
if (undepto == null) {
undepto = new departamento() { nombre = p };
dbEntity.departamento.AddObject(undepto);
dbEntity.SaveChanges();
return undepto.iddepartamento;
}
else {
return undepto.iddepartamento;
}
}
// TODO: retorna el id del programa segun el nombre, sino existe crea uno nuevo
public int GetIdProgramaByName(string nomprog)
{
programa unprograma = dbEntity.programa.SingleOrDefault(q => q.nombreprograma.ToLower() == nomprog.ToLower());
if (unprograma == null) {
unprograma = new programa() { nombreprograma = nomprog };
dbEntity.programa.AddObject(unprograma);
dbEntity.SaveChanges();
return unprograma.idprograma;
}
else {
return unprograma.idprograma;
}
}
}
}
| ce5b98030e96731c20a015d47182aa7328adf4be | [
"JavaScript",
"C#"
] | 46 | JavaScript | alejo491/gpa-si-fiet-unicauca | b65f4c5d9cb681511197bb4bebf316e819960065 | ba173402946aec0e13cc63442290711ae742d2c0 |
refs/heads/master | <repo_name>JonnhyGarcia/Control_de_versiones<file_sep>/Documentos_GitHub/DiplomadoSE2018-master/LEDs/main_Bitfild_And_structs.c
/*
* Copyright (c) 2016, NXP Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of NXP Semiconductor, Inc. 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.
*/
/**
* @file LEDsAndBitfield.c
* @brief Application entry point.
*/
#include <stdio.h>
#include "DataTypeDefinitions.h"
#include "MK64F12.h"
#define ALL_BIT_ON 0xFF
/**This is a prototype function to create a delay using a for-loop*/
void delay(uint16 delay);
int main(void) {
/**Declaration of a bitfield*/
typedef union
{
uint8 allBits;
struct{
uint8 bit0 :3;
uint8 bit1 :1;
uint8 bit2 :1;
uint8 bit3 :1;
uint8 bit4 :1;
uint8 bit5 :1;
}bitField;
} myData;
/**Variable declaration of myData type*/
myData portDBits = {0};
/**Activating the GPIOB and GPIOE clock gating*/
SIM->SCGC5 = 0x1200;
/**Pin control configuration of GPIOD pin0 and pin6 as GPIO by using a special macro contained in Kinetis studio in the MK64F12. h file*/
PORTD->PCR[0] = PORT_PCR_MUX(1);
PORTD->PCR[1] = PORT_PCR_MUX(1);
PORTD->PCR[2] = PORT_PCR_MUX(1);
PORTD->PCR[3] = PORT_PCR_MUX(1);
PORTD->PCR[4] = PORT_PCR_MUX(1);
PORTD->PCR[5] = PORT_PCR_MUX(1);
/**GPIOA pin control configuration*/
PORTA->PCR[1] = PORT_PCR_MUX(1)|0x03;
/**Assigns a safe value to the output pin21 of the GPIOB*/
GPIOD->PDOR =0x00;
/**Configures GPIOD pin0-pin5 as output*/
GPIOD->PDDR =0x3F;
/**Configures GPIOA pin4 as output*/
GPIOA->PDDR =0;
while(1) {
/**Assigns all the bitfield*/
portDBits.allBits = ALL_BIT_ON;
GPIOD->PDOR = portDBits.allBits;
delay(65000);
/**Assigns only one bit in the bitfield*/
portDBits.bitField.bit0 = 0;
/**Assigns all the bitfield to the GPIOD output port*/
GPIOD->PDOR = portDBits.allBits;
delay(65000);
portDBits.bitField.bit1 = BIT_OFF;
GPIOD->PDOR = portDBits.allBits;
delay(65000);
portDBits.bitField.bit2 = BIT_OFF;
GPIOD->PDOR = portDBits.allBits;
delay(65000);
portDBits.bitField.bit3 = BIT_OFF;
GPIOD->PDOR = portDBits.allBits;
delay(65000);
portDBits.bitField.bit4 = BIT_OFF;
GPIOD->PDOR = portDBits.allBits;
delay(65000);
portDBits.bitField.bit5 = BIT_OFF;
GPIOD->PDOR = portDBits.allBits;
delay(65000);
}
return 0 ;
}
////////////////////////////////////////////////////////////////////////////////
// EOF
////////////////////////////////////////////////////////////////////////////////
void delay(uint16 delay)
{
volatile uint16 counter;
for(counter=delay; counter > 0; counter--)
{
}
}
<file_sep>/Documentos_GitHub/DiplomadoSE2018-master/LEDs/main.c
/*
* Copyright (c) 2016, NXP Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of NXP Semiconductor, Inc. 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.
*/
/**
* @file PushButton.c
* @brief Application entry point.
*/
#include "DataTypeDefinitions.h"
#include "MK64F12.h"
void delay(uint16 delay);
/*
* @brief Application entry point.
*/
int main(void) {
/**Variable to capture the input value*/
uint32 inputValue = 0;
/**Activating the GPIOB, GPIOC and GPIOE clock gating*/
SIM->SCGC5 = 0x2C00;
/**Pin control configuration of GPIOB pin22 and pin21 as GPIO*/
PORTB->PCR[21] = 0x00000100;
PORTB->PCR[22] = 0x00000100;
/**Pin control configuration of GPIOC pin6 as GPIO with is pull-up resistor enabled*/
PORTC->PCR[6] = 0x00000103;
/**Pin control configuration of GPIOE pin26 as GPIO*/
PORTE->PCR[26] = 0x00000100;
/**Assigns a safe value to the output pin21 of the GPIOB*/
GPIOB->PDOR = 0x00200000;
/**Assigns a safe value to the output pin22 of the GPIOB*/
GPIOB->PDOR |= 0x00400000;
/**Assigns a safe value to the output pin26 of the GPIOE*/
GPIOE->PDOR |= 0x04000000;
GPIOC->PDDR &=~(0x40);
/**Configures GPIOB pin21 as output*/
GPIOB->PDDR = 0x00200000;
/**Configures GPIOB pin22 as output*/
GPIOB->PDDR |= 0x00400000;
/**Configures GPIOE pin26 as output*/
GPIOE->PDDR |= 0x04000000;
while(1) {
/**Reads all the GPIOC*/
inputValue = GPIOC->PDIR;
/**Masks the GPIOC in the bit of interest*/
inputValue = inputValue & 0x40;
/**Note that the comparison is not inputValur == False, because it is safer if we switch the arguments*/
if(FALSE == inputValue)
{
GPIOB->PDOR |= 0x00200000;/**Blue led off*/
delay(65000);
GPIOB->PDOR |= 0x00400000;/**Read led off*/
delay(65000);
GPIOE->PDOR |= 0x4000000;/**Green led off*/
delay(65000);
GPIOB->PDOR &= ~(0x00200000);/**Blue led on*/
delay(65000);
GPIOB->PDOR &= ~(0x00400000);/**Read led on*/
delay(65000);
GPIOE->PDOR &= ~(0x4000000);/**Green led on*/
delay(65000);
GPIOB->PDOR |= 0x00200000;/**Blue led off*/
delay(65000);
GPIOB->PDOR |= 0x00400000;/**Read led off*/
delay(65000);
GPIOE->PDOR |= 0x4000000;/**Green led off*/
delay(65000);
}
}
return 0 ;
}
////////////////////////////////////////////////////////////////////////////////
// EOF
////////////////////////////////////////////////////////////////////////////////
void delay(uint16 delay)
{
volatile uint16 counter;
for(counter=delay; counter > 0; counter--)
{
}
}
<file_sep>/Documentos_GitHub/DiplomadoSE2018-master/LEDs/LEDs/.metadata/version.ini
#Fri Aug 17 11:38:56 CDT 2018
org.eclipse.core.runtime=2
org.eclipse.platform=4.7.3.v20180330-0640
<file_sep>/Documentos_GitHub/DiplomadoSE2018-master/LEDs/main_3_Leds.c
/*
* Copyright (c) 2016, NXP Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of NXP Semiconductor, Inc. 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.
*/
/**
* @file ThreeLEDs.c
* @brief Application entry point.
*/
#include <stdio.h>
#include "MK64F12.h"
#include "DataTypeDefinitions.h"
void delay(uint16 delay);
/*
* @brief Application entry point.
*/
int main(void) {
/**Activating the GPIOB and GPIOE clock gating*/
SIM->SCGC5 = 0x2400;
/**Pin control configuration of GPIOB pin22 and pin21 as GPIO*/
PORTB->PCR[21] = 0x00000100;
PORTB->PCR[22] = 0x00000100;
PORTE->PCR[26] = 0x00000100;
/**Assigns a safe value to the output pin21 of the GPIOB*/
GPIOB->PDOR = 0x00200000;
/**Assigns a safe value to the output pin22 of the GPIOB*/
GPIOB->PDOR |= 0x00400000;
/**Assigns a safe value to the output pin26 of the GPIOE*/
GPIOE->PDOR |= 0x04000000;
/**Configures GPIOB pin21 as output*/
GPIOB->PDDR = 0x00200000;
/**Configures GPIOB pin22 as output*/
GPIOB->PDDR |= 0x00400000;
/**Configures GPIOE pin26 as output*/
GPIOE->PDDR |= 0x04000000;
while(1) {
GPIOB->PDOR |= 0x00200000;/**Blue led off*/
delay(65000);
GPIOB->PDOR |= 0x00400000;/**Read led off*/
delay(65000);
GPIOE->PDOR |= 0x4000000;/**Green led off*/
delay(65000);
GPIOB->PDOR &= ~(0x00200000);/**Blue led on*/
delay(65000);
GPIOB->PDOR &= ~(0x00400000);/**Read led on*/
delay(65000);
GPIOE->PDOR &= ~(0x4000000);/**Green led on*/
delay(65000);
GPIOB->PDOR |= 0x00200000;/**Blue led off*/
delay(65000);
GPIOB->PDOR |= 0x00400000;/**Read led off*/
delay(65000);
GPIOE->PDOR |= 0x4000000;/**Green led off*/
delay(65000);
/**---------------------------------------------------*/
/**---------------------------------------------------*/
__NOP();/** THIS a assembly macro*/
}
return 0 ;
}
////////////////////////////////////////////////////////////////////////////////
// EOF
////////////////////////////////////////////////////////////////////////////////
void delay(uint16 delay)
{
volatile uint16 counter;
for(counter=delay; counter > 0; counter--)
{
}
}
<file_sep>/Documentos_GitHub/DiplomadoSE2018-master/LEDs/LEDs/LEDs_Intr/source/main.c
#include <LEDs_and_SWs.h>
#include <stdio.h>
#include "board.h"
#include "peripherals.h"
#include "pin_mux.h"
#include "clock_config.h"
#include "MK64F12.h"
#include "fsl_debug_console.h"
extern uint8_t Flag_sw3;
extern uint8_t Flag_sw2;
int main(void) {
BOARD_InitBootPins();
while(1) {
if(TRUE == Flag_sw3)
{
Led_green_on_off(LED_ON);
Flag_sw3 = FALSE;
}
else if(TRUE == Flag_sw2)
{
Led_green_on_off(LED_OFF);
Flag_sw2 = FALSE;
}
}
return 0 ;
}
<file_sep>/Documentos_GitHub/DiplomadoSE2018-master/LEDs/LEDs/LEDs_Intr/source/LEDs_and_SWs.h
#ifndef LEDS_AND_SWS_H_
#define LEDS_AND_SWS_H_
#include <stdint.h>
#define LED_ON (1u)
#define LED_OFF (0u)
#define SW3 (1u)
#define SW2 (0u)
#define SW3_BIT_NUMBER (4u)
#define SW2_BIT_NUMBER (6u)
#define CLEAR_PIN (5u)
#define RED_LED_BIT (22u)
#define BLUE_LED_BIT (21u)
#define GREEN_LED_BIT (26u)
typedef enum
{
FALSE,
TRUE
} Boolean_t;
void Led_green_on_off(uint8_t on_off);
void Led_yellow_on_off(uint8_t on_off);
void Led_white_on_off(uint8_t on_off);
void Led_red_on_off(uint8_t on_off);
void Led_blue_on_off(uint8_t on_off);
uint8_t SW_read_pin(uint8_t switch_number);
#endif /* LEDS_AND_SWS_H_ */
<file_sep>/Documentos_GitHub/DiplomadoSE2018-master/PTRs/PTRs/Switch_Case/source/main.c
#include <LEDs_and_SWs.h>
#include <stdio.h>
#include "board.h"
#include "peripherals.h"
#include "pin_mux.h"
#include "clock_config.h"
#include "MK64F12.h"
#include "fsl_debug_console.h"
int main(void) {
Colors_t color_selector = RED;
BOARD_InitBootPins();
while(1) {
color_selector = Color_get_next_color();
switch (color_selector) {
case RED:
Color_Red();
break;
case BLUE:
Color_Blue();
break;
case GREEN:
Color_Green();
break;
case YELLOW:
Color_yellow();
break;
case WHITE:
Color_white();
break;
default:
Color_OFF();
break;
}
}
return 0 ;
}
<file_sep>/Documentos_GitHub/DiplomadoSE2018-master/PTRs/PTRs/.metadata/version.ini
#Fri Aug 17 20:54:39 CDT 2018
org.eclipse.core.runtime=2
org.eclipse.platform=4.7.3.v20180330-0640
<file_sep>/Documentos_GitHub/DiplomadoSE2018-master/LEDs/LEDs/Arrays/source/Arrays.c
#include <stdio.h>
#include "board.h"
#include "peripherals.h"
#include "pin_mux.h"
#include "clock_config.h"
#include "MK64F12.h"
#include "fsl_debug_console.h"
/* TODO: insert other include files here. */
#define VECTOR_SIZE 10
const uint8_t Vector1[VECTOR_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
const uint8_t Vector2[VECTOR_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int main(void) {
/* Init board hardware. */
BOARD_InitBootPins();
BOARD_InitBootClocks();
BOARD_InitBootPeripherals();
/* Init FSL debug console. */
BOARD_InitDebugConsole();
PRINTF("Hello World\n");
/* Force the counter to be placed into memory. */
volatile static int i = 0 ;
/* Enter an infinite loop, just incrementing a counter. */
while(1) {
i++ ;
}
return 0 ;
}
| 1d05709841b42999c2358a9125cde15de822eab8 | [
"C",
"INI"
] | 9 | C | JonnhyGarcia/Control_de_versiones | 3774aa2d41b21c33c116194a6ad8eb0f74e687cf | 8a5fe6aad4cb2d34ad4e4e9da00cf7e779a0d899 |
refs/heads/master | <repo_name>laidayong/spring-cloud-study<file_sep>/microservice-consumer-movie-feign/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>
<artifactId>microservice-consumer-movie-feign</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>com.itmuch.cloud</groupId>
<artifactId>spring-cloud-microservice-study</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- added by dayong -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java-util</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.protobuf-java-format</groupId>
<artifactId>protobuf-java-format</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
<file_sep>/README.md
| 项目名称 | 端口 | 描述 | URL |
| ---------------------------------------- | ---- | ---------------------- | --------------- |
| microservice-discovery-eureka | 8761/8762 | 注册中心 | / |
| microservice-consumer-movie-feign | 8020 | 服务client | /feign/1 |
| microservice-provider-user | 8000 | 服务提供者 | /1 |
1. 环境准备:为了在一台机器上测试 eureka HA,
增加
127.0.0.1 peer1 peer2
到测试机的 HOSTS 文件里
2. 构建系统:在根目录运行在根目录运行 maven clean install
3. 系统启动
3.1 启动两个eureka注册中心
java -jar microservice-discovery-eureka/target/microservice-discovery-eureka-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer1
java -jar microservice-discovery-eureka/target/microservice-discovery-eureka-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer2
注册中心通过如下url查看
http://localhost:8761/
http://localhost:8762/
3.2 启动服务提供者 (原例子使用JPA, 增加了使用MyBastis的例子)
java -jar microservice-provider-user/target/microservice-provider-user-0.0.1-SNAPSHOT.jar
注:如果希望启动多个provider, 参见 注册中心 的配置文件,增加profile
3.3 启动服务使用者 (原例子有rest service的例子, 增加了web page例子, 以及log,feign client的配置)
java -jar microservice-consumer-movie-feign/target/microservice-consumer-movie-feign-0.0.1-SNAPSHOT.jar
测试url
http://localhost:8020/feign/1
http://localhost:8020/greeting?id=2<file_sep>/microservice-provider-user/src/main/java/com/chinaubi/mapper/UserMapper.java
package com.chinaubi.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.itmuch.cloud.study.domain.User;
public interface UserMapper {
@Select("SELECT * FROM user")
List<User> getAll();
}
<file_sep>/microservice-consumer-movie-feign/protoTest.py
import urllib.request, urllib.parse, urllib.error
import socket
import employee_pb2
if __name__ == '__main__':
employee = employee_pb2.Employee()
employee_read = urllib.request.urlopen('http://localhost:8020/getEmployee').read()
employee.ParseFromString(employee_read)
print(employee)
try:
details = employee.SerializeToString()
url = urllib.request.Request('http://localhost:8020/createEmployee', details)
url.add_header("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.29 Safari/525.13")
url.add_header("Content-Type", "application/x-protobuf")
responseData = urllib.request.urlopen(url).read().decode('utf8', 'ignore')
responseFail = False
except urllib.error.HTTPError as e:
responseData = e.read().decode('utf8', 'ignore')
responseFail = False
except urllib.error.URLError:
responseFail = True
except socket.error:
responseFail = True
except socket.timeout:
responseFail = True
except UnicodeEncodeError:
print("[x] Encoding Error")
responseFail = True
print(responseData) | 5ca39b8e0ec9937ba745756d973fabccdc552342 | [
"Markdown",
"Java",
"Python",
"Maven POM"
] | 4 | Maven POM | laidayong/spring-cloud-study | fa32bdd5a2256ba6a2322a43b778381445b63eeb | f37249177278ab4340d409c85df6c6d10c8659b1 |
refs/heads/master | <repo_name>jekyun-park/git_begin<file_sep>/kawibawibo.py
import random
# 2016003718
def main():
com_finger = random.randrange(3) + 1
for i in range(10):
my_finger = int(input("가위(1), 바위(2), 보(3)를 입력하세요. : "))
while not(my_finger == 1 or my_finger == 2 or my_finger ==3):
my_finger = int(input("가위(1), 바위(2), 보(3)를 입력하세요. : "))
if(com_finger == 1):
if(my_finger == 1):
print("컴퓨터는 가위를 냈습니다 => 비김~")
elif(my_finger == 2):
print("컴퓨터는 가위를 냈습니다 => 이김~")
elif(my_finger == 3):
print("컴퓨터는 가위를 냈습니다 => 짐~")
elif(com_finger == 2):
if(my_finger == 1):
print("컴퓨터는 바위를 냈습니다 => 짐~")
elif(my_finger == 2):
print("컴퓨터는 바위를 냈습니다 => 비김~")
elif(my_finger == 3):
print("컴퓨터는 바위를 냈습니다 => 이김~")
elif(com_finger == 3):
if(my_finger == 1):
print("컴퓨터는 보를 냈습니다 => 이김~")
elif(my_finger == 2):
print("컴퓨터는 보를 냈습니다 => 짐~")
elif(my_finger == 3):
print("컴퓨터는 보를 냈습니다 => 비김~")
main()
| e6bfa20c382d54b2005baa681ef791dc3193949d | [
"Python"
] | 1 | Python | jekyun-park/git_begin | f6abc866c2ba2cd40141a4dbedfc633d243ad0b7 | c838dfed7260d0a3166b945c1007b65cd24c30bb |
refs/heads/master | <repo_name>peiwangboston/flashcard<file_sep>/ClozeCard.js
var BasicCard = require ("./BasicCard");
var ClozeCard = function (text, cloze) {
this.text = text;
this.cloze = cloze;
this.fullText = function() {
console.log(this.text);
};
this.partial = function () {
if (this.text.replace(this.cloze,"...") === this.text) {
console.log(this.cloze + " does not appear in " + this.text);
}
else {
var newText = this.text.replace(this.cloze, "...");
console.log(newText);
}
};
};
var firstPresident = new BasicCard(
"Who was the first president of the United States?", "<NAME>");
console.log(firstPresident.front);
console.log(firstPresident.back);
var firstPresidentCloze = new ClozeCard(
"<NAME> was the first president of the United States.", "<NAME>");
console.log(firstPresidentCloze.cloze);
firstPresidentCloze.partial();
firstPresidentCloze.fullText();
var brokenCloze = new ClozeCard("This doesn't work", "oops");
brokenCloze.partial();
module.exports = ClozeCard; | 3dc57b44a46c4312c808c7f0bc26530d2fce1895 | [
"JavaScript"
] | 1 | JavaScript | peiwangboston/flashcard | b3849a9b79481cc30412865ca21d56fd07d6ff6a | 275bdda6e166ce80d2e891319696342bbd263ee5 |
refs/heads/master | <file_sep>#!/bin/bash
size= df -h|awk '{print $5}'
if [ $(size) -ge 20 ]
echo "size is $size more than 20"
| be8cd43eec1486eb94ac56973a313805ca1cbf1d | [
"Shell"
] | 1 | Shell | sanmahi/myown | 4995f60eb1de08017d185f7b524670d63ff3af4f | 95f221da7c69517fd0bd45ff6ab2bb93f94e5267 |
refs/heads/master | <repo_name>scloudrun/util<file_sep>/type_conv_test.go
//
// type_conv_test.go
//
// Distributed under terms of the MIT license.
//
package util
import (
"reflect"
"testing"
)
func TestInt64(t *testing.T) {
type args struct {
val interface{}
}
tests := []struct {
name string
args args
want int64
}{
{
name: "TestInt64",
args: args{
val: `1`,
},
want: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Int64(tt.args.val); got != tt.want {
t.Errorf("Int64() = %v, want %v", got, tt.want)
}
})
}
}
func Test_int64ToBytes(t *testing.T) {
type args struct {
v int64
}
tests := []struct {
name string
args args
want []byte
}{
{
name: "TestInt64",
args: args{
v: 64,
},
want: []byte{54, 52},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := int64ToBytes(tt.args.v); !reflect.DeepEqual(got, tt.want) {
t.Errorf("int64ToBytes() = %v, want %v", got, tt.want)
}
})
}
}
func TestUint64(t *testing.T) {
type args struct {
val interface{}
}
tests := []struct {
name string
args args
want uint64
}{
{
name: "TestInt64",
args: args{
val: `1`,
},
want: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Uint64(tt.args.val); got != tt.want {
t.Errorf("Uint64() = %v, want %v", got, tt.want)
}
})
}
}
func TestFloat64(t *testing.T) {
type args struct {
val interface{}
}
tests := []struct {
name string
args args
want float64
}{
{
name: "TestInt64",
args: args{
val: `1`,
},
want: 1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Float64(tt.args.val); got != tt.want {
t.Errorf("Float64() = %v, want %v", got, tt.want)
}
})
}
}
func TestBytes(t *testing.T) {
type args struct {
val interface{}
}
tests := []struct {
name string
args args
want []byte
}{
{
name: "TestInt64",
args: args{
val: `1`,
},
want: []byte{49},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Bytes(tt.args.val); !reflect.DeepEqual(got, tt.want) {
t.Errorf("Bytes() = %v, want %v", got, tt.want)
}
})
}
}
func TestString(t *testing.T) {
type args struct {
val interface{}
}
tests := []struct {
name string
args args
want string
}{
{
name: "TestInt64",
args: args{
val: []byte{54},
},
want: "6",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := String(tt.args.val); got != tt.want {
t.Errorf("String() = %v, want %v", got, tt.want)
}
})
}
}
func TestBool(t *testing.T) {
type args struct {
value interface{}
}
tests := []struct {
name string
args args
want bool
}{
{
name: "TestInt64",
args: args{
value: `1`,
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Bool(tt.args.value); got != tt.want {
t.Errorf("Bool() = %v, want %v", got, tt.want)
}
})
}
}
<file_sep>/README.md
# util
`util` golang Universal tool kit
## Installation
Use [`go get`](https://golang.org/cmd/go/#hdr-Download_and_install_packages_and_dependencies) to install and update:
```sh
$ go get -u github.com/scloudrun/util
```
## Quick start
```sh
# assume the following codes in example.go file
$ cat example.go
```
```go
package main
import "github.com/scloudrun/util"
func main() {
fmt.Println(util.Md5("util"))
fmt.Println(util.Int64("1234"))
}
```
```
# run example.go
$ go run example.go
```
## Todo
- go test
- extend
<file_sep>/enc.go
//
// enc.go
//
// Distributed under terms of the MIT license.
//
package util
import (
"crypto/md5"
"fmt"
"hash/crc32"
"hash/crc64"
)
func Md5(str string) (res string) {
aMd5 := md5.New()
aMd5.Write([]byte(str))
res = fmt.Sprintf("%x", aMd5.Sum(nil))
return
}
func Crc32(str string) uint32 {
table := crc32.MakeTable(crc32.IEEE)
return crc32.Checksum([]byte(str), table)
}
func Crc64(str string) uint64 {
table := crc64.MakeTable(crc64.ECMA)
return crc64.Checksum([]byte(str), table)
}
<file_sep>/ip.go
//
// ip.go
//
// Distributed under terms of the MIT license.
//
package util
import (
"encoding/binary"
"net"
"regexp"
"strconv"
)
func IP2Long(ipstr string) (ip uint32) {
r := `^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})`
reg, err := regexp.Compile(r)
if err != nil {
return
}
ips := reg.FindStringSubmatch(ipstr)
if ips == nil {
return
}
ip1, _ := strconv.Atoi(ips[1])
ip2, _ := strconv.Atoi(ips[2])
ip3, _ := strconv.Atoi(ips[3])
ip4, _ := strconv.Atoi(ips[4])
if ip1 > 255 || ip2 > 255 || ip3 > 255 || ip4 > 255 {
return
}
ip += uint32(ip1 * 0x1000000)
ip += uint32(ip2 * 0x10000)
ip += uint32(ip3 * 0x100)
ip += uint32(ip4)
return
}
func IP2Int(ip net.IP) uint32 {
if len(ip) == 0 {
return 0
}
if len(ip) == 16 {
return binary.BigEndian.Uint32(ip[12:16])
}
return binary.BigEndian.Uint32(ip)
}
func Int2IP(nn uint32) net.IP {
ip := make(net.IP, 4)
binary.BigEndian.PutUint32(ip, nn)
return ip
}
<file_sep>/int.go
//
// int.go
//
// Distributed under terms of the MIT license.
//
package util
import (
"strconv"
)
func Int2bin(i int, prefix bool) string {
i64 := int64(i)
if prefix {
return "0b" + strconv.FormatInt(i64, 2) // base 2 for binary
} else {
return strconv.FormatInt(i64, 2) // base 2 for binary
}
}
func Bin2int(binStr string) int {
// base 2 for binary
result, _ := strconv.ParseInt(binStr, 2, 64)
return int(result)
}
func Int2oct(i int, prefix bool) string {
i64 := int64(i)
if prefix {
return "0o" + strconv.FormatInt(i64, 8) // base 8 for octal
} else {
return strconv.FormatInt(i64, 8) // base 8 for octal
}
}
func Oct2int(octStr string) int {
// base 8 for octal
result, _ := strconv.ParseInt(octStr, 8, 64)
return int(result)
}
func Int2hex(i int, prefix bool) string {
i64 := int64(i)
if prefix {
return "0x" + strconv.FormatInt(i64, 16) // base 16 for hexadecimal
} else {
return strconv.FormatInt(i64, 16) // base 16 for hexadecimal
}
}
func Hex2int(hexStr string) int {
// base 16 for hexadecimal
result, _ := strconv.ParseInt(hexStr, 16, 64)
return int(result)
}
<file_sep>/type_conv.go
//
// type_conv.go
//
// Distributed under terms of the MIT license.
//
package util
import (
"fmt"
"strconv"
)
const (
digits = "0123456789"
uintbuflen = 20
)
func Int64(val interface{}) int64 {
switch t := val.(type) {
case int:
return int64(t)
case int8:
return int64(t)
case int16:
return int64(t)
case int32:
return int64(t)
case int64:
return int64(t)
case uint:
return int64(t)
case uint8:
return int64(t)
case uint16:
return int64(t)
case uint32:
return int64(t)
case uint64:
return int64(t)
case bool:
if t == true {
return int64(1)
}
return int64(0)
case float32:
return int64(t)
case float64:
return int64(t)
default:
i, _ := strconv.ParseInt(String(val), 10, 64)
return i
}
panic("Invalid")
}
func Uint64(val interface{}) uint64 {
switch t := val.(type) {
case int:
return uint64(t)
case int8:
return uint64(t)
case int16:
return uint64(t)
case int32:
return uint64(t)
case int64:
return uint64(t)
case uint:
return uint64(t)
case uint8:
return uint64(t)
case uint16:
return uint64(t)
case uint32:
return uint64(t)
case uint64:
return uint64(t)
case float32:
return uint64(t)
case float64:
return uint64(t)
case bool:
if t == true {
return uint64(1)
}
return uint64(0)
default:
i, _ := strconv.ParseUint(String(val), 10, 64)
return i
}
panic("Invalid")
}
func Float64(val interface{}) float64 {
switch t := val.(type) {
case int:
return float64(t)
case int8:
return float64(t)
case int16:
return float64(t)
case int32:
return float64(t)
case int64:
return float64(t)
case uint:
return float64(t)
case uint8:
return float64(t)
case uint16:
return float64(t)
case uint32:
return float64(t)
case uint64:
return float64(t)
case float32:
return float64(t)
case float64:
return float64(t)
case bool:
if t == true {
return float64(1)
}
return float64(0)
case string:
f, _ := strconv.ParseFloat(val.(string), 64)
return f
}
panic("Invalid")
}
func Bytes(val interface{}) []byte {
if val == nil {
return []byte{}
}
switch t := val.(type) {
case int:
return int64ToBytes(int64(t))
case int8:
return int64ToBytes(int64(t))
case int16:
return int64ToBytes(int64(t))
case int32:
return int64ToBytes(int64(t))
case int64:
return int64ToBytes(int64(t))
case uint:
return uint64ToBytes(uint64(t))
case uint8:
return uint64ToBytes(uint64(t))
case uint16:
return uint64ToBytes(uint64(t))
case uint32:
return uint64ToBytes(uint64(t))
case uint64:
return uint64ToBytes(uint64(t))
case float32:
return float32ToBytes(t)
case float64:
return float64ToBytes(t)
case complex128:
return complex128ToBytes(t)
case complex64:
return complex128ToBytes(complex128(t))
case bool:
if t == true {
return []byte("true")
}
return []byte("false")
case string:
return []byte(t)
case []byte:
return t
default:
return []byte(fmt.Sprintf("%v", val))
}
panic("Invalid")
}
func String(val interface{}) string {
var buf []byte
if val == nil {
return ""
}
switch t := val.(type) {
case int:
buf = int64ToBytes(int64(t))
case int8:
buf = int64ToBytes(int64(t))
case int16:
buf = int64ToBytes(int64(t))
case int32:
buf = int64ToBytes(int64(t))
case int64:
buf = int64ToBytes(int64(t))
case uint:
buf = uint64ToBytes(uint64(t))
case uint8:
buf = uint64ToBytes(uint64(t))
case uint16:
buf = uint64ToBytes(uint64(t))
case uint32:
buf = uint64ToBytes(uint64(t))
case uint64:
buf = uint64ToBytes(uint64(t))
case float32:
buf = float32ToBytes(t)
case float64:
buf = float64ToBytes(t)
case complex128:
buf = complex128ToBytes(t)
case complex64:
buf = complex128ToBytes(complex128(t))
case bool:
if val.(bool) == true {
return "true"
}
return "false"
case string:
return t
case []byte:
return string(t)
default:
return fmt.Sprintf("%v", val)
}
return string(buf)
}
func Bool(value interface{}) bool {
b, _ := strconv.ParseBool(String(value))
return b
}
func uint64ToBytes(v uint64) []byte {
buf := make([]byte, uintbuflen)
i := len(buf)
for v >= 10 {
i--
buf[i] = digits[v%10]
v = v / 10
}
i--
buf[i] = digits[v%10]
return buf[i:]
}
func int64ToBytes(v int64) []byte {
negative := false
if v < 0 {
negative = true
v = -v
}
uv := uint64(v)
buf := uint64ToBytes(uv)
if negative {
buf2 := []byte{'-'}
buf2 = append(buf2, buf...)
return buf2
}
return buf
}
func float32ToBytes(v float32) []byte {
slice := strconv.AppendFloat(nil, float64(v), 'g', -1, 32)
return slice
}
func float64ToBytes(v float64) []byte {
slice := strconv.AppendFloat(nil, v, 'g', -1, 64)
return slice
}
func complex128ToBytes(v complex128) []byte {
buf := []byte{'('}
r := strconv.AppendFloat(buf, real(v), 'g', -1, 64)
im := imag(v)
if im >= 0 {
buf = append(r, '+')
} else {
buf = r
}
i := strconv.AppendFloat(buf, im, 'g', -1, 64)
buf = append(i, []byte{'i', ')'}...)
return buf
}
<file_sep>/map.go
//
// map.go
//
// Distributed under terms of the MIT license.
//
package util
func CopyMapString(m map[string]string) map[string]string {
if m == nil {
return map[string]string{}
}
n := make(map[string]string, len(m))
for k, v := range m {
n[k] = v
}
return n
}
func CopyMapInterface(m map[string]interface{}) map[string]interface{} {
if m == nil {
return map[string]interface{}{}
}
n := make(map[string]interface{}, len(m))
for k, v := range m {
n[k] = v
}
return n
}
func CopyMap2Interface(m map[string]string) map[string]interface{} {
if m == nil {
return map[string]interface{}{}
}
n := make(map[string]interface{}, len(m))
for k, v := range m {
n[k] = v
}
return n
}
// ExtendMapString merge n to m
func ExtendMapString(m, n map[string]string) map[string]string {
if m == nil {
m = make(map[string]string, len(n))
}
for k, v := range n {
m[k] = v
}
return m
}
// MergeMapString return new map
func MergeMapString(m, n map[string]string) map[string]string {
a := make(map[string]string, len(m)+len(n))
for k, v := range m {
a[k] = v
}
for k, v := range n {
a[k] = v
}
return a
}
<file_sep>/time.go
//
// time.go
//
// Distributed under terms of the MIT license.
//
package util
import (
"strconv"
"time"
)
var (
DefaultDateFormat = "2006-01-02"
DefaultDatetimeFormat = "2006-01-02 15:04:05"
)
func TimestampMS() int64 {
return time.Now().UnixNano() / int64(time.Millisecond)
}
func Timestamp() int64 {
return time.Now().Unix()
}
func TimestampString() string {
return strconv.FormatInt(Timestamp(), 10)
}
func DatetimeString() string {
return time.Now().Format(DefaultDatetimeFormat)
}
func DateFormat(t time.Time) string {
return t.Format(DefaultDateFormat)
}
func DatetimeFormat(t time.Time) string {
return t.Format(DefaultDatetimeFormat)
}
func DatetimeParse(t string) (time.Time, error) {
return time.Parse(DefaultDatetimeFormat, t)
}
func DatetimeParseLocal(t string) (time.Time, error) {
loc, _ := time.LoadLocation("Local")
return time.ParseInLocation(DefaultDatetimeFormat, t, loc)
}
func ToDate(t time.Time) time.Time {
t, _ = time.Parse(DefaultDateFormat, DateFormat(t))
return t
}
func LastDay() string {
return time.Now().AddDate(0, 0, -1).Format("20060102")
}
func LastMonth() string {
return time.Now().AddDate(0, -1, 0).Format("20060102")
}
| 98906b3136b3797ee33de08a83d6ebe85df9121a | [
"Markdown",
"Go"
] | 8 | Go | scloudrun/util | 3cd4fb8354e4cd2cd69c0714f25e416841d4681c | f5e657b8d83fa11280632cacdf5adc02f67f0472 |
refs/heads/master | <repo_name>developwisely/firestore-import<file_sep>/README.md
# Firestore JSON Data Import
This is a simple JavaScript app to import basic JSON data to Firestore.
## How to use
1. `npm install`
2. Edit `config.js` with **API_KEY**, **AUTH_DOMAIN**, and **PROJECT_ID** from your Firestore project.
3. Place your data inside of `data.json` in a similar format.
```js
{
// these are collections
"exampleCollection": [
// these are documents
{
"key": "value",
"key": "value"
},
{
"key": "value",
"key": "value"
},
]
}
```
4. `npm run import`
<file_sep>/import.js
const config = require('./config.js')
const data = require('./data.json');
const firebase = require("firebase");
require("firebase/firestore");
// Initialize Cloud Firestore through Firebase
firebase.initializeApp({
apiKey: config.API_KEY,
authDomain: config.AUTH_DOMAIN,
projectId: config.PROJECT_ID
});
var db = firebase.firestore();
data && Object.keys(data).forEach(key => {
const documents = data[key];
var count = 1;
documents.forEach(documentData => {
db.collection(key)
.add(documentData)
.then((docRef) => {
console.log(`"${key}" document ${count} of ${documents.length} added with ID: ${docRef.id}`);
count++;
})
.catch((error) => {
console.error(`Error adding document: ${error}`);
});
});
});<file_sep>/config.js
// Your Firestore API KEY
const API_KEY = '';
// Your Firestore Auth Domain
const AUTH_DOMAIN = '';
// Your Firestore Project Id
const PROJECT_ID = '';
module.exports = {
API_KEY,
AUTH_DOMAIN,
PROJECT_ID
} | 11f8e9f34d308da7206e7d6b91848daca0e1756a | [
"Markdown",
"JavaScript"
] | 3 | Markdown | developwisely/firestore-import | 265ccee383029ddfb5a391507be1d771596424b4 | 4d1b83b2d567702a5c0cb45789c43ff8462568fd |
refs/heads/master | <file_sep>import numpy as np
import matplotlib.pyplot as plt # http://matplotlib.org/examples/pylab_examples/polar_demo.html
import socket
from time import sleep
from drawnow import drawnow
TCP_IP = ''
print 'Started. Hope everything works!'
#index = range(0,360)
lidar_data = np.ones(360, dtype=np.int) # http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.ones.html
#ax = plt.subplot(111, projection='polar')
#ax.plot(index, lidar_data, color='r', linewidth=3)
#plt.show()
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((TCP_IP, 12345))
s.listen(1)
def getData():
global data
c, sockaddr = s.accept()
data = c.recv(1024)
index = range(0, 360)
n = 0
d = 0
def makeFig():
global n
n = n+1
validcount = 0
validangle = range(0,360)
valid = range(0,360)
weakcount = 0
weakangle = range(0,360)
weak = range(0,360)
ax = plt.subplot(111, projection='polar')
for i in range(0,360):
x = lidar_data[i] & 0x3FFF
invalid_data = lidar_data[i] & 0x8000
strength_warning = lidar_data[i] & 0x4000
#ax.plot(index, lidar_data, color='r', linestyle='None', linewidth=3, marker='.')
if invalid_data == 0:
if strength_warning == 0:
valid[validcount] = x
validangle[validcount] = float(i)/180.0*2.0*np.pi
validcount = validcount + 1
else:
weak[weakcount] = x
weakangle[weakcount] = float(i)/180.0*2.0*np.pi
weakcount = weakcount + 1
ax.plot(validangle[0:validcount], valid[0:validcount], color='r', linestyle='None', linewidth=3, marker='.')
ax.plot(weakangle[0:weakcount], weak[0:weakcount], color='y', linestyle='None', linewidth=3, marker='.')
ax.set_title(str(n))
makeFig()
plt.draw()
plt.show(block=False)
while True:
getData()
if not data:
continue
leng = len(data)
d = d+1
print(str(leng) + ' [' + str(d) + ']')
if leng == 724:
#print('[0-3]: %d,%d,%d,%d' % (ord(data[0]),ord(data[1]),ord(data[2]),ord(data[3])))
if ord(data[0])==250 and ord(data[1])==250 and ord(data[2])==250 and ord(data[3])==250:
for i in range(0, 360):
lidar_data[i] = (ord(data[i*2+4]) << 8) | ord(data[i*2+4+1])
if (lidar_data[i] > 3000):
lidar_data[i] = lidar_data[i] | 0x8000 # make invalid
lidar_data[0] = 3000
plt.cla()
makeFig()
plt.draw()
plt.pause(0.001)
<file_sep>#include "mcu_api.h"
#include "mcu_errno.h"
#include <stdio.h>
#include <stdint.h>
struct lidar_data{
uint16_t distance [360];
uint16_t signal_strength [360];
uint16_t speed [360];
};
void mcu_main()
{
/* your configuration code starts here */
gpio_setup(48, 1); /* set GPIO 48 as output */
uart_setup(1, 115200);
struct lidar_data lidar;
uint8_t buf[10];
uint16_t index;
uint16_t speed;
uint16_t distance;
uint16_t signalstrength;
uint16_t i;
while (1){
uart_read(1, buf, 1);
if (buf[0] == 0xFA){
uart_read(1, buf, 1);
if ((buf[0] >= 0xA0) && (buf[0] <= 0xF9 )){
// detected start of packet and got index
index = (buf[0] - 0xA0) * 4;
uart_read(1, buf, 2);
speed = (buf[1] << 8) | buf[0];
lidar.speed[index] = speed;
lidar.speed[index+1] = speed;
lidar.speed[index+2] = speed;
lidar.speed[index+3] = speed;
uart_read(1, buf, 4);
distance = ((buf[1] & 0x3F) << 8) | buf[0];
signalstrength = (buf[3] << 8) | buf[2];
lidar.distance[index] = distance;
lidar.signal_strength[index] = signalstrength;
uart_read(1, buf, 4);
distance = ((buf[1] & 0x3F) << 8) | buf[0];
signalstrength = (buf[3] << 8) | buf[2];
lidar.distance[index+1] = distance;
lidar.signal_strength[index+1] = signalstrength;
uart_read(1, buf, 4);
distance = ((buf[1] & 0x3F) << 8) | buf[0];
signalstrength = (buf[3] << 8) | buf[2];
lidar.distance[index+2] = distance;
lidar.signal_strength[index+2] = signalstrength;
uart_read(1, buf, 4);
distance = ((buf[1] & 0x3F) << 8) | buf[0];
signalstrength = (buf[3] << 8) | buf[2];
lidar.distance[index+3] = distance;
lidar.signal_strength[index+3] = signalstrength;
if (index == 356){ // one entire set of information received
buf[0] = 0xFA;
buf[1] = 0xFA;
buf[2] = 0xFA;
buf[3] = 0xFA;
host_send(buf, 4); // send start sequence
for (i=0; i<360; i++){
buf[5] = lidar.distance[i] >> 8;
buf[4] = lidar.distance[i] & 0xFF;
buf[3] = lidar.speed[i] >> 8;
buf[2] = lidar.speed[i] & 0xFF;
buf[1] = lidar.signal_strength[i] >> 8;
buf[0] = lidar.signal_strength[i] & 0xFF;
host_send(buf, 6);
}
mcu_sleep(200); // 2s
}
}
}
}
}
<file_sep>/* Communicate with the MCU that's sending lidar data
* Print the data
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include "mraa.h"
uint8_t buf[20];
volatile int fid;
struct lidar_data{
uint16_t distance [360];
uint16_t signal_strength [360];
uint16_t speed [360];
};
int getHeader(void){
read(fid, buf, 1);
if (buf[0] == 0xFA){
read(fid, buf, 1);
if (buf[0] == 0xFA){
read(fid, buf, 1);
if (buf[0] == 0xFA){
read(fid, buf, 1);
if (buf[0] == 0xFA){
return 1;
}
}
}
}
return 0;
}
int main(){
fid = open("/dev/ttymcu0", O_RDONLY);
if (fid == 0){
fprintf(stderr,"Couldn't open communication with MCU!\n");
return -1;
}
printf("Opened communication with MCU!\n");
struct lidar_data lidar;
uint16_t i=0;
uint8_t tc=0;
while (1){
if (getHeader()){ // detected 4 consecutive 0xFA's --> start sequence
for (i=0; i<360; i++){
read(fid, buf, 6);
lidar.distance[i] = (buf[5] << 8) | buf[4];
lidar.speed[i] = (buf[3] << 8) | buf[2];
lidar.signal_strength[i] = (buf[1] << 8) | buf[0];
}
for (i=0; i<360; i++){
printf("angle, distance = %u, %u\n", i, lidar.distance[i]);
}
}
}
return 0;
}
/*
// To test transmission over connection:
buf[0] = 0xFA;
buf[1] = 33;
buf[2] = 33;
buf[3] = 33;
send(client, send_buffer, 724, 0);
return 0;
*/<file_sep>/* Build on top of mculidar to set up a network socket and send data over
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include "mraa.h"
#define TCP_IP "192.168.4.9"
#define TCP_PORT 12345
uint8_t buf[20];
volatile int fid;
volatile int client;
struct sockaddr_in addr; // http://man7.org/linux/man-pages/man7/ip.7.html
struct lidar_data{
uint16_t distance [360];
uint16_t signal_strength [360];
uint16_t speed [360];
};
int getHeader(void){
read(fid, buf, 1);
if (buf[0] == 0xFA){
read(fid, buf, 1);
if (buf[0] == 0xFA){
read(fid, buf, 1);
if (buf[0] == 0xFA){
read(fid, buf, 1);
if (buf[0] == 0xFA){
return 1;
}
}
}
}
return 0;
}
int setupconnection(void){
// http://gnosis.cx/publish/programming/sockets.html
client = socket(AF_INET, SOCK_STREAM, 0);
if (client < 0){
printf("Failed to create socket!\n");
return -1;
}
if (connect(client, (struct sockaddr*) &addr, sizeof(addr)) <0){
fprintf(stderr, "Failed to connect to socket!\n");
return -1;
}
return 0;
}
int main(){
fid = open("/dev/ttymcu0", O_RDONLY);
if (fid == 0){
fprintf(stderr,"Couldn't open communication with MCU!\n");
return -1;
}
printf("Opened communication with MCU!\n");
struct lidar_data lidar;
uint8_t send_buffer[724];
memset(&addr, 0, sizeof(addr)); // zero the struct https://en.wikibooks.org/wiki/C_Programming/Networking_in_UNIX
addr.sin_family = AF_INET;
addr.sin_port = htons(TCP_PORT);
addr.sin_addr.s_addr = inet_addr(TCP_IP); // https://en.wikibooks.org/wiki/C_Programming/Networking_in_UNIX
send_buffer[0] = 0xFA; send_buffer[1] = 0xFA; send_buffer[2] = 0xFA; send_buffer[3] = 0xFA;
uint16_t i=0;
uint16_t tc=0;
while (1){
if (getHeader()){ // detected 4 consecutive 0xFA's --> start sequence
for (i=0; i<360; i++){
read(fid, buf, 6);
lidar.distance[i] = (buf[5] << 8) | buf[4];
lidar.speed[i] = (buf[3] << 8) | buf[2];
lidar.signal_strength[i] = (buf[1] << 8) | buf[0];
}
for (i=0; i<360; i++){
tc = i*2+4;
//printf("angle, distance = %u, %u\n", i, lidar.distance[i]);
send_buffer[tc] = lidar.distance[i] >> 8; // high byte
send_buffer[tc+1] = lidar.distance[i] & 0xFF; // low byte
}
if (setupconnection() < 0){
return -1;
}
send(client, send_buffer, 724, 0);
}
}
return 0;
}
<file_sep>import socket #for sockets
import sys #for exit
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket Created'
remote_ip = '192.168.4.9'
port = 12345
#Connect to remote server
s.connect((remote_ip , port))
#Send some data to remote server
message = "SEND DATA YAY!"
try :
#Set the whole string
s.sendall(message)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message send successfully'<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <mraa.h>
struct lidar_data{
uint16_t distance [360];
uint16_t signal_strength [360];
uint16_t speed [360];
};
int main()
{
/* your configuration code starts here */
const char* path = "/dev/ttyMFD1";
mraa_uart_context uartRead = mraa_uart_init_raw(path);
/*const char* path2 = "/dev/ttyGS0";
mraa_uart_context uartWrite = mraa_uart_init_raw(path2);*/
struct lidar_data lidar;
char buf[10];
uint16_t index;
uint16_t speed;
uint16_t distance;
uint16_t signalstrength;
for (;;){
mraa_uart_read(uartRead, buf, 1);
if (buf[0] == 0xFA){
mraa_uart_read(uartRead, buf, 1);
if ((buf[0] >= 0xA0) && (buf[0] <= 0xF9 )){
// detected start of packet and got index
index = (buf[0] - 0xA0) * 4;
mraa_uart_read(uartRead, buf, 2);
speed = (buf[1] << 8) | buf[0];
lidar.speed[index] = speed;
lidar.speed[index+1] = speed;
lidar.speed[index+2] = speed;
lidar.speed[index+3] = speed;
mraa_uart_read(uartRead, buf, 4);
distance = ((buf[1] & 0x3F) << 8) | buf[0];
signalstrength = (buf[3] << 8) | buf[2];
lidar.distance[index] = distance;
lidar.signal_strength[index] = signalstrength;
mraa_uart_read(uartRead, buf, 4);
distance = ((buf[1] & 0x3F) << 8) | buf[0];
signalstrength = (buf[3] << 8) | buf[2];
lidar.distance[index+1] = distance;
lidar.signal_strength[index+1] = signalstrength;
mraa_uart_read(uartRead, buf, 4);
distance = ((buf[1] & 0x3F) << 8) | buf[0];
signalstrength = (buf[3] << 8) | buf[2];
lidar.distance[index+2] = distance;
lidar.signal_strength[index+2] = signalstrength;
mraa_uart_read(uartRead, buf, 4);
distance = ((buf[1] & 0x3F) << 8) | buf[0];
signalstrength = (buf[3] << 8) | buf[2];
lidar.distance[index+3] = distance;
lidar.signal_strength[index+3] = signalstrength;
}
}
}
return 0;
}
<file_sep>import socket
TCP_IP = ''
print 'Started. Hope everything works!'
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((TCP_IP, 12345))
s.listen(1)
while True:
c, sockaddr = s.accept()
print 'Got connection from ', sockaddr
data = s.recv(1) | 126166350faf0771dd3704912f5a44542bfc4a5a | [
"C",
"Python"
] | 7 | Python | ZihaoXue1995/ece-edison-lidar-socket | a3ce7e99ae24ed415de34e2ce36f08c17b575c4f | d9dcfa802a2887ddcab16120401d79f7b99eccde |
refs/heads/main | <repo_name>itslilykim12/Employee-Tracker<file_sep>/README.md
## Employee-Tracker
# Purpose
The purpose of this application is to show the different tables of an employee, roles and department in the SQL database.
The user can view, add, update or delete information through the command line prompts.
# Installations
The application is built with the following tools and packages:
- MySQL & MySQL2
- console.table dependencies
- inquirer dependencies
# Video Demonstration
The following video shows the demonstration of the app!
https://drive.google.com/file/d/14_XI3QVWSQQb85YhKSl3APmoIAlKKc_o/view
# Sample Image of Assignment

# Resources
1. Inquirer: https://www.npmjs.com/package/inquirer
2. Console.table: https://www.npmjs.com/package/console.table
3. mysql2: https://www.npmjs.com/package/mysql2
# Contributions
Made by <NAME>
<file_sep>/db/db.sql
DROP DATABASE IF EXISTS tracker;
CREATE DATABASE tracker;
USE tracker;<file_sep>/db/seeds.sql
INSERT INTO department
(name)
VALUES
('Sales'),
('Human Resources'),
('IT'),
('Security'),
('Finance'),
('Development');
INSERT INTO roles (title, salary, department_id)
VALUES
('Software Web Developer',90000, 1),
('Manager', 80000, 2),
('Sales Rep', 45000, 3),
('Engineer', 90000, 4),
('Accountant',75000, 5),
('Security Guard', 60000, 6);
INSERT INTO employee
(first_name, last_name, roles_id, manager_id)
VALUES
('Nick', 'Smith', 1, 212),
('Hannah', 'Young', 2, 101),
('Madison', 'Barrett', 3, 999),
('Bella', 'Martins', 4, 348),
('Maria', 'Lopez', 5, 222),
('Josh', 'Hall', 6, 333); | c4dcfbdf81d7d5bd15ed483570790439f37ca3ad | [
"Markdown",
"SQL"
] | 3 | Markdown | itslilykim12/Employee-Tracker | 2c97dbc5ea6e9efdf9b59f4964b345e01396d051 | 5bc038504d965b168062b2391e6a5b4f44fa792a |
refs/heads/master | <repo_name>Ywine/taoBao-imitate<file_sep>/README.md
# 模仿淘宝首页
个人的练习作业,主要目的是模仿下淘宝的布局和熟系下Grid布局因为没有用过,所以我用Grid去模仿下淘宝的布局。只写的一部分没有全部写完。
<file_sep>/js/index.js
var imgUrl = [
{img:'imgs/carousel1',url:'#'},
{img:'imgs/carousel2',url:'#'},
{img:'imgs/carousel3',url:'#'},
{img:'imgs/carousel4',url:'#'},
]//轮播1的图片地址
var carouse2_img = [
{
imgs:[
{img:"imgs/tmall/q1.jpg",url:'#'},
{img:"imgs/tmall/q2.jpg",url:'#'},
]
},
{
imgs:[
{img:'imgs/tmall/w1.jpg',url:'#'},
{img:'imgs/tmall/w2.jpg',url:'#'},
]
},
{
imgs:[
{img:'imgs/tmall/e1.jpg',url:'#'},
{img:'imgs/tmall/e2.jpg',url:'#'},
]
},
{
imgs:[
{img:'imgs/tmall/r1.jpg',url:'#'},
{img:'imgs/tmall/r2.jpg',url:'#'},
]
},
{
imgs:[
{img:'imgs/tmall/t1.jpg',url:'#'},
{img:'imgs/tmall/t2.jpg',url:'#'},
]
},
/*{
imgs:[
{img:'imgs/tmall/y1.png',url:'#'},
{img:'imgs/tmall/y2.png',url:'#'},
{img:'imgs/tmall/y3.png',url:'#'},
{img:'imgs/tmall/y4.png',url:'#'},
{img:'imgs/tmall/y5.png',url:'#'},
{img:'imgs/tmall/y6.png',url:'#'},
{img:'imgs/tmall/y7.png',url:'#'},
{img:'imgs/tmall/y8.png',url:'#'},
{img:'imgs/tmall/y9.png',url:'#'},
{img:'imgs/tmall/y10.png',url:'#'},
{img:'imgs/tmall/y11.png',url:'#'},
{img:'imgs/tmall/y12.png',url:'#'},
]
},*/
]
//轮播1的容器
const carousel = document.getElementById('yzq_carousel_ul')
//圆点容器
const dol = document.getElementById('yzq_carouselOne_dol')
dol.style.left = 519.59/2-imgUrl.length/2*18+'px'
//轮播1添加图片
imgUrl.forEach( ( value , index ) => {
carousel.innerHTML += "<li><a href='"+value.url+"' ><img src="+value.img+".jpg alt=''></a></li>"
dol.innerHTML += "<li><a href='javascript:void(0);' id='dol_a"+index+"' onclick='goTo("+index+")'></a></li>"
} )
var startSite = 0 //点的开始位置
goTo(startSite)//初始化
function goTo(index){
//取消上一个点的颜色
const site = document.getElementById("dol_a"+startSite)
site .style.backgroundColor = ('#fff')
startSite = index //上一个点的位置
//设置点的颜色
const dol_a = document.getElementById("dol_a"+index)
dol_a.style.backgroundColor = ('#ff5000')
//滚动图片
carousel.style.left = -520*index+'px'
console.log(carousel.style.left,index)
}
//第一个轮播的左右点击事件
function go(item) {
if (item) {
index = startSite-1 >= 0 ? startSite-1 : imgUrl.length-1
goTo(index)
}
else{
index = startSite+1 > imgUrl.length-1 ? 0 : startSite+1
goTo(index)
}
}
//第二个轮播
const carouse2 = document.getElementById('carouseTwo')
const carouse2_dol = document.getElementById('carouseTwo_dol')
const carouse2_dol_width = 100/carouse2_img.length
console.log(100/carouse2_img.length)
carouse2_img.forEach( ( value , index ) => {
let a = ''
value.imgs.forEach( (value1, index1) => {
a += "<a href='"+value1.url+"' ><img src="+value1.img+" alt=''></a>"
})
carouse2_dol.innerHTML += "<li style='width: "+carouse2_dol_width+"%'><a href='#' id='carouse2_dol"+index+"' onclick='carouse2GoTo("+index+")'></a></li>"
carouse2.innerHTML += "<li>"+a+"</li>"
} )
var startSite2 = 0 //点的开始位置
carouse2GoTo(startSite2)//初始化
function carouse2GoTo(index){
//取消上一个点的颜色
const site = document.getElementById("carouse2_dol"+startSite2)
site .style.backgroundColor = ('#ff1648')
startSite2 = index //上一个点的位置
//设置点的颜色
const dol_a = document.getElementById("carouse2_dol"+index)
dol_a.style.backgroundColor = ('#000')
//滚动图片
carouse2.style.left = -520*index+'px'
console.log(carousel.style.left,index)
}
//第二个轮播的左右点击事件
function goTwo(item) {
if (item) {
index = startSite2-1 >= 0 ? startSite2-1 : carouse2_img.length-1
carouse2GoTo(index)
}
else{
index = startSite2+1 > carouse2_img.length-1 ? 0 : startSite2+1
carouse2GoTo(index)
}
}
| 9506d987b131280306f3279f7600d06ca35748a4 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Ywine/taoBao-imitate | 56a9f4fa4d4ccfcb1fd86d26d7159a56df2031e7 | 34dec2f2d264e4b1698e072ab51092fd8458c6c7 |
refs/heads/master | <repo_name>renatogroffe/DotNetCore-AzureFunctions3x-CotacoesMoedas-EFCore-FluentValidation<file_sep>/ServerlessMoedas/MoedasQueueTrigger.cs
using System;
using System.Linq;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using ServerlessMoedas.Data;
using ServerlessMoedas.Models;
using ServerlessMoedas.Validators;
namespace ServerlessMoedas
{
public class MoedasQueueTrigger
{
private MoedasContext _context;
public MoedasQueueTrigger(MoedasContext context)
{
_context = context;
}
[FunctionName("MoedasQueueTrigger")]
public void Run([QueueTrigger("queue-cotacoes", Connection = "AzureWebJobsStorage")]string myQueueItem, ILogger log)
{
bool dadosValidos;
Cotacao cotacao = null;
try
{
cotacao = JsonSerializer.Deserialize<Cotacao>(myQueueItem);
var resultadoValidator = new CotacaoValidator().Validate(cotacao);
dadosValidos = resultadoValidator.IsValid;
if (!dadosValidos)
log.LogError(
$"MoedasQueueTrigger - Erros de validação: {resultadoValidator.ToString()}");
}
catch
{
dadosValidos = false;
log.LogError($"MoedasQueueTrigger - Erro ao deserializar dados: {myQueueItem}");
}
if (dadosValidos)
{
var dadosCotacao = _context.Cotacoes
.Where(c => c.Sigla == cotacao.Sigla)
.FirstOrDefault();
if (dadosCotacao != null)
{
dadosCotacao.UltimaCotacao = DateTime.Now;
dadosCotacao.Valor = cotacao.Valor;
_context.SaveChanges();
}
log.LogInformation($"MoedasQueueTrigger: {myQueueItem}");
}
}
}
}<file_sep>/ServerlessMoedas/CotacoesHttpTrigger.cs
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using ServerlessMoedas.Data;
namespace ServerlessMoedas
{
public class CotacoesHttpTrigger
{
private MoedasContext _context;
public CotacoesHttpTrigger(MoedasContext context)
{
_context = context;
}
[FunctionName("CotacoesHttpTrigger")]
public IActionResult Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log)
{
string moeda = req.Query["moeda"];
log.LogInformation($"CotacoesHttpTrigger: {moeda}");
if (!String.IsNullOrWhiteSpace(moeda))
{
return (ActionResult)new OkObjectResult(
_context.Cotacoes
.Where(c => c.Sigla == moeda)
.FirstOrDefault()
);
}
else
{
return new BadRequestObjectResult(new
{
Sucesso = false,
Mensagem = "Informe uma sigla de moeda válida"
});
}
}
}
}<file_sep>/ServerlessMoedas/Startup.cs
using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using ServerlessMoedas.Data;
[assembly: FunctionsStartup(typeof(ServerlessMoedas.Startup))]
namespace ServerlessMoedas
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddEntityFrameworkSqlServer()
.AddDbContext<MoedasContext>(
options => options.UseSqlServer(
Environment.GetEnvironmentVariable("BaseCotacoes")));
}
}
}<file_sep>/ServerlessMoedas/Validators/CotacaoValidator.cs
using FluentValidation;
using ServerlessMoedas.Models;
namespace ServerlessMoedas.Validators
{
public class CotacaoValidator : AbstractValidator<Cotacao>
{
public CotacaoValidator()
{
RuleFor(c => c.Sigla).NotEmpty().WithMessage("Preencha o campo 'Sigla'")
.Length(3, 3).WithMessage("O campo 'Sigla' deve possuir 3 caracteres");
RuleFor(c => c.Valor).NotEmpty().WithMessage("Preencha o campo 'Valor'")
.GreaterThan(0).WithMessage("O campo 'Valor' deve ser maior do 0");
}
}
} | f5b4ae063f4724fc26c8c00a69d75e0ffa743918 | [
"C#"
] | 4 | C# | renatogroffe/DotNetCore-AzureFunctions3x-CotacoesMoedas-EFCore-FluentValidation | 2483f47197376f9ba552a3300c144e0662b431cb | 916ac45a2ef5d8a96995bcef329a1a523f55e98d |
refs/heads/master | <file_sep>package com.newjoiner.maven.SpringMVCCustom.controller;
import java.io.IOException;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.newjoiner.maven.SpringMVCCustom.model.Player;
import com.newjoiner.maven.SpringMVCCustom.service.PlayerService;
@Controller
public class LineupController {
@Autowired
//TODO add access modifier
PlayerService playerService;
@RequestMapping(value="/lineup", method = RequestMethod.POST)
@ResponseBody
public String saveLineup(@RequestBody Player player, Model model) throws JsonGenerationException, JsonMappingException, IOException {
playerService.savePlayer(player);
List<Player> players = playerService.findAllPlayers();
model.addAttribute("players",players);
ObjectMapper mapper = new ObjectMapper();
String allPlayersJson = mapper.writeValueAsString(players);
return allPlayersJson;
}
}
<file_sep>package com.newjoiner.maven.SpringMVCCustom.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.springframework.stereotype.Repository;
import com.newjoiner.maven.SpringMVCCustom.dao.AbstractDao;
import com.newjoiner.maven.SpringMVCCustom.model.Player;
@Repository("playerDao")
public class PlayerDaoImpl extends AbstractDao<Integer, Player> implements PlayerDao {
@Override
public Player findById(int id) {
return getByKey(id);
}
@Override
@SuppressWarnings("unchecked")
public List<Player> findAllPlayers() {
Criteria criteria = createEntityCriteria();
return criteria.list();
}
@Override
public void savePlayer(Player player) {
persist(player);
}
}<file_sep>angular.module('myApp').controller('savePlayerCtrl', ['$scope', '$http', function($scope, $http){
var self = this;
self.player = {firstName : '', lastName: ''};
function savePlayer(){
$http.post("/savePlayer", self.data).then(function(successData){
//do something
}, function(error){
//do something
});
};
}]);<file_sep>package com.newjoiner.maven.SpringMVCCustom.model;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="lineup")
public class Lineup {
public Lineup() {}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name = "pg1", nullable = false)
private String pg1;
@Column(name = "pg2", nullable = false)
private String pg2;
@Column(name = "sg1", nullable = false)
private String sg1;
@Column(name = "sg2", nullable = false)
private String sg2;
@Column(name = "sf1", nullable = false)
private String sf1;
@Column(name = "sf2", nullable = false)
private String sf2;
@Column(name = "pf1", nullable = false)
private String pf1;
@Column(name = "pf2", nullable = false)
private String pf2;
@Column(name = "c", nullable = false)
private String c;
@Column(name="date", nullable = false)
private Date date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPg1() {
return pg1;
}
public void setPg1(String pg1) {
this.pg1 = pg1;
}
public String getPg2() {
return pg2;
}
public void setPg2(String pg2) {
this.pg2 = pg2;
}
public String getSg1() {
return sg1;
}
public void setSg1(String sg1) {
this.sg1 = sg1;
}
public String getSg2() {
return sg2;
}
public void setSg2(String sg2) {
this.sg2 = sg2;
}
public String getSf1() {
return sf1;
}
public void setSf1(String sf1) {
this.sf1 = sf1;
}
public String getSf2() {
return sf2;
}
public void setSf2(String sf2) {
this.sf2 = sf2;
}
public String getPf1() {
return pf1;
}
public void setPf1(String pf1) {
this.pf1 = pf1;
}
public String getPf2() {
return pf2;
}
public void setPf2(String pf2) {
this.pf2 = pf2;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Lineup [id=" + id + ", pg1=" + pg1 + ", pg2=" + pg2 + ", sg1=" + sg1 + ", sg2=" + sg2 + ", sf1=" + sf1
+ ", sf2=" + sf2 + ", pf1=" + pf1 + ", pf2=" + pf2 + ", c=" + c + ", date=" + date + "]";
}
} | 7eb1ea168acabb66d94cb00d149c7d22efb701f5 | [
"JavaScript",
"Java"
] | 4 | Java | tyoung12290/SpringMVCCustom | 7703039e7634400a369264db2394570c69de6f5f | 4b245df580acab48a4123ae74ab3b8fe7dd32b91 |
refs/heads/master | <file_sep>//
// main.c
// a,b,c
//
// Created by qiuyu143 on 2017/6/13.
// Copyright © 2017年 qiuyu143. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
// insert code here...
FILE *fr;
FILE *fw;
fr=fopen("//Userd//20161104606//Desktop//sum//input.txt","r+");
fw=fopen("//Userd//20161104606//Desktop//sum//output.txt","w");
int a,b,c;
fscanf(fr,"%d%d",&a,&b);
c=a+b;
printf("%d+%d=%d\n",a,b,c);
fprintf(fw,"%d+%d=%d\n",a,b,c);
return 0;
}
| a02b0801d21db7956a798371e25dc6eafcd97db7 | [
"C"
] | 1 | C | 20161104606/a-b-c | 7a8cc8d85f1eaa9392e2754538e9f41c984df10f | f4695d4ae755410e7aaeb2a012f799e36a69af5d |
refs/heads/master | <file_sep># Imports here
import numpy as np
import pandas as pd
import scipy
import json
import time
import os
import torch
from torch import nn
from torch import optim
from torchvision import transforms
from torchvision import datasets
from torch import utils as utils
import torchvision.models as models
import argparse
from PIL import Image
import matplotlib.pyplot as plt
from collections import OrderedDict
torch.cuda.init()
torch.cuda.empty_cache()
defaults = {
'learning_rate' : 0.001,
'device' : "cuda:0",
'epochs' : 3,
'hidden_units' : 1024,
'arch' : "vgg16",
'save_dir' : os.getcwd()
}
#valid_archs = ("vgg16", "resnet", "alexnet", "squeezenet", "densenet", "inception")
valid_archs = ("vgg16", "densenet")
def check_valid_dir(dirpath):
return os.path.isdir(dirpath)
def set_architecture_parameters(configs):
assert(configs['arch'] in valid_archs)
return
def process_args():
''' Process the command line arguments
'''
configs = dict()
parser = argparse.ArgumentParser(description='Train a neural network.')
parser.add_argument('--learning_rate', action="store", type=float, help='Learning rate for the training. Defaults to 0.001')
parser.add_argument('--gpu', action="store_true", help='Use GPU rather than CPU for training.')
parser.add_argument('--epochs', action="store", type=int, help='Number of epochs to cycle the training. Defaults to 3.')
parser.add_argument('--hidden_units', action="store", type=int, help='Number of units in the hidden layer. Defaults to 1024.')
parser.add_argument('--arch', action="store", type=str, help='Neural Network training architecture. Defaults to VGG13.')
parser.add_argument('--save_dir', action="store", type=str, help='Directory to save the trained neural network in.')
parser.add_argument('data_dir', help='Directory with training, testing, and validation images. Subdirectories must exist named \\train, \\test, \\valid')
args = parser.parse_args()
if(args.learning_rate == None):
configs['learning_rate'] = defaults['learning_rate']
else:
configs['learning_rate'] = args.learning_rate
configs['device'] = "cpu"
if(args.gpu == True and torch.cuda.is_available()):
configs['device'] = "cuda:0"
if(args.epochs == None):
configs['epochs'] = defaults['epochs']
else:
configs['epochs'] = args.epochs
if(args.hidden_units == None):
configs['hidden_units'] = defaults['hidden_units']
else:
configs['hidden_units'] = args.hidden_units
if(args.arch == None):
configs['arch'] = defaults['arch']
else:
configs['arch'] = str(args.arch).lower()
if(configs['arch'] not in valid_archs):
print("Invalid neural network architecture. Acceptable: VGG16, DenseNet")
exit()
if(check_valid_dir(args.data_dir)):
configs['data_dir'] = args.data_dir
configs['train_dir'] = args.data_dir + "/train"
configs['valid_dir'] = args.data_dir + "/valid"
configs['test_dir'] = args.data_dir + "/test"
else:
print("Invalid data directory.")
exit()
if(args.save_dir == None):
configs['save_dir'] = defaults['save_dir']
else:
if(check_valid_dir(args.save_dir)):
configs['save_dir'] = args.save_dir
else:
print("Invalid checkpoint save directory (directory needs to exist).")
exit()
return configs
def model_init(configs):
training_data_transforms = transforms.Compose([transforms.RandomRotation(30),
transforms.RandomHorizontalFlip(),
transforms.RandomResizedCrop(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])])
validation_data_transforms = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])])
testing_data_transforms = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])])
# TODO: Load the datasets with ImageFolder
image_datasets = dict()
image_datasets['training'] = datasets.ImageFolder(configs['train_dir'], transform=training_data_transforms)
image_datasets['validation'] = datasets.ImageFolder(configs['valid_dir'], transform=validation_data_transforms)
image_datasets['testing'] = datasets.ImageFolder(configs['test_dir'], transform=testing_data_transforms)
# TODO: Using the image datasets and the trainforms, define the dataloaders
dataloaders = dict()
if configs['device']=="cpu":
b_size = 4
else:
b_size = 16
dataloaders['training'] = utils.data.DataLoader(image_datasets['training'], batch_size = b_size, shuffle = True)
dataloaders['validation'] = utils.data.DataLoader(image_datasets['validation'], batch_size = b_size, shuffle = False)
dataloaders['testing'] = utils.data.DataLoader(image_datasets['testing'], batch_size = b_size, shuffle = False)
with open('cat_to_name.json', 'r') as f:
cat_to_name = json.load(f)
return image_datasets, dataloaders, cat_to_name
def model_create(training_dataset, configs):
arch = configs['arch']
if(arch == "vgg16"):
the_model = models.vgg16(pretrained = True)
inp = the_model.classifier[0].in_features
#elif(arch == "resnet"):
# the_model = models.resnet50(pretrained = True)
# inp = 2048
#elif(arch == "alexnet"):
# the_model = models.alexnet(pretrained = True)
# inp = 9216
#elif(arch == "squeezenet"):
# the_model = models.squeezenet1_1(pretrained = True)
# print(the_model)
# inp = 512
elif(arch == "densenet"):
the_model = models.densenet121(pretrained = True)
inp = 1024
#elif(arch == "inception"):
# the_model = models.inception_v3(pretrained = True)
# inp = 128
# Freeze parameters so we don't backprop through them
for param in the_model.parameters():
param.requires_grad = False
configs['state_dict'] = the_model.state_dict()
classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(inp, configs['hidden_units'])),
('relu', nn.ReLU()),
('dropout1', nn.Dropout(p=0.2)),
('fc2', nn.Linear(configs['hidden_units'], 102)),
('dropout2', nn.Dropout(p=0.2)),
('output', nn.LogSoftmax(dim=1))
]))
the_model.classifier = classifier
criterion = nn.NLLLoss()
optimizer = optim.Adam(the_model.classifier.parameters(), lr=configs['learning_rate'])
# set up some checkpoint data
configs['opt_dict'] = optimizer.state_dict()
configs['classifier_dict'] = classifier.state_dict()
configs['class_to_idx'] = training_dataset.class_to_idx
configs['criterion'] = criterion
configs['optimizer'] = optimizer
configs['classifier'] = classifier
return the_model, criterion, optimizer
def check_accuracy_on_test(model, testloader):
correct = 0
total = 0
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)
with torch.no_grad():
for images, labels in testloader:
#images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
return correct / total
def do_deep_learning(model, trainloader, testloader, print_every, criterion, optimizer, configs):
epochs = configs['epochs']
device = configs['device']
print("Getting ready to deep learn on device: ",device)
print_every = print_every
steps = 0
# change to cuda, if available
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)
for e in range(epochs):
running_loss = 0
for ii, (inputs, labels) in enumerate(trainloader):
steps += 1
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
# Forward and backward passes.
outputs = model.forward(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if steps % print_every == 0:
validation_accuracy = check_accuracy_on_test(model, testloader)
print("Epoch: {}/{}... ".format(e+1, epochs),
"Loss: {:.4f}".format(running_loss/print_every),
"Validation Accuracy: {:.2%}".format(validation_accuracy))
running_loss = 0
def save_checkpoint(model_config):
torch.save(model_config, model_config['save_dir']+'\\checkpoint.tph')
configs = process_args()
image_datasets, dataloaders, cat_to_name = model_init(configs)
set_architecture_parameters(configs)
the_model, criterion, optimizer = model_create(image_datasets['training'], configs)
do_deep_learning(the_model, dataloaders['training'], dataloaders['validation'], 40, criterion, optimizer, configs)
validation_accuracy = check_accuracy_on_test(the_model, dataloaders['testing'])
print("Accuracy against test dataset = {:.2%}".format(validation_accuracy))
save_checkpoint(configs)
<file_sep>import numpy as np
import pandas as pd
import scipy
import json
import time
import os
import torch
from torch import nn
from torch import optim
from torchvision import transforms
from torchvision import datasets
from torch import utils as utils
import torchvision.models as models
import argparse
from PIL import Image
import matplotlib.pyplot as plt
from collections import OrderedDict
def process_args():
''' Process the command line arguments
'''
configs = dict()
parser = argparse.ArgumentParser(description='Predict an object\'s type.')
parser.add_argument('image_path', help='Image to predict.')
parser.add_argument('checkpoint_path', help='Pretrained neural network checkpoint file.')
parser.add_argument('--gpu', action="store_true", help='Use GPU rather than CPU for training.')
parser.add_argument('--topk', action="store", type=int, help='Top k category guesses.')
parser.add_argument('--category_names', action="store", type=str, help='Category names file.', default='cat_to_name.json')
args = parser.parse_args()
configs['predict_device'] = "cpu"
if(args.gpu == True and torch.cuda.is_available()):
configs['predict_device'] = "cuda:0"
if(os.path.isfile(args.image_path)):
configs['image_path'] = args.image_path
else:
print("No or invalid image file.")
exit()
if(os.path.isfile(args.checkpoint_path)):
configs['checkpoint_path'] = args.checkpoint_path
else:
print("No or invalid checkpoint file.")
exit()
if(os.path.isfile(args.category_names)):
configs['category_names'] = args.category_names
else:
print("No or invalid category names file.")
exit()
if (args.topk == None):
configs['topk'] = 5
else:
configs['topk'] = args.topk
return configs
def load_checkpoint(configs):
configs.update(torch.load(configs['checkpoint_path'], map_location=torch.device(configs['predict_device'])))
#configs.update(torch.load(configs['checkpoint_path'], ))
return configs
def model_create(configs):
arch = configs['arch']
print("Model architecture: ", arch)
if(arch == "vgg16"):
the_model = models.vgg16(pretrained = True)
inp = the_model.classifier[0].in_features
elif(arch == "resnet"):
the_model = models.resnet50(pretrained = True)
inp = 2048
elif(arch == "alexnet"):
the_model = models.alexnet(pretrained = True)
inp = 9216
elif(arch == "squeezenet"):
the_model = models.squeezenet1_1(pretrained = True)
inp = 26624
elif(arch == "densenet"):
the_model = models.densenet121(pretrained = True)
inp = 1024
elif(arch == "inception"):
the_model = models.inception_v3(pretrained = True)
inp = 128
# Freeze parameters so we don't backprop through them
for param in the_model.parameters():
param.requires_grad = False
the_model.load_state_dict(configs['state_dict'])
the_model.class_to_idx = configs['class_to_idx']
optimizer = configs['optimizer']
criterion = configs['criterion']
classifier = configs['classifier']
#the_model.classifier.load_state_dict(configs['classifier_dict'])
the_model.optimizer = optimizer
the_model.classifier = classifier
return the_model, criterion, optimizer
def process_image(image):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
pil = Image.open(image)
xform = transforms.Compose([transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])])
pil = xform(pil)
return pil
def predict(image_path, model, configs):
''' Predict the class (or classes) of an image using a trained deep learning model.
'''
model.eval()
image = process_image(image_path)
if(configs["predict_device"] == "cuda:0"):
model = model.cuda()
image = image.unsqueeze(0)
with torch.no_grad():
if(configs["predict_device"] == "cuda:0"):
image = image.cpu()
image = image.cuda()
output = model(image)
probs, labels = torch.topk(output, configs['topk'])
probs = probs.exp()
class_to_idx_inv = {model.class_to_idx[k]: k for k in model.class_to_idx}
mapped_classes = list()
if(configs["predict_device"] == "cuda:0"):
labels = labels.cpu()
probs = probs.cpu()
for label in labels.numpy()[0]:
mapped_classes.append(class_to_idx_inv[label])
return probs.numpy()[0], mapped_classes
#image_path = 'flowers\\valid\\99\\image_08063.jpg'
#topk = 5
configs = process_args()
configs = load_checkpoint(configs)
image_path = configs['image_path']
the_model, criterion, optimizer = model_create(configs)
probabilities, mapped_classes = predict(image_path, the_model, configs)
#print(type(probabilities), mapped_classes)
with open('cat_to_name.json', 'r') as f:
cat_to_name = json.load(f)
print("Image: ", image_path)
print("Category Names File: ", configs['category_names'])
print()
x = 0
for x, i in enumerate(mapped_classes):
print("{:<30} {:.2%}".format(cat_to_name[i], probabilities[x]))
| 705d38be7c6b9e32597e85b7d2556fbfd55d5841 | [
"Python"
] | 2 | Python | CernyMW/aipnd-project | 53cc276f8345f3689070ef0982b08c6ff59accc9 | 0249a0e5d06da948d0c8576393280cf1a0c11eb9 |
refs/heads/master | <file_sep><?php
/**
* @author <NAME>
* @copyright Copyright (c) 2016 Amasty (https://www.amasty.com)
* @package Amasty_Search
*/
class Amasty_Search_Model_Mysql4_Catalogsearch_Collection extends Mage_CatalogSearch_Model_Mysql4_Advanced_Collection
{
public function addFieldsToFilter($fields)
{
if ($fields) {
/*$entityIds = null;*/
$previousSelect = null;
foreach ($fields as $table => $conditions) {
foreach ($conditions as $attributeId => $conditionValue) {
$bindVarName = 'attribute_'.$attributeId;
$select = $this->getConnection()->select();
$select->from(array('t1' => $table), 'entity_id');
$conditionData = array();
if (is_array($conditionValue)) {
if (isset($conditionValue['in'])){
$conditionData[] = array('IN (?)', $conditionValue['in']);
}
elseif (isset($conditionValue['in_set'])) {
$conditionData[] = array('REGEXP \'(^|,)('.join('|', $conditionValue['in_set']).')(,|$)\'', $conditionValue['in_set']);
}
elseif (isset($conditionValue['like'])) {
$this->addBindParam($bindVarName, $conditionValue['like']);
$conditionData[] = 'LIKE :'.$bindVarName;
}
elseif (isset($conditionValue['from']) || isset($conditionValue['to'])) {
if (!empty($conditionValue['from'])) {
//change here
$isNum = (is_numeric($conditionValue['from']) || $conditionValue['from'] instanceof Zend_Db_Expr);
if (!$isNum){
$conditionValue['from'] = date("Y-m-d H:i:s", strtotime($conditionValue['from']));
}
$conditionData[] = array('>= ?', $conditionValue['from']);
}
if (!empty($conditionValue['to'])) {
//change here
$isNum = (is_numeric($conditionValue['to']) || $conditionValue['to'] instanceof Zend_Db_Expr);
if (!$isNum){
$conditionValue['to'] = date("Y-m-d H:i:s", strtotime($conditionValue['from']));
}
$conditionData[] = array('<= ?', $conditionValue['to']);
}
}
} else {
$conditionData[] = array('= ?', $conditionValue);
}
if (!is_numeric($attributeId)) {
foreach ($conditionData as $data) {
if (is_array($data)) {
$select->where('t1.'.$attributeId . ' ' . $data[0], $data[1]);
}
else {
$select->where('t1.'.$attributeId . ' ' . $data);
}
}
}
else {
$storeId = $this->getStoreId();
$select->joinLeft(
array('t2' => $table),
$this->getConnection()->quoteInto('t1.entity_id = t2.entity_id AND t1.attribute_id = t2.attribute_id AND t2.store_id=?', $storeId),
array()
);
$select->where('t1.store_id = ?', 0);
$select->where('t1.attribute_id = ?', $attributeId);
foreach ($conditionData as $data) {
if (is_array($data)) {
$select->where('IFNULL(t2.value, t1.value) ' . $data[0], $data[1]);
}
else {
$select->where('IFNULL(t2.value, t1.value) ' . $data);
}
}
}
if (!is_null($previousSelect)) {
$select->where('t1.entity_id IN(?)', new Zend_Db_Expr($previousSelect));
}
$previousSelect = $select;
}
/*if (!is_null($entityIds) && $entityIds) {
$select->where('t1.entity_id IN(?)', $entityIds);
}
elseif (!is_null($entityIds) && !$entityIds) {
continue;
}
$entityIds = array();
$rowSet = $this->getConnection()->fetchAll($select);
foreach ($rowSet as $row) {
$entityIds[] = $row['entity_id'];
}*/
}
/*if ($entityIds) {
$this->addFieldToFilter('entity_id', array('IN', $entityIds));
}
else {
$this->addFieldToFilter('entity_id', 'IS NULL');
}*/
$this->addFieldToFilter('entity_id', array('in' => new Zend_Db_Expr($select)));
}
return $this;
}
}<file_sep><?php
/**
* @author <NAME>
* @copyright Copyright (c) 2016 Amasty (https://www.amasty.com)
* @package Amasty_Search
*/
class Amasty_Search_Helper_Data extends Mage_Core_Helper_Abstract
{
/**
* Get catagories of current store
*
* @return Varien_Data_Tree_Node_Collection
*/
public function getStoreCategories()
{
$helper = Mage::helper('catalog/category');
return $helper->getStoreCategories();
}
public function isCategoryActive($category)
{
$ids = Mage::app()->getRequest()->getParam('categories');
if (is_array($ids) && in_array($category->getId(), $ids))
return true;
return false;
}
/**
* Draws category and it's sub categories as checkboxes
*
* @param Mage_Catalog_Model_Category $category
* @param int $level
* @param boolean $last
* @return string
*/
public function drawCategory($category, $level=0, $last=false)
{
$html = '';
if (!$category->getIsActive()) {
return $html;
}
if (Mage::helper('catalog/category_flat')->isEnabled()) {
$children = $category->getChildrenNodes();
$childrenCount = count($children);
} else {
$children = $category->getChildren();
$childrenCount = $children->count();
}
$hasChildren = $children && $childrenCount;
$html .= '<option value="' . $category->getId(). '" ';
//$html .= 'style="padding-left:'.(10*$level).'px"';
if ($this->isCategoryActive($category)) {
$html .= ' selected';
}
if ($hasChildren) {
$cnt = 0;
foreach ($children as $child) {
if ($child->getIsActive()) {
$cnt++;
}
}
}
$html .= '>';
$html .= str_pad($this->htmlEscape($category->getName()), $level, ' ', STR_PAD_LEFT)
. '</option>'."\n";
if ($hasChildren){
$j = 0;
$htmlChildren = '';
foreach ($children as $child) {
if ($child->getIsActive()) {
$htmlChildren.= $this->drawCategory($child, $level+1, ++$j >= $cnt);
}
}
if (!empty($htmlChildren)) {
$padding = ($level+1)*10;
//$html.= '<div style="padding-left:'.$padding.'px">';
$html .= $htmlChildren;
//$html.= '</div>';
}
}
return $html;
}
public function drawCategories()
{
$tree = '';
foreach ($this->getStoreCategories() as $cat) {
$tree .= $this->drawCategory($cat);
}
//create block
$block = Mage::getModel('core/layout')->createBlock('core/template')
->setArea('frontend')
->setTemplate('amsearch/categories.phtml');
$block->assign('_type', 'html')
->assign('_section', 'body')
->setTree($tree);
return $block->toHtml();
}
/**
* Retrieves attribute input type
*
* @param $attribute
* @return string
*/
public function getAttributeInputType($attribute, $formBlock)
{
//dropdowns
$codes = Mage::getStoreConfig('amsearch/general/ranges');
if ($codes){
$codes = explode(',', $codes);
if (in_array($attribute->getAttributeCode(), $codes))
return 'number';
}
//inputs
$class = $attribute->getFrontendClass();
if ($class == 'validate-number' || $class == 'validate-digits'){
return 'number';
}
return $formBlock->getAttributeInputType($attribute);
}
}<file_sep><?php
/**
* @author <NAME>
* @copyright Copyright (c) 2016 Amasty (https://www.amasty.com)
* @package Amasty_Search
*/
class Amasty_Search_Model_Source_Attribute extends Varien_Object
{
public function toOptionArray()
{
$product = Mage::getModel('catalog/product');
$attributes = Mage::getResourceModel('catalog/product_attribute_collection')
->setEntityTypeFilter($product->getResource()->getTypeId())
->addFieldToFilter('frontend_input', array('in'=>array('select', 'multiselect')))
->addHasOptionsFilter()
->addDisplayInAdvancedSearchFilter()
->setOrder('frontend_label', 'asc')
->load();
$options = array();
$options[] = array(
'value'=> 0,
'label' => Mage::helper('amsearch')->__('--None--'),
);
foreach ($attributes as $attribute) {
$options[] = array(
'value'=> $attribute->getAttributeCode(),
'label' => $attribute->getFrontendLabel(),
);
}
return $options;
}
}<file_sep><?php
/**
* @author <NAME>
* @copyright Copyright (c) 2016 Amasty (https://www.amasty.com)
* @package Amasty_Search
*/
class Amasty_Search_Model_Catalogsearch_Advanced extends Mage_CatalogSearch_Model_Advanced
{
protected $_customSearchCriterias = array();
/**
* Add advanced search filters to product collection
*
* @param array $values
* @return Amasty_Search_Model_CatalogSearch_Advanced
*/
public function addFilters($values)
{
$attributes = $this->getAttributes();
// NEW CODE
// convert from-to to options ids
$customCodes = Mage::getStoreConfig('amsearch/general/ranges');
if ($customCodes)
$customCodes = explode(',', $customCodes);
else
$customCodes = array();
$originalValues = $values;
foreach ($attributes as $a){
$code = $a->getAttributeCode();
if (!in_array($code, $customCodes)){
continue;
}
if (empty($values[$code]['from']) && empty($values[$code]['to'])){
unset($values[$code]);
continue;
}
$from = !empty($values[$code]['from']) ? floatVal($values[$code]['from']) : '';
$to = !empty($values[$code]['to']) ? floatVal($values[$code]['to']) : '';
$values[$code] = array();
//get all suitable options
$options = $a->getSource()->getAllOptions(false);
foreach ($options as $opt){
$notLess = ($opt['label'] >= $from || '' === $from);
$notGreater = ($opt['label'] <= $to || '' === $to);
if ($notLess && $notGreater){
$values[$code][] = $opt['value'];
}
}
}
// add categories filter
if (!empty($values['categories']) && is_array($values['categories'])){
$db = Mage::getSingleton('core/resource');
$s = $db->getConnection('amsearch_read')->select()
->from($db->getTableName('catalog/category_product'), array('product_id'))
->where('category_id IN(?)', $values['categories']);
$this->getProductCollection()->addFieldToFilter('entity_id', array('in'=>new Zend_Db_Expr($s)));
//save in search criterisas
$name = Mage::helper('amsearch')->__('Categories');
$vals = '';
foreach ($values['categories'] as $id)
$vals .= Mage::getModel('catalog/category')->load($id)->getName() . ', ';
$this->_customSearchCriterias[] = array('name'=>$name, 'value'=>substr($vals, 0, -2));
}
// END NEW CODE
$allConditions = array();
$filteredAttributes = array();
$indexFilters = Mage::getModel('catalogindex/indexer')->buildEntityFilter(
$attributes,
$values,
$filteredAttributes,
$this->getProductCollection()
);
foreach ($indexFilters as $filter) {
$this->getProductCollection()->addFieldToFilter('entity_id', array('in'=>new Zend_Db_Expr($filter)));
}
$priceFilters = Mage::getModel('catalogindex/indexer')->buildEntityPriceFilter(
$attributes,
$values,
$filteredAttributes,
$this->getProductCollection()
);
foreach ($priceFilters as $code=>$filter) {
$this->getProductCollection()->getSelect()->joinInner(
array("_price_filter_{$code}"=>$filter),
"`_price_filter_{$code}`.`entity_id` = `e`.`entity_id`",
array()
);
}
foreach ($attributes as $attribute) {
$code = $attribute->getAttributeCode();
$condition = false;
if (isset($values[$code])) {
$value = $values[$code];
if (is_array($value)) {
if (isset($value['from']) && isset($value['to'])) {
// new code
$class = $attribute->getFrontendClass();
if ($class == 'validate-number' || $class == 'validate-digits'){
if (!empty($value['from']))
$value['from'] = new Zend_Db_Expr(floatval($value['from']));
if (!empty($value['to']))
$value['to'] = new Zend_Db_Expr(floatval($value['to']));
}
if (!empty($value['from']) || !empty($value['to'])) {
$condition = $value;
}
}
elseif ($attribute->getBackend()->getType() == 'varchar') {
$condition = array('in_set'=>$value);
}
elseif (!isset($value['from']) && !isset($value['to'])) {
$condition = array('in'=>$value);
}
} else {
if (strlen($value)>0) {
if (in_array($attribute->getBackend()->getType(), array('varchar', 'text'))) {
$condition = array('like'=>'%'.$value.'%');
} elseif ($attribute->getFrontendInput() == 'boolean') {
$condition = array('in' => array('0','1'));
} else {
$condition = $value;
}
}
}
}
if (false !== $condition) {
// start new code
if (in_array($code, $customCodes)){
$attribute->setFrontendInput('text');
$value = $originalValues[$code];
}
// end new code
$this->_addSearchCriteria($attribute, $value);
if (in_array($code, $filteredAttributes))
continue;
$table = $attribute->getBackend()->getTable();
$attributeId = $attribute->getId();
if ($attribute->getBackendType() == 'static'){
$attributeId = $attribute->getAttributeCode();
$condition = array('like'=>"%{$condition}%");
}
$allConditions[$table][$attributeId] = $condition;
}
}
if ($allConditions) {
$this->getProductCollection()->addFieldsToFilter($allConditions);
} else if (!count($filteredAttributes) && !$this->_customSearchCriterias) {
Mage::throwException(Mage::helper('catalogsearch')->__('You have to specify at least one search term'));
}
//echo (string)$this->getProductCollection()->getSelect();
return $this;
}
public function getSearchCriterias()
{
$res = parent::getSearchCriterias();
return array_merge($res, $this->_customSearchCriterias);
}
public function getProductCollection()
{
if (is_null($this->_productCollection)) {
$this->_productCollection = Mage::getResourceModel('amsearch/catalogsearch_collection')
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
->addMinimalPrice()
->addTaxPercents()
->addStoreFilter();
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($this->_productCollection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInSearchFilterToCollection($this->_productCollection);
}
return $this->_productCollection;
}
}
<file_sep><?php
/**
* Magento Enterprise Edition
*
* NOTICE OF LICENSE
*
* This source file is subject to the Magento Enterprise Edition License
* that is bundled with this package in the file LICENSE_EE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.magentocommerce.com/license/enterprise-edition
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to <EMAIL> so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_CatalogSearch
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://www.magentocommerce.com/license/enterprise-edition
*/
/**
* Fulltext Collection
*
* @category Mage
* @package Mage_CatalogSearch
* @author Magento Core Team <<EMAIL>>
*/
class Mage_CatalogSearch_Model_Resource_Fulltext_Collection extends Mage_Catalog_Model_Resource_Product_Collection
{
/**
* Retrieve query model object
*
* @return Mage_CatalogSearch_Model_Query
*/
protected function _getQuery()
{
return Mage::helper('catalogsearch')->getQuery();
}
/**
* Add search query filter
*
* @param string $query
* @return Mage_CatalogSearch_Model_Resource_Fulltext_Collection
*/
public function addSearchFilter($query)
{
Mage::getSingleton('catalogsearch/fulltext')->prepareResult();
$this->getSelect()->joinInner(
array('search_result' => $this->getTable('catalogsearch/result')),
$this->getConnection()->quoteInto(
'search_result.product_id=e.entity_id AND search_result.query_id=?',
$this->_getQuery()->getId()
),
array('relevance' => 'relevance')
);
return $this;
}
/**
* Set Order field
*
* @param string $attribute
* @param string $dir
* @return Mage_CatalogSearch_Model_Resource_Fulltext_Collection
*/
public function setOrder($attribute, $dir = 'desc')
{
if ($attribute == 'relevance') {
$this->getSelect()->order("relevance {$dir}");
} else {
parent::setOrder($attribute, $dir);
}
return $this;
}
/**
* Stub method for campatibility with other search engines
*
* @return Mage_CatalogSearch_Model_Resource_Fulltext_Collection
*/
public function setGeneralDefaultQuery()
{
return $this;
}
public function addCategoriesFilter($cat_id)
{
$categories=Mage::getModel('catalog/category')->load($cat_id);
$this->_productLimitationFilters['category_ids'] = $categories;
if ($this->getStoreId() == Mage_Core_Model_App::ADMIN_STORE_ID) {
$this->_applyZeroStoreProductLimitations();
} else {
$this->_applyProductLimitations();
}
return $this;
}
protected function _applyProductLimitations()
{
$this->_prepareProductLimitationFilters();
$this->_productLimitationJoinWebsite();
$this->_productLimitationJoinPrice();
$filters = $this->_productLimitationFilters;
// Addition: support for filtering multiple categories.
if (!isset($filters['category_id']) && !isset($filters['category_ids']) && !isset($filters['visibility'])) {
return $this;
}
$conditions = array(
'cat_index.product_id=e.entity_id',
$this->getConnection()->quoteInto('cat_index.store_id=?', $filters['store_id'])
);
if (isset($filters['visibility']) && !isset($filters['store_table'])) {
$conditions[] = $this->getConnection()
->quoteInto('cat_index.visibility IN(?)', $filters['visibility']);
}
// Addition: support for filtering multiple categories.
if (!isset($filters['category_ids'])) {
$conditions[] = $this->getConnection()
->quoteInto('cat_index.category_id=?', $filters['category_id']);
if (isset($filters['category_is_anchor'])) {
$conditions[] = $this->getConnection()
->quoteInto('cat_index.is_parent=?', $filters['category_is_anchor']);
}
} else {
$conditions[] = $this->getConnection()->quoteInto('cat_index.category_id IN(' . implode(',', $filters['category_ids']) . ')', "");
}
$joinCond = join(' AND ', $conditions);
$fromPart = $this->getSelect()->getPart(Zend_Db_Select::FROM);
if (isset($fromPart['cat_index'])) {
$fromPart['cat_index']['joinCondition'] = $joinCond;
$this->getSelect()->setPart(Zend_Db_Select::FROM, $fromPart);
}
else {
$this->getSelect()->join(
array('cat_index' => $this->getTable('catalog/category_product_index')),
$joinCond,
array('cat_index_position' => 'position')
);
}
$this->_productLimitationJoinStore();
Mage::dispatchEvent('catalog_product_collection_apply_limitations_after', array(
'collection' => $this
));
return $this;
}
protected function _applyZeroStoreProductLimitations()
{
$filters = $this->_productLimitationFilters;
// Addition: supprot for filtering multiple categories.
$categoryCondition = null;
if (!isset($filters['category_ids'])) {
$categoryCondition = $this->getConnection()->quoteInto('cat_pro.category_id=?', $filters['category_id']);
} else {
$categoryCondition = $this->getConnection()->quoteInto('cat_pro.category_id IN(' . implode(',', $filters['category_ids']) . ')', "");
}
$conditions = array(
'cat_pro.product_id=e.entity_id',
$categoryCondition
);
$joinCond = join(' AND ', $conditions);
$fromPart = $this->getSelect()->getPart(Zend_Db_Select::FROM);
if (isset($fromPart['cat_pro'])) {
$fromPart['cat_pro']['joinCondition'] = $joinCond;
$this->getSelect()->setPart(Zend_Db_Select::FROM, $fromPart);
}
else {
$this->getSelect()->join(
array('cat_pro' => $this->getTable('catalog/category_product')),
$joinCond,
array('cat_index_position' => 'position')
);
}
return $this;
}
}
<file_sep><?php
class Autocompleteplus_Autosuggest_LayeredController extends Mage_Core_Controller_Front_Action
{
public function preDispatch()
{
parent::preDispatch();
$this->getResponse()->clearHeaders();
$this->getResponse()->setHeader('Content-type', 'application/json');
}
protected function _getConfig()
{
return Mage::getModel('autocompleteplus_autosuggest/config');
}
public function setLayeredSearchOnAction()
{
$response = $this->getResponse();
$request = $this->getRequest();
$authkey = $request->getParam('authentication_key');
$uuid = $request->getParam('uuid');
$scope = $request->getParam('scope', 'default');
$scopeId = $request->getParam('store_id', 1);
if (!$this->valid($uuid, $authkey)) {
$resp = json_encode(array('status' => 'error: '.'Authentication failed'));
$response->setBody($resp);
return;
}
try {
$this->_getConfig()->enableLayeredNavigation($scope, $scopeId);
Mage::app()->getCacheInstance()->cleanType('config');
} catch (Exception $e) {
$resp = json_encode(array('status' => 'error: '.print_r($e->getMessage(), true)));
$response->setBody($resp);
Mage::logException($e);
return;
}
$resp = array('new_state' => 1,
'status' => 'ok',
);
$response->setBody(json_encode($resp));
}
public function setLayeredSearchOffAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$authkey = $request->getParam('authentication_key');
$uuid = $request->getParam('uuid');
$scope = $request->getParam('scope', 'default');
$scopeId = $request->getParam('store_id', 1);
if (!$this->valid($uuid, $authkey)) {
$resp = json_encode(array('status' => 'error: '.'Authentication failed'));
$response->setBody($resp);
return;
}
try {
$this->_getConfig()->disableLayeredNavigation($scope, $scopeId);
Mage::app()->getCacheInstance()->cleanType('config');
} catch (Exception $e) {
$resp = json_encode(array('status' => 'error: '.print_r($e->getMessage(), true)));
$response->setBody($resp);
Mage::logException($e);
return;
}
$resp = array('new_state' => 0,
'status' => 'ok',
);
$response->setBody(json_encode($resp));
}
public function getLayeredSearchConfigAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$authkey = $request->getParam('authentication_key');
$uuid = $request->getParam('uuid');
$scopeId = $request->getParam('store_id', 1);
if (!$this->valid($uuid, $authkey)) {
$resp = json_encode(array('status' => $this->__('error: Authentication failed')));
$response->setBody($resp);
return;
}
try {
Mage::app()->getCacheInstance()->cleanType('config');
$current_state = $this->_getConfig()->getLayeredNavigationStatus($scopeId);
} catch (Exception $e) {
$resp = json_encode(array('status' => 'error: '.print_r($e->getMessage(), true)));
$response->setBody($resp);
Mage::logException($e);
return;
}
$resp = json_encode(array('current_state' => $current_state));
$response->setBody($resp);
}
protected function valid($uuid, $authkey)
{
if ($this->_getConfig()->getAuthorizationKey() == $authkey
&& $this->_getConfig()->getUUID() == $uuid) {
return true;
}
return false;
}
}
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of mysql4-install-1
*
* @author <NAME>
*/
$installer = $this;
$installer->startSetup();
$installer->run("
DROP TABLE IF EXISTS {$this->getTable('romcity/romcity')};
CREATE TABLE {$this->getTable('romcity/romcity')} (
`city_id` mediumint(8) unsigned NOT NULL auto_increment,
`country_id` varchar(4) NOT NULL default '0',
`region_id` varchar(4) NOT NULL default '0',
`cityname` varchar(255) default NULL,
PRIMARY KEY (`city_id`),
KEY `FK_CITY_REGION` (`region_id`))
ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Region Cities';
");
$write = Mage::getSingleton("core/resource")->getConnection("core_write");
// Now you can run ANY Magento code you want
//echo '<pre>';print_r($regions_array);
// Initiate curl
$url="http://api.rajaongkir.com/starter/city/?key=1dea532801d380fbde5bf6de9fa6845b";
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
$result= json_decode($result,true);
/*add Region*/
$query='INSERT INTO `directory_country_region` (`country_id`, `code`, `default_name`) VALUES '
. '(:country_id,:code,:name)';
foreach($result['rajaongkir']['results'] as $res)
{
$region_array[]=$res['province'];
}
$region_array= array_unique($region_array);
foreach($region_array as $res1)
{
//$query .= '("ID","'.$res1.'","'.$res1.'"),';
$binds=array("country_id"=>"ID","code"=>$res1,"name"=>$res1);
$write->query($query, $binds);
}
/*add City */
// Change 12 to the ID of the product you want to load
$regionCollection = Mage::getModel('directory/region_api')->items("ID");
foreach($regionCollection as $regions)
{
$regions_array[$regions['region_id']]=$regions['code'];
}
$query='INSERT INTO `directory_country_region_city` (`country_id`, `region_id`, `cityname`) VALUES (:country_id,:region_id,:cityname)';
foreach($result['rajaongkir']['results'] as $res)
{
// $region_array[]=$res['province'];
$region_id=array_search($res['province'],$regions_array);
// $query .= '("ID","'.$region_id.'","'.$res['city_name'].'"),';
$binds=array("country_id"=>"ID","region_id"=>$region_id,"cityname"=>$res['city_name']);
$write->query($query, $binds);
}
$installer->endSetup(); | 4c40201fff0a74c5d7ed6aa9d2ac9b0a00068d3e | [
"PHP"
] | 7 | PHP | vasimm02/magento | 15d779a23f2d4cb27ecc5b5a6fdb3119d2626a15 | efaa733d2b544ed9b355ed6139248389ecc32c30 |
refs/heads/master | <repo_name>CapNick/ManyFacesWeb<file_sep>/db/migrate/20180227171809_remove_modules_from_faces.rb
class RemoveModulesFromFaces < ActiveRecord::Migration[5.0]
def change
remove_column :faces, :modules, :string
end
end
<file_sep>/db/migrate/20171109143536_add_photo_to_faces.rb
class AddPhotoToFaces < ActiveRecord::Migration[5.0]
def change
add_column :faces, :photo, :string
add_column :faces, :created_at, :datetime
add_column :faces, :updated_at, :datetime
end
end
<file_sep>/db/migrate/20171123195841_add_overrides.rb
class AddOverrides < ActiveRecord::Migration[5.0]
def change
add_column :faces, :ovr_name, :string
add_column :faces, :ovr_type, :string
add_column :faces, :ovr_position, :string
add_column :faces, :ovr_modules, :string
add_column :faces, :ovr_room, :string
add_column :faces, :ovr_email, :string
add_column :faces, :ovr_phone, :string
add_column :faces, :ovr_photo, :string
end
end
<file_sep>/app/views/layouts/_layout.json.jbuilder
json.extract! layout, :width, :height
json.url layouts_url(layout, format: :json)
<file_sep>/README.rdoc
== README
# ManyFaces Admin Website
This web application can be used to update the content and layout of the ManyFaces digital staff board.
--------------------
# Setup
1. Install Rails
To start the web server, Rails must be installed. All of the necessary steps for installing Rails are listed in section 3.1 of [this page](http://guides.rubyonrails.org/getting_started.html).
----------
2. Install libraries
Once Rails has been installed, navigate into the application's file directory using a terminal, e.g.
$ cd C://.../ManyFacesWeb
Then run the following command to install all of the libraries that the application depends on:
$ bundle install
----------
3. Create the database
To create the database, run the following commands from inside the application's file directory:
$ rails db:migrate
$ rails db:seed
Note that this only has to be done **once**, before the web server is launched for the first time.
----------
4. Launch the web server
To launch the web server, run the following command from inside the application's file directory:
$ rails server
The web application can then be accessed at [localhost:3000](http://localhost:3000) using a web browser. The application has been tested for compatibility with Google Chrome, Mozilla Firefox and Microsoft Edge.
To shut down the web server, press CTRL+C inside the same terminal window.
--------------------
# FAQ
* How do I add a user account?
All database updates that cannot be performed using the web application will require use of the Rails console.
To open the Rails console, navigate into the application's file directory using a terminal, then run the command:
$ rails console
From the console, run the following command to create new login credentials:
$ User.create!(email: 'new_email_here', password: '<PASSWORD>')
Note that passwords must be at least 6 characters long.
To close the Rails console, run the ``quit`` command.
----------
* How do I change my password?
To change your password, first open the Rails console (see previous question), then run the following commands:
$ temp = User.where(email: 'your_email_here').first
$ temp.password = '<PASSWORD>'
$ temp.save
These commands will create a reference to your user record, update the password, and apply the change.
----------
* How do I add more grid dimensions to the 'Reorder Faces' screen?
To add a new set of dimensions, first open the Rails console (see first question), then run the following commands:
$ Layout.create!(width: 'new_width_here', height: 'new_height_here', selected: 'false')
This set of dimensions can then be selected from the 'Reorder Faces' screen.<file_sep>/db/migrate/20171109142244_create_faces.rb
class CreateFaces < ActiveRecord::Migration[5.0]
def change
create_table :faces do |t|
t.string :name
t.string :room
t.string :modules
t.string :email
end
end
end
<file_sep>/db/migrate/20180315223535_rename_index.rb
class RenameIndex < ActiveRecord::Migration[5.0]
def change
rename_column :faces, :index, :_index
end
end
<file_sep>/app/models/face.rb
class Face < ActiveRecord::Base
mount_uploader :model_file, ModelUploader
# these fields cannot be nil
validates :name, presence: true, uniqueness: true, length: {minimum: 2, maximum: 40}
validates :_type, presence: true
validates :position, presence: true
end<file_sep>/app/controllers/faces_controller.rb
require 'httparty'
require 'nokogiri'
require 'spawnling'
class FacesController < ApplicationController
include HTTParty
include Nokogiri
before_action :authenticate_user!, except: [:collection] # user must log in before the following actions
before_action :get_face, only: [:edit, :update, :show, :destroy] # get the selected staff member from the Faces table before these actions
# the /faces/collection.json page
def collection
@faces = Face.where(visible: true).order('_index ASC') # get all visible staff members, ordered by their position in the grid
end
# the root, 'view all staff' page
def index
@faces = Face.order('name') # get all staff members, ordered by their name
@faces_all = Face.where(visible: true) # get only visible staff members
end
# the 'add new staff member' page
def new
@face = Face.new # create a new Face object
end
# the 'update staff member' page
def edit
end
# update a staff member's details
def update
if @face.update(face_params) # if validation checks are passed
flash[:notice] = "Staff member was successfully updated." # display a confirmation message
redirect_to faces_path # return to the previous page
else
render 'edit' # otherwise, load any error messages
end
end
# create a new staff member in the Faces table
def create
@face = Face.new(face_params) # create a new Face object
@face._index = Face.count == 0 ? 0 : Face.order('_index DESC').first._index + 1 # give it a unique grid position
if @face.room.empty?
@face.room = "None" # use default room value
end
if @face.email.empty?
@face.email = "None" # use default email value
end
if @face.phone.empty?
@face.phone = "None" # use default contact number value
end
if @face.photo.empty?
@face.photo = "None" # use default photo URL value
end
if @face.save # if the new record was accepted
flash[:notice] = "Staff member was successfully created." # display a confirmation message
redirect_to faces_path # return to the previous page
else
render 'new' # otherwise, load any error messages
end
end
# deletes a staff member
def destroy
old_index = @face._index # get the grid position of the staff member
@face.destroy # delete the staff member
flash[:notice] = "Staff member was successfully deleted." # display a confirmation message
Face.where('_index > ?', old_index).update_all('_index = _index - 1') # decrement the indexes of staff members that follow
redirect_to faces_path # reload the page
end
# sync the Faces table with the UoN CS staff information website
def scrape
$order = Face.count == 0 ? 0 : Face.order('_index DESC').first._index + 1 # set the initial grid position
scrape_page "Academic" # scrape the CS academic staff web page
scrape_page "Administrative" # scrape the CS admin staff web page
scrape_page "Technical" # scrape the CS technical staff web page
update_rooms # scrape the rooms of all staff members
redirect_to faces_path # reload the page
end
# update the 'visibility' for a staff member
def toggle_visible
@face = Face.find(params[:face]) # find the staff member's Face object
old_index = @face._index # get their current grid position
visible = !@face.visible # toggle the 'visibility' value
new_index = visible ? Face.order('_index DESC').first._index + 1 : -1 # set index to -1 if now invisible or the maximum index if now visible
@face.update_attributes(visible: visible, _index: new_index) # apply changes
unless visible # if staff member is now visible
Face.where('_index > ?', old_index).update_all('_index = _index - 1') # decrement the position of staff members that follow
end
end
# the 'layout customisation' page
def reorder
@faces = Face.where('_index >= ?', 0).order('_index') # get all visible staff members, ordered by their grid position
@layouts = Layout.order('width') # get the list of selectable grid dimensions
@selected = Layout.where(selected: true).first # get the currently selected grid dimensions
end
# updates the layout of the grid of staff members
def update_order
# updates staff member grid positions
order = params[:order] # get the order, passed from the client
index = 0 # set the initial grid position
order.each do |obj| # for each grid element
if obj != 'blank' # if the element is not a blank frame
vals = obj.split('-')
@face = Face.find(vals[0]) # get the next staff member
unless @face._index == index # if their index is different
@face.update_attribute(:_index, index) # update their index
end
unless @face.label == vals[1] # if their label is different
@face.update_attribute(:label, vals[1]) # update their label
end
end
index += 1 # increment the current grid position
end
# update grid dimensions
width = params[:width] # get the selected width, passed from the client
height = params[:height] # get the selected height, passed from the client
@oldLayout = Layout.where(selected: true).first # get the Layout object that was previously selected
unless @oldLayout.width.to_s == width && @oldLayout.height.to_s == height # unless the dimensions have not changed
@newLayout = Layout.where(width: width, height: height).first # get the Layout object with the selected dimensions
@oldLayout.selected = false # deselect the old Layout object in the table
@newLayout.selected = true # select the new Layout object in the table
@oldLayout.save # save both objects
@newLayout.save
end
redirect_to faces_path # return to the previous page
end
private
# gets the staff member object with the selected record 'id'
def get_face
@face = Face.find(params[:id])
end
def face_params
params.require(:face).permit(:name, :_type, :position, :room, :email, :phone, :photo, :model_file, :visible, :ovr_name, :ovr_type, :ovr_position, :ovr_room, :ovr_email, :ovr_phone, :ovr_photo, :remove_model_file)
end
# pulls a group of staff members' information from the UoN CS website
def scrape_page(type)
field = type.to_s.downcase # academic, administrative or technical?
uri = 'https://www.nottingham.ac.uk/computerscience/people/' # the URL to scrape from
page = Nokogiri::HTML(HTTParty.get(uri)) # the page source
page.at_css("div#lookup-#{field}").css('tr').map do |row| # for each row in the details table
if row.css('th').text.to_s.include?('Academic Staff in Malaysia') # do not scrape international staff details
break
end
unless row.css('a')[0].nil?
unless row.css('td')[0].css('a')[0]['href'].include? 'mailto:'
names = row.css('td')[0].css('a')[0].text.to_s.split(', ') # extract name
first_name = names[1].delete(' ')
last_name = names[0].delete(' ')
webpage = uri + row.css('td')[0].css('a')[0]['href'] # extract academic webpage
name = first_name + ' ' + last_name
contact = row.css('td')[1].text.to_s.gsub(/\s+/, "") # extract contact number
title = row.css('td')[2].text # extract role in school
email = row.css('a')[0]['href'] + '@nottingham.ac.uk' # extract email address
image_url = uri + 'staff-images/' + first_name.downcase + last_name.downcase + '.jpg' # extract portrait photo
order = $order
$order += 1 # increment the next grid position
@face = Face.all.where(name: name).first
if @face # if the staff member already exists
# puts "updating existing..."
@face.update_attributes(:email => email, :photo => image_url, :phone => contact, :position => title, :_type => type, :url => webpage) # update the existing staff object
else
# puts "creating new..."
Face.create(:name => name, :room => "None", :email => email, :photo => image_url, :phone => contact, :position => title, :_type => type, :url => webpage, :_index => order, :label => "") # otherwise create a new one
end
end
end
end
end
# pull a staff member's room from their personal website
def scrape_room(webpage)
page = Nokogiri::HTML(HTTParty.get(webpage)) # get the page source
address_line = page.at_css("div#lookup-personal-details").css('span.street-address').first.to_s # extract the first line of staff member's address
temp = address_line.split(">")[1].to_s # remove HTML tags
temp = temp.split("<")[0]
if temp.to_s.include? '&'
temp.to_s.sub! '&', '&' # fix encoding issues
end
if temp.to_s.length == 0
temp = "None" # not all staff members have rooms, so replace with 'None' if so
else
if temp.start_with?('Room') # remove the word 'room'
temp.slice!(0, 5)
end
end
temp.to_s
end
# update the rooms of all staff members in the Faces table
def update_rooms
Face.all.each do |f| # for all staff members
if f.url? # if their personal website was previously scraped
f.room = scrape_room f.url # scrape their room from it
f.save
end
end
end
end<file_sep>/db/migrate/20180227172137_remove_ovr_modules_from_faces.rb
class RemoveOvrModulesFromFaces < ActiveRecord::Migration[5.0]
def change
remove_column :faces, :ovr_modules, :string
end
end
<file_sep>/app/assets/javascripts/faces.js
// updates a staff member's 'visible' field
function toggle_visible(id) {
$.ajax({ // generate an ajax request
method: "POST",
url: "/faces/toggle_visible", // invoke the toggle_visible controller action
data: "face="+id,
success: function() {
var selector = '#' + id; // get the selected staff member's table row ID
var row = $(selector);
if (row.hasClass('default')) {
row.attr('class', 'coloured'); // update the colour of the row appropriately
} else {
row.attr('class', 'default');
}
}
});
}
// saves the updated staff board layout
function update_order() {
$('#progressbar').css('display', 'block'); // displays a progress bar
var order = [];
$('#ordering li').each(function(e) { // for each element in the list
if ($(this).hasClass('blank')) { // if the element is a blank div
order.push('blank'); // push the 'blank' string into the order array
} else {
var id = $(this).attr('id'); // get the id of the staff member
var label = $('#label-' + id).val(); // get any text entered into their 'label' field
order.push(id + '-' + label); // push their id and label into the order array
}
});
var dimens = $('#dimensions').val().split(' x '); // get the selected width and height
$.ajax({ // generate an ajax request
method: "POST",
url: "/faces/update_order", // invoke the update_order controller action
data: {'order': order, 'width': dimens[0], 'height': dimens[1]} // transfer the ordered list of staff and the selected dimensions
});
}
// adds a new blank frame to the grid of staff members
function add_blank() {
$('#ordering').prepend("" +
"<li style='border: 1px dashed #c5c5c5'" +
"class='blank'>" +
"<button class='btn-delete-blank'" +
"onclick='delete_blank(this)'>" +
"Delete</button>" +
"</li>"); // add the blank frame to the start of the list
window.cutoff = window.cutoff + 1; // 'cut off' one more staff member
update_cutoff();
}
// removes a blank frame from the grid of staff members
function delete_blank(button) {
button.parentNode.remove(); // remove the blank frame
window.cutoff = window.cutoff - 1; // 'cut off' one less staff member
update_cutoff();
}
// updates the width/height of the grid of staff members
function update_dimens(dimens) {
var xy = dimens.split(' x ');
var x = parseInt(xy[0]); // get the selected width (in models)
var y = parseInt(xy[1]); // get the selected height (in models)
var width = x * 102; // get the new width of the on-screen grid
$('#ordering').css('width', width + 'px'); // apply the new width
var total = x * y; // get the total number of staff members displayed
var items = $('#ordering li');
window.cutoff = items.length - total; // get the number of staff members that will be 'cut off'
update_cutoff();
}
// colours the frames in the grid of staff members according to whether
// they have been cut off by the selected dimensions
function update_cutoff() {
var items = $('#ordering li');
var shown = items.length - window.cutoff;
items.slice(0, shown).not('.blank').css('background-color', '#f6f6f6'); // colour the frames of visible staff members light grey
if (window.cutoff > 0) { // if any staff members are cut off
items.slice(-window.cutoff).not('.blank').css('background-color', '#d9d9d9'); // colour the frames of invisible staff members dark grey
}
}
$(document).on('turbolinks:load', function() {
$('#btn-sync').click(function() { // when the 'sync' button is clicked
var icon = $(this).find(".glyphicon.glyphicon-refresh");
animateClass = "glyphicon-refresh-animate";
icon.addClass(animateClass); // rotate the 'syncing' icon
});
$('#ordering').sortable({ // make the grid of staff members sortable
placeholder: "placeholder",
stop: function(event, ui) {
update_cutoff(); // update the colour of the displaced frames
}
});
$('#progressbar').progressbar({
value: false // display progress, but no value
});
$('.datatable').dataTable({ // add sorting and search functionality to the staff table
columnDefs: [{
targets: [7, 8, 9],
sortable: false}] // do not allow the sorting of the last 3 columns
});
$('.datatable').each(function(){
var datatable = $(this);
var search_input = datatable.closest('.dataTables_wrapper').find('div[id$=_filter] input'); // get the search field
search_input.attr('placeholder', 'e.g. <NAME>'); // add placeholder text to the search field
search_input.attr('id', 'search');
search_input.addClass('form-control input-sm'); // add styling to the search field
var length_sel = datatable.closest('.dataTables_wrapper').find('div[id$=_length] select');
length_sel.addClass('form-control input-sm'); // add styling to the '# of items' dropdown menu
});
$('.btn-visible').click(function() { // when a 'visibility' button is clicked
var span = $(this).children('span');
var visible = span.hasClass('glyphicon-eye-open'); // check whether button icon is an open or closed eye
var oldClass = visible ? 'glyphicon-eye-open' : 'glyphicon-eye-close';
var newClass = visible ? 'glyphicon-eye-close' : 'glyphicon-eye-open';
span.addClass(newClass).removeClass(oldClass); // toggle the button icon
});
var dimens = $('#dimensions');
dimens.selectmenu(); // make the list of selectable dimensions a dropdown menu
dimens.on('selectmenuchange', function() { // when a selection is made
update_dimens($(this).val()); // update the dimensions of the on-screen grid of staff members
});
});
<file_sep>/db/migrate/20180301205253_add_photo_file_to_faces.rb
class AddPhotoFileToFaces < ActiveRecord::Migration[5.0]
def change
add_column :faces, :photo_file, :string
end
end
<file_sep>/db/migrate/20180313151417_add_label_to_faces.rb
class AddLabelToFaces < ActiveRecord::Migration[5.0]
def change
add_column :faces, :label, :string
end
end
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
User.create!(email: '<EMAIL>', password: '<PASSWORD>')
Layout.create!(width: 5, height: 3, selected: false)
Layout.create!(width: 10, height: 5, selected: true)
Layout.create!(width: 14, height: 6, selected: false)<file_sep>/db/migrate/20171113153206_add_position_to_faces.rb
class AddPositionToFaces < ActiveRecord::Migration[5.0]
def change
add_column :faces, :telephone, :string
add_column :faces, :position, :string
add_column :faces, :type, :string
end
end
<file_sep>/db/migrate/20180315223219_rename_order_to_index.rb
class RenameOrderToIndex < ActiveRecord::Migration[5.0]
def change
rename_column :faces, :order, :index
end
end
<file_sep>/db/migrate/20180418152317_rename_photo_file_to_model.rb
class RenamePhotoFileToModel < ActiveRecord::Migration[5.0]
def change
remove_column :faces, :model, :string
rename_column :faces, :photo_file, :model_file
end
end
<file_sep>/db/migrate/20180409181103_create_layouts.rb
class CreateLayouts < ActiveRecord::Migration[5.0]
def change
create_table :layouts do |t|
t.integer :width
t.integer :height
t.boolean :selected
end
end
end
<file_sep>/db/migrate/20171113155036_rename_columns.rb
class RenameColumns < ActiveRecord::Migration[5.0]
def change
rename_column :faces, :type, :_type
rename_column :faces, :telephone, :phone
end
end
<file_sep>/app/controllers/layouts_controller.rb
class LayoutsController < ApplicationController
# the /layouts.json page
def index
@layouts = Layout.where(selected: true) # get the currently selected dimensions
end
end<file_sep>/README.md
# ManyFaces Admin Website
This web application can be used to update the content and layout of the ManyFaces digital staff board.
### Setup
**1. Install Rails**
To start the web server, Rails must be installed. All of the necessary steps for installing Rails are listed in section 3.1 of [this page](http://guides.rubyonrails.org/getting_started.html).
**2. Install libraries**
Once Rails has been installed, navigate into the application's file directory using a terminal, e.g.
$ cd C://.../ManyFacesWeb
Then run the following command to install all of the libraries that the application depends on:
$ bundle install
**3. Create the database**
To create the database, run the following commands from inside the application's file directory:
$ rails db:migrate
$ rails db:seed
Note that this only has to be done **once**, before the web server is launched for the first time.
**4. Launch the web server**
To launch the web server, run the following command from inside the application's file directory:
$ rails server
The web application can then be accessed at [localhost:3000](http://localhost:3000) using a web browser. The application has been tested for compatibility with Google Chrome, Mozilla Firefox and Microsoft Edge.
To shut down the web server, press CTRL+C inside the same terminal window.
### FAQ
**- How do I add a user account?**
All database updates that cannot be performed using the web application will require use of the Rails console.
To open the Rails console, navigate into the application's file directory using a terminal, then run the command:
$ rails console
From the console, run the following command to create new login credentials:
$ User.create!(email: 'new_email_here', password: '<PASSWORD>')
Note that passwords must be at least 6 characters long.
To close the Rails console, run the ``quit`` command.
**- How do I change my password?**
To change your password, first open the Rails console (see previous question), then run the following commands:
$ temp = User.where(email: 'your_email_here').first
$ temp.password = '<PASSWORD>'
$ temp.save
These commands will create a reference to your user record, update the password, and apply the change.
**- How do I add more grid dimensions to the 'Reorder Faces' screen?**
To add a new set of dimensions, first open the Rails console (see first question), then run the following commands:
$ Layout.create!(width: 'new_width_here', height: 'new_height_here', selected: 'false')
This set of dimensions can then be selected from the 'Reorder Faces' screen. | e8970e6d37ca4851e6115b00ce829382a892861f | [
"JavaScript",
"RDoc",
"Ruby",
"Markdown"
] | 21 | Ruby | CapNick/ManyFacesWeb | 20136d0c6ddf0b227e445efc65e9f421ee1b0f36 | bc5b4b0c023ddc11c2e0006b5a757b1c670d39dd |
refs/heads/main | <repo_name>paulinakorpak/seats-booking<file_sep>/src/features/message/components/Message/index.js
import React from 'react';
import { Alert } from 'react-bootstrap';
import { useSelector } from 'react-redux';
import { selectMessage } from '../../messageSlice';
function Message() {
const message = useSelector(selectMessage);
if (!message) {
return null;
}
return (
<Alert
className="text-center position-fixed w-100"
variant={message.type}
data-test="alert"
>
{message.content}
</Alert>
);
}
export default Message;
<file_sep>/src/features/booking/components/SeatsMap/helpers.js
export const getLastSeatCoords = (seats) => seats.reduce(
([lastRow, lastCol], seat) => [
seat.cords.y > lastRow ? seat.cords.y : lastRow,
seat.cords.x > lastCol ? seat.cords.x : lastCol,
],
[0, 0],
);
export const suggestSeats = (seatsNumber, adjacentSeats, lastRow, lastCol, seats) => {
let suggestedSeats = [];
for (let row = lastRow; row >= 0; row -= 1) {
for (let col = 0; col <= lastCol; col += 1) {
const firstSeat = seats.find((item) => item.cords.x === col && item.cords.y === row);
if (firstSeat && !firstSeat.reserved) {
suggestedSeats.push(firstSeat);
if (adjacentSeats) {
for (let next = col + 1; next < col + seatsNumber; next += 1) {
const nextSeat = seats.find((item) => item.cords.x === next && item.cords.y === row);
if (nextSeat && !nextSeat.reserved) {
suggestedSeats.push(nextSeat);
} else {
col = next;
suggestedSeats = [];
break;
}
}
}
if (suggestedSeats.length === seatsNumber) {
return suggestedSeats;
}
}
}
}
return [];
};
<file_sep>/src/features/booking/components/SeatsMap/index.js
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import PropTypes from 'prop-types';
import Container from './styles';
import Seat from '../Seat';
import fetchSeats from '../../bookingAPI';
import { getLastSeatCoords, suggestSeats } from './helpers';
import Space from '../Space';
import { selectSeatsNumber, selectAdjacentSeats } from '../../bookingSlice';
import { setMessage, clearMessage } from '../../../message/messageSlice';
import { ALL_SEATS_SELECTED, NO_SEATS_SELECTED, SUGGESTION_NOT_POSSIBLE } from '../../../message/messageTypes';
function SeatsMap({ selectedSeats, setSelectedSeats }) {
const [seats, setSeats] = useState([]);
const dispatch = useDispatch();
const seatsNumber = useSelector(selectSeatsNumber);
const adjacentSeats = useSelector(selectAdjacentSeats);
const [lastRow, lastCol] = getLastSeatCoords(seats);
useEffect(() => {
fetchSeats()
.then((data) => {
setSeats(data);
});
}, []);
useEffect(() => {
if (seats.length > 0) {
const suggestedSeats = suggestSeats(seatsNumber, adjacentSeats, lastRow, lastCol, seats);
setSelectedSeats(suggestedSeats);
if (suggestedSeats.length === 0) {
dispatch(setMessage(SUGGESTION_NOT_POSSIBLE));
}
}
}, [seats]);
const handleSeatClick = (seat) => {
const alreadySelected = selectedSeats.find((item) => item.id === seat.id);
if (!alreadySelected) {
if (selectedSeats.length < seatsNumber) {
setSelectedSeats([...selectedSeats, seat]);
} else {
dispatch(setMessage(ALL_SEATS_SELECTED));
}
} else {
setSelectedSeats(selectedSeats.filter((item) => item.id !== seat.id));
dispatch(clearMessage(ALL_SEATS_SELECTED));
}
dispatch(clearMessage(NO_SEATS_SELECTED));
dispatch(clearMessage(SUGGESTION_NOT_POSSIBLE));
};
const gridContent = [];
let key = 0;
for (let row = lastRow; row >= 0; row -= 1) {
const rowContent = [];
for (let col = 0; col <= lastCol; col += 1) {
const seat = seats.find((item) => item.cords.x === col && item.cords.y === row);
if (seat) {
const selected = selectedSeats.some((item) => item.id === seat.id);
rowContent.push(
<Seat
key={key}
seat={seat}
selected={selected}
handleSeatClick={handleSeatClick}
/>,
);
} else {
rowContent.push(
<Space
key={key}
/>,
);
}
key += 1;
}
gridContent.push(<div key={row} className="d-flex justify-content-center">{rowContent}</div>);
}
return (
<Container>
{gridContent}
</Container>
);
}
export default SeatsMap;
SeatsMap.propTypes = {
selectedSeats: PropTypes.arrayOf(PropTypes.object).isRequired,
setSelectedSeats: PropTypes.func.isRequired,
};
<file_sep>/src/pages/booking/SeatsPage/styles.js
import styled from 'styled-components';
import { Button as Btn } from 'react-bootstrap';
export const Wrapper = styled.div`
margin: auto;
`;
export const Footer = styled.div`
margin-top: 30px;
height: 30px;
flex-direction: column;
@media (min-width: 768px) {
flex-direction: row;
}
`;
export const SeatType = styled.div`
margin-right: 20px;
.symbol {
min-width: 20px;
min-height: 20px;
border: 1px grey solid;
margin-right: 10px;
@media (min-width: 768px) {
min-width: 30px;
min-height: 30px;
}
}
.booked {
background-color: grey;
}
.selected {
background-color: orange;
}
.text {
font-size: 8px;
@media (min-width: 768px) {
font-size: 12px;
}
}
`;
export const Button = styled(Btn)`
width: 50%;
margin-top: 30px;
@media (min-width: 768px) {
width: 25%;
margin-top: 0;
}
`;
<file_sep>/src/features/booking/components/SeatsMap/styles.js
import styled from 'styled-components';
const Container = styled.div`
border: 1px solid grey;
padding: 10px;
@media (min-width: 768px) {
padding: 30px;
}
`;
export default Container;
<file_sep>/src/features/booking/bookingAPI.js
const fetchSeats = () => fetch(`${process.env.REACT_APP_BOOKING_API_URL}/seats`)
.then((response) => response.json());
export default fetchSeats;
<file_sep>/src/features/booking/components/Space/styles.js
import styled from 'styled-components';
const Element = styled.div`
width: 20px;
height: 20px;
margin: 5px;
@media (min-width: 768px) {
width: 30px;
height: 30px;
}
`;
export default Element;
<file_sep>/src/features/booking/bookingSteps.js
export const FORM_STEP = 'Form';
export const MAP_STEP = 'Map';
export const SUMMARY_STEP = 'Summary';
const bookingSteps = [FORM_STEP, MAP_STEP, SUMMARY_STEP];
export default bookingSteps;
<file_sep>/src/pages/booking/SummaryPage/index.js
import React from 'react';
import { Alert } from 'react-bootstrap';
import SeatsSummary from '../../../features/booking/components/SeatsSummary';
function SummaryPage() {
return (
<Alert
variant="light"
className="d-flex flex-column align-items-center justify-content-between align-self-center h-50"
data-test="summary"
>
<Alert.Heading className="text-center">Twoja rezerwacja przebiegła pomyślnie!</Alert.Heading>
<hr />
<SeatsSummary />
<hr />
<p className="text-justify mt-4">
Dziękujemy! W razie problemów prosimy o kontakt z działem administracji.
</p>
</Alert>
);
}
export default SummaryPage;
<file_sep>/src/features/booking/bookingSlice.js
import { createSlice } from '@reduxjs/toolkit';
import bookingSteps from './bookingSteps';
const initialState = {
step: bookingSteps[0],
seatsNumber: 0,
adjacentSeats: false,
bookedSeats: [],
};
export const bookingSlice = createSlice({
name: 'booking',
initialState,
reducers: {
setNextStep: (state) => {
const stepIndex = bookingSteps.findIndex((step) => step === state.step);
state.step = bookingSteps[stepIndex + 1];
},
setSeatsNumber: (state, action) => {
state.seatsNumber = action.payload;
},
setAdjacentSeats: (state, action) => {
state.adjacentSeats = action.payload;
},
setBookedSeats: (state, action) => {
state.bookedSeats = action.payload;
},
},
});
export const {
setNextStep, setSeatsNumber, setAdjacentSeats, setBookedSeats,
} = bookingSlice.actions;
export const selectStep = (state) => state.booking.step;
export const selectSeatsNumber = (state) => state.booking.seatsNumber;
export const selectAdjacentSeats = (state) => state.booking.adjacentSeats;
export const selectBookedSeats = (state) => state.booking.bookedSeats;
export default bookingSlice.reducer;
<file_sep>/src/app/store.js
import { configureStore } from '@reduxjs/toolkit';
import bookingReducer from '../features/booking/bookingSlice';
import messageReducer from '../features/message/messageSlice';
const store = configureStore({
reducer: {
booking: bookingReducer,
message: messageReducer,
},
});
export default store;
<file_sep>/src/app/app.js
import React from 'react';
import { useSelector } from 'react-redux';
import Wrapper from './styles';
import FormPage from '../pages/booking/FormPage';
import SeatsPage from '../pages/booking/SeatsPage';
import SummaryPage from '../pages/booking/SummaryPage';
import { selectStep } from '../features/booking/bookingSlice';
import { FORM_STEP, MAP_STEP, SUMMARY_STEP } from '../features/booking/bookingSteps';
import Message from '../features/message/components/Message';
function App() {
const step = useSelector(selectStep);
return (
<>
<Message />
<Wrapper className="container-sm d-flex justify-content-center align-items-center">
{ step === FORM_STEP && <FormPage /> }
{ step === MAP_STEP && <SeatsPage /> }
{ step === SUMMARY_STEP && <SummaryPage /> }
</Wrapper>
</>
);
}
export default App;
<file_sep>/src/pages/booking/FormPage/index.js
import React from 'react';
import SeatsForm from '../../../features/booking/components/SeatsForm';
function FormPage() {
return <SeatsForm />;
}
export default FormPage;
<file_sep>/src/features/booking/components/Seat/styles.js
import styled from 'styled-components';
const Element = styled.div`
width: 20px;
height: 20px;
margin: 5px;
border: 1px solid grey;
cursor: pointer;
&.reserved {
background-color: grey;
cursor: default;
}
&.selected {
background-color: orange;
}
@media (min-width: 768px) {
width: 30px;
height: 30px;
}
`;
export default Element;
<file_sep>/src/features/booking/components/SeatsSummary/index.js
import React from 'react';
import { ListGroup } from 'react-bootstrap';
import { useSelector } from 'react-redux';
import { selectBookedSeats } from '../../bookingSlice';
function SeatsSummary() {
const bookedSeats = useSelector(selectBookedSeats);
return (
<>
<h4 className="text-center text-uppercase text-secondary">wybrane miejsca:</h4>
<ListGroup
className="mt-2 w-75"
data-test="seats-summary"
>
{
bookedSeats.map((seat) => (
<ListGroup.Item
key={seat.id}
variant="dark"
className="p-2 d-flex justify-content-around"
>
RZĄD
<strong>{seat.cords.y}</strong>
MIEJSCE
<strong>{seat.cords.x}</strong>
</ListGroup.Item>
))
}
</ListGroup>
</>
);
}
export default SeatsSummary;
<file_sep>/src/pages/booking/SeatsPage/index.js
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import SeatsMap from '../../../features/booking/components/SeatsMap';
import {
Wrapper, Footer, SeatType, Button,
} from './styles';
import { setBookedSeats, setNextStep } from '../../../features/booking/bookingSlice';
import { setMessage } from '../../../features/message/messageSlice';
import { NO_SEATS_SELECTED } from '../../../features/message/messageTypes';
function SeatsPage() {
const [selectedSeats, setSelectedSeats] = useState([]);
const dispatch = useDispatch();
const handleClick = () => {
if (selectedSeats.length > 0) {
dispatch(setBookedSeats(selectedSeats));
dispatch(setNextStep());
} else {
dispatch(setMessage(NO_SEATS_SELECTED));
}
};
return (
<Wrapper
className="d-flex flex-column justify-content-center align-items-center"
data-test="seats-map"
>
<SeatsMap
selectedSeats={selectedSeats}
setSelectedSeats={setSelectedSeats}
/>
<Footer className="d-flex">
<div className="d-flex justify-content-between">
<SeatType className="d-flex align-items-center">
<div className="symbol" />
<div className="text">Dostępne</div>
</SeatType>
<SeatType className="d-flex align-items-center">
<div className="symbol booked" />
<div className="text">Zarezerwowane</div>
</SeatType>
<SeatType className="d-flex align-items-center">
<div className="symbol selected" />
<div className="text">Wybrane</div>
</SeatType>
</div>
<Button
onClick={handleClick}
variant="outline-secondary"
className="align-self-center"
data-test="seats-page-submit"
>
Rezerwuj
</Button>
</Footer>
</Wrapper>
);
}
export default SeatsPage;
<file_sep>/src/app/styles.js
import styled from 'styled-components';
const Wrapper = styled.div`
width: 100wv;
height: 100vh;
min-width: 500px;
font-size: 15px;
@media (min-width: 900px) {
min-width: 900px;
}
`;
export default Wrapper;
| 868586ed14e43d67660e2fadcbd02f4e46bf1085 | [
"JavaScript"
] | 17 | JavaScript | paulinakorpak/seats-booking | 6e7855eeca04e3639b6446f370e034f0afac4404 | 80ca09a215d3d627a7192dbba2f563b3b7e3d186 |
refs/heads/main | <repo_name>sgtnamder/Hobby_project<file_sep>/HobbyProject/src/main/resources/static/index.js
'use strict';
const output = document.getElementById("output");
function wait() {
setTimeout(location.reload.bind(location), 250);
}
async function getRaces() {
const response = await fetch(`http://localhost:8080/race/`);
const get = await response.json();
console.info(get);
get.forEach(get => console.log(get));
get.forEach(get => renderRace(get));
};
let renderRace = ({ id, name, date, time, drivers, }) => {
let column = document.createElement("div");
column.className = "col";
let card = document.createElement("div");
card.className = "card";
column.appendChild(card);
let cardHeader = document.createElement("div");
cardHeader.className = "card-header";
cardHeader.innerText = `Name: ${name}, Date: ${date}, Time: ${time} `;
card.appendChild(cardHeader);
let cardBody = document.createElement("div");
cardBody.className = "card-body";
card.appendChild(cardBody);
let listGroup = document.createElement("div");
listGroup.className = "list-group";
cardBody.appendChild(listGroup);
let Raceid = id;
let renderDriver = ({ id, name, teamName, points, driverNum, time, position, }) => {
let driverList = document.createElement("button");
driverList.type = "button";
driverList.innerText = `Name: ${name}, Team Name: ${teamName}, Points: ${points}, Driver Num: ${driverNum}, Time: ${time}, Position ${position}`;
driverList.className = "list-group-item list-group-item-action"
driverList.setAttribute('data-bs-toggle', 'modal');
driverList.setAttribute('data-bs-target', '#updateDriverModal');
driverList.addEventListener("click", function () {
document.getElementById("updateDriverForm").addEventListener("submit", function (event) {
event.preventDefault();
let data = {
name: document.getElementById("UDName").value,
teamName: document.getElementById("UTeamName").value,
points: document.getElementById("UPoints").value,
driverNum: document.getElementById("UDriverNum").value,
time: document.getElementById("UDTime").value,
position: document.getElementById("UPosition").value,
}
fetch("http://localhost:8080/driver/update/" + id, {
method: 'PUT',
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(data)
})
.then(console.log(JSON.stringify(data)))
.then(wait())
.then(res => { res.json() })
.then((data) => console.log(`Request succeeded with JSON response ${data}`))
.catch((error) => console.log(`Request failed ${error}`))
});
})
let deleteDriverButton = document.createElement("button");
deleteDriverButton.innerText = "Delete";
deleteDriverButton.className = "card-button";
deleteDriverButton.addEventListener("click", function () {
deletedriver(id);
});
listGroup.appendChild(driverList);
listGroup.appendChild(deleteDriverButton);
}
drivers.forEach(drivers => renderDriver(drivers));
let cardFooter = document.createElement("div");
cardFooter.className = "card-footer";
card.appendChild(cardFooter);
let deleteButton = document.createElement("button");
deleteButton.innerText = "Delete";
deleteButton.className = "card-button";
deleteButton.addEventListener("click", function () {
deleteRace(id);
});
cardFooter.appendChild(deleteButton);
let updateButton = document.createElement("button");
updateButton.innerText = "Update Race";
updateButton.className = "card-button";
updateButton.setAttribute('data-bs-toggle', 'modal');
updateButton.setAttribute('data-bs-target', '#updateModal');
updateButton.addEventListener("click", function () {
document.getElementById("updateRaceForm").addEventListener("submit", function (event) {
event.preventDefault();
let data = {
name: document.getElementById("UName").value,
date: document.getElementById("UDate").value,
time: document.getElementById("UTime").value
}
fetch("http://localhost:8080/race/update/" + id, {
method: 'PUT',
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(data)
})
.then(console.log(JSON.stringify(data)))
.then(wait())
.then(res => { res.json() })
.then((data) => console.log(`Request succeeded with JSON response ${data}`))
.catch((error) => console.log(`Request failed ${error}`))
});
});
cardFooter.appendChild(updateButton);
let addButton = document.createElement("button");
addButton.innerText = "Add Driver";
addButton.className = "card-button";
addButton.setAttribute('data-bs-toggle', 'modal');
addButton.setAttribute('data-bs-target', '#addModal');
addButton.addEventListener("click", function () {
addDriver(id)
});
cardFooter.appendChild(addButton);
output.appendChild(column);
}
getRaces().catch((err) => console.error(`${err}`));
document.getElementById("createRaceForm").addEventListener("submit", function (event) {
event.preventDefault();
let data = {
name: document.getElementById("Name").value,
date: document.getElementById("Date").value,
time: document.getElementById("Time").value
}
fetch("http://localhost:8080/race/add", {
method: 'post',
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(data)
})
.then(console.log(JSON.stringify(data)))
.then(res => { res.json() })
.then(wait())
.then((data) => console.log(`Request succeeded with JSON response ${data}`))
.catch((error) => console.log(`Request failed ${error}`))
});
const addDriver = async (id) => {
document.getElementById("createDriverForm").addEventListener("submit", function (event) {
event.preventDefault();
let data = {
name: document.getElementById("AName").value,
teamName: document.getElementById("TeamName").value,
points: document.getElementById("Points").value,
driverNum: document.getElementById("DriverNum").value,
time: document.getElementById("DTime").value,
position: document.getElementById("Position").value,
race: {
id: id
}
}
fetch("http://localhost:8080/driver/add", {
method: 'post',
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(data)
})
.then(console.log(JSON.stringify(data)))
.then(res => { res.json() })
.then(wait())
.then((data) => console.log(`Request succeeded with JSON response ${data}`))
.catch((error) => console.log(`Request failed ${error}`))
});
}
const deleteRace = async (id) => {
fetch("http://localhost:8080/race/delete/" + id, {
method: 'delete',
})
.then((data) => {
console.log(`Request succeeded with JSON response ${data}`);
wait();
})
.catch((error) => console.log(`Request failed ${error}`))
};
const deletedriver = async (id) => {
fetch("http://localhost:8080/driver/delete/" + id, {
method: 'delete',
})
.then((data) => {
console.log(`Request succeeded with JSON response ${data}`);
wait();
})
.catch((error) => console.log(`Request failed ${error}`))
};
<file_sep>/HobbyProject/src/test/resources/race-data.sql
insert into race (`id`,`name`,`date`,`time`) values (null, 'Azerbaijan','06,06,2021','13.00');<file_sep>/HobbyProject/bin/src/main/resources/application-prod.properties
server.port=8080
spring.datasource.url=jdbc:mysql//localhost:3006/raceplanner
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true<file_sep>/HobbyProject/src/main/java/com/qa/hobby/mapper/RaceMapper.java
package com.qa.hobby.mapper;
import java.util.ArrayList;
import java.util.List;
import com.qa.hobby.domain.Driver;
import com.qa.hobby.domain.Race;
import com.qa.hobby.dto.DriverDTO;
import com.qa.hobby.dto.RaceDTO;
public class RaceMapper {
private DriverMapper driverMapper;
//creates a new instances of driver mapper to use in the mapper
public RaceMapper(DriverMapper driverMapper) {
super();
this.driverMapper = driverMapper;
}
// maps races to a dto to send back to the front-end
public RaceDTO mapTo(Race race) {
RaceDTO dto = new RaceDTO();
dto.setId(race.getId());
dto.setName(race.getName());
dto.setDate(race.getDate());
dto.setTime(race.getTime());
List<DriverDTO> drivers = new ArrayList<>();
for(Driver driver : race.getDrivers()) {
drivers.add(this.driverMapper.mapTo(driver));
}
dto.setDrivers(drivers);
return dto;
}
}
<file_sep>/HobbyProject/src/main/java/com/qa/hobby/mapper/DriverMapper.java
package com.qa.hobby.mapper;
import com.qa.hobby.domain.Driver;
import com.qa.hobby.dto.DriverDTO;
public class DriverMapper {
public DriverMapper(){
}
// maps drivers to a dto to send back to the front-end
public DriverDTO mapTo(Driver driver) {
DriverDTO dto = new DriverDTO();
dto.setDriverNum(driver.getDriverNum());
dto.setId(driver.getId());
dto.setName(driver.getName());
dto.setPoints(driver.getPoints());
dto.setPosition(driver.getPosition());
dto.setTeamName(driver.getTeamName());
dto.setTime(driver.getTime());
return dto;
}
}
<file_sep>/HobbyProject/src/test/java/com/qa/hobby/unit/DriverServiceUnitTest.java
package com.qa.hobby.unit;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ActiveProfiles;
import com.qa.hobby.domain.Driver;
import com.qa.hobby.dto.DriverDTO;
import com.qa.hobby.repo.DriverRepo;
import com.qa.hobby.service.DriverService;
@SpringBootTest
@ActiveProfiles("test")
public class DriverServiceUnitTest {
@Autowired
private DriverService service;
@MockBean
private DriverRepo repo;
@Test
void testAddDriver(){
//given
Driver driver = new Driver("S.Perez","Redbull",25,11,"2:13:36:410",1);
DriverDTO driverDTO = new DriverDTO("S.Perez","Redbull",25,11,"2:13:36:410",1);
//when
Mockito.when(this.repo.save(driver)).thenReturn(driver);
//then
assertThat(this.service.addDriver(driver)).usingRecursiveComparison().isEqualTo(driverDTO);
Mockito.verify(this.repo,Mockito.times(1)).save(driver);
}
@Test
void testGetallDrivers() {
//given
Driver driver = new Driver("S.Perez","Redbull",25,11,"2:13:36:410",1);
List<Driver> drivers = new ArrayList<>();
drivers.add(driver);
DriverDTO driverDTO = new DriverDTO("S.Perez","Redbull",25,11,"2:13:36:410",1);
List<DriverDTO> driversDTO = new ArrayList<>();
driversDTO.add(driverDTO);
//when
Mockito.when(this.repo.findAll()).thenReturn(drivers);
//then
assertThat(this.service.getDrivers()).usingRecursiveComparison().isEqualTo(driversDTO);
Mockito.verify(this.repo,Mockito.times(1)).findAll();
}
@Test
void testUpdateDriver() {
//given
Integer id = 1;
Driver driver = new Driver("S.Perez","Redbull",25,11,"2:13:36:410",1);
Driver existing = new Driver(id, null, null, null, null, null, null);
Driver updated = new Driver(id,"S.Perez","Redbull",25,11,"2:13:36:410",1);
//when
Mockito.when(this.repo.findById(id)).thenReturn(Optional.of(existing));
Mockito.when(this.repo.save(updated)).thenReturn(updated);
//then
assertThat(this.service.updateDriver(id, driver)).usingRecursiveComparison().isEqualTo(updated);
Mockito.verify(this.repo,Mockito.times(1)).save(updated);
Mockito.verify(this.repo,Mockito.times(1)).findById(id);
}
@Test
void testDeleteDriver() {
//given
Integer id = 1;
boolean value = true;
//when
Mockito.when(this.repo.existsById(id)).thenReturn(!value);
//then
assertThat(this.service.deleteDriver(id)).isEqualTo(value);
Mockito.verify(this.repo,Mockito.times(1)).existsById(id);
}
}
<file_sep>/HobbyProject/src/test/resources/planner-schema.sql
drop table if exists race CASCADE;
drop table if exists driver CASCADE;
create table race
(
`id` integer AUTO_INCREMENT PRIMARY KEY,
`name` varchar(255),
`date` varchar(255),
`time` varchar(255)
);
create table driver
(
`id`integer AUTO_INCREMENT PRIMARY KEY,
`name`varchar(255),
`team_name`varchar(255) ,
`points`integer ,
`driver_num`integer,
`time`varchar(255) ,
`position`integer ,
`race_id`integer
);<file_sep>/HobbyProject/src/test/java/com/qa/hobby/selenium/SeleniumTests.java
package com.qa.hobby.selenium;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumTests {
private WebDriver driver;
private static String URL = "http://localhost:8080/";
@Before
public void setup() {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\richa\\Desktop\\projects\\Hobby_project\\Hobby_project\\HobbyProject\\src\\test\\resources\\drivers\\chrome\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().setSize(new Dimension(1366, 768));
driver.manage().timeouts().implicitlyWait(5000, TimeUnit.MILLISECONDS);
}
@Test
public void testplanner() throws InterruptedException {
AddRace();
UpdateRace();
AddDriver();
UpdateDriver();
DeleteDriver();
DeleteRace();
}
@After
public void cleanup() {
driver.quit();
}
public void AddRace() throws InterruptedException {
driver.get(URL);
WebElement target = driver.findElement(By.xpath("//*[@id=\"Name\"]"));
target.sendKeys("Monaco");
target = driver.findElement(By.xpath("//*[@id=\"Date\"]"));
target.sendKeys("18/06/21");
target = driver.findElement(By.xpath("//*[@id=\"Time\"]"));
target.sendKeys("12.30");
target = driver.findElement(By.xpath("//*[@id=\"createRaceForm\"]/button[2]"));
target.click();
Thread.sleep(500);
target = driver.findElement(By.xpath("//*[@id=\"output\"]/div[1]/div/div[1]"));
assertEquals("Name: Monaco, Date: 18/06/21, Time: 12.30", target.getText());
}
public void UpdateRace() throws InterruptedException {
WebElement target = driver.findElement(By.xpath("//*[@id=\"output\"]/div/div/div[3]/button[2]"));
target.click();
Thread.sleep(500);
target = driver.findElement(By.xpath("//*[@id=\"UName\"]"));
target.sendKeys("London");
target = driver.findElement(By.xpath("//*[@id=\"UDate\"]"));
target.sendKeys("18/06/22");
target = driver.findElement(By.xpath("//*[@id=\"UTime\"]"));
target.sendKeys("13.30");
target = driver.findElement(By.xpath("//*[@id=\"updateRaceForm\"]/button[2]"));
target.click();
Thread.sleep(500);
target = driver.findElement(By.xpath("//*[@id=\"output\"]/div[1]/div/div[1]"));
assertEquals("Name: London, Date: 18/06/22, Time: 13.30", target.getText());
}
public void AddDriver() throws InterruptedException {
WebElement target = driver.findElement(By.xpath("//*[@id=\"output\"]/div/div/div[3]/button[3]"));
target.click();
Thread.sleep(500);
target = driver.findElement(By.xpath("//*[@id=\"AName\"]"));
target.sendKeys("1");
target = driver.findElement(By.xpath("//*[@id=\"TeamName\"]"));
target.sendKeys("1");
target = driver.findElement(By.xpath("//*[@id=\"Points\"]"));
target.sendKeys("1");
target = driver.findElement(By.xpath("//*[@id=\"DriverNum\"]"));
target.sendKeys("1");
target = driver.findElement(By.xpath("//*[@id=\"DTime\"]"));
target.sendKeys("1");
target = driver.findElement(By.xpath("//*[@id=\"driverNum\"]"));
target.sendKeys("1");
target = driver.findElement(By.xpath("//*[@id=\"Position\"]"));
target.sendKeys("1");
target = driver.findElement(By.xpath("//*[@id=\"createDriverForm\"]/button[2]"));
target.click();
Thread.sleep(500);
target = driver.findElement(By.xpath("//*[@id=\"output\"]/div/div/div[2]/div/button[1]"));
assertEquals("Name: 1, Team Name: 1, Points: 1, Driver Num: 1, Time: 1, Position 1", target.getText());
}
public void UpdateDriver() throws InterruptedException {
WebElement target = driver.findElement(By.xpath("//*[@id=\"output\"]/div/div/div[2]/div/button[1]"));
target.click();
Thread.sleep(500);
target = driver.findElement(By.xpath("//*[@id=\"UDName\"]"));
target.sendKeys("2");
target = driver.findElement(By.xpath("//*[@id=\"UTeamName\"]"));
target.sendKeys("2");
target = driver.findElement(By.xpath("//*[@id=\"UPoints\"]"));
target.sendKeys("2");
target = driver.findElement(By.xpath("//*[@id=\"UDriverNum\"]"));
target.sendKeys("2");
target = driver.findElement(By.xpath("//*[@id=\"UDTime\"]"));
target.sendKeys("2");
target = driver.findElement(By.xpath("//*[@id=\"UdriverNum\"]"));
target.sendKeys("2");
target = driver.findElement(By.xpath("//*[@id=\"UPosition\"]"));
target.sendKeys("2");
target = driver.findElement(By.xpath("//*[@id=\"updateDriverForm\"]/button[2]"));
target.click();
Thread.sleep(500);
target = driver.findElement(By.xpath("//*[@id=\"output\"]/div/div/div[2]/div/button[1]"));
assertEquals("Name: 2, Team Name: 2, Points: 2, Driver Num: 2, Time: 2, Position 2", target.getText());
}
public void DeleteDriver() throws InterruptedException {
WebElement target = driver.findElement(By.xpath("//*[@id=\"output\"]/div/div/div[2]/div/button[2]"));
target.click();
}
public void DeleteRace() throws InterruptedException {
WebElement target = driver.findElement(By.xpath("//*[@id=\"output\"]/div/div/div[3]/button[1]"));
target.click();
}
}
<file_sep>/README.md
Coverage: 80% ish
Jira link: https://rredman.atlassian.net/jira/software/projects/HP/boards/6
Git repo : https://github.com/sgtnamder/sgtnamder_assessment
Hobby project
The project was to create a font-end back-end and db to create a list of races and populate each race with the drivers participating
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.
ensure instillation of SQL
### Prerequisites
To Run this project you will need
-- java vesrion 8/1.8 to 14
-- MYSQL or equivelent SQL server
--Google Chrome(should work with other browsers)
What things you need to install the software and how to install them
installing MYSQL
1. Get the file from [SQL](https://dev.mysql.com/downloads/installer/)
2.Install the files ensuring that MYSQL sever and MYSQL workbench are present
3.open the command prompt and run
cd C:\Program Files\MySQL\MySQL Server 8.0\bin
then
mysqld --console --initialize
4. you should see a temp passwword at the bottom make not of this
now enter
mysqld --console
5. oepn a new window and enter
cd C:\Program Files\MySQL\MySQL Server 8.0\bin
then
mysql -u root -p
6. enter the temp password from before
7. you should see mysql> only on the command line now
now reset your password throught entering the command:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'root';
paswword for sql is now root
installing java
1. get install from [java](https://www.oracle.com/java/technologies/javase/jdk14-archive-downloads.html)
2. run install file to completion
3. jaba programe will be lacated in C:/Program Files/Java
4. in the windows menu serch for Edit the system environment variables
5. go to advanced and click on environment variables
6. in system variables create a new call JAVA_HOME, with value being C:\Program Files\Java\jdk-14.0.2
7. you should see a new JAVA_HOME variable
8. find parth and edit it, then add a new variable called %JAVA_HOME%\bin
7. to test is the java has been installed open cmmand prompt and enter java -version
### Installing
Due to this being a front-end programe type it cannot be run throught the .jar
Instead open the project within an eclipeIDE.
Ensure that you have gooten SpringBoot from the eclipes store located in the help tab and called eclipe marketplace
From here you can run a live version through the Boot dashboard, simply click on local, then the project you want to run e.g. HobbyProject and then at the top click on start/restart button
Now open your internet browser and type http://localhost:8080/. you should see a webpage for the application
## Running the tests
Explains how to run the automated tests for this system. Broken down into which tests and what they do
before running the test ensure to switch the data in application.properties to the data in application-test.properties
### Unit Tests
Unit Testing is where a number of tests are run on the systems code to ensure that the part is returning the correct values.
The testing for Java project have been done using Junit and Mickto and are located in the src/test/java/com/qa/ims and are split by DAO using Junit and controller using Mockito
some exapmle fo each test can be seen below.
To run the tests in elipcse right click on the file HobbyProject\src\test\resources the coverage then Junit
#### Mockito test example
@Test
void testAddDriver(){
//given
Driver driver = new Driver("S.Perez","Redbull",25,11,"2:13:36:410",1);
DriverDTO driverDTO = new DriverDTO("S.Perez","Redbull",25,11,"2:13:36:410",1);
//when
Mockito.when(this.repo.save(driver)).thenReturn(driver);
//then
assertThat(this.service.addDriver(driver)).usingRecursiveComparison().isEqualTo(driverDTO);
Mockito.verify(this.repo,Mockito.times(1)).save(driver);
}
This tests to see if the mocked driver is added to the list and then the function addDriver will return a driverDTO
### Integration Tests
Integration tests are used to test Post Put Get and Delete and are testing the responses from the fontend and checking that what is sent back it what is expected.
#### JUnit test example
@Test
void testDriverCreate() throws Exception {
Driver testDriver = new Driver("S.Perez","Redbull",25,11,"2:13:36:410",1);
String testDriverJson = this.mapper.writeValueAsString(testDriver);
DriverDTO savedDriver = new DriverDTO("S.Perez","Redbull",25,11,"2:13:36:410",1);
savedDriver.setId(2);
String SavedDriverJson = this.mapper.writeValueAsString(savedDriver);
RequestBuilder mockRequest = post("/driver/add").content(testDriverJson).contentType(MediaType.APPLICATION_JSON);
ResultMatcher checkStatus = status().isOk();
ResultMatcher checkbody = content().json(SavedDriverJson);
this.mvc.perform(mockRequest).andExpect(checkStatus).andExpect(checkbody);
}
This tests to see if the Post works by sending a JSON request to the and checking it recives a 200 response code and if the body of the response is what is expected.
### User-acceptance Tests
to run this test you must ensure that you have the correct file destination for the chrome driver in :
System.setProperty("webdriver.chrome.driver",
"file parth fo the chrom driver");
it should be located in \HobbyProject\src\test\resources\drivers\chrome\chromedriver.exe
Selenium Tests the front-end HTML and CSS to ensure that the feature interact correctly with the backend
to run selenium ensure that programe is running on local host 8080, or change
private static String URL = "correct url";
#### Selenium Example
@test
public void AddRace() throws InterruptedException {
driver.get(URL);
WebElement target = driver.findElement(By.xpath("//*[@id=\"Name\"]"));
target.sendKeys("Monaco");
target = driver.findElement(By.xpath("//*[@id=\"Date\"]"));
target.sendKeys("18/06/21");
target = driver.findElement(By.xpath("//*[@id=\"Time\"]"));
target.sendKeys("12.30");
target = driver.findElement(By.xpath("//*[@id=\"createRaceForm\"]/button[2]"));
target.click();
Thread.sleep(500);
target = driver.findElement(By.xpath("//*[@id=\"output\"]/div[1]/div/div[1]"));
assertEquals("Name: Monaco, Date: 18/06/21, Time: 12.30", target.getText());
}
This will test to see if a Race has been added using the frontend text and ensure that the response is shown on the page.
## Deployment
Add additional notes about how to deploy this on a live system
## Built With
* [Maven](https://maven.apache.org/) - Dependency Management
## Versioning
I used [Git](https://github.com) for versioning
## Authors
* **<NAME>** -[sgtnamder](https://github.com/sgtnamder)
## License
Project not lincesed
## Acknowledgments
Thank you to <NAME> and <NAME> for help sorting out bugs and blocker issues
* Hat tip to anyone whose code was used
* Inspiration
* etc<file_sep>/HobbyProject/src/main/java/com/qa/hobby/controller/RaceController.java
package com.qa.hobby.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qa.hobby.domain.Race;
import com.qa.hobby.dto.RaceDTO;
import com.qa.hobby.service.RaceService;
@RestController
@RequestMapping("/race")// creates an address for modifying races
public class RaceController {
private RaceService service;
@Autowired // create the a new instance if service
public RaceController(RaceService service) {
super();
this.service = service;
}
@PostMapping("/add") // creates and address to add a races
public RaceDTO addRace(@RequestBody Race race) {
return this.service.addRace(race);
}
@GetMapping("/")// creates and address to get all races
public List<RaceDTO> getAllRaces(){
return this.service.getAllRaces();
}
@PutMapping("/update/{id}")// creates and address to update races by id
public RaceDTO updateRace(@RequestBody Race race, @PathVariable Integer id) {
return this.service.updateRace(id, race);
}
@DeleteMapping("/delete/{id}")// creates and address to delete races by id
public Boolean deleteRace(@PathVariable Integer id) {
return this.service.deleteRace(id);
}
}
| 3eb924c9f29229f28d86b79af017b2bb231bf993 | [
"SQL",
"JavaScript",
"Markdown",
"INI",
"Java"
] | 10 | JavaScript | sgtnamder/Hobby_project | 9698a3bc651ba779efdf5a25fc318f726fccc626 | cbab9ef6f0665d3a26c4861f74dd97f994fddb43 |
refs/heads/master | <file_sep>$(document).ready(function() {
"use strict";
//Menu Trigger
$(".menu-trigger").click(function() {
$(".header").toggleClass("active");
});
//End Menu Trigger
//header-fullscreen__trigger
$('.header-fullscreen__trigger').click(function() {
$('.bars, .bar, .header-fullscreen').toggleClass('active');
});
//end header-fullscreen__trigger
//Detect Menu Item & Add Active Class
$(function($) {
var path = window.location.href;
$('.header-fullscreen__navbar .main-nav a').each(function() {
if ( this.href === path ) {
$(this).addClass('active');
}
});
});
//End Detect Menu Item & Add Active Class
//Form
$(function() {
$('input, textarea, form, .form-group').on("click", function(e) {
$(this).addClass('active');
});
$(document).on("click", function(e) {
if( $(e.target).is('input, textarea, form, .form-group') === false ) {
$('input, textarea, form, .form-group').removeClass('active');
}
});
})
//End Form
});
<file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: May 26, 2020 at 09:32 AM
-- Server version: 10.4.11-MariaDB
-- PHP Version: 7.2.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `form`
--
CREATE DATABASE IF NOT EXISTS `form` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
USE `form`;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`created_at` datetime DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `password`, `created_at`) VALUES
(1, 'calin', <PASSWORD>', '2020-05-20 16:30:00'),
(2, 'Tiberiu', <PASSWORD>$BEIQdCXNdqZmFleJN7zTnOzmOctjkdePFpBHRsIokP7f3LQGdXS8.', '2020-05-20 17:19:06'),
(3, 'Tasca', '$2y$10$illAtvwY71y7iGSgp0q8BuPZfK/ITg6oLHfBxtzP6heS6IYQdxzLi', '2020-05-20 17:19:52'),
(4, 'calin_tasca', '$2y$10$.qEIwWcuQ0EeXb6m2Jh3HeH28Sod4whavZiEvxyga26FC1EIcgrlu', '2020-05-20 17:22:41');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `username` (`username`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
include('includes/header.php');
?>
<?php
//Initialize session
session_start();
//Check if the user is login
if( !isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true ) {
header('location: login.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Welcome</title>
<!-- ========== CSS INCLUDES ========== -->
<link rel="stylesheet" href="assets/css/master.css">
</head>
<body class="welcome">
<div class="wrapper">
<div class="container">
<div class="row center-col">
<div class="col-sm-6">
<div class="page-header">
<h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
</div>
<p>
<a href="reset-password.php" class="btn">Reset Your Password</a>
<a href="logout.php" class="btn">Sign Out of Your Account</a>
</p>
</div>
</div>
</div>
</div>
<script src="assets/js/jquery.js"></script>
<script src="assets/bootstrap-master/assets/javascripts/bootstrap.min.js"></script>
<script src="assets/js/plugins.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<?php
include('includes/footer.php');
?><file_sep><?php
include('includes/header.php');
?>
<?php
//Include config file
require_once('config.php');
//Define variables and initialize with empty values
$username = $password = $confirm_password = '';
$username_err = $password_err = $confirm_password_err = '';
//Process form data when form is submitted
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
// Validate username
if( empty(trim($_POST['username'])) ) {
$username_err = 'Please enter a username';
} else {
//Prepare select statement
$sql = 'SELECT id FROM users WHERE username = ?';
if( $stmt = mysqli_prepare($link, $sql) ) {
//Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, 's', $param_username);
//Set parameters
$param_username = trim($_POST['username']);
//Attempt to exe the prepared statement
if ( mysqli_stmt_execute($stmt) ) {
//store result
mysqli_stmt_store_result($stmt);
if ( mysqli_stmt_num_rows($stmt) == 1 ) {
$username_err = 'This user is already in use.';
} else {
$username = trim($_POST['username']);
}
} else {
echo 'Something went wrong. Please try again later.';
}
}
//Close statement
mysqli_stmt_close($stmt);
}
//End validate username
//Validate password
if( empty(trim($_POST['password'])) ) {
$password_err = 'Please enter a password.';
} elseif ( strlen(trim($_POST['password'])) < 6 ) {
$password_err = 'Password must have at least 6 characters.';
} else {
$password = trim($_POST['password']);
}
//Validate confirm password
if( empty(trim($_POST['password'])) ) {
$confirm_password_err = 'Please confirm password.';
} else {
$confirm_password = trim($_POST['confirm_password']);
if ( empty($password_err) && ($password != $confirm_password) ) {
$confirm_password_err = 'Password did not match.';
}
}
//Check input errors before inserting in DB
if( empty($username_err) && empty($password_err) && empty($confirm_password_err) ) {
//Prepare insert statement
$sql = 'INSERT INTO users (username, password) VALUES(?, ?)';
if( $stmt = mysqli_prepare($link, $sql) ) {
//Bind variables to prepared statement as parameters
mysqli_stmt_bind_param($stmt, 'ss', $param_username, $param_password);
//Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT);//Hashing the password
//Attempt to exe the prepared statement
if( mysqli_stmt_execute($stmt) ) {
//Redirect lo login page
header('location: login.php');
} else {
echo 'Something went wrong. Please try again.';
}
//Close statement
mysqli_stmt_close($stmt);
}
}
//Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>SignUp</title>
<!-- ========== CSS INCLUDES ========== -->
<link rel="stylesheet" href="assets/css/master.css">
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="row center-col">
<div class="col-sm-6">
<h2><em>Sign Up</em></h2>
<p class="fill">Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="<PASSWORD>" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn" value="Submit">
<input type="reset" class="btn" value="Reset">
</div>
<p>Already have an account? <a href="login.php">Login here</a>.</p>
</form>
</div>
</div>
</div>
</div>
<script src="assets/js/jquery.js"></script>
<script src="assets/bootstrap-master/assets/javascripts/bootstrap.min.js"></script>
<script src="assets/js/plugins.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<?php
include('includes/footer.php');
?> | 5771210cb04ab7bd3ba5b5501f567d0ef171c3a9 | [
"JavaScript",
"SQL",
"PHP"
] | 4 | JavaScript | TTCGit/Form-Registration | 5bfa18a884ac33e14c7e04b961bf5716a8c161b0 | cca6e1bd7fea2ab0d451574ff32b155b68046564 |
refs/heads/main | <file_sep>"# JavaObserverPatternImpl2"
<file_sep>package com.nubari;
import java.lang.ref.PhantomReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class SearchObject implements Subject {
private String searchObjectName;
private List<Observer> observers;
private Integer searchQuery;
private Integer searchValue;
private boolean canCarryOutOperation;
private boolean busy = false;
private static int counter;
public SearchObject(int searchQuery) {
this.searchQuery = searchQuery;
observers = new ArrayList<>();
canCarryOutOperation = true;
counter++;
this.searchObjectName = "Search Object " + counter;
}
public SearchObject() {
counter++;
this.searchObjectName = "Search Object " + counter;
observers = new ArrayList<>();
canCarryOutOperation = true;
}
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
int indexOfObserver = observers.indexOf(observer);
if (indexOfObserver >= 0) {
observers.remove(observer);
}
}
@Override
public void notifyObservers(Integer searchValue) {
for (Observer searchManager : observers) {
searchManager.update(searchValue);
}
}
public Number getSearchQuery() {
return searchQuery;
}
public void setSearchQuery(Integer number) {
this.searchQuery = number;
}
public void carryOutSearch(List<Integer> source, Integer searchQuery) {
this.searchQuery = searchQuery;
busy = true;
System.out.println("Search Object " + getSearchObjectName() + " pinged");
System.out.println("Search Object " + getSearchObjectName() + " can carry out operations : " + canCarryOutOperation);
while (canCarryOutOperation) {
boolean valueFound = false;
// for (Number value : source) {
// System.out.println("current value is " + value.toString() + " from " + this.getSearchObjectName());
// System.out.println();
// System.out.println("Search Object " + this + " Carrying out search");
// System.out.println();
// if (value.equals(searchQuery)) {
// this.searchValue = value;
// valueFound = true;
// notifyObservers(searchValue);
// busy = false;
// break;
// } else {
// System.out.println("No match found checking next value" + this.getSearchObjectName());
// System.out.println();
// }
// }
//
Collections.sort(source);
int high = source.size() - 1;
int low = 0;
while (low <= high) {
int mid = (low + high) / 2;
Integer value = source.get(mid);
System.out.println("current value is " + value + " from " + this.getSearchObjectName());
System.out.println();
if (value.equals(searchQuery)) {
this.searchValue = value;
valueFound = true;
notifyObservers(searchValue);
busy = false;
break;
} else if (value > searchQuery) {
System.out.println("current value greater moving to next iteration" + this.getSearchObjectName());
System.out.println();
high = mid - 1;
} else {
System.out.println("current value lesser moving to next iteration" + this.getSearchObjectName());
System.out.println();
low = mid + 1;
}
}
if (!valueFound) {
notifyObservers(null);
canCarryOutOperation = false;
busy = false;
}
}
}
public List<Observer> getObservers() {
return this.observers;
}
public void turnOffOperations() {
canCarryOutOperation = false;
}
public void turnOnOperations() {
canCarryOutOperation = true;
}
public String getSearchObjectName() {
return this.searchObjectName;
}
public boolean isBusy() {
return busy;
}
public String toString() {
return getSearchObjectName();
}
}
| 6f9b4ef9bbe43adc71b6821da6c53f93f3e0f10d | [
"Markdown",
"Java"
] | 2 | Markdown | mofe64/JavaObserverPatternImpl2 | 9b3564429e9331e09229dc16c8bd2f424a0856e6 | 12b210272a376fa7ed99ca2397aaf1f0cd3d3541 |
refs/heads/master | <file_sep>
lista_libri = ['Eclisse' , '<NAME>' , 'Spartacus' , '2001' , 'Promessi Sposi' , '<NAME>' , 'Memor<NAME>' , 'Lolita' , 'il conte di Montecristo' , 'Il Gattopardo' , '1984' , 'Cime tempestose' , 'Il processo' , 'I fratelli Karamazov']
libri_prestati = []
for i in lista_libri:
a=lista_libri.index(i)
if a==13:
print(i)
else:
print(i, end= ", ")
print('')
lista_libri.sort()
for i in lista_libri:
a=lista_libri.index(i)
print(a+1, lista_libri[a])
print('')
numero_libri=int(input('Quanti libri vuoi prendere in prestito? '))
n=0
print('')
while n<numero_libri:
print('')
b=int(input('digita il numero del libro che vuoi prendere in prestito '))
while b<1 or b>14:
if b<1:
b=int(input('il numero è troppo piccolo, riprovare '))
else:
b=int(input('il numero è troppo grande, riprovare '))
c=b-1
libro_prestato=lista_libri[c]
libri_prestati.append(libro_prestato)
lista_libri.pop(c)
print('')
print('il libro è stato aggiunto alla lista dei libri prestati')
n_disponibili=len(lista_libri)
n_prestati=len(libri_prestati)
print('')
print('libri disponibili')
for i in lista_libri:
a=lista_libri.index(i)
print(a+1 , i)
print('')
print('libri prestati')
for i in libri_prestati:
a=libri_prestati.index(i)
print(a+1, i)
n=n+1
<file_sep>from random import randint
voti_Enzo=[]
voti_Nunzio=[]
voti_insuf_Enzo=[]
voti_insuf_Nunzio=[]
print('')
n_Enzo=float(input('Quanti voti ha Enzo? '))
print('')
n_Nunzio=float(input('Quanti voti ha Nunzio? '))
print('')
a=0
while a<n_Enzo:
print('')
voto_inserire=float(input('inserisci il voto di Enzo '))
voti_Enzo.append(voto_inserire)
if voto_inserire<6:
voti_insuf_Enzo.append(voto_inserire)
a= a+1
print('')
a=0
while a<n_Nunzio:
print('')
voto_inserire=float(input('inserisci il voto di Nunzio '))
voti_Nunzio.append(voto_inserire)
if voto_inserire<6:
voti_insuf_Nunzio.append(voto_inserire)
a=a+1
print('')
nome=input('scriva il nome dello studente di cui vuole vedere i voti: ')
while nome!="Enzo" and nome!="Nunzio":
print('')
nome=input('Il nome dello studente è errato, riprovare (ricorda la prima lettera maiuscola!): ')
somma_Enzo=0
for i in voti_Enzo:
somma_Enzo=somma_Enzo + i
lunghezza_Enzo=len(voti_Enzo)
media_Enzo= somma_Enzo/lunghezza_Enzo
somma_Nunzio=0
for i in voti_Nunzio:
somma_Nunzio=somma_Nunzio + i
lunghezza_Nunzio=len(voti_Nunzio)
media_Nunzio= somma_Nunzio/lunghezza_Nunzio
print('')
if nome=="Enzo":
print('')
print('I voti di Enzo sono:')
for i in voti_Enzo:
print(i)
print('')
print('I voti insufficienti di Enzo sono:')
for i in voti_insuf_Enzo:
print(i)
print('la media di Enzo è ' , media_Enzo)
if media_Enzo<6:
print('La media di Enzo è insufficiente')
if nome=="Nunzio":
print('')
print('I voti di Nunzio sono:')
for i in voti_Nunzio:
print(i)
print('')
print('I voti insufficienti di Nunzio sono:')
for i in voti_insuf_Nunzio:
print(i)
print('la media di Nunzio è ' , media_Nunzio)
if media_Nunzio<6:
print('La media di Nunzio è insufficiente')
if media_Enzo<media_Nunzio:
print('Nunzio ha una media superiore a Enzo')
else:
print('Enzio ha una media superiore a Nunzio')
data= randint(22,30)
print('I due studenti vanno interrogati il ' , data , ' maggio') | a83a78bba3ab0a5661d5fab8b25996fe9244bf64 | [
"Python"
] | 2 | Python | ricklusuardi/repository_5 | 13492923d104432bf2118d2fdbf76621c56f3e9d | c1170d531cde131232116ffc5f77420efeb929b9 |
refs/heads/master | <repo_name>sevennetwork/sentry-cli<file_sep>/Cargo.toml
[package]
authors = ["<NAME> <<EMAIL>>"]
build = "build.rs"
name = "sentry-cli"
version = "1.28.1"
[dependencies]
anylog = "0.2.0"
app_dirs = "1.1.1"
backtrace = "0.3.4"
chardet = "0.2.4"
chrono = { version = "0.4.0", features = ["serde"] }
clap = { version = "2.29.0", default-features = false, features = ["suggestions", "wrap_help"] }
console = "0.5.0"
curl = "0.4.8"
dotenv = "0.10.1"
elementtree = "0.5.0"
encoding = "0.2.33"
error-chain = "0.11.0"
git2 = { version = "0.6.9", default-features = false }
glob = "0.2.11"
hostname = "0.1.3"
humansize = "1.0.2"
if_chain = "0.1.2"
ignore = "0.3.1"
indicatif = "0.8.0"
itertools = "0.7.4"
java-properties = "1.1.0"
lazy_static = "1.0.0"
libc = "0.2.34"
log = "0.3.8"
mach_object = "0.1.6"
memmap = "0.6.1"
might-be-minified = "0.2.1"
open = "1.2.1"
plist = "0.2.4"
prettytable-rs = "0.6.7"
regex = "0.2.3"
runas = "0.1.4"
rust-ini = "0.10.0"
serde = "1.0.24"
serde_derive = "1.0.24"
serde_json = "1.0.8"
sha1 = "0.3.0"
sourcemap = "2.2.0"
symbolic-common = "2.0.0"
symbolic-debuginfo = "2.0.0"
symbolic-proguard = "2.0.0"
url = "1.6.0"
username = "0.2.0"
uuid = { version = "0.5.1", features = ["v4", "serde"] }
walkdir = "2.0.1"
which = "1.0.3"
zip = "0.2.6"
parking_lot = "0.5.3"
[profile.dev]
codegen-units = 2
[target."cfg(not(windows))"]
[target."cfg(not(windows))".dependencies]
chan = "0.1.19"
chan-signal = "0.3.1"
openssl-probe = "0.1.2"
uname = "0.1.1"
[target."cfg(target_os=\"macos\")".dependencies]
mac-process-info = "0.1.0"
osascript = "0.3.0"
unix-daemonize = "0.1.2"
[features]
managed = []
<file_sep>/js/__tests__/helper.test.js
/* eslint-env jest */
var helper = require('../helper');
var SOURCEMAPS_OPTIONS = require('../releases/options/uploadSourcemaps');
describe('SentryCli helper', function() {
test('call sentry-cli --version', function() {
expect.assertions(1);
return helper.execute(['--version']).then(function() {
expect(true).toBe(true);
});
});
test('call sentry-cli with wrong command', function() {
expect.assertions(1);
return helper.execute(['fail']).catch(function(e) {
expect(e.message).toMatch('Command failed:');
});
});
test('call prepare command add default ignore', function() {
var command = ['releases', 'files', 'release', 'upload-sourcemaps', '/dev/null'];
expect(helper.prepareCommand(command)).toEqual([
'releases',
'files',
'release',
'upload-sourcemaps',
'/dev/null'
]);
});
test('call prepare command with array option', function() {
var command = ['releases', 'files', 'release', 'upload-sourcemaps', '/dev/null'];
expect(
helper.prepareCommand(command, SOURCEMAPS_OPTIONS, { stripPrefix: ['node', 'app'] })
).toEqual([
'releases',
'files',
'release',
'upload-sourcemaps',
'/dev/null',
'--strip-prefix',
'node',
'--strip-prefix',
'app'
]);
// Should throw since it is no array
expect(function() {
helper.prepareCommand(command, SOURCEMAPS_OPTIONS, { stripPrefix: 'node' });
}).toThrow();
});
test('call prepare command with boolean option', function() {
var command = ['releases', 'files', 'release', 'upload-sourcemaps', '/dev/null'];
expect(
helper.prepareCommand(command, SOURCEMAPS_OPTIONS, { sourceMapReference: false })
).toEqual([
'releases',
'files',
'release',
'upload-sourcemaps',
'/dev/null',
'--no-sourcemap-reference'
]);
expect(
helper.prepareCommand(command, SOURCEMAPS_OPTIONS, { sourceMapReference: true })
).toEqual(['releases', 'files', 'release', 'upload-sourcemaps', '/dev/null']);
expect(helper.prepareCommand(command, SOURCEMAPS_OPTIONS, { rewrite: true })).toEqual(
['releases', 'files', 'release', 'upload-sourcemaps', '/dev/null', '--rewrite']
);
expect(function() {
helper.prepareCommand(command, SOURCEMAPS_OPTIONS, { sourceMapReference: 'node' });
}).toThrow();
});
test('call prepare command with string option', function() {
var command = ['releases', 'files', 'release', 'upload-sourcemaps', '/dev/null'];
expect(helper.prepareCommand(command, SOURCEMAPS_OPTIONS, { ext: 'js' })).toEqual([
'releases',
'files',
'release',
'upload-sourcemaps',
'/dev/null',
'--ext',
'js'
]);
expect(
helper.prepareCommand(command, SOURCEMAPS_OPTIONS, { urlPrefix: '~/' })
).toEqual([
'releases',
'files',
'release',
'upload-sourcemaps',
'/dev/null',
'--url-prefix',
'~/'
]);
expect(
helper.prepareCommand(command, SOURCEMAPS_OPTIONS, { ignoreFile: '/js.ignore' })
).toEqual([
'releases',
'files',
'release',
'upload-sourcemaps',
'/dev/null',
'--ignore-file',
'/js.ignore'
]);
});
});
<file_sep>/js/releases/__tests__/index.test.js
/* eslint-env jest */
var SentryCli = require('../../');
describe('SentryCli releases', function() {
test('call sentry-cli releases propose-version', function() {
expect.assertions(1);
var cli = new SentryCli();
return cli.releases.proposeVersion().then(function(version) {
expect(version).toBeTruthy();
});
});
test('call sentry-cli releases upload-sourcemaps', function() {
expect.assertions(1);
var cli = new SentryCli();
return cli.releases
.uploadSourceMaps('#abc', { include: ['hello'] })
.then(function(version) {
expect(version).toBeTruthy();
});
});
});
<file_sep>/src/commands/upload_breakpad.rs
use std::collections::HashSet;
use std::ffi::OsStr;
use std::fs::File;
use std::iter::Fuse;
use std::path::{Path, PathBuf};
use clap::{App, AppSettings, Arg, ArgMatches};
use console::style;
use indicatif::{ProgressBar, ProgressStyle};
use symbolic_common::{ByteView, ObjectKind};
use symbolic_debuginfo::FatObject;
use uuid::Uuid;
use walkdir::{DirEntry, IntoIter as WalkDirIter, WalkDir};
use zip::ZipWriter;
use zip::write::FileOptions;
use api::{Api, DSymFile};
use config::Config;
use prelude::*;
use utils::{ArgExt, copy_with_progress, get_sha1_checksum, invert_result, make_byte_progress_bar,
TempFile, validate_uuid};
pub fn make_app<'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> {
app.about("Upload breakpad symbols to a project.")
.setting(AppSettings::Hidden)
.org_project_args()
.arg(Arg::with_name("paths")
.value_name("PATH")
.help("A path to search recursively for symbol files.")
.multiple(true)
.number_of_values(1)
.index(1))
.arg(Arg::with_name("uuids")
.value_name("UUID")
.long("uuid")
.help("Search for specific UUIDs.")
.validator(validate_uuid)
.multiple(true)
.number_of_values(1))
.arg(Arg::with_name("require_all")
.long("require-all")
.help("Errors if not all UUIDs specified with --uuid could be found."))
.arg(Arg::with_name("no_reprocessing")
.long("no-reprocessing")
.help("Do not trigger reprocessing after uploading."))
}
struct ProjectContext {
api: Api,
org: String,
project: String,
}
impl ProjectContext {
pub fn from_cli(matches: &ArgMatches) -> Result<ProjectContext> {
let config = Config::get_current();
let (org, project) = config.get_org_and_project(matches)?;
Ok(ProjectContext {
api: Api::new(),
org: org,
project: project,
})
}
}
#[derive(Debug)]
struct Sym {
path: PathBuf,
checksum: String,
name: String,
size: u64,
}
type Batch = Vec<Sym>;
struct BatchIter<'a> {
path: PathBuf,
max_size: u64,
uuids: Option<&'a HashSet<Uuid>>,
found: &'a mut HashSet<Uuid>,
iter: Fuse<WalkDirIter>,
}
impl<'a> BatchIter<'a> {
pub fn new(
path: PathBuf,
max_size: u64,
uuids: Option<&'a HashSet<Uuid>>,
found: &'a mut HashSet<Uuid>,
) -> BatchIter<'a> {
let iter = WalkDir::new(&path).into_iter().fuse();
BatchIter {
path: path,
max_size: max_size,
uuids: uuids,
found: found,
iter: iter,
}
}
fn found_all(&self) -> bool {
if let Some(ref uuids) = self.uuids {
self.found.is_superset(uuids)
} else {
false
}
}
fn is_filled(&self, batch: &Batch) -> bool {
batch.iter().map(|sym| sym.size).sum::<u64>() >= self.max_size
}
fn process_file(&mut self, entry: DirEntry, pb: &ProgressBar) -> Result<Option<Sym>> {
// The WalkDir iterator will automatically recurse into directories
let meta = entry.metadata()?;
if !meta.is_file() {
return Ok(None);
}
// Require the usual "sym" extension for Breakpad symbols
let path = entry.path();
if path.extension() != Some(OsStr::new("sym")) {
return Ok(None);
}
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
pb.set_message(name);
}
// Make sure that this is a breakpad file
let data = ByteView::from_path(path)?;
match FatObject::peek(&data) {
Ok(ObjectKind::Breakpad) => {}
_ => return Ok(None),
};
// Parse the object and make sure it contains a valid UUID
let fat = FatObject::parse(data)?;
let object = fat.get_object(0)?.unwrap();
let uuid = match object.uuid() {
Some(uuid) => uuid,
None => return Ok(None),
};
// See if the UUID matches the provided UUIDs
if !self.uuids.map_or(true, |uuids| uuids.contains(&uuid)) {
return Ok(None);
}
let file_name = Path::new("DebugSymbols")
.join(path.strip_prefix(&self.path).unwrap())
.to_string_lossy()
.into_owned();
Ok(Some(Sym {
path: path.to_path_buf(),
checksum: get_sha1_checksum(object.as_bytes())?,
name: file_name,
size: meta.len(),
}))
}
fn next_sym(&mut self, pb: &ProgressBar) -> Result<Option<Sym>> {
while let Some(entry) = self.iter.next() {
if let Some(sym) = self.process_file(entry?, pb)? {
return Ok(Some(sym));
}
}
Ok(None)
}
fn next_batch(&mut self) -> Result<Option<Batch>> {
let pb = ProgressBar::new_spinner();
pb.enable_steady_tick(100);
pb.set_style(ProgressStyle::default_spinner()
.tick_chars("/|\\- ")
.template("{spinner} Looking for symbols... {msg:.dim}\
\n symbol files found: {prefix:.yellow}"));
let mut batch = vec![];
while !self.is_filled(&batch) && !self.found_all() {
match self.next_sym(&pb)? {
Some(sym) => {
batch.push(sym);
pb.set_prefix(&format!("{}", batch.len()));
},
None => break,
}
}
pb.finish_and_clear();
Ok(if batch.len() == 0 {
None
} else {
Some(batch)
})
}
}
impl<'a> Iterator for BatchIter<'a> {
type Item = Result<Batch>;
fn next(&mut self) -> Option<Self::Item> {
invert_result(self.next_batch())
}
}
fn filter_missing_syms(batch: Batch, context: &mut ProjectContext) -> Result<Batch> {
info!("Checking for missing debug symbols: {:#?}", &batch);
let missing_checksums = {
let checksums = batch.iter().map(|ref s| s.checksum.as_str()).collect();
context.api.find_missing_dsym_checksums(&context.org, &context.project, &checksums)?
};
let missing = batch.into_iter()
.filter(|sym| missing_checksums.contains(&sym.checksum))
.collect();
info!("Missing debug symbols: {:#?}", &missing);
Ok(missing)
}
fn compress_syms(batch: Batch) -> Result<TempFile> {
let total_bytes = batch.iter().map(|sym| sym.size).sum();
let pb = make_byte_progress_bar(total_bytes);
let tf = TempFile::new()?;
let mut zip = ZipWriter::new(tf.open());
for ref sym in batch {
zip.start_file(sym.name.clone(), FileOptions::default())?;
copy_with_progress(&pb, &mut File::open(&sym.path)?, &mut zip)?;
}
pb.finish_and_clear();
Ok(tf)
}
fn upload_syms(batch: Batch, context: &mut ProjectContext) -> Result<Vec<DSymFile>> {
println!(
"{} Compressing {} missing debug symbol files",
style(">").dim(),
style(batch.len()).yellow()
);
let archive = compress_syms(batch)?;
println!("{} Uploading debug symbol files", style(">").dim());
Ok(context.api.upload_dsyms(&context.org, &context.project, archive.path())?)
}
fn process_batch(batch: Batch, context: &mut ProjectContext) -> Result<usize> {
println!(
"{} Found {} breakpad symbol files.",
style(">").dim(),
style(batch.len()).yellow()
);
let missing = filter_missing_syms(batch, context)?;
if missing.len() == 0 {
println!("{} Nothing to compress, all symbols are on the server", style(">").dim());
println!("{} Nothing to upload", style(">").dim());
return Ok(0);
}
let uploaded = upload_syms(missing, context)?;
if uploaded.len() > 0 {
println!("Newly uploaded debug symbols:");
for sym in &uploaded {
println!(" {} ({}; {})", style(&sym.uuid).dim(), &sym.object_name, sym.cpu_name);
}
}
Ok(uploaded.len())
}
pub fn execute<'a>(matches: &ArgMatches<'a>) -> Result<()> {
let paths = match matches.values_of("paths") {
Some(paths) => paths.map(|path| PathBuf::from(path)).collect(),
None => vec![],
};
if paths.len() == 0 {
// We allow this because reprocessing will still be triggered
println!("Warning: no paths were provided.");
}
let mut found = HashSet::new();
let uuids = matches.values_of("uuids").map(|uuids| {
uuids.map(|s| Uuid::parse_str(s).unwrap()).collect()
});
let config = Config::get_current();
let mut context = ProjectContext::from_cli(matches)?;
let max_size = config.get_max_dsym_upload_size()?;
let mut total_uploaded = 0;
// Search all paths and upload symbols in batches
for path in paths.into_iter() {
let iter = BatchIter::new(path, max_size, uuids.as_ref(), &mut found);
for (i, batch) in iter.enumerate() {
if i > 0 {
println!("");
}
println!("{}", style(format!("Batch {}", i)).bold());
total_uploaded += process_batch(batch?, &mut context)?;
}
}
if total_uploaded > 0 {
println!("Uploaded a total of {} breakpad symbols", style(total_uploaded).yellow());
}
// Trigger reprocessing only if requested by user
if !matches.is_present("no_reprocessing") {
if !context.api.trigger_reprocessing(&context.org, &context.project)? {
println!("{} Server does not support reprocessing. Not triggering.", style(">").dim());
}
} else {
println!("{} skipped reprocessing", style(">").dim());
}
// did we miss explicitly requested symbols?
if matches.is_present("require_all") {
if let Some(ref uuids) = uuids {
let missing: HashSet<_> = uuids.difference(&found).collect();
if !missing.is_empty() {
println!("");
println_stderr!("{}", style("error: not all requested dsyms could be found.").red());
println_stderr!("The following symbols are still missing:");
for uuid in &missing {
println!(" {}", uuid);
}
return Err(ErrorKind::QuietExit(1).into());
}
}
}
Ok(())
}
<file_sep>/js/helper.js
'use strict';
/* global Promise */
var os = require('os');
var path = require('path');
var childProcess = require('child_process');
function transformOption(option, values) {
if (Array.isArray(values)) {
return values
.map(function(value) {
return [option.param, value];
})
.reduce(function(acc, value) {
return acc.concat(value);
}, []);
}
return [option.param, values];
}
var binaryPath =
os.platform() === 'win32'
? path.resolve(__dirname, '..\\bin\\sentry-cli.exe')
: path.resolve(__dirname, '../sentry-cli');
module.exports = {
normalizeOptions: function(commandOptions, options) {
return Object.keys(commandOptions).reduce(function(newOptions, sourceMapOption) {
var paramValue = options[sourceMapOption];
if (typeof paramValue === 'undefined') {
return newOptions;
}
var paramType = commandOptions[sourceMapOption].type;
var paramName = commandOptions[sourceMapOption].param;
if (paramType === 'array') {
if (!Array.isArray(paramValue)) {
throw new Error(sourceMapOption + ' should be an array');
}
return newOptions.concat(
transformOption(commandOptions[sourceMapOption], paramValue)
);
} else if (paramType === 'boolean' || paramType === 'inverted-boolean') {
if (typeof paramValue !== 'boolean') {
throw new Error(sourceMapOption + ' should be a bool');
}
if (paramType === 'boolean' && paramValue) {
return newOptions.concat([paramName]);
} else if (paramType === 'inverted-boolean' && paramValue === false) {
return newOptions.concat([paramName]);
}
return newOptions;
}
return newOptions.concat(paramName, paramValue);
}, []);
},
prepareCommand: function(command, commandOptions, options) {
return command.concat(this.normalizeOptions(commandOptions || {}, options || {}));
},
getPath: function() {
if (process.env.NODE_ENV === 'test') {
return path.resolve(__dirname, '__mocks__/sentry-cli');
}
return binaryPath;
},
execute: function(args) {
var env = Object.assign({}, process.env);
var that = this;
return new Promise(function(resolve, reject) {
childProcess.execFile(that.getPath(), args, { env: env }, function(err, stdout) {
if (err) return reject(err);
// eslint-disable-next-line
console.log(stdout);
return resolve(stdout);
});
});
}
};
<file_sep>/js/index.js
'use strict';
var pkgInfo = require('../package.json');
var helper = require('./helper');
function SentryCli(configFile) {
if (typeof configFile === 'string') process.env.SENTRY_PROPERTIES = configFile;
}
SentryCli.prototype.getConfigStatus = function() {
return helper.execute(['info', '--config-status-json']);
};
SentryCli.getVersion = function() {
return pkgInfo.version;
};
SentryCli.getPath = function() {
return helper.getPath();
};
SentryCli.prototype.releases = require('./releases');
module.exports = SentryCli;
<file_sep>/js/releases/index.js
'use strict';
/* global Promise */
var helper = require('../helper');
var DEFAULT_IGNORE = ['node_modules'];
var SOURCEMAPS_OPTIONS = require('./options/uploadSourcemaps');
module.exports = {
new: function(release) {
return helper.execute(['releases', 'new', release]);
},
finalize: function(release) {
return helper.execute(['releases', 'finalize', release]);
},
proposeVersion: function() {
return helper.execute(['releases', 'propose-version']);
},
uploadSourceMaps: function(release, options) {
if (typeof options === 'undefined' || typeof options.include === 'undefined') {
throw new Error('options.include must be a vaild path(s)');
}
return Promise.all(
options.include.map(function(sourcemapPath) {
var command = ['releases', 'files', release, 'upload-sourcemaps', sourcemapPath];
var newOptions = Object.assign({}, options);
if (!newOptions.ignoreFile && !newOptions.ignore) {
newOptions.ignore = DEFAULT_IGNORE;
}
return helper.execute(
helper.prepareCommand(command, SOURCEMAPS_OPTIONS, options)
);
}, this)
);
}
};
<file_sep>/Dockerfile
FROM alpine:edge AS sentry-build
RUN apk add --no-cache \
cargo \
cmake \
curl-dev \
make \
openssl-dev \
rust
WORKDIR /work
ENV OPENSSL_LIB_DIR=/usr/lib/
ENV OPENSSL_INCLUDE_DIR=/usr/include
ENV OPENSSL_STATIC=1
ADD Cargo.toml Cargo.lock build.rs ./
RUN mkdir -p src \
&& echo "fn main() {}" > src/main.rs \
&& cargo build --release
ADD src src/
RUN touch src/main.rs \
&& cargo build --release --features managed \
&& mv target/release/sentry-cli /usr/local/bin
FROM alpine:3.6
WORKDIR /work
RUN apk add --no-cache libcurl llvm-libunwind libgcc
COPY --from=sentry-build /usr/local/bin/sentry-cli /bin
CMD ["/bin/sentry-cli"]
| eba604d2007b0be87b74c2f78ee2e3f99d852962 | [
"TOML",
"Rust",
"JavaScript",
"Dockerfile"
] | 8 | TOML | sevennetwork/sentry-cli | f1e2073fc9ba048f845cfda6161edc558d23a4e4 | 302baafff947e9e442749b033ed64003b847b8b7 |
refs/heads/master | <repo_name>holtpd/grammable<file_sep>/spec/models/gram_spec.rb
require 'rails_helper'
RSpec.describe Gram, type: :model do
it { should validate_presence_of :message }
it { should validate_presence_of :picture }
it { should belong_to :user }
# pending "add some examples to (or delete) #{__FILE__}"
end
| e74ea9498cebc41947f556e052153a664f444b60 | [
"Ruby"
] | 1 | Ruby | holtpd/grammable | d7a640a96fb1a8195448686d7c972ab19d1a1b5e | d5c125eb33d1077c71cca4bbbe334ad78c2e58bf |
refs/heads/master | <repo_name>DSK9012/Food-ordering-app<file_sep>/client/src/Redux/ActionCreators.js
import * as ActionTypes from './ActionTypes';
import setAuthToken from '../utils/setAuthToken';
import axios from 'axios';
import { actions } from 'react-redux-form';
//fetching all items
export const fetchAllItems=()=>async dispatch=>{
dispatch({
type:ActionTypes.itemsLoading
});
try {
const response=await axios.get("/Home");
dispatch({
type:ActionTypes.getAllItems,
payload:response.data
});
} catch (error) {
dispatch({
type:ActionTypes.itemsLoadingFailed,
payload:error.message
});
}
}
//fetching specific items
export const fetchSpecificItems=(specificType)=>async dispatch=>{
if(localStorage.token){
setAuthToken(localStorage.token);
}
dispatch({
type:ActionTypes.itemsLoading
});
try {
const response=await axios.get(`/Home/${specificType}`);
dispatch({
type:ActionTypes.getSpecificItems,
payload:response.data
});
dispatch(fetchCartItems());
dispatch(loadingUser());
} catch (error) {
dispatch({
type:ActionTypes.itemsLoadingFailed,
payload:error.message
});
}
}
//fetching sorted items
export const fetchSortedItems=(specificType, sortType)=>async dispatch=>{
dispatch({
type:ActionTypes.itemsLoading
});
try {
const response=await axios.get(`/Home/${specificType}/${sortType}`);
dispatch({
type:ActionTypes.getSortedItems,
payload:response.data
});
} catch (error) {
dispatch({
type:ActionTypes.itemsLoadingFailed,
payload:error.message
});
}
}
//register user
export const registerUser=(username, email, password, cpassword)=> async dispatch=>{
const config={
headers:{
'Content-Type':'application/json'
}
}
const body=JSON.stringify({username, email, password, cpassword});
try {
const response= await axios.post('/user/register', body, config);
dispatch({
type:ActionTypes.registerUser,
payload:response.data
});
alert("User registered successfully...!");
dispatch(actions.reset('User'));
dispatch(loadingUser());
} catch (error) {
console.log(error.message);
dispatch({
type:ActionTypes.setAlert,
payload:error.response.data.errors
});
dispatch({
type:ActionTypes.registerFail,
});
}
}
//Login user
export const loginUser=(email, password)=> async dispatch=>{
const config={
headers:{
'Content-Type':'application/json'
}
}
const body=JSON.stringify({email, password});
try {
const response= await axios.post("/user/login", body, config);
dispatch({
type:ActionTypes.loginUser,
payload:response.data
});
dispatch(actions.reset('User'));
dispatch(loadingUser());
} catch (error) {
console.log(error.message);
if(error.message!=="Network Error"){
dispatch({
type:ActionTypes.setAlert,
payload:error.response.data.errors
});
}
dispatch({
type:ActionTypes.loginFail
});
}
}
//Logout user
export const logoutUser=()=>({
type:ActionTypes.logoutUser
});
//Loading user
export const loadingUser=()=>async dispatch=>{
if(localStorage.token){
setAuthToken(localStorage.token);
}
try {
const response=await axios.get("/user");
dispatch({
type:ActionTypes.loadingUser,
payload:response.data
});
} catch (error) {
console.log(error.message);
dispatch({
type:ActionTypes.authError
});
}
}
//Putting items in cart
export const addItem=(itemId, itemname, image, type, price, quantity)=>async dispatch=>{
const config={
headers:{
'Content-Type':'application/json'
}
}
const body=JSON.stringify({itemId, itemname, image, type, price, quantity});
try {
const response=await axios.post("/cart", body, config);
dispatch({
type:ActionTypes.addItem,
payload:response
});
dispatch(fetchCartItems());
dispatch(loadingUser());
} catch (error) {
console.log(error);
dispatch({
type:ActionTypes.authError
});
}
}
//fetching all cart items
export const fetchCartItems=()=>async (dispatch)=>{
try {
const response=await axios.get('/cartItems');
dispatch({
type:ActionTypes.getCartItems,
payload:response.data
});
dispatch(loadingUser());
} catch (error) {
dispatch({
type:ActionTypes.itemsLoadingFailed,
payload:error.message
});
}
}
//add comment to item
export const addComment=(itemId, username, comment)=>async dispatch=>{
const config={
headers:{
'Content-Type':'application/json'
}
}
const body=JSON.stringify({itemId, username, comment});
try {
const response=await axios.post("/addComment", body, config);
dispatch({
type:ActionTypes.addComment,
payload:[response.data]
});
dispatch(loadingUser());
} catch (error) {
console.log(error.message);
dispatch({
type:ActionTypes.authError
});
}
}
//get Item by ID
export const getItem=(itemId)=>async dispatch=>{
dispatch({
type:ActionTypes.itemsLoading
});
try {
//const response=await axios.get(`/item/${itemId}`);
dispatch({
type:ActionTypes.getItem,
payload:itemId
});
dispatch(loadingUser());
} catch (error) {
console.log(error.message);
dispatch({
type:ActionTypes.authError
});
}
}
<file_sep>/client/src/MyComponents/LoginComponent.js
import React from "react";
import { Control, Form } from 'react-redux-form';
import { Button} from 'reactstrap';
import { Link, Redirect } from 'react-router-dom';
import { loginUser } from '../Redux/ActionCreators';
import { connect } from 'react-redux';
class Login extends React.Component{
handleSubmit(values){
this.props.loginUser(values.email, values.password);
}
render(){
const alert=this.props.users.errors.map((error)=>{
return(
<React.Fragment>
<p style={{ backgroundColor:'red', borderRadius:'5px', color:'white', padding:'5px' }}>{error.msg}</p>
</React.Fragment>
);
});
if(this.props.isAuthenticated){
return (<Redirect to="/home" />);
} else{
return(
<React.Fragment>
<div className="login_bg">
<div className="container">
<div className="row m-1">
<div className="col-12 col-md-4 offset-md-4 login_col">
<Link to="/Welcome" style={{textDecoration:'none', color:'black'}}><h3 className="mb-0" style={{fontStyle:'italic'}}>Jungies food items</h3></Link>
<small style={{color:'gray', fontFamily:'arial'}} className="ml-1">we understand your hungry</small>
<div className="mt-2">
{alert}
</div>
<Form model="User" onSubmit={(values)=>this.handleSubmit(values)}>
<Control.text model=".email"
id="email"
name="email"
placeholder="Email"
className="form-control mt-4 mb-4"
/>
<Control.password model=".password"
id="password"
name="password"
placeholder="<PASSWORD>"
className="form-control"
/>
<Button type="submit" className="mt-3 mb-2" style={{width:'100%', backgroundColor:'teal', borderRadius:'1'}}>LOG IN</Button>
<p style={{color:'gray'}}><small>Don't have account</small><br/>Click <Link to="/Welcome/register">here</Link> to register</p>
</Form>
</div>
</div>
</div>
</div>
</React.Fragment>
);
}
}
}
const mapStateToProps=state=>({
isAuthenticated:state.users.isAuthenticated,
users:state.users
});
export default connect(mapStateToProps, { loginUser })(Login);<file_sep>/client/src/MyComponents/HomeComponent.js
import React from 'react';
import FoodType from './FoodTypeComponent';
import FoodItems from './FoodItemsComponent';
import NavBar from './NavbarComponent';
class Home extends React.Component{
render(){
return(
<React.Fragment>
<div className="home">
<NavBar />
<FoodType />
<FoodItems />
</div>
</React.Fragment>
);
}
}
export default Home;<file_sep>/client/src/MyComponents/PrivateRoute.js
import React from 'react'
import { Route, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
const PrivateRoute = ({ user:{isAuthenticated, loading}, component:Component}) => (
<Route render={()=>!isAuthenticated && !loading ?(<Redirect to="/welcome/login" />):(<Component />)} />
);
const mapStateToProps=state=>({
user:state.users
});
export default connect(mapStateToProps)(PrivateRoute);<file_sep>/client/src/MyComponents/ItemInfoComponent.js
import React from 'react';
import { Card, CardBody, CardImg, CardHeader, Button } from 'reactstrap';
import Loading from './LoadingComponent';
import NavBar from './NavbarComponent';
import { Form, Control } from 'react-redux-form';
import { addComment } from '../Redux/ActionCreators';
import { connect } from 'react-redux';
class ItemInfo extends React.Component{
handleSubmit(values){
this.props.addComment(this.props.items.items[0]._id , this.props.userDetails!==null && this.props.userDetails.username, values.comment);
}
render(){
if(this.props.items.isLoading){
return(
<div className="container" style={{ paddingTop:'300px', textAlign:'center' }}>
<div className="row">
<Loading />
</div>
</div>
);
}else if(this.props.items.errMsg){
return(
<div className="container" style={{ paddingTop:'100px' }}>
<div className="row justify-content-center">
<div className="col-12">
<h3>{this.props.itemErrMsg}</h3>
</div>
</div>
</div>
);
}else {
return(
<React.Fragment>
<NavBar />
<div className="view_item ">
<div className="container " style={{paddingTop:'100px'}}>
<div className="row mt-0">
<div className="col-12">
<h2 className="ml-2">{this.props.items.items[0].itemname}</h2>
<hr />
</div>
</div>
<div className="row">
<div className="col-12 col-md-4">
<Card>
<CardImg height="300px" src={"/Images/"+this.props.items.items[0].image} alt={this.props.items.items[0].itemname}/>
</Card>
</div>
<div className="col-12 col-md-8">
<Card style={{height:'300px'}} outline color="info">
<CardHeader style={{backgroundColor:'turquoise', textAlign:'center'}}><strong>Item Details</strong>
</CardHeader>
<CardBody >
<dl className="row" style={{textAlign:'center'}}>
<dt className="col-6">Item name</dt>
<dd className="col-6">{ this.props.items.items[0].itemname}</dd>
<dt className="col-6">Price</dt>
<dd className="col-6">₹{ this.props.items.items[0].price}</dd>
<dt className="col-6">Item type</dt>
<dd className="col-6" style={{color:'red'}}>{ this.props.items.items[0].type}</dd>
<dt className="col-6">Available for</dt>
<dd className="col-6">{ this.props.items.items[0].availablefor}</dd>
</dl>
</CardBody>
</Card>
</div>
</div>
<div className="row mt-3">
<div className="col-12">
<h2>Comment</h2>
</div>
</div>
<Form model="User" onSubmit={(values) => this.handleSubmit(values)}>
<div className="row ">
<div className="col-md-10 mt-1">
<Control.text model=".comment"
id="comment"
name="comment"
placeholder="Enter your taste..."
className=" form-control mr-0"
style={{width:'100%', outline:'none',border:'none', backgroundColor:'rgb(228, 208, 208)', color:'gray',borderBottom:'1px solid gray'}}
/>
</div>
<div className="col-md-2 mt-1" >
<Button type="submit" style={{backgroundColor:'teal', width:'100%'}} className="ml-0"><i className="fa fa-paper-plane" aria-hidden="true"></i>
</Button>
</div>
</div>
</Form>
<div className="container mt-3 ">
{
this.props.items.items[0].comments.length>0?this.props.items.items[0].comments.map((user)=>{
return (
<React.Fragment key={user.id}>
<div className="row mt-1" style={{borderBottom:'1px solid teal' }}>
<div className="col-12">
<i className="fa fa-user"></i> <b>{user.username}</b>{' '}
<small>{new Date(user.date).toLocaleTimeString()}</small>
<br/>
<small style={{position:'absolute', top:'10', right:'0'}}>{new Date(user.date).toDateString()}</small>
<p>{user.comment}</p>
</div>
</div>
</React.Fragment>
);
}) : ''
}
</div><br/><br/><br/>
</div>
</div>
</React.Fragment>
);
}
}
}
const mapStateToProps=state=>({
userDetails:state.users.userDetails,
items:state.items
});
export default connect(mapStateToProps, { addComment })(ItemInfo);
<file_sep>/server.js
const express=require("express");
const path = require('path');
const fooditems=require("./routes/fooditems");
const user=require("./routes/user");
const cart=require("./routes/cart");
const comments=require("./routes/comments");
const connectDB = require("./config/db");
const app=express();
const cors = require('cors');
// connect to DB
connectDB();
app.use(cors());
//intializing express middleware
app.use(express.json({extended:false}));
//Routes
app.use(fooditems);
app.use(user);
app.use(cart);
app.use(comments);
// Serve static assets in production
if(process.env.NODE_ENV==='production'){
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
//Running our Food App server
const serverPort=process.env.PORT || 5000;
app.listen(serverPort, ()=>{console.log(`Your food app server is running at port ${serverPort}`)});<file_sep>/client/src/MyComponents/NavbarComponent.js
import React from 'react';
import { Navbar, Nav, NavItem, NavbarBrand, NavbarToggler, Collapse, UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';
import { NavLink } from 'react-router-dom';
import { logoutUser } from '../Redux/ActionCreators';
import { connect } from 'react-redux';
class NavBar extends React.Component{
constructor(props){
super(props);
this.state={
isNavOpen:false
}
}
toggleNav(){
this.setState({
isNavOpen:!this.state.isNavOpen
});
}
render(){
const publicLinks=(
<React.Fragment>
<NavItem >
<NavLink to='/Welcome/login' className="nav-link" onClick={()=>this.toggleNav()} style={{color:'white'}}>
<i className="fa fa-user-circle fa-lg" aria-hidden="true" ></i> Log in
</NavLink>
</NavItem>
</React.Fragment>
);
const privateLinks=(
<React.Fragment>
<NavItem className="mr-3" active>
<NavLink to='/home' className="nav-link " onClick={()=>this.toggleNav()} style={{color:'white'}}>
<i className="fa fa-home fa-lg" aria-hidden="true" ></i> Home
</NavLink>
</NavItem>
<NavItem className="mr-3" >
<NavLink to='/home/cart' onClick={()=>this.toggleNav()} className="nav-link" style={{color:'white'}} >
<i className="fa fa-shopping-cart fa-lg" aria-hidden="true"></i> Cart
</NavLink>
</NavItem>
<UncontrolledDropdown >
<DropdownToggle tag="dropdown" className="nav-link" caret style={{cursor:'pointer', color:'white'}}>
<i className="fa fa-user-circle fa-lg" aria-hidden="true" ></i>{this.props.user.userDetails!==null && this.props.user.userDetails.username.toUpperCase()}
</DropdownToggle>
<DropdownMenu >
<DropdownItem tag="dropdown" className="drop" >
<NavLink style={{color:'black'}} className="nav-link" to="">
<i className="fa fa-user" aria-hidden="true"></i> My Profile
</NavLink>
</DropdownItem>
<DropdownItem tag="dropdown" className="drop" >
<NavLink className="nav-link" style={{color:'black'}} to="">
<i className="fa fa-heart" aria-hidden="true"></i> My Favourites
</NavLink>
</DropdownItem>
<DropdownItem tag="dropdown" className="drop" >
<NavLink style={{color:'black'}} to='/Welcome' className="nav-link" onClick={this.props.logoutUser} >
<i className="fa fa-sign-out" aria-hidden="true"></i> Log out
</NavLink>
</DropdownItem>
</DropdownMenu>
</UncontrolledDropdown>
</React.Fragment>
);
return(
<React.Fragment>
<Navbar className="home_navbar" dark expand="md" fixed="top">
<div className="container">
<NavbarBrand href='/welcome'><i className="fa fa-cutlery fa-lg" style={{textShadow:'0px 0px 3px white',color:'rgb(204, 120, 10)'}} aria-hidden="true"></i>
<b> Jungies Food Items</b>
</NavbarBrand>
<NavbarToggler onClick={()=>this.toggleNav()} className="mr-0"/>
<Collapse isOpen={this.state.isNavOpen} navbar >
<Nav navbar className="ml-auto">
{!this.props.user.isAuthenticated ? publicLinks : privateLinks}
</Nav>
</Collapse>
</div>
</Navbar>
</React.Fragment>
);
}
}
const mapStateToProps=state=>({
user:state.users
});
export default connect(mapStateToProps, { logoutUser })(NavBar);<file_sep>/client/src/Redux/Items.js
import * as ActionTypes from './ActionTypes';
export const Item= (state = { isLoading:true, errMsg:null, items:[], specificItems:[], cartItems:[], comments:[] }, action) => {
switch(action.type)
{
case ActionTypes.itemsLoading:
return {...state, isLoading:true};
case ActionTypes.itemsLoadingFailed:
return {...state, isLoading:false, errMsg:action.payload};
case ActionTypes.getAllItems:
case ActionTypes.addComment:
return {...state, isLoading:false, errMsg:null, items:action.payload};
case ActionTypes.getSpecificItems:
case ActionTypes.getSortedItems:
return {...state, isLoading:false, errMsg:null, specificItems:action.payload};
case ActionTypes.getCartItems:
return {...state, isLoading:false, errMsg:null, cartItems:action.payload};
case ActionTypes.getComments:
return {...state, isLoading:false, errMsg:null, comments:action.payload};
case ActionTypes.addItem:
return {...state, isLoading:false, errMsg:null};
case ActionTypes.getItem:
return {...state, isLoading:false, errMsg:null, items:state.specificItems.filter((item)=>item._id===action.payload) };
default:
return state;
}
};
<file_sep>/client/src/MyComponents/MainComponent.js
import React from 'react';
import { Switch, Route, Redirect, withRouter } from 'react-router-dom';
import Cart from './CartComponent';
import Home from './HomeComponent';
import ItemInfo from './ItemInfoComponent';
import { loadingUser } from '../Redux/ActionCreators';
import { connect } from 'react-redux';
import Landing from './LandingPageComponent';
import Login from './LoginComponent';
import Register from './RegisterComponent';
import PrivateRoute from './PrivateRoute';
import setAuthToken from '../utils/setAuthToken';
if(localStorage.token){
setAuthToken(localStorage.token);
}
class Main extends React.Component{
componentDidMount(){
this.props.loadingUser();
}
render(){
return(
<React.Fragment>
<Switch>
<Route exact path='/' component={Landing} />
<Route exact path='/Welcome' component={Landing} />
<Route exact path='/Welcome/register' component={Register} />
<Route exact path='/Welcome/login' component={Login}/>
<PrivateRoute exact path='/home/Cart' component={Cart} />
<PrivateRoute exact path='/home' component={Home} />
<PrivateRoute exact path='/home/:itemname' component={ItemInfo} />
<Redirect to='/Welcome' />
</Switch>
</React.Fragment>
);
}
}
const mapStateToProps=state=>({
items:state.items
});
export default withRouter(connect(mapStateToProps, { loadingUser })(Main)); <file_sep>/client/src/MyComponents/LandingPageComponent.js
import React from 'react';
import { Button, Jumbotron, Card, CardImg } from 'reactstrap';
import { Link } from 'react-router-dom';
import Loading from './LoadingComponent';
import { connect } from 'react-redux';
import { fetchAllItems } from '../Redux/ActionCreators';
import NavBar from './NavbarComponent';
class Landing extends React.Component{
componentDidMount(){
this.props.fetchAllItems();
}
render(){
return(
<React.Fragment>
<NavBar />
<Jumbotron>
<div className="container mt-4">
<div className="row">
<div className="col-12 col-sm-6">
<h1>Welcome Hunger...</h1>
<p>We take inspiration from the World's best cuisines, and create a unique fusion experience. Our lipsmacking creations will tickle your culinary senses!</p>
</div>
{ (!this.props.isAuthenticated) &&
(<div className="col-12 col-sm-6">
<div style={{textAlign:'center', paddingTop:'50px' }}>
<Link to="/Welcome/Login" >
<Button outline className=" jumb_button mr-1">Log in</Button>
</Link>
<Link to="/Welcome/Register">
<Button outline className="jumb_button">Register</Button>
</Link>
</div>
</div>)
}
</div>
</div>
</Jumbotron>
<div className="container">
<div className="row">
<div className="col-8 offset-2 fast_time" style={{borderColor:'teal'}}>
<strong >All items</strong>
</div>
</div>
</div>
<div className="container mb-3">
<RenderItems items={this.props.items} />
</div>
</React.Fragment>
);
}
}
function RenderItems(props){
const allItems=props.items.items.map((item)=>{
return(
<React.Fragment key={item._id}>
<div className="col-12 col-md-6 col-lg-4 mt-3">
<div className="all_item_box" >
<div className="row mt-2 mb-2 mr-0" >
<div className="col-12 col-md-6 ">
<Card >
<CardImg height="150px" width="100%" src={"/Images/"+item.image} alt={item.itemname}/>
</Card>
</div>
<div className="col-12 col-md-6" style={{textAlign:'center', fontFamily:'arial', height:'100px', width:'100%'}}>
<b>{item.itemname}</b>
<p className="mt-1 mb-1">₹{ item.price }</p>
<small style={{ color:'red', fontWeight:'bold', fontStyle:'italic' }} >{item.type}</small><br/>
</div>
</div>
</div>
</div>
</React.Fragment>
);
})
if(props.items.isLoading){
return(
<div className="container">
<div className="row" style={{ paddingTop:'100px', textAlign:'center' }}>
<Loading />
</div>
</div>
);
}
else if(props.items.errMsg){
return(
<div className="container">
<div className="row justify-content-center" style={{ paddingTop:'100px' }}>
<h2 style={{color:'gray'}}>{props.items.errMsg}</h2>
</div>
</div>
);
}
else{
return(
<div className="container">
<div className="row">
{allItems}
</div>
</div>
);
}
}
const mapStateToProps=state=>({
items:state.items,
isAuthenticated:state.users.isAuthenticated
});
export default connect(mapStateToProps, { fetchAllItems })(Landing);<file_sep>/client/src/Redux/user.js
import * as ActionTypes from './ActionTypes';
const initialState={
token:localStorage.getItem("token"),
isAuthenticated:false,
loading:true,
userDetails:null,
errors:[]
}
export const User=(state=initialState, action)=>{
const {type, payload}=action;
switch(type){
case ActionTypes.setAlert:
return {...state, errors:payload};
case ActionTypes.loadingUser:
return {...state, isAuthenticated:true, loading:false, userDetails:payload};
case ActionTypes.registerUser:
case ActionTypes.loginUser:
localStorage.setItem('token', payload.token);
return {...state, isAuthenticated:true, loading:false, token:payload.token, errors:[]};
case ActionTypes.registerFail:
case ActionTypes.authError:
case ActionTypes.loginFail:
case ActionTypes.logoutUser:
localStorage.removeItem('token');
return {...state, isAuthenticated:false, loading:false, token:null, userDetails:null};
default:
return state;
}
}<file_sep>/models/Cart.js
const mongoose=require('mongoose');
const Schema=mongoose.Schema;
const cartSchema=new Schema({
user:{
type:mongoose.Schema.Types.ObjectId,
ref:"users"
},
items:[{
itemId:{
type:String,
required:true
},
itemname:{
type:String,
required:true
},
image:{
type:String,
required:true
},
type:{
type:String,
required:true
},
price:{
type:Number,
required:true
},
quantity:{
type:Number,
required:true,
default:0
}
}]
});
const cart=mongoose.model("cart", cartSchema);
module.exports=cart;<file_sep>/middleware/authToken.js
const jwt=require("jsonwebtoken");
module.exports=function(req, res, next){
//get token from header
const token=req.header('auth-token');
//check token existence
try{
if(!token){
return res.status(401).json({msg:"No token, authorization denied"});
}
//verify token
const decodedToken=jwt.verify(token, "<PASSWORD>");
req.user=decodedToken.user;
next();
} catch(error){
res.status(401).json({msg:"Token is not valid"})
}
}; | b81a6baeec3fc470d41d5bc04401db6b8623f72c | [
"JavaScript"
] | 13 | JavaScript | DSK9012/Food-ordering-app | 47f1aa6c2a0102278b6c7ce7e0663d8c334053a3 | a6b489144e3b1ca1dbb782bdb854bb337a993fb4 |
refs/heads/main | <repo_name>zmirshafiei/Mafia-Game<file_sep>/mafiagame.py
import random
import sys
roles = ['پدر خوانده', 'دکتر لکتر', 'مافیا ساده1', 'مافیا ساده2', 'دکتر', 'روانپزشک', 'کاراگاه', 'شهردار', 'حرفه ای', 'جان سخت', 'شهروند ساده1', 'شهروند ساده2']
selection = random.shuffle(roles)
# تعریف متغیر جهت نگهداری محتوای فایل خروجی
output = ""
# متغیر نگهدارنده لیست شرکت کنندگان به همراه نقش ها
participant_list = {}
# متغیر تعداد شرکت کنندگان
round_count = 0
try:
round_count = int(input("تعداد افراد شرکت کننده را وارد کنید:\n"))
if round_count < 9:
print("تعداد شرکت کنندگان نباید کمتر از 9 باشد")
sys.exit()
except:
print("تعداد شرکت کنندگان باید یک عدد صحیح باشد.")
sys.exit()
round = 0
while round < round_count:
# نمایش یک ورودی برای گرفتن نام شرکت کنندگان. round+1 برابر است با شماره شرکت کنندگان که از 1 شروع میشود.
participant = input('نام شرکت کننده '+str((round+1))+' را وارد کنید\n ')
participant_list[participant] = roles[round]
round = round + 1
# اضافه کردن اولین خط به متغیر output برای فایل خروجی
output += "شرکت کننده = نقش:\n"
# گرفتن یک لوپ از آیتم های دیکشنری participant_list
for name, role in participant_list.items():
# اضافه کردن شرکت کنندگان و نقش ها به خطوط متغیر output
output += name+" "+role+"\n"
# تعریف متغیر حاوی کارت های بازی
cardes = ["مسیر سبز", "فرش قرمز", "ذهن زیبا", "دروغ سیزده", "بیخوابی", "شلیک نهایی"]
# بُر زدن مقادیر جهت تصادفی شدن متغیر
random.shuffle(cardes)
# اضافه کردن خط "کارت ها" به متغیر output
output += "کارت ها:\n"
# گرفتن لوپ از کارت های بازی
for carde in cardes:
# اضافه کردن شماره کارت ها و اسامی آنها به متغیر output
output += str(cardes.index(carde)+1)+" "+carde+"\n"
# تعریف یک نام برای فایل خروجی
filename = "mafia.txt"
# باز کردن فایل خروجی در حالت نوشتاری و با انکودینگ utf-8
with open(filename, "w", encoding="utf-8") as f:
# نوشتن متغیر output در فایل باز شده
f.write(output)
| 037f93867835c2f3c7c5059aff9f4f2813358bec | [
"Python"
] | 1 | Python | zmirshafiei/Mafia-Game | bfa46fc307f773860b615b9589ef1fb90e250e1f | 33fcb65a2fe4001c01c5c7833480738ea5cee54d |
refs/heads/master | <repo_name>arabog/bEfE1Terminal<file_sep>/server.js
const express = require("express")
const request = require('request');
const app = express()
const port = 5000
app.get("/", (req, res) => {
res.send("Hello world!!!")
})
app.get("/newEndpt", (req, res) => {
request("https://apitemplate21.herokuapp.com/api/posts",
function (error, response, body) {
if(!error && response.statusCode == 200) {
const parseBody = JSON.parse(body)
res.send(parseBody)
}
}
);
})
app.listen(port, () => {
console.log(`Server listening on port ${port}`)
}) | 4fab27bef292b4014ebb7eb32a51d7ac7c98d11a | [
"JavaScript"
] | 1 | JavaScript | arabog/bEfE1Terminal | 93134b9d429b4e11231ba310c61a196997a08b9b | 0986c2b1a3bafe341aa8028d8ce20ec5218fd726 |
refs/heads/main | <repo_name>TanayDiwan29/Kill-The-Monster<file_sep>/sketch.js
const Engine=Matter.Engine;
const World=Matter.World;
const Bodies=Matter.Bodies;
const Body=Matter.Body;
const Constraint=Matter.Constraint;
var world,engine;
var attempts=0;
var status="Not Defeated";
function preload() {
//preload the images here
bg=loadImage("bg.png");
}
function setup() {
//making the engine
engine=Engine.create();
//making the world
world=engine.world;
//the canvas
createCanvas(1200, 500);
// create sprites here
ground=new Ground(350,250,900,20);
superman=new Superman(200,100,250,60);
monster=new Monster(700,100,100,100);
rope=new Rope(superman.body,{x:200,y:100});
//first row
b1=new Box(400,150);
b4=new Box(400,150-40);
b5=new Box(400,150-80);
//second row
b2=new Box(440,150);
b6=new Box(440,150-40);
b7=new Box(440,150-80);
b8=new Box(440,150-120);
//third row
b3=new Box(480,150);
b9=new Box(480,150-40);
b10=new Box(480,150-80);
}
function draw() {
background(bg);
Engine.update(engine);
textSize(20);
text("Attempts : "+attempts,width-170,50);
text("Status : "+status,width-200,80);
if(monster.body.position.y>260){
status="Defeated";
}
ground.display();
superman.display();
monster.display();
rope.display();
b1.display();
b2.display();
b3.display();
b4.display();
b5.display();
b6.display();
b7.display();
b8.display();
b9.display();
b10.display();
}
function mouseDragged(){
Matter.Body.setPosition(superman.body,{x:mouseX,y:mouseY});
}
function mouseReleased(){
attempts=attempts+1;
rope.fly();
}
function keyPressed(){
if(keyCode===32){
rope.attach(superman.body);
}
} | a78d9c6783ac23da0f1b65b472a12fcc2e35f30d | [
"JavaScript"
] | 1 | JavaScript | TanayDiwan29/Kill-The-Monster | 532ba65b8e2db33e30c1b90a0314d30f18b4862d | cfe94a859ddbc21157ad8063d514c1f65ce3508b |
refs/heads/main | <file_sep>MENU = {
'espresso': {
'ingredients': {
'water': 50,
'coffee': 18,
},
'cost': 1.5,
},
'latte': {
'ingredients': {
'water': 200,
'milk': 150,
'coffee': 24,
},
'cost': 2.5,
},
'cappuccino': {
'ingredients': {
'water': 250,
'milk': 100,
'coffee': 24,
},
'cost': 3.0,
}
}
resources = {
'water': 300,
'milk': 200,
'coffee': 100,
}
profit = 0
# TODO: 4. Check resources
def check_resources_sufficient(drink_ingredient):
for item in drink_ingredient:
if drink_ingredient[item] > resources[item]:
print(f'Sorry there is not enough {item}.')
return False
return True
# TODO: 5. Process coins & get total paid
def coin_insert():
print('Please insert coins.')
quarters = int(input('How many quarters: '))
dimes = int(input('How many dimes: '))
nickles = int(input('How many nickles: '))
pennies = int(input('How many pennies: '))
paid = round((quarters * 0.25 + dimes * 0.10 + nickles * 0.05 + pennies * 0.01), 2)
return paid
#Check if the paid is sufficient for purchase
def payment_proceed(paid_total, price):
if paid_total > price:
global profit
profit += price
changes = round((paid_total - price), 2)
print(f'Here is {changes} in changes')
return True
else:
print('Sorry that is not enough money. Money refunded.')
return False
# TODO: 7. Make coffee and deduct resources
def update_report(drink_ingredient):
for item in drink_ingredient:
resources[item] -= drink_ingredient[item]
# print(f'{item}: {resources[item]}')
is_continue = True
while is_continue:
order = input('What would you like? (espresso/latte/cappuccino): ')
if order == 'off':
is_continue = False
elif order == 'report':
for item in resources:
print(f'{item}: {resources[item]}')
print(f'money: {profit}')
else:
drink_ingredient = MENU[order]['ingredients']
resources_sufficient = check_resources_sufficient(drink_ingredient)
if resources_sufficient:
#Call the get coins
paid_total = coin_insert()
price = MENU[order]['cost']
if payment_proceed(paid_total, price):
update_report(drink_ingredient)
print(f'Here is your {order} ☕️.Enjoy!')
else:
is_continue = False
# TODO: 6. Check transaction
if input('Type yes if you want to re-order: ') != 'yes':
print('Thank you. See you next time!')
is_continue = False
<file_sep>import utils as ul
def coffee_bot():
print('Welcome to the cafe!')
drinks = []
order_drink = 'y'
while order_drink.lower() == 'y':
size = ul.get_size()
print('Great!')
drink_type = ul.get_drink_type()
drink = '{} {}'.format(size,drink_type)
drinks.append(drink)
print('Alright! That\'s a', drink )
while True:
order_drink = input('Would you like to order another drink? (y/n) \n')
if order_drink in ['y', 'n', 'Y', 'N']:
break
name = ul.get_name()
print('Awesome {}! Here\'s your order: '.format(name))
for item in drinks:
print('- ', item)
print('Your drink will be ready shortly. Please go the counter to get your drinks!')
coffee_bot()
<file_sep>from turtle import Turtle, Screen
import pandas as pd
from get_name import Name
turtle = Turtle()
screen = Screen()
image = 'blank_states_img.gif'
screen.addshape(image)
turtle.shape(image)
data_file = pd.read_csv('50_states.csv')
all_state = data_file.state.tolist()
correct_count = 0
correct_list = []
game_is_on = True
while game_is_on:
guess = screen.textinput(f'{correct_count}/50 Correct', 'What is another state name?')
state_guess_info = data_file[data_file['state'] == guess.title()]
screen.tracer(0) # prevent screen flash
if not state_guess_info.empty:
if guess not in correct_list:
screen.update() # update screen
x_cor = state_guess_info['x'].tolist() # or use int(state_info.x)
y_cor = state_guess_info['y'].tolist()
name_state = Name()
name_state.goto(x_cor[0], y_cor[0])
name_state.write(guess, font=('monaco', 10, 'bold'))
correct_count += 1
correct_list.append(guess)
if guess == 'exit':
game_is_on = False
missing_state = [state for state in all_state if state not in correct_list]
df_missing_state = pd.DataFrame(missing_state)
df_missing_state.to_csv('your_missing_answer.csv')
screen.bye()
screen.mainloop()
<file_sep>from turtle import Screen, Turtle
FONT = ('Courtier', 30, 'normal')
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
self.hideturtle()
self.penup()
self.goto(-250, 260)
self.score = 0
with open('high_score.txt') as file:
self.high_score = int(file.read())
self.update_score()
def update_score(self):
self.clear()
self.write(f'Score: {self.score} Highest score: {self.high_score}', font=FONT)
def increase_score(self):
self.score += 1
self.update_score()
#
# def end_game(self):
# self.goto(0, 0)
# self.write('Game over', align='center', font=FONT)
def reset_game(self):
if self.score > self.high_score:
self.high_score = self.score
with open('high_score.txt', 'w') as file:
file.write(f'{self.high_score}')
self.score = 0
self.update_score()
<file_sep>#2 Sep 2021
import os
logo = """
_____________________
| _________________ |
| | Lynn 0. | | .----------------. .----------------. .----------------. .----------------.
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
| ___ ___ ___ ___ | | | ______ | || | __ | || | _____ | || | ______ | |
| | 7 | 8 | 9 | | + | | | | .' ___ | | || | / \ | || | |_ _| | || | .' ___ | | |
| |___|___|___| |___| | | | / .' \_| | || | / /\ \ | || | | | | || | / .' \_| | |
| | 4 | 5 | 6 | | - | | | | | | | || | / ____ \ | || | | | _ | || | | | | |
| |___|___|___| |___| | | | \ `.___.'\ | || | _/ / \ \_ | || | _| |__/ | | || | \ `.___.'\ | |
| | 1 | 2 | 3 | | x | | | | `._____.' | || ||____| |____|| || | |________| | || | `._____.' | |
| |___|___|___| |___| | | | | || | | || | | || | | |
| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
| |___|___|___| |___| | '----------------' '----------------' '----------------' '----------------'
|_____________________|
"""
def add(a,b):
return a + b
def substract(a,b):
return a - b
def multiply(a,b):
return a * b
def divide(a,b):
return a / b
def exponent(a,b):
return a ** b
operators = {
'+' : add,
'-' : substract,
'*' : multiply,
'/' : divide,
'**': exponent
}
def calculation():
cont = True
print(logo)
num1 = float(input('What is the number? '))
for item in operators:
print(item)
while cont:
chosen_operator = input('Pick an operator: ')
if chosen_operator in operators:
num2 = float(input('What is next number? '))
total = operators[chosen_operator](num1,num2)
print(f'{num1} {chosen_operator} {num2} = {total}')
is_continue = input(f'Type Y if you want to continue with {total}, R to reset or N to exit: ').lower()
if is_continue == 'y':
num1 = total
elif is_continue == 'r':
os.system('clear')
calculation()
cont = False
elif is_continue == 'n':
print('Thanks for using. Bye!')
cont = False
else:
print('Invalid operator. Please try again')
calculation()
<file_sep>from turtle import Turtle, Screen
import turtle
my_turtle = Turtle()
my_turtle.shape('turtle')
my_turtle.color('blue')
my_screen = Screen()
def backward():
return my_turtle.backward(10)
def forward():
return my_turtle.forward(10)
def turn_left():
new_heading = my_turtle.heading() + 10
return my_turtle.setheading(new_heading)
def turn_right():
new_heading = my_turtle.heading() - 10
return my_turtle.setheading(new_heading)
def clear():
my_turtle.clear()
my_turtle.penup()
my_turtle.home()
my_turtle.pendown()
my_screen.onkey(key='s', fun=backward)
my_screen.onkey(key='w', fun=forward)
my_screen.onkey(key='a', fun=turn_left)
my_screen.onkey(key='d', fun=turn_right)
my_screen.onkey(key='c', fun=clear)
my_screen.listen()
my_screen.exitonclick()
<file_sep>import time
from turtle import Screen
from player import Player
from car_manager import Car
from score_board import ScoreBoard
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor('white')
screen.title('Turtle Crossing Capstone by imlynn')
screen.tracer(0)
player = Player()
screen.listen()
screen.onkey(player.move_forward, 'Up')
score_board = ScoreBoard()
game_is_on = True
game_loop = 0
lst_car = []
while game_is_on:
time.sleep(0.1)
screen.update()
# create a new car every 6th loop
if game_loop % 6 == 0:
car = Car()
lst_car.append(car)
# create a series of car moving
for num in range(len(lst_car)):
lst_car[num].move_car()
# detect player collide with top edge & need more precise on collision
for car in lst_car:
if player.distance(car) < 20:
print('Contacted')
score_board.reset_game()
player.reset_game()
# detect player collide top edge
if player.ycor() > 280:
player.starting_pos()
score_board.clear()
score_board.increase_score()
car.speed_up()
game_loop += 1
screen.exitonclick()
<file_sep>from turtle import Turtle
class Player(Turtle):
def __init__(self):
super().__init__()
self.shape('turtle')
self.color('green')
self.penup()
self.left(90)
self.starting_pos()
def starting_pos(self):
self.goto(0, -280)
def move_forward(self):
new_y = self.ycor() + 10
self.goto(0, new_y)
def reset_game(self):
self.starting_pos()
<file_sep># python_learning
Play around Python
<file_sep>#29Aug2021
from game_hangman_resource import logo, word_list, stages
import random
#print game logo
print(logo)
display = []
lives = 6
end_game = False
false_guess = []
#system generates random word
chosen_word = random.choice(word_list)
for char in chosen_word:
display += '_'
print(f'Here is the word you gonna guess: {display}')
print(f'Test: The system chose: {chosen_word}')
while not end_game:
user_guess = input('Pick a character: ').lower()
if user_guess in display:
print(f'Hey, {user_guess} is correct but it is already here. Go with another character.')
else:
for position in range(len(chosen_word)):
letter = chosen_word[position]
if letter == user_guess:
display[position] = letter
print(' '.join(display))
if user_guess not in chosen_word:
if user_guess not in false_guess:
false_guess.append(user_guess)
lives -= 1
print(f'Unfortunately, you lost a live. You only have {lives} time to try.')
if lives == 0:
end_game = True
print('Unfortunately, you lost the game.')
print(stages[lives])
else:
print(f'You guessed {user_guess} already. We will not count this time. Please try with another.')
if '_' not in display:
end_game = True
print('You win the game. Congrats!')
<file_sep>import random
from turtle import Turtle, Screen
my_screen = Screen()
my_screen.setup(600, 600)
user_bet = my_screen.textinput('Make your bet', 'Which one is the winner? Type your answer: ')
colors = ['yellow', 'black', 'orange', 'red', 'maroon', 'blue', 'purple']
y_position = [-200, -150, -100, 0, 100, 150, 200]
turtle_lst = []
for index in range(len(colors)):
my_turtle = Turtle(shape='turtle')
my_turtle.color(colors[index])
my_turtle.penup()
my_turtle.goto(x=-280, y=y_position[index])
turtle_lst.append(my_turtle)
def move_forward():
distance = random.randint(0, 10)
turtle.forward(distance)
race_on = False
if user_bet:
race_on = True
while race_on:
for turtle in turtle_lst:
move_forward()
if turtle.xcor() > 280:
winning_turtle = turtle.pencolor()
if user_bet == winning_turtle:
print(f'You win!The winner is the {winning_turtle} turtle')
else:
print(f'You lose!The winner is the {winning_turtle} turtle')
race_on = False
my_screen.exitonclick()
<file_sep>import random
import os
print('Welcome to the Blackjack')
#Pick random card
def deal_card():
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
card = random.choice(cards)
return card
#Check blackjack and return sum
def score_calculate(lst):
total = sum(lst)
if total == 21 and len(lst) == 2:
return 0
elif total > 21 and 11 in lst:
lst.remove(11)
lst.append(1)
return total
else:
return total
#Check final result
def compare(user_score, dealer_score):
if user_score == dealer_score:
print ('It is a draw.')
elif dealer_score == 0:
print('Blackjack. Dealer wins!')
elif user_score == 0:
print('Blackjack. You win!')
elif user_score > 21:
print('Bust! Dealer wins!')
elif dealer_score > 21:
print('Bust! You win!')
elif user_score > dealer_score:
print('You win')
else:
print('Dealer wins')
def play_game():
user_card = []
dealer_card = []
for item in range(2):
user_card.append(deal_card())
dealer_card.append(deal_card())
print(f'Your card: {user_card}')
print(f'Dealer card: {dealer_card[0]}, x')
game_end = False
while not game_end:
user_score = score_calculate(user_card)
print(f'With {user_card}, your score is: {user_score}')
dealer_score =score_calculate(dealer_card)
#Check if any of player get blackjack and flag the game_end
if user_score == 21 or dealer_score == 21 or user_score > 21:
game_end = True
else:
more_draw = input('Do you want to draw another card? Type y or n: ')
if more_draw == 'y':
user_card.append(deal_card())
else:
game_end = True
while dealer_score < 17:
dealer_card.append(deal_card())
dealer_score =score_calculate(dealer_card)
print(f'With {dealer_card}, the dealer score is: {dealer_score}')
compare(user_score, dealer_score)
# Clear the console and play a new game
while input('Type y if you want to play a new game and n to exit: ') == 'y':
os.system('clear')
play_game()
play_game()
<file_sep>import tkinter
from tkinter import END
from tkinter import messagebox
import random
import pyperclip
# TODO: 2.Password generator
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '*', '+']
def generate_password():
password_entry.delete(0, END)
random_letters = random.randint(3, 7)
random_symbols = random.randint(1, 3)
random_numbers = random.randint(1, 3)
password_list = []
password_list += [random.choice(letters) for char in range(random_letters)]
password_list += [random.choice(symbols) for char in range(random_symbols)]
password_list += [random.choice(numbers) for char in range(random_numbers)]
random.shuffle(password_list)
password = ''.join(password_list)
password_entry.insert(0, password)
pyperclip.copy(password) # copy and paste clipboard function
# TODO: 3.Save password
def add():
website_input = website_entry.get()
email_input = email_entry.get()
password_input = password_entry.get()
if len(email_input) == 0 or len(website_input) == 0 or len(password_input) == 0:
is_blank = messagebox.showerror(title='Alert!', message='Do not leave any fields empty')
print(is_blank)
else:
is_ok = messagebox.askokcancel(title='Confirm',
message=f'Are you sure you want to add this information? \n '
f'Website: {website_input}\n Email: {email_input}\n Password: {password_input}')
if is_ok:
with open('data.txt', 'a') as data_file:
data_file.write(f'{website_input} | {email_input} |{password_input}\n')
clear_field()
def clear_field():
website_entry.delete(0, END)
password_entry.delete(0, END)
# TODO: 1.Create UI
window = tkinter.Tk()
window.title('Password Manager')
window.config(padx=100, pady=100)
canvas = tkinter.Canvas(width=200, height=200)
img = tkinter.PhotoImage(file='logo.png')
create_img = canvas.create_image(100, 100, image=img)
canvas.grid(row=1, column=2)
# create Label
website_txt = tkinter.Label()
website_txt.config(text='Website: ')
website_txt.grid(row=2, column=1)
email_txt = tkinter.Label()
email_txt.config(text='Email/Username: ')
email_txt.grid(row=3, column=1)
password_txt = tkinter.Label()
password_txt.config(text='Password: ')
password_txt.grid(row=4, column=1)
# create entry
website_entry = tkinter.Entry(width=35)
website_entry.grid(row=2, column=2, columnspan=2)
website_entry.focus()
email_entry = tkinter.Entry(width=35)
email_entry.insert(0, '<EMAIL>') # get 2 params: index & string
email_entry.grid(row=3, column=2, columnspan=2)
password_entry = tkinter.Entry(width=21)
password_entry.grid(row=4, column=2)
# create button
generate_btn = tkinter.Button(text='Generate Button', padx=10, command=generate_password)
generate_btn.grid(row=4, column=3)
add_btn = tkinter.Button(text='Add', width=36, command=add)
add_btn.grid(row=5, column=2, columnspan=2)
window.mainloop()
<file_sep>from turtle import Turtle
import random
COLOR = ['red', 'yellow', 'blue', 'orange', 'deep pink', 'indigo']
X_CAR = 280
class Car(Turtle):
def __init__(self):
super().__init__('square')
self.shapesize(stretch_wid=1, stretch_len=3)
self.penup()
self.starting_position()
self.color(random.choice(COLOR))
self.speed = 5
def starting_position(self):
new_y = random.randint(-230, 280)
self.goto(X_CAR, new_y)
def move_car(self):
new_x = self.xcor() - self.speed
self.goto(new_x, self.ycor())
def speed_up(self):
self.speed += 10
<file_sep>def print_message():
print('We\'re sorry, we did not understand your selection. Please enter the corresponding letter for your response.')
def get_drink_type():
res = input('What type of drink would you like?\n[a] Brewed Coffee \n[b] Mocha \n[c] Latte \n>')
if res.lower() == 'a':
return 'Brewed Coffee'
elif res.lower() == 'b':
return order_mocha()
elif res.lower() == 'c':
return order_latte()
else:
print_message()
return get_drink_type()
def get_size():
res = input('What size drink can I get for your? \n[a] Tall \n[b] Grande \n[c] Venti \n>')
if res.lower() == 'a':
return 'Tall'
elif res.lower() == 'b':
return 'Grande'
elif res.lower() == 'c':
return 'Venti'
else:
print_message()
return get_size()
def order_latte():
res = input('And what kind of milk for your latte?\n[a] 2% milk \n[b] Non-fat milk \n[c] Soy milk \n>')
if res.lower() == 'a':
return 'Latte with 2% milk'
elif res.lower() == 'b':
return 'Latte with Non-fat milk'
elif res.lower() == 'c':
return 'Latte with Soy milk'
else:
print_message()
return order_latte()
def order_mocha():
while True:
res = input('Would you like to try our limited-edition peppermint mocha?\n[a] Sure! \n[b] Maybe next time!\n>')
if res.lower() == 'a':
return 'peppermint mocha'
elif res.lower() == 'b':
return 'Mocha'
print_message()
def get_name():
res = input('Can we get your name? :')
return res
<file_sep>from turtle import Turtle
class Name(Turtle):
def __init__(self):
super().__init__()
self.penup()
self.hideturtle()
self.color('blue')
| 81552023807cdd320d93fedf2d62f4a92a376e52 | [
"Markdown",
"Python"
] | 16 | Python | haanguyenn/python_learning | e96f7bf06a21e2197a5919403e885b278a1504ce | f41870771c32ccd8a1509f42fd02c87ba52b3b34 |
refs/heads/master | <repo_name>hafewa/GenerateMapBackgroundWithUnity<file_sep>/Assets/Scripts/GenerateGoogleMapController.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Google地图生成器
/// 在Editor中执行
/// </summary>
//[ExecuteInEditMode]
public class GenerateGoogleMapController : MonoBehaviour
{
/// <summary>
/// 地图大小(像素)
/// </summary>
public static Vector2 MapSize;
/// <summary>
/// 设置每个像素代表的距离
/// </summary>
public static float LengthPerPixel;
/// <summary>
/// 材质保存位置
/// </summary>
public static string MaterialSavePath;
/// <summary>
/// 获取到的所有贴图,每一行
/// </summary>
public static List<List<MapProperty>> AllMapTextures = new List<List<MapProperty>>();
/// <summary>
/// 当前生成的瓦片数量
/// </summary>
public static int CurrentGenerateCountNum = 0;
/// <summary>
/// 生成地图瓦片
/// </summary>
public static void StartGenerateGoogleMap()
{
CurrentGenerateCountNum = 0;
GameObject container = GameObject.Find("GenerateMapContainer");
if (container != null)
{
//删除Scene已有的地图瓦片
DestroyChildren(container.transform);
}
else
{
container = new GameObject("GenerateMapContainer");
}
//有多少列——每行有多少个
int ColumnCount = AllMapTextures.Count;
//按列生成
for (int column = 0; column < ColumnCount; column++)
{
//有多少行
int RowCount = AllMapTextures[column].Count;
//生成每一列的父物体
GameObject parentObj = new GameObject(AllMapTextures[column][0].MapName.Split('_')[0]);
parentObj.transform.SetParent(container.transform);
//生成每一列中的子物体
for (int Row = 0; Row < RowCount; Row++)
{
GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Plane);
obj.transform.SetParent(parentObj.transform);
//设置瓦片大小
obj.transform.localScale = new Vector3(MapSize.x * LengthPerPixel / 10.0f, 1, MapSize.y * LengthPerPixel / 10.0f);
//设置瓦片位置
obj.transform.localPosition = -new Vector3(
(column + 0.5f - ColumnCount / 2.0f) * obj.transform.localScale.x,
0,
(RowCount / 2.0f - Row - 0.5f) * obj.transform.localScale.z) * 10f;
//生成瓦片材质
Material material = CreateMaterail(AllMapTextures[column][Row].MapName, AllMapTextures[column][Row].Map,
MaterialSavePath.Remove(0, MaterialSavePath.IndexOf("Assets")) + "\\" + AllMapTextures[column][Row].MapName + ".mat");
//为瓦片物体赋值材质
obj.GetComponent<Renderer>().material = material;
//改变瓦片名称
obj.name = material.name;
CurrentGenerateCountNum++;
//Debug.Log(column + ":" + Row);
}
}
}
/// <summary>
/// 获取指定路径下的所有贴图(地图瓦片)
/// </summary>
/// <param name="mapPath"></param>
public static void GetAllTextures(string mapPath)
{
if (string.IsNullOrEmpty(mapPath))
{
Debug.LogError("请输入路径!");
return;
}
AllMapTextures = new List<List<MapProperty>>();
DirectoryInfo directoryInfo = null;
//获取路径下的所有文件夹
try
{
directoryInfo = new DirectoryInfo(mapPath);
}
catch (Exception)
{
directoryInfo = null;
}
if (directoryInfo == null)
{
Debug.LogError("目录不存在!");
return;
}
DirectoryInfo[] dirs = null;
try
{
dirs = directoryInfo.GetDirectories();
}
catch (Exception)
{
Debug.LogError("目录不存在!");
return;
}
if (dirs == null || dirs.Length == 0)
{
Debug.LogError("该目录下不存在存放瓦片的子文件夹!");
return;
}
//遍历所有目录
foreach (var dir in dirs)
{
//获取所有后缀为jpg的文件(仅遍历当前目录,子目录不遍历)
FileInfo[] fileInfos = dir.GetFiles("*.jpg", SearchOption.TopDirectoryOnly);
List<MapProperty> textures = new List<MapProperty>();
//获取当前路径下的所有Texture并指定AllTextures的属性
foreach (var file in fileInfos)
{
//Texture texture = AssetDatabase.LoadAssetAtPath<Texture>(file.FullName);
//删除当前文件路径的前部(Assets之前的路径),从而获取相对路径
string path = file.FullName.Remove(0, file.FullName.IndexOf("Assets"));
//获取当前路径下指定的Texture
Texture texture = (Texture)AssetDatabase.LoadAssetAtPath(path, typeof(Texture));
//获取针对Texture生成的Material的名称
string textureSaveName = dir.Name + "_" + file.Name.Replace(".jpg", "");
//初始化TextureProperty属性
MapProperty textureProperty = new MapProperty();
textureProperty.Map = texture;
textureProperty.MapName = textureSaveName;
textures.Add(textureProperty);
}
if (textures != null && textures.Count != 0)
AllMapTextures.Add(textures);
}
}
/// <summary>
/// 删除子物体
/// </summary>
/// <param name="container">父物体</param>
private static void DestroyChildren(Transform container)
{
Transform[] trs = container.GetComponentsInChildren<Transform>();
for (int i = trs.Length - 1; i >= 0; i--)
{
if (trs[i] != container)
{
DestroyImmediate(trs[i].gameObject);
}
}
}
/// <summary>
/// 创建材质(Standard材质)
/// </summary>
/// <param name="matName">材质名称</param>
/// <param name="texture">材质贴图</param>
/// <param name="savePath">材质保存位置</param>
/// <returns></returns>
private static Material CreateMaterail(string matName, Texture texture, string savePath)
{
Material material = new Material(Shader.Find("Standard"));
material.mainTexture = texture;
material.SetFloat("_Glossiness", 0f);
//创建材质
AssetDatabase.CreateAsset(material, savePath);
//更新Asset目录(没必要每个新生成的材质都刷新Asset目录)
//AssetDatabase.Refresh();
return material;
}
}
/// <summary>
/// 地图瓦片属性
/// </summary>
public class MapProperty
{
/// <summary>
/// 贴图的保存名称
/// </summary>
public string MapName;
/// <summary>
/// 贴图
/// </summary>
public Texture Map;
}<file_sep>/Assets/Editor/GenerateGoogleMapWindow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class GenerateGoogleMapWindow : EditorWindow
{
string googleMapPosition;
string GoogleMapPosition
{
set
{
if (googleMapPosition != value)
{
googleMapPosition = value;
GenerateGoogleMapController.GetAllTextures(value);
//解决每次路径选择完毕后在点击其他输入框时才显示出选择路径的问题
GoogleMapPosition = GoogleMapPosition;
ClickButtonState = false;
}
}
get
{
return googleMapPosition;
}
}
string GenerateMaterialPosition = "";
float lengthPerPixel;
float LengthPerPixel
{
set
{
if (lengthPerPixel != value)
{
lengthPerPixel = value;
LengthPerPixel = LengthPerPixel;
ClickButtonState = false;
GenerateGoogleMapController.LengthPerPixel = value;
}
}
get
{
return lengthPerPixel;
}
}
string LengthPerPixelString = "";
string MapObjectName = "GeneratedMaps";
string ClickGenerateButtonTipInfo = "";
bool ClickButtonState = false;
void OnInspectorUpdate() //更新
{
Repaint(); //重新绘制
}
GenerateGoogleMapWindow()
{
this.titleContent = new GUIContent("Google瓦片地图生成器");
}
[MenuItem("Tools/Google瓦片地图生成器")]
private static void GenerateGoogleMap()
{
EditorWindow.GetWindow(typeof(GenerateGoogleMapWindow));
}
private void OnGUI()
{
GUILayout.BeginVertical();
GUILayout.Space(10);
GUIStyle titleStyle = new GUIStyle();
titleStyle.fontSize = 20;
titleStyle.alignment = TextAnchor.MiddleCenter;
GUILayout.Label("Google瓦片地图生成器", titleStyle);
GUILayout.Space(10);
#region 选择瓦片地图地址
GUILayout.BeginHorizontal();
GUILayout.Label("瓦片地图地址:", GUILayout.Width(75));
GoogleMapPosition = EditorGUILayout.TextField("", GoogleMapPosition);
if (GUILayout.Button("...",GUILayout.Width(30)))
{
GoogleMapPosition = EditorUtility.OpenFolderPanel("选择瓦片地图地址", UnityEngine.Application.dataPath, "");
}
GUILayout.EndHorizontal();
GUIStyle TipInfoStyle = new GUIStyle();
TipInfoStyle.alignment = TextAnchor.MiddleCenter;
if (GenerateGoogleMapController.AllMapTextures != null && GenerateGoogleMapController.AllMapTextures.Count != 0 && GenerateGoogleMapController.AllMapTextures[0] != null && GenerateGoogleMapController.AllMapTextures[0].Count != 0)
{
TipInfoStyle.normal.textColor = Color.blue;
GUILayout.Space(5);
GUILayout.Label("共检索到" + GenerateGoogleMapController.AllMapTextures.Count + "x" + GenerateGoogleMapController.AllMapTextures[0].Count + " = " + GenerateGoogleMapController.AllMapTextures.Count * GenerateGoogleMapController.AllMapTextures[0].Count + "张瓦片" + " 瓦片分辨率为:" + GenerateGoogleMapController.AllMapTextures[0][0].Map.width + "x" + GenerateGoogleMapController.AllMapTextures[0][0].Map.height, TipInfoStyle);
GenerateGoogleMapController.MapSize = new Vector2(GenerateGoogleMapController.AllMapTextures[0][0].Map.width, GenerateGoogleMapController.AllMapTextures[0][0].Map.height);
GUILayout.Space(5);
TipInfoStyle.normal.textColor = Color.red;
}
else
{
TipInfoStyle.normal.textColor = Color.red;
GUILayout.Space(5);
GUILayout.Label("未检索到瓦片!",TipInfoStyle);
GUILayout.Space(5);
}
#endregion
GUILayout.BeginHorizontal();
GUIStyle TextFieldStyle = new GUIStyle(EditorStyles.label);
bool inputError = false;
GUILayout.Label("每像素代表的实际距离:", GUILayout.Width(120));
LengthPerPixelString = EditorGUILayout.TextField("", LengthPerPixelString, GUILayout.Width(50));
try
{
LengthPerPixel = float.Parse(LengthPerPixelString);
inputError = false;
}
catch (System.Exception)
{
inputError = true;
}
GUILayout.Label("米", GUILayout.Width(15));
GUILayout.EndHorizontal();
GUILayout.Space(5);
if (inputError == true)
{
GUILayout.Label("请重新输入数字!", TipInfoStyle,GUILayout.Width(185));
GUILayout.Space(5);
}
#region 选择材质保存位置
GUILayout.BeginHorizontal();
GUILayout.Label("材质保存地址:",GUILayout.Width(75));
GenerateMaterialPosition = EditorGUILayout.TextField("", GenerateMaterialPosition);
if (GUILayout.Button("...",GUILayout.Width(30)))
{
GenerateMaterialPosition = EditorUtility.OpenFolderPanel("选择材质保存地址", UnityEngine.Application.dataPath, "");
GenerateGoogleMapController.MaterialSavePath = GenerateMaterialPosition;
}
GUILayout.EndHorizontal();
#endregion
if (GUILayout.Button("生成地图瓦片"))
{
ClickGenerateButtonTipInfo = "";
if (string.IsNullOrEmpty(GoogleMapPosition))
{
ClickGenerateButtonTipInfo += "请选择瓦片地图地址\n";
}
if (LengthPerPixel == 0)
{
ClickGenerateButtonTipInfo += "请输入瓦片每像素代表的距离\n";
}
if (string.IsNullOrEmpty(GenerateMaterialPosition))
{
ClickGenerateButtonTipInfo += "请选择材质保存地址\n";
}
ClickButtonState = true;
GenerateGoogleMapController.StartGenerateGoogleMap();
}
if (!string.IsNullOrEmpty(ClickGenerateButtonTipInfo))
{
GUILayout.Label(ClickGenerateButtonTipInfo, TipInfoStyle);
}
if (string.IsNullOrEmpty(ClickGenerateButtonTipInfo) && ClickButtonState)
{
if (GenerateGoogleMapController.AllMapTextures == null || GenerateGoogleMapController.AllMapTextures.Count == 0 || GenerateGoogleMapController.AllMapTextures[0].Count == 0)
{
return;
}
GUILayout.Space(5);
Rect ProcessRect = GUILayoutUtility.GetRect(50, 20);
float process = GenerateGoogleMapController.CurrentGenerateCountNum / (GenerateGoogleMapController.AllMapTextures.Count * GenerateGoogleMapController.AllMapTextures[0].Count);
if (process != 1f)
{
EditorGUI.ProgressBar(ProcessRect, process, "生成进度");
}
else
{
EditorGUI.ProgressBar(ProcessRect, process, "完成");
}
}
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
}
}
<file_sep>/Assets/Editor/RendererEditor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.Rendering;
public class RendererEditor : Editor
{
[MenuItem("Tools/RendererSettingWithNoLightAndShadow")]
public static void RenderSettingWithNoLightAndShadow()
{
Transform transform = Selection.activeTransform;
foreach (var render in transform.GetComponentsInChildren<Renderer>())
{
render.shadowCastingMode = ShadowCastingMode.Off;
render.receiveShadows = false;
}
}
}
<file_sep>/README.md
# GenerateMapBackgroundWithUnity
See https://blog.csdn.net/beihuanlihe130/article/details/102631861
| f7fba03147129ec7ead8101ca6d8ad186713c692 | [
"Markdown",
"C#"
] | 4 | C# | hafewa/GenerateMapBackgroundWithUnity | 1f8cc617bb3b9fdc8375f8fb0c5c8ea234f4ab33 | 078d1e322b817a02f3e810185dea4118d2997126 |
refs/heads/master | <file_sep>import React from "react";
import { Link } from "gatsby";
import "semantic-ui-css/semantic.min.css";
import Layout from "../components/Layout";
import Navigation from "../components/Navbar";
export default () => (
<Layout>
<Navigation />
<div style={{ color: `purple` }}>
<h1>Hello Gatsby!</h1>
<p>What a world.</p>
<Link to="/contact/">Contact</Link>
<img src="https://source.unsplash.com/random/400x200" alt="" />
</div>
</Layout>
);
| af3983e54baa3962a1694e5f7d91120f97a87c78 | [
"JavaScript"
] | 1 | JavaScript | Lea-jacta-est/first_gatsby | 2680fd647b6aadd536caaa9976ed8f731efa3c98 | 79345c79b860604e17ee37bd8e9b552f2ecab297 |
refs/heads/master | <repo_name>MonkeyKingNo1/springBootConcurrency<file_sep>/src/test/java/com/mk/ConcurrentTest.java
package com.mk;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import com.mk.annotations.ThreadUnSafe;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
/**
* 使用信号量进行并发测试
* @author MonkeyKing
*
*/
@Slf4j
@Log4j2
@ThreadUnSafe
public class ConcurrentTest {
private static int clientTotal = 5000;//终端数量
private static int threadTotal = 200;//线程数量
private static int count = 0 ;//执行计数
//给出一个自增的方法
private static void add(){
count ++;
}
//使用线程池调用
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();//带有缓存的线程池
//创建信号量
Semaphore semaphore = new Semaphore(threadTotal);
//闭锁
CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for(int i = 0 ; i < clientTotal;i++){
executorService.execute(() -> {
try{
semaphore.acquire();
add();
semaphore.release();
}catch(Exception e){
e.printStackTrace();
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();//关闭线程池
System.out.println("执行的次数:"+count);
}
}
| 5df11d2ddcc923752a1f5ec0d6c3ed7ebf6c1876 | [
"Java"
] | 1 | Java | MonkeyKingNo1/springBootConcurrency | a9a749de3aeb1871a6e7dd84664fa9f540990ee8 | 31d80a666b3fabd08b273344331ca76d3c3bc08e |
refs/heads/master | <file_sep>-- MySQL Script generated by MySQL Workbench
-- 10/30/16 16:59:16
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 ;
USE `mydb` ;
-- -----------------------------------------------------
-- Table `mydb`.`Clients`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Clients` (
`email` INT NOT NULL,
`passwd` MEDIUMTEXT NOT NULL,
PRIMARY KEY (`email`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`Address`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Address` (
`idAddress` INT NOT NULL AUTO_INCREMENT,
`number` INT NOT NULL COMMENT 'House Number (ie: 8309)',
`street` VARCHAR(50) NOT NULL COMMENT 'Street Number or Name (ie: NE 82nd Ave)',
`city` VARCHAR(50) NOT NULL,
`State` VARCHAR(2) NOT NULL COMMENT 'State Abbreviation (ie: WA)',
`zipcode` INT(10) NOT NULL,
PRIMARY KEY (`idAddress`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`Establishments`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Establishments` (
`name` VARCHAR(60) NOT NULL,
`number_taps` INT(3) NOT NULL,
`has_food` TINYINT(1) NOT NULL,
`family_friendly` TINYINT(1) NOT NULL,
`full_bar` TINYINT(1) NOT NULL,
`description` MEDIUMTEXT NOT NULL,
`image` VARCHAR(80) NOT NULL,
`idAddress` INT NOT NULL,
`Address_idAddress` INT NOT NULL,
PRIMARY KEY (`name`),
INDEX `fk_Establishments_Address_idx` (`Address_idAddress` ASC),
CONSTRAINT `fk_Establishments_Address`
FOREIGN KEY (`Address_idAddress`)
REFERENCES `mydb`.`Address` (`idAddress`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep>/*
* CrawlActivity - PubCrawler Applicaiton
* TCSS450 - Fall 2016
*
*/
package edu.uw.tacoma.jwolf059.pubcrawler.details;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import edu.uw.tacoma.jwolf059.pubcrawler.R;
/**
* A simple {@link Fragment} subclass.
*/
public class PubDetails extends AppCompatActivity {
/** URL Part 1 requires placeid to be added to the end of the string */
public static final String URL_1 = "https://maps.googleapis.com/maps/api/place/details/json?placeid=";
/** URL Part 2 is added after the placeid */
public static final String URL_2 = "&key=<KEY>";
//Thang these variables are just for testing do what you want with them.
public static TextView mTitle;
public static TextView mID;
public static TextView mRating;
public static TextView mIsOpen;
public static TextView mHours;
public static TextView mWebsite;
public static TextView mImage;
public static TextView mAddress;
public static TextView mPhone;
public static TextView mHasFood;
/**
* Constructor for the PubDetail Activity.
*/
public PubDetails() {
// Required empty public constructor
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pub_details);
// This is an example of how the Name, ID, Rating, and IsOpen data can be accessed.
// It is being passed through the Activtiy Extras. Format and make changes as you see fit.
mTitle = (TextView) findViewById(R.id.test);
mTitle.setText(getIntent().getStringExtra("Name"));
mID = (TextView) findViewById(R.id.test2);
mID.setText(getIntent().getStringExtra("ID"));
mRating = (TextView) findViewById(R.id.test3);
mRating.setText(getIntent().getStringExtra("RATING"));
mIsOpen = (TextView) findViewById(R.id.test4);
if (getIntent().getBooleanExtra("ISOPEN", true)) {
mIsOpen.setText("Open");
} else {
mIsOpen.setText("Closed");
}
mHours = (TextView) findViewById(R.id.test5);
mWebsite = (TextView) findViewById(R.id.test6);
mImage = (TextView) findViewById(R.id.test7);
mAddress = (TextView) findViewById(R.id.test8);
mPhone = (TextView) findViewById(R.id.test9);
mHasFood = (TextView) findViewById(R.id.test10);
String url = buildDetailsURL();
DetailTask detail = new DetailTask();
detail.execute(new String[]{url});
}
/**
* Builds the URL using the Place ID. The URL will allow access to details for the given place.
* @return A URL that includes the Place ID, Webaddress, and Key.
*/
public String buildDetailsURL() {
StringBuilder sb = new StringBuilder();
sb.append(URL_1);
sb.append(getIntent().getStringExtra("ID"));
sb.append(URL_2);
return sb.toString();
}
/**
* Creates the DetiaTask that executes the Details infomation gathering.
*/
private class DetailTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... urls) {
String response = "";
HttpURLConnection urlConnection = null;
for (String url : urls) {
try {
java.net.URL urlObject = new URL(url);
urlConnection = (HttpURLConnection) urlObject.openConnection();
InputStream content = urlConnection.getInputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
response = "Unable to connect, Reason: "
+ e.getMessage();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
return response;
}
/**
* It checks to see if there was a problem with the URL(Network) which is when an
* exception is caught. It tries to call the parse Method and checks to see if it was successful.
* If not, it displays the exception.
*
* @param result
*/
@Override
protected void onPostExecute(String result) {
Log.i("json result in Detail ", result);
try {
JSONObject jsonObject = new JSONObject(result);
detailsJSONParse(jsonObject);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Detailed data inaccessible at this time" +
e.getMessage(), Toast.LENGTH_LONG).show();
Log.e("onPostExecuteDeatils: ", e.getMessage());
}
}
/**
* Parses the JSON object to extract detailed information about the Place. Extracts the
* Website, photoreference, address, phone number, hasFood, and the Hours of operation
* (when avaiable).
* @param theObject the JSON object for this specific Place.
*/
public void detailsJSONParse(JSONObject theObject) {
String schedule = "";
try {
JSONObject bar = theObject.getJSONObject("result");
String address = bar.getString("formatted_address");
String phone = bar.getString("formatted_phone_number");
String website = bar.getString("website");
JSONArray photos = bar.getJSONArray("photos");
JSONObject pic = photos.getJSONObject(0);
String photoReference = pic.getString("photo_reference");
// Determines if the Pub has food available.
JSONArray types = bar.getJSONArray("types");
String hasFood = "No";
for (int i = 0; i < types.length(); i++) {
if (((String) types.get(i)).equals("food") || ((String) types.get(i)).equals("food")) {
hasFood = "Yes";
break;
}
}
// Displays the information.
mWebsite.setText(website);
mImage.setText(photoReference);
mAddress.setText(address);
mPhone.setText(phone);
mHasFood.setText(hasFood);
// Sometimes this object does not exist so the the exception will be caught.
JSONObject hours = bar.getJSONObject("opening_hours");
schedule = hours.getString("weekday_text");
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Detailed data inaccessible at this time" +
e.getMessage(), Toast.LENGTH_LONG).show();
Log.i("detailsJSONParse: ", e.getMessage());
schedule = "Hours not avaiable";
}
mHours.setText(schedule);
}
}
}
<file_sep>/*
* CrawlActivity - PubCrawler Applicaiton
* TCSS450 - Fall 2016
*
*/
package edu.uw.tacoma.jwolf059.pubcrawler.model;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import static com.facebook.FacebookSdk.getApplicationContext;
/**
* The Crawl will store all stops (pubs) used in the Crawl as well as compute the distance between stops.
* @version 21 Nov 2016
* @author <NAME>
*
*/
public class Crawl implements Serializable {
private String URL_1 = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=";
private String URL_2 = "&mode=walking&key=<KEY>";
private String mName;
private ArrayList<Pub> mCrawlPath;
private HashMap<Integer, Double> mDistance;
private double mLegDistance;
private DistanceTask mTask;
public Crawl(String theName) {
mName = theName;
mCrawlPath = new ArrayList<>();
mDistance = new HashMap<>();
}
public void addPub(Pub thePub) {
if(thePub != null) {
mCrawlPath.add(thePub);
}
}
public void caculateDistance() {
for (int i = 1; i < mCrawlPath.size(); i++) {
String url = distanceURLBuilder(mCrawlPath.get(i - 1).getmAddress(), mCrawlPath.get(i).getmAddress());
DistanceTask mTask = new DistanceTask();
mTask.execute(new String[]{url});
mDistance.put(i, mLegDistance);
}
}
public String getmName() {
return mName;
}
public ArrayList<Pub> getmCrawlPath() {
return mCrawlPath;
}
public HashMap<Integer, Double> getmDistance() {
return mDistance;
}
public void randomCrawlCreation(ArrayList<Pub> thePubList, Pub theStart, Integer theStops, Boolean theHasFood) {
Random rand = new Random();
addPub(theStart);
thePubList.remove(theStart);
while (mCrawlPath.size() <= theStops) {
int index = rand.nextInt(thePubList.size());
if (mCrawlPath.size() == theStops / 2) {
Pub p = thePubList.get(index);
if (p.getmHasFood().endsWith("Yes")) {
addPub(p);
thePubList.remove(index);
} else {
continue;
}
} else {
addPub(thePubList.get(index));
thePubList.remove(index);
}
}
caculateDistance();
for(int i = 1; i < mDistance.size(); i++) {
String name = mCrawlPath.get(i).getmName();
Double distance = mDistance.get(i);
Log.i(name, ": " + distance);
}
}
/**
* Creates the Distance URL that requested the distance between Orgin and Destination from
* the Goolge map API.
* @param theOrigin String Address for the Start location.
* @param theDestination String Address for the Destination.
* @return a URL request for distance between the Origin and Destination.
*/
public String distanceURLBuilder(String theOrigin, String theDestination) {
StringBuilder sb = new StringBuilder();
sb.append(URL_1);
sb.append("'");
sb.append(cleanSpace(theOrigin));
sb.append("'");
sb.append("&destinations=");
sb.append("'");
sb.append(cleanSpace(theDestination));
sb.append("'");
sb.append(URL_2);
return sb.toString();
}
/**
* Creates the DistanceTask that executes the distance request URL.
*/
private class DistanceTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... urls) {
String response = "";
HttpURLConnection urlConnection = null;
for (String url : urls) {
try {
java.net.URL urlObject = new URL(url);
urlConnection = (HttpURLConnection) urlObject.openConnection();
InputStream content = urlConnection.getInputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
response = "Unable to Login, Reason: "
+ e.getMessage();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
return response;
}
/**
* It checks to see if there was a problem with the URL(Network) which is when an
* exception is caught. It tries to call the parse Method and checks to see if it was successful.
* If not, it displays the exception.
*
* @param result
*/
@Override
protected void onPostExecute(String result) {
Log.i("jsonPostExecute result ", result);
try {
JSONObject jsonObject = new JSONObject(result);
Log.e("jsonObject: ", jsonObject.toString());
JSONArray rows = jsonObject.getJSONArray("rows");
Log.e("rows: ", rows.toString());
JSONObject first = rows.getJSONObject(0);
Log.e("first: ", first.toString());
Log.e("Elements: ", "before");
JSONArray elements = first.getJSONArray("elements");
JSONObject second = elements.getJSONObject(0);
Log.e("Elements: ", second.toString());
JSONObject distanceObject = second.getJSONObject("distance");
int distance = distanceObject.getInt("value");
mLegDistance = distance;
Log.i("Distance :", String.valueOf(distance));
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Unable to caculate the distance" +
e.getMessage(), Toast.LENGTH_LONG).show();
Log.e("Wrong Data", e.getMessage());
}
}
}
public String cleanSpace(String theText) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < theText.length(); i++) {
if (theText.charAt(i) == 32) {
stringBuilder.append("%20");
} else if (theText.charAt(i) == 35) {
stringBuilder.append("%23");
} else {
stringBuilder.append(theText.charAt(i));
}
}
return stringBuilder.toString();
}
}
<file_sep>package edu.uw.tacoma.jwolf059.pubcrawler.listView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import edu.uw.tacoma.jwolf059.pubcrawler.R;
import edu.uw.tacoma.jwolf059.pubcrawler.model.Pub;
import java.util.List;
import edu.uw.tacoma.jwolf059.pubcrawler.listView.PubCrawlFragment.OnListFragmentInteractionListener;
/**
* {@link RecyclerView.Adapter} that can display a {@link Pub} and makes a call to the
* specified {@link OnListFragmentInteractionListener}.
* TODO: Replace the implementation with code for your data type.
*/
public class MyPubRecyclerViewAdapter2 extends RecyclerView.Adapter<MyPubRecyclerViewAdapter2.ViewHolder> {
private final List<Pub> mPubList;
private final OnListFragmentInteractionListener mListener;
public MyPubRecyclerViewAdapter2(List<Pub> items, OnListFragmentInteractionListener listener) {
mPubList = items;
mListener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i("Recycle", "Created");
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_publist, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Pub pub = mPubList.get(position);
holder.mPub = pub;
holder.mTitle.setText(pub.getmName());
holder.mHasFood.setText("Food Avaiable: " + pub.getmHasFood());
holder.mAddress.setText(pub.getmAddress());
holder.mRating.setText("Rating: " + String.valueOf(pub.getmRating()));
if (pub.getIsOpen()) {
holder.mIsOpen.setText("Open");
} else {
holder.mIsOpen.setText("Closed");
}
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onListFragmentInteraction(holder.mPub);
}
}
});
}
@Override
public int getItemCount() {
return mPubList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mTitle;
public final TextView mRating;
public final TextView mIsOpen;
public final TextView mAddress;
public final TextView mHasFood;
public Pub mPub;
public ViewHolder(View view) {
super(view);
mView = view;
mTitle = (TextView) view.findViewById(R.id.pub_title);
mRating = (TextView) view.findViewById(R.id.rating_list);
mIsOpen = (TextView) view.findViewById(R.id.is_open);
mAddress = (TextView) view.findViewById(R.id.address_list);
mHasFood = (TextView) view.findViewById(R.id.has_food);
}
@Override
public String toString() {
return super.toString() + " '" + mTitle.getText() + "'";
}
}
}
<file_sep>/*
* CrawlActivity - PubCrawler Applicaiton
* TCSS450 - Fall 2016
*
*/
package edu.uw.tacoma.jwolf059.pubcrawler.OptionScreens;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import edu.uw.tacoma.jwolf059.pubcrawler.R;
/**
* Framgemnt that displays the applicaitons two types of pub Crawl creation methods
* (Random & User Selected)
* @version 21 November 2016
* @author <NAME>
*/
public class CrawlTypeFragment extends Fragment {
/**
* Constructor for the CrawlTypeFragment.
*/
public CrawlTypeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_crawl_type, container, false);
}
}
<file_sep>/*
* CrawlActivity - PubCrawler Applicaiton
* TCSS450 - Fall 2016
*
*/
package edu.uw.tacoma.jwolf059.pubcrawler.map;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.facebook.login.LoginManager;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import edu.uw.tacoma.jwolf059.pubcrawler.details.PubDetailsFragment;
import edu.uw.tacoma.jwolf059.pubcrawler.R;
import edu.uw.tacoma.jwolf059.pubcrawler.login.LoginActivity;
import edu.uw.tacoma.jwolf059.pubcrawler.model.Pub;
import static android.preference.PreferenceManager.getDefaultSharedPreferences;
/**
* The Findpub Activity will launch the map view and pub list fragments.
* @version 2 Nov 2016
* @author <NAME>
*
*/
public class PubLocateActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleMap.OnInfoWindowClickListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
/* Constant to use with the permission. */
private static final int MY_PERMISSIONS_LOCATIONS = 0;
/* A Google Api Client to use Google services. */
private GoogleApiClient mGoogleApiClient;
private static final String TAG = "LocationsActivity";
/** The desired interval for location updates. Inexact. Updates may be more or less frequent. */
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
/**
* The fastest rate for active location updates. Exact. Updates will never be more frequent
* than this value.
*/
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
/** The location request with configured properties details. */
private LocationRequest mLocationRequest;
/** The current location. */
private Location mCurrentLocation;
public static final String URL_0 = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=47.253361,-122.439191&keyword=brewery&name=bar&type=pub&radius=10000&key=<KEY>";
/** URl used to gather pub locaitons. The locaiton must be added to the end of the string */
public static final String URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=";
/** Second half of the URL added after the location. */
public static final String URL_2 = "&keyword=brewery&name=bar&type=pub&radius=10000&key=<KEY>";
// the GoogleMap oject used for displaying locaiton and pubs.
private GoogleMap mMap;
/* The Support Map Fragment. */
private SupportMapFragment mMapFragment;
// ArrayList of Pub object created using returned JSON Object.
private ArrayList<Pub> mPubList;
// Map used to store the Marker Object and the Index of the referenced pub object.
private HashMap<Marker, Integer> mPubMarkerMap = new HashMap<>();
/**
* Creates the findpub Activity.
* @param savedInstanceState the bundle containig the savedInstance data.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pub_locator);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
// Check if we have permissions to access location.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION
, Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_LOCATIONS);
}
mLocationRequest = new LocationRequest();
// Sets the desired interval for active location updates. This interval is
// inexact. You may not receive updates at all if no location sources are available, or
// you may receive them slower than requested. You may also receive updates faster than
// requested if other applications are requesting location at a faster interval.
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Sets the fastest rate for active location updates. This interval is exact, and your
// application will never receive updates faster than this value.
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mMapFragment = new SupportMapFragment();
try {
mMapFragment.getMapAsync(this);
} catch (Exception e) {
Log.e("PubLocate" , e.getMessage());
}
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container_locator, mMapFragment)
.commit();
}
/**
* {@inheritDoc}
* @param googleMap
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(AppIndex.API).build();
}
mGoogleApiClient.connect();
}
/**
* Takes all pubs in the mPubList and creates markers on the map. When the marker is created
* it is added to the mPubMarkerMap where the marker becomes the key and the index value of the
* pub is added as the value.
*/
public void addMarkers() {
for (int i = 0; i < mPubList.size(); i++) {
Pub pub = mPubList.get(i);
//Creates a LatLng object with the pubs locaiton.
LatLng location = new LatLng(pub.getmLat(), pub.getmLng());
Marker mark = mMap.addMarker(new MarkerOptions().position(location).title(pub.getmName()));
//Add the new Marker and the Pubs index value to the HashMap.
mPubMarkerMap.put(mark, i);
}
}
/**
* Creates the Pub Seach URL to be sent to the Google Place server that will return a JSON object
* of all pubs within a 10 kilometer radius.
* @return String that contains the URL to include current locaiton.
*/
public String buildPubSearchURL() {
StringBuilder sb = new StringBuilder();
sb.append(URL);
sb.append(String.valueOf(mCurrentLocation.getLatitude()));
sb.append(",");
sb.append(String.valueOf(mCurrentLocation.getLongitude()));
sb.append(URL_2);
Log.i("The search URL - Thang", sb.toString());
return sb.toString();
}
/**
* {@inheritDoc}
* Also adds detail information to the Activity's Extras and starts the PubDetails Activity.
* @param marker
*/
@Override
public void onInfoWindowClick(Marker marker) {
Pub pub = mPubList.get(mPubMarkerMap.get(marker));
Bundle args = new Bundle();
args.putString("NAME", pub.getmName());
args.putBoolean("IS_OPEN", pub.getIsOpen());
args.putDouble("RATING", pub.getmRating());
args.putString("ID", pub.getmPlaceID());
PubDetailsFragment detailsFragment = new PubDetailsFragment();
detailsFragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_locator, detailsFragment, "DETAILS_FRAGMENT")
.addToBackStack(null)
.commit();
}
public List<Pub> getmPubList() {
return mPubList;
}
public void setmPubList(List thePubList) {
mPubList = (ArrayList<Pub>) thePubList;
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_LOCATIONS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// locations-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "Locations need to be working for this portion, please provide permission"
, Toast.LENGTH_SHORT)
.show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
/**
* Requests location updates from the FusedLocationApi.
*/
protected void startLocationUpdates() {
// The final argument to {@code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
/**
* Removes location updates from the FusedLocationApi.
*/
protected void stopLocationUpdates() {
// It is a good practice to remove location requests when the activity is in a paused or
// stopped state. Doing so helps battery performance and is especially
// recommended in applications that request frequent location updates.
// The final argument to {@code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onDestroy() {
super.onDestroy();
stopLocationUpdates();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}
protected void onStart() {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
super.onStart();
}
protected void onStop() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
// If the initial location was never previously requested, we use
// FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store
// its value in the Bundle and check for it in onCreate(). We
// do not request it again unless the user specifically requests location updates by pressing
// the Start Updates button.
//
// Because we cache the value of the initial location in the Bundle, it means that if the
// user launches the activity,
// moves to a new location, and then changes the device orientation, the original location
// is displayed as the activity is re-created.
if (mCurrentLocation == null) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mCurrentLocation != null)
Log.i(TAG, mCurrentLocation.toString());
startLocationUpdates();
}
}
LoginTask task = new LoginTask();
String url = buildPubSearchURL();
try {
String result = task.execute(url).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// Add a marker, and move the camera.
LatLng currentLocation = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 11f));
mMap.setOnInfoWindowClickListener(this);
}
/**
* Callback that fires when the location changes.
*/
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
Log.d(TAG, mCurrentLocation.toString());
mMapFragment.newInstance();
}
@Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
/**
* Return the current location.
* @return the current location.
*/
public Location getCurrentLocation() {
return mCurrentLocation;
}
//NEED this
private class LoginTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
HttpURLConnection urlConnection = null;
for (String url : urls) {
try {
java.net.URL urlObject = new URL(url);
urlConnection = (HttpURLConnection) urlObject.openConnection();
InputStream content = urlConnection.getInputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
response = "Unable to Login, Reason: "
+ e.getMessage();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
Log.i("Response", response);
return response;
}
/**
* It checks to see if there was a problem with the URL(Network) which is when an
* exception is caught. It tries to call the parse Method and checks to see if it was successful.
* If not, it displays the exception.
*
* @param result
*/
@Override
protected void onPostExecute(String result) {
Log.i("json result ", result);
mPubList = Pub.parsePubJSON(result);
addMarkers();
}
}
/**
* If the Menu Item is selected Log the user out.
*
* @param item the menu item selected
* @return boolean if action was ttaken.
*/
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
SharedPreferences sharedPreferences =
getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.edit().putBoolean(getString(R.string.LOGGEDIN), false)
.commit();
LoginManager.getInstance().logOut();
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
finish();
return true;
} else {
return false;
}
}
/**
* {@inheritDoc}
*
* @param menu the menu to be created
* @return boolean if menu was created
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
}<file_sep>package edu.uw.tacoma.jwolf059.pubcrawler;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.facebook.login.LoginManager;
import java.util.ArrayList;
import edu.uw.tacoma.jwolf059.pubcrawler.details.PubDetailsFragment;
import edu.uw.tacoma.jwolf059.pubcrawler.listView.PubCrawlFragment;
import edu.uw.tacoma.jwolf059.pubcrawler.login.LoginActivity;
import edu.uw.tacoma.jwolf059.pubcrawler.model.Crawl;
import edu.uw.tacoma.jwolf059.pubcrawler.model.Pub;
import static android.preference.PreferenceManager.getDefaultSharedPreferences;
public class CrawlDetailsActivity extends AppCompatActivity implements PubCrawlFragment.OnListFragmentInteractionListener{
/** Constant value for accessing the Publist in a Budle or extra*/
public static final String PUB_LIST = "pub_list";
//Crawl Object contains all pubs in Crawl.
private Crawl mCrawl;
//Array containing all pubs in Crawl.
private ArrayList<Pub> mPubList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("CrawlDetailsActivity", "Created");
setContentView(R.layout.activity_crawl_details);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
mCrawl = (Crawl) getIntent().getSerializableExtra(PUB_LIST);
mPubList = mCrawl.getmCrawlPath();
TextView crawlTitle = (TextView) findViewById(R.id.crawl_title);
String title = mCrawl.getmName();
Log.e("get name: ", title);
crawlTitle.setText(title);
PubCrawlFragment publistDetails = new PubCrawlFragment();
Bundle arg = new Bundle();
Log.i("Size", String.valueOf(mPubList.size()));
arg.putSerializable(PUB_LIST, mPubList);
publistDetails.setArguments(arg);
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction()
.replace(R.id.activity_crawl_details, publistDetails);
transaction.commit();
Button bt = (Button) findViewById(R.id.start_crawl);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), CrawlPageActivity.class);
i.putExtra(PUB_LIST, mCrawl);
startActivity(i);
}
});
}
@Override
public void onListFragmentInteraction(Pub thePub) {
Pub pub = thePub;
System.out.println(thePub.getmName());
Bundle args = new Bundle();
args.putString("NAME", pub.getmName());
args.putBoolean("IS_OPEN", pub.getIsOpen());
args.putDouble("RATING", pub.getmRating());
args.putString("ID", pub.getmPlaceID());
PubDetailsFragment detailsFragment = new PubDetailsFragment();
detailsFragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.replace(R.id.activity_crawl_details, detailsFragment, "DETAILS_FRAGMENT")
.addToBackStack(null)
.commit();
}
/**
* If the Menu Item is selected Log the user out.
* @param item the menu item selected
* @return boolean if action was ttaken.
*/
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
SharedPreferences sharedPreferences =
getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.edit().putBoolean(getString(R.string.LOGGEDIN), false)
.commit();
LoginManager.getInstance().logOut();
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
finish();
return true;
} else {
return false;
}
}
/**{@inheritDoc}
*
* @param menu the menu to be created
* @return boolean if menu was created
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
}
<file_sep><?PHP
ini_set('display_errors', '1');
error_reporting(E_ALL);
$command = $_GET['cmd'];
// Connect to the Database
$dsn = 'mysql:host=cssgate.insttech.washington.edu;dbname=jwolf059';
$username = 'jwolf059';
$password = '<PASSWORD>';
try {
$db = new PDO($dsn, $username, $password);
if ($command == "pub") {
$select_sql = 'SELECT * FROM Establishments e JOIN Address a ON e.address_idAddress = a.idAddress;'
$pubs_query = $db->query($select_sql);
$pubs = $pubs_query->fetchAll(PDO::FETCH_ASSOC);
if ($pubs) {
echo json_encode($pubs);
}
}
} catch (PDOException $e) {
$error_message = $e->getMessage();
echo 'There was an error connecting to the database.';
echo $error_message;
exit();
}
?>
<file_sep>package edu.uw.tacoma.jwolf059.pubcrawler;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import edu.uw.tacoma.jwolf059.pubcrawler.login.LoginActivity;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
/**
* Created by jwolf on 11/15/2016.
*/
@RunWith(AndroidJUnit4.class)
@LargeTest
public class LoginActivityTest {
/**
* A JUnit {@link Rule @Rule} to launch your activity under test.
* Rules are interceptors which are executed for each test method and will run before
* any of your setup code in the {@link @Before} method.
* <p>
* {@link ActivityTestRule} will create and launch of the activity for you and also expose
* the activity under test. To get a reference to the activity you can use
* the {@link ActivityTestRule#getActivity()} method.
*/
@Rule
public ActivityTestRule<LoginActivity> mActivityRule = new ActivityTestRule<>(
LoginActivity.class);
@Before
public void logout() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mActivityRule.getActivity());
sharedPreferences.edit().putBoolean("loggedin", false).commit();
}
@Test
public void testRegister() {
// Type text and then press the button.
onView(withId(R.id.userid_edit))
.perform(typeText("<EMAIL>"));
onView(withId(R.id.userid_edit)).perform(closeSoftKeyboard());
onView(withId(R.id.password))
.perform(typeText("<PASSWORD>"));
onView(withId(R.id.password)).perform(closeSoftKeyboard());
onView(withId(R.id.sign_in))
.perform(click());
onView(withText("Logged In"))
.inRoot(withDecorView(not(is(
mActivityRule.getActivity()
.getWindow()
.getDecorView()))))
.check(matches(isDisplayed()));
}
@Test
public void testLoginNotRegistered() {
// Type text and then press the button.
onView(withId(R.id.userid_edit))
.perform(typeText("<EMAIL>."));
onView(withId(R.id.userid_edit)).perform(closeSoftKeyboard());
onView(withId(R.id.password))
.perform(typeText("<PASSWORD>@#"));
onView(withId(R.id.password)).perform(closeSoftKeyboard());
onView(withId(R.id.sign_in))
.perform(click());
onView(withText("Incorrect Username or Password:"))
.inRoot(withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView())))).check(matches(isDisplayed()));
}
}
<file_sep>/*
* CrawlActivity - PubCrawler Applicaiton
* TCSS450 - Fall 2016
*
*/
package edu.uw.tacoma.jwolf059.pubcrawler.OptionScreens;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.facebook.login.LoginManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import edu.uw.tacoma.jwolf059.pubcrawler.R;
import edu.uw.tacoma.jwolf059.pubcrawler.data.CrawlDB;
import edu.uw.tacoma.jwolf059.pubcrawler.login.LoginActivity;
import edu.uw.tacoma.jwolf059.pubcrawler.map.PubCrawlMapActivity;
import edu.uw.tacoma.jwolf059.pubcrawler.model.Crawl;
import edu.uw.tacoma.jwolf059.pubcrawler.model.Pub;
import static android.preference.PreferenceManager.getDefaultSharedPreferences;
/**
* The Random Crawler Activity will take the users input and create a random Crawl.
* @version 21 Nov 2016
* @author <NAME>
*
*/
public class RandomCrawlActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
/**
* URl used to gather pub locaitons. The locaiton must be added to the end of the string
*/
public static final String URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=";
/**
* Second half of the URL added after the location.
*/
public static final String URL_2 = "&keyword=brewery&name=bar&type=pub&radius=10000&key=<KEY>";
// List of Pubs
private ArrayList<Pub> mPubList;
private Spinner mPubListSpinner;
private Spinner mStopNumber;
private Pub mStartPub;
private int mNumberOfStops;
private Crawl mCrawl;
private String mCrawlName;
private Boolean wantFood = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_crawl);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
PubSearchTask task = new PubSearchTask();
mPubList = new ArrayList<>();
Button button = (Button) findViewById(R.id.create_crawl);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText nameField = (EditText) findViewById(R.id.crawl_name);
mCrawlName = nameField.getText().toString();
mCrawl = new Crawl(mCrawlName);
mCrawl.randomCrawlCreation(mPubList,mStartPub, mNumberOfStops, wantFood);
Intent crawlMap = new Intent(getApplicationContext(), PubCrawlMapActivity.class);
crawlMap.putExtra("object", mCrawl);
startActivity(crawlMap);
}
});
CheckBox cb = (CheckBox) findViewById(R.id.checkBox2);
cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(wantFood) {
wantFood = false;
Log.e("Food", "False");
} else {
wantFood = true;
Log.e("Food", "true");
}
}
});
if (!searchCompleted()) {
task.execute(new String[]{buildPubSearchURL()});
} else {
createUI();
}
}
/**
* Create and fill the UI elements using data from Google Places.
*/
public void createUI() {
// Build the pub list spinner
mPubListSpinner = (Spinner) findViewById(R.id.pub_selector);
mPubListSpinner.setOnItemSelectedListener(this);
ArrayList<String> pubs = new ArrayList<>();
for (Pub p : mPubList) {
pubs.add(p.getmName());
}
ArrayAdapter<String> pubDataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, pubs);
pubDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mPubListSpinner.setAdapter(pubDataAdapter);
// Build the number of stops list spinner
mStopNumber = (Spinner) findViewById(R.id.number_pubs);
mStopNumber.setOnItemSelectedListener(this);
ArrayList<String> numbers = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
Integer num = new Integer(i);
numbers.add(num.toString());
}
ArrayAdapter<String> stopsDataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, numbers);
stopsDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mStopNumber.setAdapter(stopsDataAdapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getId() == (findViewById(R.id.pub_selector).getId())) {
mStartPub = mPubList.get(position);
//Toast.makeText(parent.getContext(), "Pub Selected: " + position, Toast.LENGTH_LONG).show();
} else if (parent.getId() == (findViewById(R.id.number_pubs).getId())) {
mNumberOfStops = position;
//Toast.makeText(parent.getContext(), "Stops Selected: " + item, Toast.LENGTH_LONG).show();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
public boolean searchCompleted() {
//Check to see if a search has already been done (Save data usage)
return false;
}
/**
* Creates the Pub Seach URL to be sent to the Google Place server that will return a JSON object
* of all pubs within a 10 kilometer radius.
*
* @return String that contains the URL to include current locaiton.
*/
public String buildPubSearchURL() {
// Ken, Need to be able to get the Longitute and Latitude from a member variable.
StringBuilder sb = new StringBuilder();
sb.append(URL);
//This will be the actaul device locaiton
sb.append("47.253361,-122.439191");
sb.append(URL_2);
return sb.toString();
}
/**
* Creates the PubSearchTask that executes the Pub Search.
*/
private class PubSearchTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... urls) {
String response = "";
HttpURLConnection urlConnection = null;
for (String url : urls) {
try {
java.net.URL urlObject = new URL(url);
urlConnection = (HttpURLConnection) urlObject.openConnection();
InputStream content = urlConnection.getInputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
response = "Unable to Login, Reason: "
+ e.getMessage();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
return response;
}
/**
* It checks to see if there was a problem with the URL(Network) which is when an
* exception is caught. It tries to call the parse Method and checks to see if it was successful.
* If not, it displays the exception.
*
* @param result
*/
@Override
protected void onPostExecute(String result) {
Log.i("json result ", result);
mPubList = Pub.parsePubJSON(result);
createUI();
}
}
/**
* If the Menu Item is selected Log the user out.
* @param item the menu item selected
* @return boolean if action was ttaken.
*/
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
SharedPreferences sharedPreferences =
getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.edit().putBoolean(getString(R.string.LOGGEDIN), false)
.commit();
LoginManager.getInstance().logOut();
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
finish();
return true;
} else {
return false;
}
}
/**{@inheritDoc}
*
* @param menu the menu to be created
* @return boolean if menu was created
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
}
<file_sep>package edu.uw.tacoma.jwolf059.pubcrawler.details;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import edu.uw.tacoma.jwolf059.pubcrawler.R;
/**
* A simple {@link Fragment} subclass.
*/
public class PubDetailsFragment extends Fragment {
/**
* URL Part 1 requires placeid to be added to the end of the string
*/
private static final String URL_1 = "https://maps.googleapis.com/maps/api/place/details/json?placeid=";
/**
* URL Part 2 is added after the placeid
*/
private static final String URL_2 = "&key=<KEY>";
/**
* The first part of the url to download image.
*/
private static final String URL_3 = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=";
private static TextView mHours;
private static TextView mWebsite;
private static ImageView mImage;
private static TextView mAddress;
private static TextView mPhone;
private static TextView mHasFood;
public CallbackManager callbackManager;
public ShareDialog shareDialog;
private String mWebsiteString;
public PubDetailsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_pub_details, container, false);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(this);
mHours = (TextView) view.findViewById(R.id.hours_text_view);
mWebsite = (TextView) view.findViewById(R.id.website_text_view);
mImage = (ImageView) view.findViewById(R.id.image_view);
mAddress = (TextView) view.findViewById(R.id.address_text_view);
mPhone = (TextView) view.findViewById(R.id.phone_text_view);
mHasFood = (TextView) view.findViewById(R.id.has_food_text_view);
// Set the pub's name
TextView nameView = (TextView) view.findViewById(R.id.name_text_view);
nameView.setText(getArguments().getString("NAME"));
// Set the pub's rating
RatingBar ratingBar = (RatingBar) view.findViewById(R.id.rating_bar);
ratingBar.setRating((float) getArguments().getDouble("RATING"));
// Set the pub's rating
TextView ratingView = (TextView) view.findViewById(R.id.rating_text_view);
ratingView.setText(String.valueOf(getArguments().getDouble("RATING")));
// Set opening status
TextView openStatusView = (TextView) view.findViewById(R.id.open_status_view);
if (getArguments().getBoolean("IS_OPEN")) {
openStatusView.setTextColor(Color.GREEN);
openStatusView.setText("Open");
} else {
openStatusView.setTextColor(Color.RED);
openStatusView.setText("Closed");
}
try {
String url = buildDetailsURL();
DetailTask detail = new DetailTask();
String result = detail.execute(url).get();
} catch (Exception e) {
Log.e("Details", e.getMessage());
}
Button bt = (Button) view.findViewById(R.id.share_btn);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("PubCrawler")
.setContentDescription("Come join me at " + getArguments().getString("NAME") + " for a pint of frothy awesomeness!")
.setImageUrl(Uri.parse("https://students.washington.edu/jwolf059/beer.png"))
.setContentUrl(Uri.parse(mWebsiteString)).build();
shareDialog.show(linkContent);
}
}
});
return view;
}
/**
*{@inheritDoc}
*/
@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
/**
* Builds the URL using the Place ID. The URL will allow access to details for the given place.
*
* @return A URL that includes the Place ID, Webaddress, and Key.
*/
public String buildDetailsURL() {
StringBuilder sb = new StringBuilder();
sb.append(URL_1);
sb.append(getArguments().getString("ID"));
sb.append(URL_2);
return sb.toString();
}
//******************************
/**
* Creates the DetiaTask that executes the Details infomation gathering.
*/
private class DetailTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... urls) {
String response = "";
HttpURLConnection urlConnection = null;
for (String url : urls) {
try {
java.net.URL urlObject = new URL(url);
urlConnection = (HttpURLConnection) urlObject.openConnection();
InputStream content = urlConnection.getInputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
response = "Unable to connect, Reason: "
+ e.getMessage();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
return response;
}
/**
* It checks to see if there was a problem with the URL(Network) which is when an
* exception is caught. It tries to call the parse Method and checks to see if it was successful.
* If not, it displays the exception.
*
* @param result
*/
@Override
protected void onPostExecute(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
detailsJSONParse(jsonObject);
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Detailed data inaccessible at this time" +
e.getMessage(), Toast.LENGTH_LONG).show();
Log.e("onPostExecuteDeatils: ", e.getMessage());
}
}
/**
* Parses the JSON object to extract detailed information about the Place. Extracts the
* Website, photoreference, address, phone number, hasFood, and the Hours of operation
* (when avaiable).
*
* @param theObject the JSON object for this specific Place.
*/
public void detailsJSONParse(JSONObject theObject) {
String schedule = "";
try {
JSONObject bar = theObject.getJSONObject("result");
String address = bar.getString("formatted_address");
String phone = bar.getString("formatted_phone_number");
mWebsiteString = bar.getString("website");
JSONArray photos = bar.getJSONArray("photos");
JSONObject pic = photos.getJSONObject(0);
String photoReference = pic.getString("photo_reference");
// Determines if the Pub has food available.
JSONArray types = bar.getJSONArray("types");
String hasFood = "No";
for (int i = 0; i < types.length(); i++) {
if (types.get(i).equals("food") || types.get(i).equals("food")) {
hasFood = "Yes";
break;
}
}
// Displays the information.
mWebsite.setText(mWebsiteString);
System.out.println(URL_3 + 418 + "&photoreference=" + photoReference + URL_2);
// Set the image.
new DownloadImageTask((ImageView) getActivity().findViewById(R.id.image_view))
.execute(URL_3 + 418 + "&photoreference=" + photoReference + URL_2);
// Set the address.
mAddress.setText(address);
mPhone.setText(phone);
mHasFood.setText("Food available: " + hasFood);
// Sometimes this object does not exist so the the exception will be caught.
JSONObject hours = bar.getJSONObject("opening_hours");
schedule = hours.getString("weekday_text");
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Detailed data inaccessible at this time" +
e.getMessage(), Toast.LENGTH_LONG).show();
Log.i("detailsJSONParse: ", e.getMessage());
schedule = "Hours not avaiable";
}
mHours.setText(schedule);
}
}
//****************************************
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
<file_sep>package edu.uw.tacoma.jwolf059.pubcrawler;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.facebook.login.LoginManager;
import java.util.ArrayList;
import edu.uw.tacoma.jwolf059.pubcrawler.login.LoginActivity;
import edu.uw.tacoma.jwolf059.pubcrawler.model.Crawl;
import edu.uw.tacoma.jwolf059.pubcrawler.model.Pub;
import static android.preference.PreferenceManager.getDefaultSharedPreferences;
public class CrawlPageActivity extends AppCompatActivity {
/** Constant value for accessing the Publist in a Bundle or extra*/
public static final String PUB_LIST = "pub_list";
/** Constant value for accessing the pubcount in a Bundle or extra*/
public static final String PUB_COUNT = "pub_count";
//Crawl Object contains all pubs in Crawl.
private Crawl mCrawl;
//Array containing all pubs in Crawl.
private ArrayList<Pub> mPubList;
//Current Pub Count
private int mPubCount;
private Pub mPub;
private TextView mTitle;
private TextView mIsOpen;
private TextView mAddress;
private TextView mRate;
private TextView mHasFood;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crawl_page);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
mTitle = (TextView) findViewById(R.id.title_for_pub);
mIsOpen = (TextView) findViewById(R.id.isopen_for_pub);;
mAddress = (TextView) findViewById(R.id.address_for_pub);;
mRate = (TextView) findViewById(R.id.rating_cur);
mHasFood = (TextView) findViewById(R.id.isfood_avaiable);
mPubCount = 0;
mCrawl = (Crawl) getIntent().getSerializableExtra(PUB_LIST);
mPubList = mCrawl.getmCrawlPath();
mPub = mPubList.get(0);
System.out.println("THis is it: " + mPub.getmName());
System.out.println(mTitle);
mTitle.setText(mPub.getmName());
if (mPub.getIsOpen()) {
mIsOpen.setText("Open");
} else {
mIsOpen.setText("Closed");
}
mAddress.setText(mPub.getmAddress());
mRate.setText(String.valueOf(mPub.getmRating()));
mHasFood.setText(mPub.getmHasFood());
Button last = (Button) findViewById(R.id.last);
last.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mPubCount != 0) {
mPubCount--;
mPub = mPubList.get(mPubCount);
mTitle.setText(mPub.getmName());
if (mPub.getIsOpen()) {
mIsOpen.setText("Open");
} else {
mIsOpen.setText("Closed");
}
mAddress.setText(mPub.getmAddress());
mRate.setText(String.valueOf(mPub.getmRating()));
mHasFood.setText(mPub.getmHasFood());
String url = urlBuilder(mPub);
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}
}
});
Button next = (Button) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPubCount++;
mPub = mPubList.get(mPubCount);
mTitle.setText(mPub.getmName());
if (mPub.getIsOpen()) {
mIsOpen.setText("Open");
} else {
mIsOpen.setText("Closed");
}
mAddress.setText(mPub.getmAddress());
mRate.setText(String.valueOf(mPub.getmRating()));
mHasFood.setText(mPub.getmHasFood());
String url = urlBuilder(mPub);
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}
});
}
public String urlBuilder(Pub thePub) {
StringBuilder sb = new StringBuilder();
Double lat = thePub.getmLat();
Double lng = thePub.getmLng();
sb.append("google.navigation:q=");
sb.append(lat);
sb.append(",");
sb.append(lng);
return sb.toString();
}
/**
* If the Menu Item is selected Log the user out.
* @param item the menu item selected
* @return boolean if action was ttaken.
*/
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
SharedPreferences sharedPreferences =
getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.edit().putBoolean(getString(R.string.LOGGEDIN), false)
.commit();
LoginManager.getInstance().logOut();
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
finish();
return true;
} else {
return false;
}
}
/**{@inheritDoc}
*
* @param menu the menu to be created
* @return boolean if menu was created
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
}
| d4aec1a33fe7bd1490a6a05f940cfafdd9e77fe1 | [
"Java",
"SQL",
"PHP"
] | 12 | SQL | jwolf059/PubCrawler | 9f42039e76c069fa9d887c70ca631ccbf1a54b97 | f100a1318090c54a044e74726a59e706627f9b15 |
refs/heads/master | <file_sep>/// <reference types="express-session" />
import express = require('express');
declare module 'passport' {
export interface AuthenticateOptions {
callbackURL: string,
prompt: string
}
}
declare namespace passport_openidconnect {
class AcpStrategy {
constructor(options: StrategyOptions, callback: strategyCallBackFunction);
authenticate(req: express.Request, options: StrategyOptions): any;
authorizationParams(options: StrategyOptions): any;
configure(identifier: Function, done: Function): any;
}
type strategyCallBackFunction = (req: express.Request,
iss: any,
sub: any,
profile?: OICProfile,
accessToken?: string,
refreshToken?: string,
params?: any,
callback?: (err: string, user: any, info: string) => void) => void;
interface OICProfile {
id: string,
displayName: string;
name: ProfileName,
_raw: string
_json: any;
}
interface ProfileName {
familyName: string,
givenName: string,
middleName: string
}
interface StrategyOptions {
authorizationURL: string,
tokenURL: string,
userInfoURL: string,
clientID: string,
clientSecret: string,
callbackURL: string,
scope: string,
passReqToCallback?: boolean,
prompt?: string
}
function config(fn: any): void;
function disco(fn: any): void;
function register(fn: any): void;
function registration(options: any, save: any): any;
}
export = passport_openidconnect;
<file_sep>Changelog:
Release v.0.7 to v2.0.0
Removed `pkginfo` dependency, removes `version` from being exposed
<file_sep># Passport-OpenID Connect
Forked from: [Passport](https://github.com/jaredhanson/passport) strategy for authenticating
with [OpenID Connect](http://openid.net/connect/). For purposes of adding and removing necessary pieces of logic pertaining to Accolade's use of this software.
Accolade OIC implementation will redirect to another url for user info. This version will redirect there.
After verifying changes/fixes, this package must be manully uploaded to Artifactory
* Bump Version in `package.json`
* Ensure Artifactory is locally configured
* `npm publish`
This module lets you authenticate using OpenID Connect in your Node.js
applications. By plugging into Passport, OpenID Connect authentication can be
easily and unobtrusively integrated into any application or framework that
supports [Connect](http://www.senchalabs.org/connect/)-style middleware,
including [Express](http://expressjs.com/).
## Credits
- [<NAME>](http://github.com/jaredhanson)
## License
[The MIT License](http://opensource.org/licenses/MIT)
Copyright (c) 2011-2013 <NAME> <[http://jaredhanson.net/](http://jaredhanson.net/)>
| 7c8e29a785d821db221e42ad8a57c6b7e338c4d9 | [
"Markdown",
"TypeScript"
] | 3 | TypeScript | konciergeMD/passport-openidconnect | 4f4ee48d9c9499082bd089f37754ca8478701eed | 52a2d62b577bc95c37f8ccc5aed5e11b022c3d47 |
refs/heads/master | <file_sep>#!/usr/bin/env python3
from flask import Flask
from flask import request
import json
import logging
import os
import paho.mqtt.publish as publish
app = Flask(__name__)
if __name__ != '__main__':
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
def str2bool(v):
return str(v).lower() in ('yes', 'true', 'y', 't', '1')
@app.route('/')
def http2mqtt():
mqtt_host = os.environ.get('MQTT_HOST', '127.0.0.1')
mqtt_port = os.environ.get('MQTT_PORT', 1883)
try:
base_topic = os.environ.get('BASE_TOPIC').strip('/')
retain = str2bool(os.environ.get('RETAIN', '1'))
dev = request.args.get('dev')
batt = float(request.args.get('batt'))
lat = float(request.args.get('lat'))
lon = float(request.args.get('lon'))
acc = float(request.args.get('acc'))
topic = '{}/{}/state'.format(base_topic, dev)
app.logger.info('{}, {}, {}, {}, {}'.format(dev, batt, lat, lon, acc))
payload = json.dumps(dict(battery_level=batt, latitude=lat, longitude=lon, gps_accuracy=acc))
publish.single(topic, payload, hostname=mqtt_host, port=int(mqtt_port), retain=retain)
except Exception as e:
print('Unable to publish message: {}'.format(e))
pass
return payload
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
<file_sep>flask
gunicorn
paho.mqtt
<file_sep># docker-http2mqtt - Insecure HTTP to MQTT bridge
You most likely don't want to use this, there is no security in place and it was whipped together haphazardly.
The main reason I wrote this is because I wanted to use Macrodroid to interact with bluetooth beacons and publish state to a local message broker for home automation stuff. I didn't want to use Tasker and the MQTT Publish plugin as they have both become extremely unreliable.
I highly recommend against exposing this to the public internet unless you have some other controls in place.
##### docker-compose:
```
version: "3.7"
volumes:
mqttdata:
services:
mosquitto:
image: eclipse-mosquitto
ports:
- 18833:1883
volumes:
- /opt/data/mqtt/mosquitto/config:/mosquitto/config
- mqttdata:/mosquitto/data
http2mqtt:
image: jceloria/http2mqtt
environment:
- MQTT_HOST=mosquitto
- MQTT_PORT=18833
- BASE_TOPIC=location
ports:
- 8000:8000
```
##### example:
```
$─► curl 'http://localhost:8000/?device=a1:b2:c3:d4:e5:f6&message=office'
{"message":"office","topic":"location/a1:b2:c3:d4:e5:f6/state"}
```

<file_sep>FROM python:3-alpine
WORKDIR /usr/src/app
COPY . ./
RUN pip install --no-cache-dir -r requirements.txt
CMD ["gunicorn", "-b 0.0.0.0:8000", "-w 4", "main:app"]
| 7af48e45f43dbf82b09d21208772d8a7ce3ca643 | [
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 4 | Python | jceloria/docker-http2mqtt | 0821ae5c731a7acacb4fd59a5a6f99d57f4e1268 | 84944fd9b4cffd6fa56ae2d99eec9829337d2f9c |
refs/heads/master | <file_sep>const uploadImage = require('./upload-image/upload-image.service.js');
const uploadImages = require('./upload-images/upload-images.service.js');
const segmentationImage = require('./segmentation-image/segmentation-image.service.js');
// eslint-disable-next-line no-unused-vars
module.exports = function (app) {
app.configure(uploadImage);
app.configure(uploadImages);
app.configure(segmentationImage);
};
<file_sep>// Initializes the `upload-images` service on path `/upload-images`
const { UploadImages } = require('./upload-images.class');
const createModel = require('../../models/upload-images.model');
const hooks = require('./upload-images.hooks');
// feathers-blob service
const blobService = require('feathers-blob');
const multer = require('multer');
const multipartMiddleware = multer();
// Here we initialize a FileSystem storage,
// but you can use feathers-blob with any other
// storage service like AWS or Google Drive.
const fs = require('fs-blob-store');
const blobStorage = fs('./uploads');
const resizeOptimizeImages = require('resize-optimize-images');
const storage = multer.diskStorage({
destination: (_req, _file, cb) => cb(null, 'uploads'), // where the files are being stored
filename: (_req, file, cb) => cb(null, `${Date.now()}-${file.originalname}`) // getting the file name
});
const upload = multer({
storage,
limits: {
fieldSize: 1e+8, // Max field value size in bytes, here it's 100MB
fileSize: 1e+7 // The max file size in bytes, here it's 10MB
// files: the number of files
// READ MORE https://www.npmjs.com/package/multer#limits
}
});
module.exports = function (app) {
const options = {
Model: createModel(app),
paginate: app.get('paginate'),
multi: [ 'create' ]
};
// // Initialize our service with any options it requires
// app.use('/upload-images',
// // multer parses the file named 'uri'.
// // Without extra params the data is
// // temporarely kept in memory
// multipartMiddleware.single('uri'),
// // another middleware, this time to
// // transfer the received file to feathers
// function(req,res,next){
// req.feathers.file = req.file;
// next();
// },
// blobService({ Model: blobStorage}));
app.use('/upload-images',
upload.array('files'), (req, _res, next) => {
const { method } = req;
if (method === 'POST' || method === 'PATCH') {
// I believe this middleware should only transfer
// files to feathers and call next();
// and the mapping of data to the model shape
// should be in a hook.
// this code is only for this demo.
req.feathers.files = req.files; // transfer the received files to feathers
// for transforming the request to the model shape
const body = [];
for (const file of req.files)
body.push({
orignalName: file.originalname,
newNameWithPath: file.path,
quality:req.body.quality
});
req.body = method === 'POST' ? body : body[0];
}
next();
}, new UploadImages(options, app));
// Get our initialized service so that we can register hooks
const service = app.service('upload-images');
service.hooks(hooks);
};
<file_sep>const { Service } = require('feathers-nedb');
exports.UploadImages = class UploadImages extends Service {
};
<file_sep>const tfjs = require('@tensorflow/tfjs');
import * as cocoSsd from '@tensorflow-models/coco-ssd';
module.exports = {
before: {
all: [],
find: [],
get: [],
create: [async context => {
const promise1 = new Promise(function (resolve, reject) {
const { createCanvas, Image } = require('canvas');
const img = new Image();
img.src = `${context.data[0].newNameWithPath}`;
const canvas = createCanvas(img.width, img.height);
const ctx = canvas.getContext('2d');
img.onload = () => {
ctx.drawImage(img, 0, 0);
const input = tfjs.browser.fromPixels(canvas);
(async () => {
const model = await cocoSsd.load().catch((err) => {
//console.log(err);
});
// Classify the image.
const predictions = await model.detect(input).catch((err) => {
//console.log(err);
});
//console.log(predictions);
// console.log(__dirname)
predictions.forEach(predicted => {
const x = predicted.bbox[0]
const y = predicted.bbox[1]
const width = predicted.bbox[2]
const height = predicted.bbox[3]
ctx.strokeStyle = "#c92121";
ctx.lineWidth = 3;
ctx.strokeRect(x, y, width, height);
ctx.font = "50px Arial";
ctx.strokeText(`${predicted.class}`, x, y);
})
const dataURL = canvas.toDataURL('image/jpeg')
resolve(dataURL);
})();
};
img.onload();
});
return promise1.then(function (value) {
// console.log(JSON.stringify(value));
context.data = value;
return context;
});
}],
update: [],
patch: [],
remove: []
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
<file_sep>// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/api/hooks.html
// eslint-disable-next-line no-unused-vars
module.exports = (options = {}) => {
return async context => {
//console.log(JSON.stringify(context.data.text))
if(context.data.text){
context.result ="ANANI SIKIM";
return context;
}
};
};
<file_sep>const { Service } = require('feathers-nedb');
exports.SegmentationImage = class SegmentationImage extends Service {
};
<file_sep>
const processImage = require('../../hooks/process-image');
const resizeOptimizeImages = require('resize-optimize-images');
module.exports = {
before: {
all: [],
find: [],
get: [],
create: [function(context) {
(async () => {
// Set the options.
const options = {
images: [`${context.data[0].newNameWithPath}`],
width: 600,
quality:parseInt(context.data[0].quality)
};
// Run the module.
await resizeOptimizeImages(options);
})();
}],
update: [],
patch: [],
remove: []
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
<file_sep>const { Service } = require('feathers-sequelize');
exports.UploadImage = class UploadImage extends Service {
};
| f7962f8c8e36a5847f9e5e4b43865fbb3955399d | [
"JavaScript"
] | 8 | JavaScript | fetok12/Image-Segmantation-With-Tensorflow | 51c89c78b8cd0338986a9c5dddfe982f60eb2fcb | 5e3d8cf4321511f150189fbd9778e6e2becd4806 |
refs/heads/master | <repo_name>lsahdjf/EagleRay-Imp<file_sep>/include/impacta_operators/impacta_stenops.h
/*
**********************************************************
IMPACT Version 2.3
Stencil operator "box" - contains series of operator
stencils to be passed from function to funciton
Version 2.7
1
AGRT
21/2/07
16/4/07 - since j operator components are actually all
the same(!) I have eliminated two of them,
25/1/2010 AGRT
I am including a stencil which introduces some numerical
diffusion. See IMPACTA_Switch Elements for details
**********************************************************
*/
#ifndef INC_IMPACTA_STENOPS_H
#define INC_IMPACTA_STENOPS_H
//system
//user
using namespace globalconsts;
// Center differenced operators
namespace differentials_x_c_y_c
{
char xdiff[10]="center";
char ydiff[10]="center";
class IMPACT_StenOps // stencil operators
{
private:
IMPACT_stencil * null_;
IMPACT_stencil * ddx_; //i.e. d/d|x| ^x (x hat)
IMPACT_stencil * ddy_; //ditto for y
IMPACT_stencil * ddxfw_; //i.e. d/d|x| ^x (x hat) forward differenced
IMPACT_stencil * ddyfw_; //ditto for y
IMPACT_stencil * ddxbw_; //i.e. d/d|x| ^x (x hat) backward differenced
IMPACT_stencil * ddybw_; //ditto for y
IMPACT_stencil ** div_; // divergence stencil
IMPACT_stencil *d2dx_;
IMPACT_stencil *d2dy_;
IMPACT_vint je_; // current stencil for E equation
public:
IMPACT_StenOps(IMPACT_Config *c);
~IMPACT_StenOps();
//Access methods for differential stencils
IMPACT_stencil *ddx(int *i);
IMPACT_stencil *ddy(int *j);
IMPACT_stencil *div(int *i,int *j);
IMPACT_stencil *ddxi(int *i,int *j, IMPACT_Dim *x1);
IMPACT_stencil *ddxi_uw(int *i,int *j, IMPACT_Dim *x1, bool uw);
IMPACT_stencil *d2dx2i(int *i, int *j, IMPACT_Dim *x1);
IMPACT_stencil Laplacian(int *i, int *j);
IMPACT_vint * je(IMPACT_Dim *x1);
IMPACT_stencil * null();
};
IMPACT_StenOps::IMPACT_StenOps(IMPACT_Config *c)
{
//This constructor creates a templateobject with
// variaous cartesian differential and integral operators.
ddx_=new IMPACT_stencil[c->Nx()+2];
ddy_=new IMPACT_stencil[c->Ny()+2];
ddxfw_=new IMPACT_stencil[c->Nx()+2];
ddyfw_=new IMPACT_stencil[c->Ny()+2];
ddxbw_=new IMPACT_stencil[c->Nx()+2];
ddybw_=new IMPACT_stencil[c->Ny()+2];
d2dx_=new IMPACT_stencil[c->Nx()+2];
d2dy_=new IMPACT_stencil[c->Ny()+2];
null_ = new IMPACT_stencil(0.0,0.0,0.0,0.0,0.0);
int iplus,iminus,jplus,jminus;
for (int i=1;i<c->Nx()+1;++i) // (1/(dx[i+1]+dx[i-1]) and its negative in i+1 and i-1
{
iplus=i+1;
iminus=i-1;
ddx_[i]=IMPACT_stencil(0.0,1.0/(c->dx(&iminus)+c->dx(&iplus)),-1.0/(c->dx(&iminus)+c->dx(&iplus)),0.0,0.0);
ddxfw_[i]=IMPACT_stencil(-1.0/(c->dx(&i)),1.0/(c->dx(&i)),0.0,0.0,0.0);
ddxbw_[i]=IMPACT_stencil(1.0/(c->dx(&i)),0.0,-1.0/(c->dx(&i)),0.0,0.0);
d2dx_[i]=IMPACT_stencil(-2.0/c->dx(&i)/c->dx(&i),1.0/c->dx(&i)/c->dx(&i),1.0/c->dx(&i)/c->dx(&i),0.0,0.0);
}
for (int j=1;j<c->Ny()+1;++j)
{
jplus=j+1;
jminus=j-1;
ddy_[j]=IMPACT_stencil(0.0,0.0,0.0,1.0/(c->dy(&jminus)+c->dy(&jplus)),-1.0/(c->dy(&jminus)+c->dy(&jplus)));
ddyfw_[j]=IMPACT_stencil(-1.0/(c->dy(&j)),0.0,0.0,1.0/(c->dy(&j)),0.0);
ddybw_[j]=IMPACT_stencil(1.0/(c->dy(&j)),0.0,0.0,0.0,-1.0/(c->dy(&j)));
d2dy_[j]=IMPACT_stencil(-2.0/c->dy(&j)/c->dy(&j),0.0,0.0,1.0/c->dy(&j)/c->dy(&j),1.0/c->dy(&j)/c->dy(&j));
}
div_=new IMPACT_stencil * [c->Nx()+2];
div_[0]=new IMPACT_stencil [c->Ny()+2];
div_[c->Nx()+1]=new IMPACT_stencil [c->Ny()+2];
for (int i=1;i<c->Nx()+1;++i)
{
div_[i]=new IMPACT_stencil [c->Ny()+2];
for (int j=1;j<c->Ny()+1;++j)
{
div_[i][j]=(ddx_[i]+ddy_[j]);
}
}
/*
This next stencil is for the current density (int f1 v^3 dv)
but actually it is j/epsilon0 as it is in the equation:
E_n+1+dtj_n+1/epsilon0-c^2 dt curlB_n+1 = E_n
*/
je_.resize(c);
double val;
for (int k=1;k<=c->Nv();++k)
{
val = -fourthirdspi*c->v3(&k)*c->dv(&k)*c_L*c_L
*equation_switches::jimp_in_E_equation/deltasquared;
// /epsilon0*e_charge*c->dt();
// v^3dv/epsilon0*-e *dt
je_.set(k,val);
}
}
IMPACT_StenOps::~IMPACT_StenOps()
{
delete[] ddx_;
delete[] ddy_;
delete[] ddxfw_;
delete[] ddyfw_;
delete[] ddxbw_;
delete[] ddybw_;
delete[] div_;
delete null_;
delete[] d2dx_;
delete[] d2dy_;
}
IMPACT_stencil * IMPACT_StenOps::ddx(int *i)
{
return &ddx_[*i];
}
IMPACT_stencil * IMPACT_StenOps::ddy(int *j)
{
return &ddy_[*j];
}
IMPACT_stencil * IMPACT_StenOps::div(int *i,int *j)
{
return &div_[*i][*j];
}
IMPACT_stencil * IMPACT_StenOps::d2dx2i(int *i, int *j, IMPACT_Dim *x1)
{
IMPACT_stencil * temp;
temp=null_;
switch (x1->get())
{
case 1:
temp = &d2dx_[*i];
break;
case 2:
temp = &d2dy_[*j];
break;
case 3:
temp = null_;
}
return temp;
}
IMPACT_stencil IMPACT_StenOps::Laplacian(int *i, int *j)
{
IMPACT_stencil temp;
temp=d2dx_[*i]+d2dy_[*j];
return temp;
}
IMPACT_stencil * IMPACT_StenOps::ddxi(int *i,int *j, IMPACT_Dim *x1)
{
IMPACT_stencil * temp;
temp=null_;
switch (x1->get())
{
case 1:
temp = &ddx_[*i];
break;
case 2:
temp = &ddy_[*j];
break;
case 3:
temp = null_;
}
return temp;
}
IMPACT_stencil * IMPACT_StenOps::ddxi_uw(int *i,int *j, IMPACT_Dim *x1, bool uw)
{
IMPACT_stencil * temp;
temp=null_;
switch (x1->get())
{
case 1:
if (uw) temp = &ddxfw_[*i];
else temp = &ddxbw_[*i];
// temp = &ddx_[*i];
break;
case 2:
if (uw) temp = &ddyfw_[*j];
else temp = &ddybw_[*j];
// temp = &ddy_[*j];
break;
case 3:
temp = null_;
}
return temp;
}
IMPACT_vint * IMPACT_StenOps::je(IMPACT_Dim *x1)
{
return &je_;
}
IMPACT_stencil * IMPACT_StenOps::null()
{
return null_;
}
// Lax stencil - averaging over adjacent cells
IMPACT_stencil LAX(1.0,0.0,0.0,0.0,0.0);
} // end of namespace
#endif /* INC_IMPACTA_STENOPS_H */
<file_sep>/include/impacta_raytrace/tracer.h
/*
Main program tracing a ray through a density map then mapping the intensity onto a grid.
Bilinear Interpolation used for interpolating density matrix as well as mapping intensity.
Timestep is declared in main()
ReadinGrids() retrieves x, y and n.
Traceonestep traces one step through x,y,n,b
<NAME>
02/01/2013
03/07 - Incoroporated into IMPACTA through impacta_filehandling.h and impacta_headers.h
08/2013 - Added X wave and calculation of dielectric constant
*/
void intensity_diffusion(IMPACT_Config *conf)
//int Nx, int Ny, double sx, double sy)
{
int iminus,iplus,jminus,jplus;
double sx, sy;
IMPACT_Matrix tempint;
tempint.ChangeSize(conf->Nx(),conf->Ny());
tempint.setall(0.0);
for (int t=1;t<IMPACT_Heating::diffsteps;++t)
{
for (int i=1;i<=conf->Nx();++i)
{
for (int j=1;j<=conf->Ny();++j)
{
sx=1e-1;sy=1e-1;
if (i==1)
{
iminus = 1;
iplus = 2;
}
else if (i==conf->Nx())
{
iplus = conf->Nx();
iminus = conf->Nx()-1;
}
else
{
iminus = i-1;
iplus = i+1;
}
if (j==1)
{
jminus = 1;
jplus = 2;
}
else if (j==conf->Ny())
{
jplus = conf->Ny();
jminus = conf->Ny()-1;
}
else
{
jminus = j-1;
jplus = j+1;
}
// sy *= (conf->dy(&jminus)*conf->dy(&jminus))/(conf->dx(&iminus)*conf->dx(&iminus)+conf->dy(&jminus)*conf->dy(&jminus));
// sx *= (conf->dx(&iminus)*conf->dx(&iminus))/(conf->dx(&iminus)*conf->dx(&iminus)+conf->dy(&jminus)*conf->dy(&jminus));
//sx *= 1.0/(1.0+pow(conf->dy(&jminus)/conf->dx(&iminus),4));
//sy *= 1.0/(1.0+pow(conf->dx(&iminus)/conf->dy(&jminus),4));
tempint.set(i,j,IMPACT_Heating::i_mat.get(i,j)
+sx*(IMPACT_Heating::i_mat.get(iplus,j)-2*IMPACT_Heating::i_mat.get(i,j)+IMPACT_Heating::i_mat.get(iminus,j))
+sy*(IMPACT_Heating::i_mat.get(i,jplus)-2*IMPACT_Heating::i_mat.get(i,j)+IMPACT_Heating::i_mat.get(i,jminus)));
}
}
for (int i=1;i<=conf->Nx();++i)
{
for (int j=1;j<=conf->Ny();++j)
{
IMPACT_Heating::i_mat.set(i,j,tempint.get(i,j));
}
}
}
}
void updatelocalintensity(IMPACT_Matrix &tempint,IMPACT_Matrix &localint)
{
int Nx, Ny;
localint.size(&Nx,&Ny);
for (int i=1;i<=Nx;++i)
{
for (int j=1;j<=Ny;++j)
{
localint.set(i,j,localint.get(i,j)+tempint.get(i,j));
}
}
}
void intensitycalc(IMPACT_Config *conf, IMPACT_Matrix &n_mat, IMPACT_Vector &ray_vec,
IMPACT_Matrix &localint, double mult)
{
int tempi;
double tempv;
bool check;
// int lowx=0, uppx=conf->Nx()+1, lowy=0, uppy=conf->Ny()+1;
int lowx=-1, uppx=conf->Nx()+1, lowy=-1, uppy=conf->Ny()+1;
double xpos = ray_vec.Get(1);
double ypos = ray_vec.Get(2);
// if (std::isnan(tempvG))
// {
// tempvG=1e12;
// }
// Find indices for x
check = 0;
// tempi = (uppx-lowx)/2;
// while (!check)
// {
// tempv = conf->xpos(tempi);
// if (xpos < tempv)
// {
// uppx=tempi;
// }
// else if (xpos > tempv)
// {
// lowx=tempi;
// }
// else if (xpos == tempv)
// {
// lowx=tempi;
// uppx=tempi+1;
// }
// check = ((uppx-lowx)==1);
// tempi = lowx+(uppx-lowx)/2;
// }
// tempxuppV = fabs(xpos-conf->xpos(lowx))/(conf->xpos(uppx)-conf->xpos(lowx));
// tempxlowV = 1-tempxuppV;
// // Find indices for y
// check = 0;
// tempi = (uppy-lowy)/2;
// while (!check)
// {
// tempv = conf->ypos(tempi);
// if (ypos < tempv)
// {
// uppy=tempi;
// }
// else if (ypos > tempv)
// {
// lowy=tempi;
// }
// else if (ypos == tempv)
// {
// lowy=tempi;
// uppy=tempi+1;
// }
// check = ((uppy-lowy)==1);
// tempi = lowy+(uppy-lowy)/2;
// }
// tempyuppV = fabs(ypos-conf->ypos(lowy))/(conf->ypos(uppy)-conf->ypos(lowy));
// tempylowV = 1-tempyuppV;
// mult /= ((conf->ypos(uppy)-conf->ypos(lowy))*(conf->xpos(uppx)-conf->xpos(lowx)));
// if (uppx == conf->Nx()+1) uppx=0;
// if (uppy == conf->Ny()+1) uppy=0;
// if ((lowx*lowy*uppx*uppy) == 0)
// {
// if (lowx==0 && (lowy*uppy) !=0 ) // Left
// {
// localint.set(uppx,lowy,localint.get(uppx,lowy)+mult*(tempxuppV*tempylowV));
// localint.set(uppx,uppy,localint.get(uppx,uppy)+mult*(tempxuppV*tempyuppV));
// }
// else if (lowy == 0 && (lowx * uppx)!=0 ) // Bottom
// {
// localint.set(lowx,uppy,localint.get(lowx,uppy)+mult*(tempxlowV*tempyuppV));
// localint.set(uppx,uppy,localint.get(uppx,uppy)+mult*(tempxuppV*tempyuppV));
// }
// else if (uppx == 0 && (lowy * uppy)!=0) // Right
// {
// localint.set(lowx,lowy,localint.get(lowx,lowy)+mult*(tempxlowV*tempylowV));
// localint.set(lowx,uppy,localint.get(lowx,uppy)+mult*(tempxlowV*tempyuppV));
// }
// else if (uppy == 0 && (lowx * uppx)!=0) // Top
// {
// localint.set(lowx,lowy,localint.get(lowx,lowy)+mult*(tempxlowV*tempylowV));
// localint.set(uppx,lowy,localint.get(uppx,lowy)+mult*(tempxuppV*tempylowV));
// }
// else if (lowx == 0 && lowy == 0) // Lower Left
// {
// localint.set(uppx,uppy,localint.get(uppx,uppy)+mult*(tempxuppV*tempyuppV));
// }
// else if (lowx == 0 && uppy == 0) // Upper Left
// {
// localint.set(uppx,lowy,localint.get(uppx,lowy)+mult*(tempxuppV*tempylowV));
// }
// else if (uppx == 0 && lowy == 0) // Lower Right
// {
// localint.set(lowx,uppy,localint.get(lowx,uppy)+mult*(tempxlowV*tempyuppV));
// }
// else if (uppx == 0 && uppy == 0) // Upper Right
// {
// localint.set(lowx,lowy,localint.get(lowx,lowy)+mult*(tempxlowV*tempylowV));
// }
// }
// else // Rest
// {
// localint.set(lowx,lowy,localint.get(lowx,lowy)+mult*(tempxlowV*tempylowV));
// localint.set(lowx,uppy,localint.get(lowx,uppy)+mult*(tempxlowV*tempyuppV));
// localint.set(uppx,lowy,localint.get(uppx,lowy)+mult*(tempxuppV*tempylowV));
// localint.set(uppx,uppy,localint.get(uppx,uppy)+mult*(tempxuppV*tempyuppV));
// }
tempi = (uppx-lowx)/2;
while (!check)
{
tempv = conf->xb(tempi);
if (xpos < tempv)
{
uppx=tempi;
}
else if (xpos > tempv)
{
lowx=tempi;
}
else if (xpos == tempv)
{
lowx=tempi;
uppx=tempi+1;
}
check = ((uppx-lowx)==1);
tempi = lowx+(uppx-lowx)/2;
}
// Find indices for y
check = 0;
tempi = (uppy-lowy)/2;
while (!check)
{
tempv = conf->yb(tempi);
if (ypos < tempv)
{
uppy=tempi;
}
else if (ypos > tempv)
{
lowy=tempi;
}
else if (ypos == tempv)
{
lowy=tempi;
uppy=tempi+1;
}
check = ((uppy-lowy)==1);
tempi = lowy+(uppy-lowy)/2;
}
// std::cout << "xpos=" << xpos << "ypos=" << ypos <<std::endl;
// std::cout << "lowx=" << lowx << ", uppx=" << uppx << std::endl;
if (xpos == conf->xb(lowx) && ypos != conf->yb(lowy))
{
if (lowx==0)
localint.set(uppx,uppy,localint.get(uppx,uppy)+0.5/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
else if (lowx==conf->Nx())
{
localint.set(lowx,uppy,localint.get(lowx,uppy)+0.5/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(lowx)-conf->xb(lowx-1)))*mult);
}
else
{
// std::cout << "hello2=" << std::endl;
localint.set(lowx,uppy,localint.get(lowx,uppy)+0.5/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(lowx)-conf->xb(lowx-1)))*mult);
localint.set(uppx,uppy,localint.get(uppx,uppy)+0.5/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
}
}
else if (xpos != conf->xb(lowx) && ypos == conf->yb(lowy))
{
if (lowy==0)
localint.set(uppx,uppy,localint.get(uppx,uppy)+0.5/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
else if (lowy==conf->Ny())
{
localint.set(uppx,lowy,localint.get(uppx,lowy)+0.5/((conf->yb(lowy)-conf->yb(lowy-1))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
}
else
{
// std::cout << "hello3=" << std::endl;
localint.set(uppx,lowy,localint.get(uppx,lowy)+0.5/((conf->yb(lowy)-conf->yb(lowy-1))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
localint.set(uppx,uppy,localint.get(uppx,uppy)+0.5/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
}
}
else if (xpos == conf->xb(lowx) && ypos == conf->yb(lowy))
{
if (lowx==0 && lowy==0)
{
localint.set(uppx,uppy,localint.get(uppx,uppy)+0.25/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
}
else if (lowx==conf->Nx() && lowy==conf->Ny())
{
localint.set(lowx,lowy,localint.get(lowx,lowy)+0.25/((conf->yb(lowy)-conf->yb(lowy-1))*(conf->xb(lowx)-conf->xb(lowx-1)))*mult);
}
else if (lowx==0 && lowy==conf->Ny())
{
localint.set(uppx,lowy,localint.get(uppx,lowy)+0.25/((conf->yb(lowy)-conf->yb(lowy-1))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
}
else if (lowx==conf->Nx() && lowy==0)
{
localint.set(lowx,uppy,localint.get(lowx,uppy)+0.25/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(lowx)-conf->xb(lowx-1)))*mult);
}
else if (lowx==0)
{
localint.set(uppx,lowy,localint.get(uppx,lowy)+0.25/((conf->yb(lowy)-conf->yb(lowy-1))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
localint.set(uppx,uppy,localint.get(uppx,uppy)+0.25/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
}
else if (lowy==0)
{
localint.set(lowx,uppy,localint.get(lowx,uppy)+0.25/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(lowx)-conf->xb(lowx-1)))*mult);
localint.set(uppx,uppy,localint.get(uppx,uppy)+0.25/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
}
else if (lowx==conf->Nx())
{
localint.set(lowx,lowy,localint.get(lowx,lowy)+0.25/((conf->yb(lowy)-conf->yb(lowy-1))*(conf->xb(lowx)-conf->xb(lowx-1)))*mult);
localint.set(lowx,uppy,localint.get(lowx,uppy)+0.25/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(lowx)-conf->xb(lowx-1)))*mult);
}
else if (lowy==conf->Ny())
{
localint.set(lowx,lowy,localint.get(lowx,lowy)+0.25/((conf->yb(lowy)-conf->yb(lowy-1))*(conf->xb(lowx)-conf->xb(lowx-1)))*mult);
localint.set(uppx,lowy,localint.get(uppx,lowy)+0.25/((conf->yb(lowy)-conf->yb(lowy-1))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
}
else
{
// std::cout << "hello4=" << std::endl;
localint.set(lowx,lowy,localint.get(lowx,lowy)+0.25/((conf->yb(lowy)-conf->yb(lowy-1))*(conf->xb(lowx)-conf->xb(lowx-1)))*mult);
localint.set(uppx,lowy,localint.get(uppx,lowy)+0.25/((conf->yb(lowy)-conf->yb(lowy-1))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
localint.set(lowx,uppy,localint.get(lowx,uppy)+0.25/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(lowx)-conf->xb(lowx-1)))*mult);
localint.set(uppx,uppy,localint.get(uppx,uppy)+0.25/((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(uppx)-conf->xb(lowx)))*mult);
}
}
else
{
mult /= ((conf->yb(uppy)-conf->yb(lowy))*(conf->xb(uppx)-conf->xb(lowx)));
// mult /= ((conf->dy(&uppy))*(conf->dx(&uppx)));
localint.set(uppx,uppy,localint.get(uppx,uppy)+mult);
}
// }
}
void traceonestep(IMPACT_Config *conf,IMPACT_Vector &ray_vec,
IMPACT_Matrix &eps_mat,IMPACT_Matrix &gradepsx, IMPACT_Matrix &gradepsy,
double eps, double ds, bool &flag, bool &firststep)
{
IMPACT_Vector r_h(3), r0(3), r1(3);
IMPACT_Vector r_temp(3);
IMPACT_Vector v0(3), v1(3);
IMPACT_Vector gradn_h(3),gradb_h(3),gradI_h(3), omega_0(3), omega_h(3), grad_eps0(3);
IMPACT_Vector temp(3), temp2(3), tempVstep(3);
double n_h, tempdouble,tempdouble2,tempindex;
// double xmx = x_vec.Get(x_vec.length())+dx/2;
// double ymx = y_vec.Get(y_vec.length())+dy/2;
// double xmn = x_vec.Get(1)-dx/2;
// double ymn = y_vec.Get(1)-dy/2;
double vals [3];
r0.Set(1,ray_vec.Get(1));
r0.Set(2,ray_vec.Get(2));
r0.Set(3,0.0);
v0.Set(1,ray_vec.Get(3));
v0.Set(2,ray_vec.Get(4));
v0.Set(3,0.0);
// First Half Step
// STEP 1
temp.Duplicate(&v0); // DO I WANT GETVEC OR DUPLICATE?
temp.MultiplyAll(ds/2.0); // temp is now v0*ds/2
addVecs(r0,temp,r_h);
//std::cout << "\n\n";gradepsy.Print();std::cout << "\n\n";
interp23(conf,gradepsx,gradepsy,eps_mat,r_h.Get(1),r_h.Get(2),vals);
gradn_h.Set(1,vals[0]); //INTERPOLATIONS!
gradn_h.Set(2,vals[1]);
gradn_h.Set(3,0.0);
n_h = vals[2]-eps;
gradn_h.MultiplyAll(0.5/n_h); // Is now grad index / index
// std::cout << "gradnh is: "; gradn_h.PrintArray(); std::cout<< "and n_h is: " << n_h << "\n\n";
// STEP 2
crossVecs(gradn_h,temp,omega_0); // With ds
// std::cout << "Omega_0 is: "; omega_0.PrintArray();
// Step 3
temp.Duplicate(&omega_0);
// temp.MultiplyAll(ds/2.0);
crossVecs(v0,omega_0,temp);
addVecs(v0,temp,temp);
temp.MultiplyAll(ds/2.0);
crossVecs(gradn_h,temp,omega_h);
// std::cout << "Omega_(1/2) is: "; omega_h.PrintArray();
// Step 4
// double tempVstep;
// tempVstep = omega_h.VecSum();
// tempVstep = 2.0/(1.0+tempVstep*ds*ds/4.0);
specialVstep(omega_h,ds,tempVstep);
crossVecs(v0,omega_h,temp);
// temp.MultiplyAll(ds/2.0);
addVecs(v0,temp,temp2);
crossVecs(temp2,omega_h,temp2);
// temp2.MultiplyAll(ds/2.0);
// temp2.MultiplyAll(tempVstep);
elementMultVecs(temp2,tempVstep,temp2);
addVecs(v0,temp2,v1);
// std::cout << "v_1 is: "; v1.PrintArray();
v1.MultiplyAll(ds/2.0);
// Check for correctness
addVecs(r_h,v1,r_temp);
// std::cout << "r_temp is: "; r_temp.PrintArray(); std::cout<< "\n";
// INBOUNDS
// if (r_temp.Get(1) <= conf->xpos(conf->Nx()+1) && r_temp.Get(2) <= conf->ypos(conf->Ny()+1)
// && r_temp.Get(1) >= conf->xpos(0) && r_temp.Get(2) >= conf->ypos(0))
if (r_temp.Get(1) < conf->xb(conf->Nx()) && r_temp.Get(2) < conf->yb(conf->Ny())
&& r_temp.Get(1) > conf->xb(0) && r_temp.Get(2) > conf->yb(0))
{
tempindex = (interp2(conf,eps_mat,r_temp.Get(1),r_temp.Get(2))-eps);
//std::cout << "tempindex = " << tempindex << "\n";
if (tempindex > 0) // Interpolate
{ // Step 5 If allowed to enter
ray_vec.Set(1,r_temp.Get(1));
ray_vec.Set(2,r_temp.Get(2));
ray_vec.Set(3,2.0/ds*v1.Get(1));
ray_vec.Set(4,2.0/ds*v1.Get(2));
}
else if (firststep)
{
flag = 0;
}
else
{
// Reflection if not allowed
grad_eps0.reset();
// Gradient calculation @ r0
grad_eps0.Set(1,interp2(conf,gradepsx,r0.Get(1),r0.Get(2))); // Interpolate
grad_eps0.Set(2,interp2(conf,gradepsy,r0.Get(1),r0.Get(2))); // Interpolate
grad_eps0.Set(3,0.0);
tempdouble=dotVecs(v0,grad_eps0);
tempdouble2=grad_eps0.VecSum();
double LcosA= -1.0*tempdouble/tempdouble2;
grad_eps0.MultiplyAll(LcosA);
// std::cout << "\n\n";grad_eps0.PrintArray();std::cout << "\n\n";
//std::cout << "\n\n"<< LcosA << "\n\n";
IMPACT_Vector v_par(3);
v_par.Duplicate(&grad_eps0);
v_par.MultiplyAll(2.0);
addVecs(v0,v_par,v1);
ray_vec.Set(3,v1.Get(1));
ray_vec.Set(4,v1.Get(2));
// std::cout << "vx = " << v1.Get(1) << "\n";
// std::cout << "vy = " << v1.Get(2) << "\n";
// v1.MultiplyAll(ds/2);
tempdouble = interp2(conf,eps_mat,r0.Get(1),r0.Get(2));
// std::cout << "eps = " << tempdouble << "\n";
// std::cout << "\n\n";v0.PrintArray();std::cout << "\n\n";
// std::cout << "\n\n";grad_eps0.PrintArray();std::cout << "\n\n";
addVecs(v0,grad_eps0,v1);
v1.MultiplyAll(4*LcosA*tempdouble);
//std::cout << "\n\n";v1.PrintArray();std::cout << "\n\n";
ray_vec.Set(1,r0.Get(1)+v1.Get(1));
ray_vec.Set(2,r0.Get(2)+v1.Get(2));
// std::cout << "dx = " << v1.Get(1) << "\n";
// std::cout << "dy = " << v1.Get(2) << "\n";
// addVecs(r_h,v1,r1);
// ray_vec.Set(1,r1.Get(1));
// ray_vec.Set(2,r1.Get(2));
}
}
else // OUT OF BOUNDS
{
flag=0;
}
}
void tracerunner(IMPACT_Matrix &n_mat, IMPACT_Matrix &Bz_mat, IMPACT_StenOps *sten, IMPACT_Config *conf, IMPACT_MPI_Config *M)
{
// For the Main Loop
bool flag=1, firststep=1, discard = 0;
IMPACT_Matrix tempint, localint;
localint.ChangeSize(conf->Nx(),conf->Ny());
localint.setall(0.0);
tempint.ChangeSize(conf->Nx(),conf->Ny());
tempint.setall(0.0);
// for (int zs=0;zs<conf->Nx()+1;++zs)
// std::cout<<"xb[0]: " << conf->xb(zs)<< "\n";
///////////////------------------------------------------------------------///////////////
// Initialization of plasma properties
// IMPACT_Matrix gradnx, gradny;
// IMPACT_Matrix gradxBz, gradyBz;
IMPACT_Matrix eps_mat,gradepsx,gradepsy;
IMPACT_Heating::i_mat.ChangeSize(conf->Nx(),conf->Ny());
IMPACT_Heating::i_mat.setall(0.0);
// double xmin=x_vec.Get(1)-dx_vec.Get(1);
// double ymin=y_vec.Get(1)-dy_vec.Get(1);
// double xmax=x_vec.Get(conf->Nx)+dx_vec.Get(conf->Nx);
// double ymax=y_vec.Get(conf->Ny)+dy_vec.Get(conf->Ny);
// double xmin=x_vec.Get(1)-dx/2;
// double ymin=y_vec.Get(1)-dy/2;
// double xmax=x_vec.Get(Nx)+dx/2;
// double ymax=y_vec.Get(conf->Ny)+dy/2;
/////////////////////////////////////////////////////////////
// Determine STEP SIZE //////////////////////////////////////
int n_max;
int i =1;
double dxmin = conf->dx(&i);
double dymin = conf->dy(&i);
double ds = IMPACT_Heating::ds;
for (i=2;i<=conf->Nx();++i)
{
if (dxmin > conf->dx(&i))
{
dxmin = conf->dx(&i);
}
}
for (i=2;i<=conf->Ny();++i)
{
if (dymin > conf->dy(&i))
{
dymin = conf->dy(&i);
}
}
if (dxmin > dymin)
{
ds *= dymin;
n_max = (conf->get_xmax()-conf->get_xmin())/ds*4;
}
else
{
//globalconsts::pi*
ds *= dxmin;
n_max = (conf->get_ymax()-conf->get_ymin())/ds*4;
}
// std::cout<< "\n\n ds: " << ds << "\n\n";
/////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
epscalc(eps_mat,n_mat,Bz_mat);
gradcalc(sten,conf,eps_mat,gradepsx,gradepsy);
///////////////------------------------------------------------------------///////////////
// Ray Trace Quantities
IMPACT_Vector rayvec(4);double xc;
//IMPACT_Vector rayfull(4);
int r; // Position
int n=1; // Time Step
double theta_live;
double mult;
///////////////------------------------------------------------------------///////////////
// VARIATION IN CRITICAL DENSITY ACCORDING TO AIRY FUNCTION
double tempeps; // For Airy noise
double deltac=globalconsts::c_L/globalconsts::omega_p_nuei_n; // Airy
double max_loc=findindex(conf,eps_mat,0,IMPACT_Heating::direction);
// bool airyflag = max_loc>1;
bool airyflag=0;
double scln;
// = IMPACT_Heating::direction*fabs(1.0/interp2(x_vec,y_vec,gradepsy,floor(Nx/2.0),max_loc))+
// (-1.0*IMPACT_Heating::direction+1)*
// fabs(1.0/interp2(x_vec,y_vec,gradepsx,max_loc,floor(Ny/2.0)));
if (airyflag)
{
if (IMPACT_Heating::direction)
{
scln = fabs(1.0/interp2(conf,gradepsy,conf->xpos(conf->Nx()/2),max_loc));
}
else
{
scln = fabs(1.0/interp2(conf,gradepsx,max_loc,conf->ypos(conf->Ny()/2)));
}
}
// // FIND ETA = 1, LOCATION OF MAX INTENSITY
max_loc-=pow(deltac*deltac*scln/IMPACT_Heating::n_c,1.0/3.0);
// For Airy Loop
bool ncflg;
// bool airyflag = 1;
///////////////-------------------------------------------------------------///////////////
boost::posix_time::ptime time_t_epoch(boost::gregorian::date(2014,1,1));
boost::posix_time::ptime tick = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration diff = tick - time_t_epoch;
long x = diff.total_microseconds();
// Random Number Generation
typedef boost::mt19937 RNGType;
long seed = 1e4*(M->rank())+x;
// printf("Seed: %.17g\n", seed);
// std::cout<< "\n\n microseconds: " << x << "\n\n";
// std::cout<< "\n\n seed: " << seed << "\n\n";
RNGType rng(seed);
//boost::uniform_real<> degreesample(0,1.0);
boost::uniform_real<> Xsample(-1.0,2.0);
boost::uniform_real<> Ysample(0.0,1.0);
boost::uniform_real<> degsample(-1.0,1.0);
//boost::variate_generator< RNGType, boost::uniform_real<> > deg_gen(rng, degreesample);
boost::variate_generator< RNGType, boost::uniform_real<> > x_gen(rng, Xsample);
boost::variate_generator< RNGType, boost::uniform_real<> > y_gen(rng, Ysample);
boost::variate_generator< RNGType, boost::uniform_real<> > deg_gen(rng, degsample);
///////////////------------------------------------------------------------///////////////
// Live Loop Quantity containers
double livemult;
double pertcoeff;
double temploc;
double dx_orig = conf->xb(1)-conf->xb(0);
double dy_orig = conf->yb(1)-conf->yb(0);
// Group Velocity
double vG0;
double ntemp;
double btemp;
// Airy Loop
double Xtemp,Ytemp;
// each step
double tempvG;
bool check;
int tempi;
double tempv;
int upp,low;
// Ray Diagnostics!!!!!!!!!
//
std::string dir = "MNT/Te/";
dir = IMPACT_Messages::Data_Directory + dir;
std::string rayfile = "ray_";
std::string raydmpname = IMPACT_Out(dir,rayfile,0);
const int ifnotdump = 0; //((*tstep+1) % ndump)+1;
//std::cout<< "\n ifnotdump : " << ifnotdump << "\n";
int rayndump=1;//IMPACT_Heating::beam_res/10;
int ifraydump;
std::ofstream raystream;
if (!ifnotdump && !(M->rank())) raystream.open(raydmpname.c_str());
bool bool_u = 0,bool_s = 0,bool_g = 0;
if (IMPACT_Heating::shape==0) {bool_u = 1; bool_s = 0; bool_g = 0;}
if (IMPACT_Heating::shape==1) {bool_u = 0; bool_s = 1; bool_g = 0;}
if (IMPACT_Heating::shape==2) {bool_u = 0; bool_s = 0; bool_g = 1;}
int local_ray_ind=1+M->rank()*IMPACT_Heating::beam_res;
int local_ray_total=(M->rank()+1)*IMPACT_Heating::beam_res;
int totalbeamres = M->size()*IMPACT_Heating::beam_res;
double sigma = IMPACT_Heating::beam_width/sqrt(8*log(2));
double totalGaussianbeamwidth = 2.0*sigma;
bool currentraydir;
double x0,y0;
double turnx,turny;
bool turn;
int beam;
int totalbeams = 4;
mult = (bool_g*2.0*sigma+(!bool_g)*IMPACT_Heating::beam_width)/IMPACT_Heating::beam_res*ds/dx_orig/dy_orig;
// mult = IMPACT_Heating::beam_width/totalbeamres*ds/dx/dy;
// double sx = 0.01*(dymin*dymin)/(dxmin*dxmin+dymin*dymin);
// double sy = 0.01*(dxmin*dxmin)/(dxmin*dxmin+dymin*dymin);
// for (r=1;r<=IMPACT_Heating::beam_res;++r)
for (r=local_ray_ind;r<=local_ray_total;++r)
{
for (beam=1;beam<=totalbeams;++beam)
{
flag = 1;
turn = 0;
firststep=1;
n = 1;
ncflg=1;
if (beam==1)
{
// INNER BEAM 1 (23.5 degrees)
currentraydir = IMPACT_Heating::direction;
theta_live=IMPACT_Heating::theta;
sigma = IMPACT_Heating::beam_width/sqrt(8*log(2))/sin(theta_live);
// y0 = 6.5*IMPACT_Heating::ray_y0;
x0 = IMPACT_Heating::ray_x0;
y0 = IMPACT_Heating::ray_y0;
livemult = mult;//livemult = mult;
}
else if (beam==2)
{
// INNER BEAM 2 (30 degrees)
currentraydir = !IMPACT_Heating::direction;
theta_live=30.0*globalconsts::pi/180.0;
sigma = IMPACT_Heating::beam_width/sqrt(8*log(2))/sin(theta_live);
// y0 = 12.0*IMPACT_Heating::ray_y0;
x0 = IMPACT_Heating::ray_x0;
y0 = 1300+IMPACT_Heating::ray_y0;
livemult = mult;//livemult = mult;
}
else if (beam==3)
{
// OUTER BEAM 1 (44.5 degrees)
currentraydir = IMPACT_Heating::direction;
theta_live=45.5*globalconsts::pi/180.0;
sigma = IMPACT_Heating::beam_width/sqrt(8*log(2))/sin(theta_live);
sigma = 1.5*sigma;
// totalGaussianbeamwidth = 1.5*sigma;
x0 = 100+IMPACT_Heating::ray_x0;
y0 = IMPACT_Heating::ray_y0;
livemult = mult;
}
else if (beam==4)
{
// OUTER BEAM 1 (50 degrees)
currentraydir = !IMPACT_Heating::direction;
theta_live=50.0*globalconsts::pi/180.0;
sigma = IMPACT_Heating::beam_width/sqrt(8*log(2))/sin(theta_live);
sigma = 1.5*sigma;
// totalGaussianbeamwidth = 1.5*sigma;
// y0 = 4.0*IMPACT_Heating::ray_y0;
x0 = IMPACT_Heating::ray_x0;
y0 = 150+IMPACT_Heating::ray_y0;
livemult = mult;
}
// dTheta goes here
// theta_live=IMPACT_Heating::theta+IMPACT_Heating::dtheta*deg_gen();
theta_live=theta_live+IMPACT_Heating::dtheta*(1.0-2.0*(r-1)/totalbeamres);
// Perturbation to intensity profile goes here
// pertcoeff = 1+0.0*cos(4*2.0*globalconsts::pi*r/IMPACT_Heating::beam_res);
// Initialize Ray positions and directions.
// Also initialize intensity
// if (!IMPACT_Heating::direction)
if (!currentraydir)
{
xc = x0+(2.0*sigma)/2.0;
low = 0;upp=conf->Nx()+1;
// rayvec.Set(1,IMPACT_Heating::ray_x0+(r-0.5)/IMPACT_Heating::beam_res*IMPACT_Heating::beam_width);
rayvec.Set(1,x0+(r-0.5)/totalbeamres*
(bool_g*(2.0*sigma)+(!bool_g)*IMPACT_Heating::beam_width));
rayvec.Set(2,conf->yb(0)+0.1*ds);
rayvec.Set(3,cos(theta_live));
rayvec.Set(4,sin(theta_live));
check = 0;
tempi = (upp-low)/2;
while (!check)
{
tempv = conf->xpos(tempi);
if (rayvec.Get(1) < tempv)
{
upp=tempi;
}
else if (rayvec.Get(1) > tempv)
{
low=tempi;
}
else if (rayvec.Get(1) == tempv)
{
low=tempi;
upp=tempi+1;
}
check = ((upp-low)==1);
tempi = low+(upp-low)/2;
}
livemult = livemult*(conf->xpos(upp)-conf->xpos(low))*dy_orig*
fabs(rayvec.Get(4))*((bool_u)+
(bool_s*(pow(sin((rayvec.Get(1)-x0)/IMPACT_Heating::beam_width*globalconsts::pi),2)))+
(bool_g*exp(-1.0/2.0*pow((rayvec.Get(1)-xc)/sigma,4.0))));
// (bool_g*(exp(-1.0*pow((rayvec.Get(1)-xc)/(IMPACT_Heating::beam_width/6.0),2.0)/2))));
// livemult*= pertcoeff;
// Ray Diag
//rayndump = IMPACT_Heating::beam_res/10;//(IMPACT_Heating::beam_width/dx);
}
else
{
xc = y0+(2.0*sigma)/2.0;
low = 0;upp=conf->Ny()+1;
rayvec.Set(1,conf->xb(0)+0.1*ds);
// rayvec.Set(2,IMPACT_Heating::ray_y0+(r-0.5)/IMPACT_Heating::beam_res*IMPACT_Heating::beam_width);
// rayvec.Set(2,y0+(r-0.5)/totalbeamres*
rayvec.Set(2,y0+(r-0.5)/totalbeamres*
(bool_g*(2.0*sigma)+(!bool_g)*IMPACT_Heating::beam_width));
rayvec.Set(3,sin(theta_live));
rayvec.Set(4,cos(theta_live));
check = 0;
tempi = (upp-low)/2;
while (!check)
{
tempv = conf->ypos(tempi);
if (rayvec.Get(2) < tempv)
{
upp=tempi;
}
else if (rayvec.Get(2) > tempv)
{
low=tempi;
}
else if (rayvec.Get(2) == tempv)
{
low=tempi;
upp=tempi+1;
}
check = ((upp-low)==1);
tempi = low+(upp-low)/2;
}
livemult = livemult*(conf->ypos(upp)-conf->ypos(low))*dx_orig*fabs(rayvec.Get(3))*((bool_u)+
(bool_s*(pow(sin((rayvec.Get(2)-y0)/IMPACT_Heating::beam_width*globalconsts::pi),2)))+
// (bool_g*(exp(-1.0*pow((rayvec.Get(2)-xc)/(IMPACT_Heating::beam_width/6.0),2.0)/2))));
(bool_g*exp(-1.0/2.0*pow((rayvec.Get(2)-xc)/sigma,4.0))));
// livemult*= pertcoeff;
// Ray Diag
//rayndump = 4*IMPACT_Heating::beam_res/(IMPACT_Heating::beam_width/dy);
}
// OBTAIN CRITICAL DENSITY VALUES ACCORDING TO AIRY FUNCTION ASYMPTOTIC EXPANSION USING RUDIMENTARY
// <NAME>
if (airyflag)
{
while (ncflg)
{
Xtemp = x_gen();
Ytemp = y_gen();
if (3.48979847492*pow(boost::math::airy_ai(Xtemp),2.0)>=Ytemp)
{
Xtemp+=1.0;
Xtemp*=pow(deltac*deltac*scln/IMPACT_Heating::n_c,1.0/3.0);
// std::cout<< "\n\n scln is " << Xtemp << "\n\n";
// Xtemp*=pow(1.0*1.0*scln/IMPACT_Heating::n_c,1.0/3.0);
temploc=max_loc+Xtemp;
ncflg=0;
// std::cout<< "\n\n temploc is " << temploc << "\n\n";
}
}
if (IMPACT_Heating::direction)
{
if (temploc > conf->ypos(conf->Ny())) {temploc = conf->ypos(conf->Ny());}
tempeps = interp2(conf,eps_mat,conf->xpos(floor(conf->Nx()/2.0)),temploc);
}
else
{
if (temploc > conf->xpos(conf->Nx())) {temploc = conf->xpos(conf->Nx());}
tempeps = interp2(conf,eps_mat,temploc,conf->xpos(floor(conf->Ny()/2.0)));
}
}
else
{
tempeps = 0.0; //0.02*deg_gen();
}
//tempeps = 0;
ntemp = interp2(conf,n_mat,rayvec.Get(1),rayvec.Get(2))/IMPACT_Heating::n_c;
btemp = pow(interp2(conf,Bz_mat,rayvec.Get(1),rayvec.Get(2))/globalconsts::omega_p_nuei_n,2.0)/IMPACT_Heating::n_c;
vG0 = sqrt(interp2(conf,eps_mat,rayvec.Get(1),rayvec.Get(2))-tempeps); // sqrt(epsilon)
vG0 = (vG0)/(vG0*vG0+
ntemp*((1-ntemp)*(1-ntemp)+ntemp*btemp)/(1-ntemp-btemp)/(1-ntemp-btemp));
discard=0;
livemult=vG0*livemult;
// Ray Diagnostics
// Ray Diag
ifraydump = 0; //(r % rayndump);
// std::cout << "xpos=" << rayvec.Get(1) << "ypos=" << rayvec.Get(2) <<std::endl;
// MAIN LOOP
while (flag)
{
if ((!ifraydump) && !(M->rank()) && !ifnotdump)
{
rayvec.PrintArraytoFile(raystream);
}
// if (!(M->rank())) std::cout << "\n\n xpos=" << rayvec.Get(1) << ", ypos=" << rayvec.Get(2) << "\n\n";
ntemp = interp2(conf,n_mat,rayvec.Get(1),rayvec.Get(2))/IMPACT_Heating::n_c;
btemp = pow(interp2(conf,Bz_mat,rayvec.Get(1),rayvec.Get(2))/globalconsts::omega_p_nuei_n,2.0)/IMPACT_Heating::n_c;
tempvG = sqrt(interp2(conf,eps_mat,rayvec.Get(1),rayvec.Get(2))-tempeps);
tempvG = (tempvG)/(tempvG*tempvG+
ntemp*((1-ntemp)*(1-ntemp)+ntemp*btemp)/(1-ntemp-btemp)/(1-ntemp-btemp));
// std::cout << "xpos=" << rayvec.Get(1) << " ypos=" << rayvec.Get(2) <<std::endl;//
// std::cout << "ntemp=" << ntemp << "\n\n";
intensitycalc(conf,n_mat,rayvec,tempint,livemult/tempvG);//
traceonestep(conf,rayvec,eps_mat,gradepsx,gradepsy,tempeps,ds,flag,firststep);
++n;
if (rayvec.Get(3)<0.0)
{
if (!turn)
{
turnx=rayvec.Get(1);
turny=rayvec.Get(2);
turn=1;
}
else
{
livemult*=pow((1.0-1e-3),sqrt((rayvec.Get(1)-turnx)*(rayvec.Get(1)-turnx)+(rayvec.Get(2)-turny)*(rayvec.Get(2)-turny)));
turnx=rayvec.Get(1);
turny=rayvec.Get(2);
}
// flag = 0;
//discard = 1; std::cout << "uh oh \n";
}
firststep=0;
}
if (!discard) updatelocalintensity(tempint,localint);
tempint.setall(0.0);
if ((!ifraydump) && !(M->rank()) && !ifnotdump)
{
raystream << "\r\n" << "\r\n";
}
}
}
// Share Intensity here:
double localval;
double gval;
double numprocs = M->size();
for (int i=1;i<=conf->Nx();++i)
{
for (int j=1;j<=conf->Ny();++j)
{
localval = localint.get(i,j);
MPI_Reduce(&localval,&gval,1, MPI_DOUBLE, MPI_SUM,0,MPI::COMM_WORLD);
MPI_Bcast(&gval,1,MPI_DOUBLE,0,MPI::COMM_WORLD);
//std::cout<<"\n From rank: "<< M->rank() << " ----- localval = " << localval <<"------ gval = " << gval << "\n";
// if (!(M->rank())) {
IMPACT_Heating::i_mat.set(i,j,gval/numprocs);
// }
}
// if (!(M->rank())) {
}
// std::cout<<"\n From rank: "<< M->rank() << " --\n";
// IMPACT_Heating::i_mat.Print();
// }
// else
// {
// std::cout<<"\n From rank: "<< M->rank() << " --\n";
// IMPACT_Heating::i_mat.Print();
// }
intensity_diffusion(conf);
if (!ifnotdump && !(M->rank())) raystream.close();
}<file_sep>/include/impacta_equations/impacta_f1equation.h
/*
**********************************************************
f1 equation IMPACT code for inner and outer cells
Version 1.2
1
AGRT
20/2/07
27/2 - Need to put in Bxf1 term!!! done.
15/04/07 - Changed div for grad
**********************************************************
*/
//code for inner cells of f0 equation - i.e. not at boundaries
inline void f1equation_inner(IMPACT_Config *c, IMPACT_ParVec *vlagged,IMPACT_ParVec *vtemp, IMPACT_StenOps * O,IMPACT_Var* f0,IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f1,IMPACT_Var* f2,int *i,int *j,int *k,IMPACT_Dim *x1)
{
/*
**********************************************************
INSERT f1 Equation terms CODE HERE
**********************************************************
*/
f1->set(vtemp,equation_switches::e_inert_on*c->idt(),i,j,k,x1);
// set f1 n+1 element to 1.0
//vgrad f0
double v=c->v(k)*equation_switches::inf1_vgradf0_on;
IMPACT_stencil temp_sten = (*O->ddxi(i,j,x1))*v;
f0->insert(&temp_sten,vtemp,i,j,k);
//Gradient in z term
if (x1->get()==3)
{
f0->inc(vtemp,v*IMPACT_Heating::Dnbydzgrid.get(i,j),i,j,k);
f0->inc(vtemp, (v*v/Initial_Conditions::Te.get(i,j)-1.5)*v*IMPACT_Heating::DTbydzgrid.get(i,j),i,j,k);
}
//-Edf0/dv
if (c->NE()>0)
E->set(vtemp,-equation_switches::inf1_Edf0dv_on
*f0->ddv(vlagged,c,i,j,k),i,j,x1);
// double erfv=erf(v);
// double expmv2oversqrtpi = exp(-1.0*c->v2(k))/sqrt(globalconsts::pi);
// double ei_cols=(equation_switches::Cei_on*Initial_Conditions::Z.get(i,j)*Initial_Conditions::Z.get(i,j)*Initial_Conditions::ni.get(i,j)
// -(erfv*(0.5/c->v2(k)-1.0)-expmv2oversqrtpi/c->v(k))
// )/c->v3(k)-2.0*f0->get(vlagged,i,j,k);
double ei_cols=equation_switches::Cei_on*Initial_Conditions::Z.get(i,j)
*Initial_Conditions::Z.get(i,j)*Initial_Conditions::ni.get(i,j)/c->v3(k)
/((Initial_Conditions::Z.get(i,j)/globalconsts::oneover_atomic_Z+0.236)/(1.0+0.236*Initial_Conditions::Z.get(i,j)/globalconsts::oneover_atomic_Z)
*.236);
// +
// 0*(expmv2oversqrtpi-globalconsts::fourthirds*
// (expmv2oversqrtpi*c->v2(k)+c->v3(k)*(1.0-erfv))+erfv*(c->v(k)-0.5/c->v(k)))
// *((Initial_Conditions::Z.get(i,j)/globalconsts::oneover_atomic_Z+0.236)/(1.0+0.236*Initial_Conditions::Z.get(i,j)/globalconsts::oneover_atomic_Z)
// *.236)
//collision term - only ion collisions first iteration
f1->inc(vtemp,ei_cols,i,j,k,x1);
// B x f1
double multiplier=-equation_switches::inf1_f1xB_on;
IMPACT_Dim x2,x3;
GetOrthogonal(x1,&x2,&x3);
if (x2>3-c->NB()&&x3<=c->Nf1())
f1->inc(vtemp,B->get(vlagged,i,j,&x2)*multiplier*Bimp,i,j,k,&x3);
if (x3>3-c->NB()&&x2<=c->Nf1())
f1->inc(vtemp,-(B->get(vlagged,i,j,&x3)*multiplier*Bimp),i,j,k,&x2);
if (x2>3-c->NB()&&x3<=c->Nf1())
B->inc(vtemp,f1->get(vlagged,i,j,k,&x3)*multiplier*(1-Bimp),i,j,&x2);
if (x3>3-c->NB()&&x2<=c->Nf1())
B->inc(vtemp,-f1->get(vlagged,i,j,k,&x2)*multiplier*(1-Bimp),i,j,&x3);
//f2 parts
//a_j d/dvv^3f2_ij
multiplier = -0.4/c->v3(k);
double dv3f2bydv=0.0;
if (c->Nf2()>0)
{
for (x2=1;x2<=c->N3f2();++x2) //N3f2 is whether z is included or not
{
dv3f2bydv=f2->ddv_v3(vlagged,c,i,j,k,x1,&x2);
E->inc(vtemp,dv3f2bydv*multiplier,i,j,&x2);
}
//2/5vdiv f2
multiplier = 0.4*c->v(k);
for (x2=1;x2<=c->N3f2();++x2) //N3f2 is whether z is included or not
{
temp_sten=(*O->ddxi(i,j,&x2))*multiplier;
f2->insert(&temp_sten,vtemp,i,j,k,x1,&x2);
}
}
bool uw; int dir;
if (IMPACTA_ions::ion_motion)
{
// Ion motion terms
// + C.grad f1
for (IMPACT_Dim x4=1;x4<=c->Nf1();++x4)
{
temp_sten = (*O->ddxi(i,j,&x4))*
Initial_Conditions::C_i[x4.get()-1].get(i,j);
// Upwind
/*dir = x4.get()-1;
uw = Initial_Conditions::C_i[dir].sign(i,j);
temp_sten = (*O->ddxi_uw(i,j,&x4,uw))*
Initial_Conditions::C_i[dir].get(i,j);*/
f1->insert(&temp_sten,vtemp,i,j,k,x1);
}
/* // Cxwdf0/dv - now explicit - agrt 2011
GetOrthogonal(x1,&x2,&x3);
if (x3>3-c->NB())
B->inc(vtemp,-f0->ddv(vlagged,c,i,j,k)
*Initial_Conditions::C_i[x2.get()-1].get(i,j),i,j,&x3);
if (x2>3-c->NB())
B->inc(vtemp,f0->ddv(vlagged,c,i,j,k)
*Initial_Conditions::C_i[x3.get()-1].get(i,j),i,j,&x2);*/
}
}
//code for outer cells of f0 equation - i.e. boundaries
inline void f1equation_outer(IMPACT_Config *c, IMPACT_ParVec *vlagged,IMPACT_ParVec * vtemp, IMPACT_StenOps * O, IMPACT_Var* f0,IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f1,IMPACT_Var* f2,int* i,int *j,int *k,IMPACT_Dim *x1)
{
/*
**********************************************************
INSERT f1 Equation terms CODE HERE - BC versions
**********************************************************
*/
f1->set(vtemp,equation_switches::e_inert_on*c->idt(),i,j,k,x1);
// set f1 n+1 element to 1.0
//vgrad f0
double v=c->v(k)*equation_switches::inf1_vgradf0_on;
IMPACT_stencil temp_sten = (*O->ddxi(i,j,x1))*v;
f0->insert_BC(&temp_sten,vtemp,i,j,k);
if (x1->get()==3)
{
f0->inc(vtemp,v*IMPACT_Heating::Dnbydzgrid.get(i,j),i,j,k);
f0->inc(vtemp, (v*v/Initial_Conditions::Te.get(i,j)-1.5)*v*IMPACT_Heating::DTbydzgrid.get(i,j),i,j,k);
}
//-Edf0/dv
if (c->NE()>0)
E->set(vtemp,-equation_switches::inf1_Edf0dv_on
*f0->ddv_BC(vlagged,c,i,j,k),i,j,x1);
// double erfv=erf(v);
// double expmv2oversqrtpi = exp(-1.0*c->v2(k))/sqrt(globalconsts::pi);
double ei_cols=equation_switches::Cei_on*Initial_Conditions::Z.get(i,j)
*Initial_Conditions::Z.get(i,j)*Initial_Conditions::ni.get(i,j)/c->v3(k)
/((Initial_Conditions::Z.get(i,j)/globalconsts::oneover_atomic_Z+0.236)/(1.0+0.236*Initial_Conditions::Z.get(i,j)/globalconsts::oneover_atomic_Z)
*.236);
// double ei_cols=(equation_switches::Cei_on*Initial_Conditions::Z.get(i,j)*Initial_Conditions::Z.get(i,j)*Initial_Conditions::ni.get(i,j)
// -(erfv*(0.5/c->v2(k)-1.0)-expmv2oversqrtpi/c->v(k))
// )/c->v3(k)-2.0*f0->get(vlagged,i,j,k);
// 0*(expmv2oversqrtpi-globalconsts::fourthirds*
// (expmv2oversqrtpi*c->v2(k)+c->v3(k)*(1.0-erfv))+erfv*(c->v(k)-0.5/c->v(k)))
//collision term - only ion collisions first iteration
f1->inc(vtemp,ei_cols,i,j,k,x1);
// B x f1
double multiplier=-equation_switches::inf1_f1xB_on;
// This cyclicly works out orthogonal correct coordinates for x1 andx2
IMPACT_Dim x2,x3;
GetOrthogonal(x1,&x2,&x3);
if (x2>3-c->NB()&&x3<=c->Nf1())
f1->inc(vtemp,B->get(vlagged,i,j,&x2)*multiplier*Bimp,i,j,k,&x3);
if (x3>3-c->NB()&&x2<=c->Nf1())
f1->inc(vtemp,-(B->get(vlagged,i,j,&x3)*multiplier*Bimp),i,j,k,&x2);
if (x2>3-c->NB()&&x3<=c->Nf1())
B->inc(vtemp,f1->get(vlagged,i,j,k,&x3)*multiplier*(1-Bimp),i,j,&x2);
if (x3>3-c->NB()&&x2<=c->Nf1())
B->inc(vtemp,-f1->get(vlagged,i,j,k,&x2)*multiplier*(1-Bimp),i,j,&x3);
//f2 parts
//a_j d/dvv^3f2_ij
multiplier = -0.4/c->v3(k);
double dv3f2bydv=0.0;
if (c->Nf2()>0)
{
for (x2=1;x2<=c->N3f2();++x2) //N3f2 is whether z is included or not
{
dv3f2bydv=f2->ddv_v3_BC(vlagged,c,i,j,k,x1,&x2);
E->inc(vtemp,dv3f2bydv*multiplier,i,j,&x2);
}
//2/5vdiv f2
multiplier = 0.4*c->v(k);
for (x2=1;x2<=c->N3f2();++x2) //N3f2 is whether z is included or not
{
temp_sten=(*O->ddxi(i,j,&x2))*multiplier;
f2->insert_BC(&temp_sten,vtemp,i,j,k,x1,&x2);
}
}
bool uw; int dir;
if (IMPACTA_ions::ion_motion)
{
// Ion motion terms
// + C.grad f1
for (IMPACT_Dim x4=1;x4<=c->Nf1();++x4)
{
temp_sten = (*O->ddxi(i,j,&x4))*
Initial_Conditions::C_i[x4.get()-1].get(i,j);
// Upwind
/*dir = x4.get()-1;
uw = Initial_Conditions::C_i[dir].sign(i,j);
temp_sten = (*O->ddxi_uw(i,j,&x4,uw))*
Initial_Conditions::C_i[dir].get(i,j);*/
f1->insert_f1BC(&temp_sten,vtemp,i,j,k,x1);
}
/* // Cxwdf0/dv - now explicit agrt 2011
GetOrthogonal(x1,&x2,&x3);
if (x3>3-c->NB())
B->inc(vtemp,-f0->ddv_BC(vlagged,c,i,j,k)
*Initial_Conditions::C_i[x2.get()-1].get(i,j),i,j,&x3);
if (x2>3-c->NB())
B->inc(vtemp,f0->ddv_BC(vlagged,c,i,j,k)
*Initial_Conditions::C_i[x3.get()-1].get(i,j),i,j,&x2); */
}
}
<file_sep>/include/impacta_io/impacta_input_maths.h
void IMPACTA_Get_Func(std::string function,double **grid,int Nx,int Ny,double *gridx, double *gridy);
int IMPACTA_Check_Symbol(std::string symbol)
{
int answer=0;
for (int i=0;i<nsymbols;++i)
if(!strcmp(symbol.c_str(),IMPACTA_symbols[i].c_str())) answer=i+1;
return answer;
}
int IMPACTA_Check_Number(std::string number)
{
int answer=0;
for (int i=0;i<nnumbers;++i)
if(!strcmp(number.c_str(),IMPACTA_numbers[i].c_str()))
answer=i+1;
return answer;
}
int IMPACTA_Check_Function(std::string function)
{
int answer=0;
for (int i=0;i<nfuncs;++i)
if(!strcmp(function.c_str(),IMPACTA_funcs[i].c_str())) answer=i+1;
return answer;
}
double IMPACTA_str2dbl(std::string a)
{
std::istringstream inum("");
std::ostringstream onum("");
onum<<a;
inum.str(onum.str());
double ans;
inum>>ans;
return ans;
}
void IMPACTA_Do_Func(double **grid,double **gridtemp,const int Nx,const int Ny,int functiontype)
{
for (int i=0;i<Nx;++i)
for (int j=0;j<Ny;++j)
{
switch (functiontype)
{
case 1:
break;
case 2:
grid[i][j]=cos(gridtemp[i][j]);
break;
case 3:
grid[i][j]=sin(gridtemp[i][j]);
break;
case 4:
grid[i][j]=tan(gridtemp[i][j]);
break;
case 5:
grid[i][j]=exp(gridtemp[i][j]);
break;
case 6:
grid[i][j]=tanh(gridtemp[i][j]);
break;
case 7:
grid[i][j]=sinh(gridtemp[i][j]);
break;
case 8:
grid[i][j]=cosh(gridtemp[i][j]);
break;
case 9:
grid[i][j]=log(gridtemp[i][j]);
break;
}
}
}
void IMPACTA_Get_Term(double **gridtemp,int operators,std::string v1,
double *gridx,double *gridy,int Nx,int Ny)
{
int behaviour=0;
if (!strcmp(v1.c_str(),"X")) behaviour=1;
if (!strcmp(v1.c_str(),"Y")) behaviour=2;
if (!strcmp(v1.c_str(),"LX")) behaviour=3;
if (!strcmp(v1.c_str(),"LY")) behaviour=4;
if (!strcmp(v1.c_str(),"PI")) behaviour=5;
if (!strcmp(v1.c_str(),"FUNCTION")) behaviour=6; //do nothing
for (int i=0;i<Nx;++i)
for (int j=0;j<Ny;++j)
switch(behaviour)
{
case 0:
gridtemp[i][j]=IMPACTA_str2dbl(v1); break;
case 1:
gridtemp[i][j]=gridx[i]; break;
case 2:
gridtemp[i][j]=gridy[j]; break;
case 3:
gridtemp[i][j]=(gridx[Nx-1]-gridx[0])*(double)Nx/(double)(Nx-1);
break;
case 4:
gridtemp[i][j]=(gridy[Ny-1]-gridy[0])*(double)Ny/(double)(Ny-1);
break;
case 5:
gridtemp[i][j]=pi; break;
}
}
void IMPACTA_Operate(double *grid1,double *grid2,int operators)
{
switch (operators)
{
case 1:
*grid1+=*grid2; break;
case 2:
*grid1-=*grid2; break;
case 3:
*grid1*=*grid2; break;
case 4:
*grid1/=*grid2; break;
case 5:
*grid1=pow(*grid1,*grid2);break;
}
}
void IMPACTA_Do_Algebra(double **grid1,double **grid2,int operators,
int Nx,int Ny)
{
for (int i=0;i<Nx;++i)
for (int j=0;j<Ny;++j)
IMPACTA_Operate(&grid1[i][j],&grid2[i][j],operators);
}
void IMPACTA_Function(double **grid,const int Nx,const int Ny,int functiontype,std::string func_pow)
{
double **gridtemp;
gridtemp =new double*[Nx];
for (int i=0;i<Nx;++i)
gridtemp[i] =new double [Ny];
for (int i=0;i<Nx;++i)
for (int j=0;j<Ny;++j)
gridtemp[i][j]=grid[i][j];
for (int i=0;i<Nx;++i)
for (int j=0;j<Ny;++j)
IMPACTA_Do_Func(grid,gridtemp, Nx, Ny,functiontype);
for (int i=0;i<Nx;++i)
for (int j=0;j<Ny;++j)
grid[i][j]=pow(grid[i][j],IMPACTA_str2dbl(func_pow));
delete[] gridtemp;
}
void IMPACTA_Count_Maths(std::string function, int *num)
{
// Split functions into operators/maths
int length = strlen(function.c_str());
std::string check_function="";
int num_terms=0;
for (int i=0;i<length;++i)
{
check_function+=function[i];
if (IMPACTA_Check_Number(check_function)) check_function="";
if (IMPACTA_Check_Symbol(check_function))
{ check_function=""; ++num_terms;}
}
*num=num_terms;
}
void IMPACTA_Do_Maths(std::string function,int *operators,std::string *values, int *num)
{
// Split functions into operators/maths
int length = strlen(function.c_str());
std::string check_function="";
int num_terms=*num;
for (int i=0;i<num_terms;++i)
{
operators[i]=0;
values[i]="";
}
int stepper=0;
for (int i=0;i<length;++i)
{
check_function+=function[i];
if (IMPACTA_Check_Number(check_function))
{
while (!IMPACTA_Check_Symbol(check_function)&&i<length)
{
values[stepper]+=check_function;
++i;
check_function=function[i];
}
--i;
check_function="";
++stepper;
}
if (IMPACTA_Check_Symbol(check_function))
{
operators[stepper]=IMPACTA_Check_Symbol(check_function);
check_function="";}
}
}
int IMPACTA_Get_Func_n(std::string function)
{
int length = strlen(function.c_str());
std::string check_function="";
int n_sep_funcs=1;
std::string tempstring;
// First check function for errors
for (int i=0;i<length;++i)
{
check_function+=function[i];
if (IMPACTA_Check_Number(check_function)) check_function="";
if (IMPACTA_Check_Symbol(check_function)) check_function="";
if (IMPACTA_Check_Function(check_function)) check_function="";
tempstring=""; tempstring+=check_function;
if (!strcmp(tempstring.c_str(),")")) check_function="";
}
if (strcmp(check_function.c_str(),""))
{
std::cout<<"IMPACTA: ERROR - In mathematical expression in input deck\n";
std::cout<<"Error: "<<check_function<<'\n';
exit(0);
}
// then get number of functions of first order (i.e. first iteration
// of brackets) - doesn't matter if there are too many
int templen=1;
for (int i=0;i<length;++i)
{
check_function+=function[i];
if (IMPACTA_Check_Number(check_function)) check_function="";
if (IMPACTA_Check_Symbol(check_function)) check_function="";
if (IMPACTA_Check_Function(check_function))
{
templen=strlen(IMPACTA_funcs[IMPACTA_Check_Function(check_function)-1].c_str());
tempstring="";
if (i>templen+1) {
++n_sep_funcs;
tempstring+=function[i-templen-1];
if (!strcmp(tempstring.c_str(),")")) --n_sep_funcs;
}
/**/
check_function="";
int bracketcheck=1; //one open bracket;
while (bracketcheck>0&&i<length)
{
++i;
check_function+=function[i];
if (!strcmp(check_function.c_str(),")"))
{--bracketcheck; check_function="";}
if (IMPACTA_Check_Number(check_function)) check_function="";
if (IMPACTA_Check_Symbol(check_function)) check_function="";
if (IMPACTA_Check_Function(check_function))
{ ++bracketcheck; check_function="";}
}
check_function="";
tempstring="";
if (i<length-1)
{
tempstring+=function[i+1];
if (IMPACTA_Check_Number(tempstring)||
IMPACTA_Check_Symbol(tempstring)) ++n_sep_funcs;
}
}
}
return n_sep_funcs;
}
void IMPACTA_Get_Func_i(std::string function,double **grid,int Nx,int Ny,double *gridx,double *gridy)
{
int length = strlen(function.c_str());
std::string check_function="";
int n_sep_funcs=IMPACTA_Get_Func_n(function);
std::string tempstring;
int templen=1;
// Make parts for building up function
std::string *thefunctions;
thefunctions = new std::string[n_sep_funcs];
std::string *func_pow;
int *func_ops;
func_ops=new int[n_sep_funcs];//operator on function
func_pow=new std::string[n_sep_funcs];//power function raised to
int *functiontype;
functiontype=new int[n_sep_funcs];
//initialize values
for (int i=0;i<n_sep_funcs;++i)
{
thefunctions[i]="";
func_ops[i]=0;
functiontype[i]=0;
func_pow[i]="1.0";
}
int stepper=0; //to step through the function parts
// Now extract functions of first order
for (int i=0;i<length;++i)
{
check_function+=function[i];
if (i==0&&IMPACTA_Check_Symbol(check_function)!=1&&
IMPACTA_Check_Symbol(check_function)!=2)
func_ops[stepper]=1; //This to give every one an operation
if (i==0) func_ops[0]=IMPACTA_Check_Symbol(check_function);
if (IMPACTA_Check_Number(check_function))
{
thefunctions[stepper]+=
IMPACTA_numbers[IMPACTA_Check_Number(check_function)-1];
check_function="";
}
if (IMPACTA_Check_Symbol(check_function))
{
if (stepper<n_sep_funcs-1)
func_ops[stepper+1]=IMPACTA_Check_Symbol(check_function);
check_function="";
if (i<length-1)
{
tempstring="";
tempstring+=function[i+1];
int test=0;
test+=IMPACTA_Check_Number(tempstring);
test+=IMPACTA_Check_Symbol(tempstring);
if (i<length-2) tempstring+=function[i+2];
test+=IMPACTA_Check_Number(tempstring);
if (i<length-3) tempstring+=function[i+3];
test+=IMPACTA_Check_Number(tempstring);
if (test)
thefunctions[stepper]+=function[i];
}
else thefunctions[stepper]+=function[i];
}
if (IMPACTA_Check_Function(check_function))
{
tempstring="";
templen=strlen(IMPACTA_funcs[IMPACTA_Check_Function(check_function)-1].c_str());
tempstring="";
if (i>templen+1) {
++stepper;
tempstring+=function[i-templen-1];
if (!strcmp(tempstring.c_str(),")"))
{
--stepper;
tempstring=""; tempstring+=function[i-templen];
func_ops[stepper]=IMPACTA_Check_Symbol(tempstring);
}
//if (stepper<n_sep_funcs-1)
//func_ops[stepper]=func_ops[stepper+1];}
}
thefunctions[stepper]="";
if (stepper<n_sep_funcs)
functiontype[stepper]=IMPACTA_Check_Function(check_function);
check_function="";
int bracketcheck=1; //one open bracket;
while (bracketcheck>0&&i<length)
{
++i;
check_function+=function[i];
if (strcmp(check_function.c_str(),")")||bracketcheck>1)
thefunctions[stepper]+=function[i];
if (!strcmp(check_function.c_str(),")"))
{ --bracketcheck; check_function="";}
if (IMPACTA_Check_Number(check_function)) check_function="";
if (IMPACTA_Check_Symbol(check_function)) check_function="";
if (IMPACTA_Check_Function(check_function))
{ ++bracketcheck; check_function="";}
}
if (i<length-2)
{
tempstring=function[i+1];
if (IMPACTA_Check_Symbol(tempstring)==5)
{
tempstring=function[i+2];
func_pow[stepper]=tempstring;
++i;++i;
}
}
tempstring="";
if (i<length-1)
{
tempstring+=function[i+1];
if (IMPACTA_Check_Number(tempstring)||
IMPACTA_Check_Symbol(tempstring)) ++stepper;
}
check_function="";
}
}
// Now set operation, function type and power for these functions
// Stage 2 - now do the maths
//
int **operators;
std::string **values;
int *num_terms;
operators=new int*[n_sep_funcs];
values=new std::string*[n_sep_funcs];
num_terms=new int[n_sep_funcs];
for (int i=0;i<n_sep_funcs;++i)
{
num_terms[i]=1;
if (!functiontype[i])
IMPACTA_Count_Maths(thefunctions[i],&num_terms[i]);
operators[i]=new int[num_terms[i]];
values[i]=new std::string[num_terms[i]];
for (int j=0;j<num_terms[i];++j)
{
operators[i][j]=func_ops[i];
values[i][j]="function";
}
}
for (int i=0;i<n_sep_funcs;++i)
if (!functiontype[i])
IMPACTA_Do_Maths(thefunctions[i],operators[i],
values[i],&num_terms[i]);
// Now everything is ordered.
//now put into one long line
int n_terms=0;
for (int i=0;i<n_sep_funcs;++i)
{
n_terms+=num_terms[i];
}
int * opline;
std::string *valline;
int *done_job;
opline=new int[n_terms];
done_job=new int[n_terms];
for (int i=0;i<n_terms;++i) done_job[i]=1; // if term used already
valline=new std::string[n_terms];
stepper=0;
int *map_func_i;
map_func_i=new int[n_sep_funcs];
for (int i=0;i<n_sep_funcs;++i)
{
map_func_i[i]=0;
if (functiontype[i]) map_func_i[i]=stepper;
for (int j=0;j<num_terms[i];++j)
{
opline[stepper]=operators[i][j];
valline[stepper]=values[i][j];
++stepper;
}
}
/*std::cout<<"nterms="<<n_terms<<'\n';
for (int i=0;i<n_terms;++i)
std::cout<<"op="<<opline[i]<<", val="<<valline[i]<<'\n';
for (int i=0;i<n_sep_funcs;++i) std::cout<<"mapfunc="<<map_func_i[i]<<',';
std::cout<<'\n';*/
double ***gridtemp;
gridtemp=new double **[n_terms];
for (int i=0;i<n_terms;++i)
{
gridtemp[i]=new double*[Nx];
for (int j=0;j<Nx;++j)
{
gridtemp[i][j]=new double[Ny];
for (int k=0;k<Ny;++k)
gridtemp[i][j][k]=0.0;
}
}
// Work out terms
//Start with Functions
// if (n_sep_funcs>1)
for (int i=0;i<n_sep_funcs;++i)
if (functiontype[i])
IMPACTA_Get_Func(thefunctions[i],gridtemp[map_func_i[i]],
Nx,Ny,gridx,gridy);
for (int i=0;i<n_sep_funcs;++i)
{
if (functiontype[i])
IMPACTA_Function(gridtemp[map_func_i[i]],
Nx,Ny,functiontype[i],func_pow[i]);
}
// Now evaluate terms
for (int i=0;i<n_terms;++i)
if (strcmp(valline[i].c_str(),"function"))
IMPACTA_Get_Term(gridtemp[i],opline[i],valline[i],gridx,gridy,Nx,Ny);
//
/* START OF CALCULATIONS - Using Bodmas ordering*/
// Now do powers
for (int i=0;i<n_terms;++i)
if (opline[i]==5)
{
IMPACTA_Do_Algebra(gridtemp[i-1],gridtemp[i],
opline[i],Nx,Ny);
done_job[i]=0;
}
// now do the divisions
for (int i=0;i<n_terms;++i)
if (opline[i]==4&&done_job[i]==1)
{
stepper=i-1;
while (!done_job[stepper]&&stepper>0) --stepper;
IMPACTA_Do_Algebra(gridtemp[stepper],gridtemp[i],
opline[i],Nx,Ny);
done_job[i]=0;
}
// now do the multiplication
for (int i=1;i<n_terms;++i)
if (opline[i]==3&&done_job[i]==1)
{
stepper=i-1;
while (!done_job[stepper]&&stepper>0) --stepper;
IMPACTA_Do_Algebra(gridtemp[stepper],gridtemp[i],
opline[i],Nx,Ny);
done_job[i]=0;
}
// finally sum all terms
//first term, if - need to change
if (opline[0]==2)
for (int i=0;i<Nx;++i)
for (int j=0;j<Ny;++j)
gridtemp[0][i][j]=-gridtemp[0][i][j];
//now sum all the rest onto first one
for (int i=1;i<n_terms;++i)
if ((opline[i]==1||opline[i]==2)&&done_job[i]==1)
{
stepper=i-1;
while (!done_job[stepper]&&stepper>0) --stepper;
IMPACTA_Do_Algebra(gridtemp[stepper],gridtemp[i],
opline[i],Nx,Ny);
done_job[i]=0;
}
for (int i=0;i<Nx;++i)
for (int j=0;j<Ny;++j)
grid[i][j]=gridtemp[0][i][j];
//Clean up
delete[] thefunctions;
delete[] func_pow;
delete[] func_ops;
delete[] functiontype;
delete[] opline;
delete[] done_job;
delete[] map_func_i;
for (int i=0;i<n_sep_funcs;++i)
{
delete[] operators[i];
delete[] values[i];
}
delete[] operators;
delete[] values;
delete[] num_terms;
for (int i=0;i<n_terms;++i)
{
for (int j=0;j<Nx;++j)
delete[] gridtemp[i][j];
delete[] gridtemp[i];
}
delete []gridtemp;
}
void IMPACTA_Get_Func(std::string function,double **grid,int Nx,int Ny,double *gridx,double *gridy)
{
// First set to uppercase
int length = strlen(function.c_str());
for (int i=0;i<length;++i)
function[i]=(char) toupper(function.c_str()[i]);
std::string tempfunc="";
tempfunc+=function[0];
if (IMPACTA_Check_Symbol(tempfunc)!=1&&IMPACTA_Check_Symbol(tempfunc)!=2)
{
tempfunc="+"+function;
function=tempfunc;
}
IMPACTA_Get_Func_i(function,grid,Nx,Ny,gridx,gridy);
}
<file_sep>/include/impacta_io/impacta_filehandling.h
/*
**********************************************************
File handling - functions for writing and reading moments
Version 2.6
AGRT
27/3/07
25/7/07 - Finally updated so that the actual distribution functions
are output.
24/9/07 - Now copies the input deck into the data directory as a
record of what the parameters are
7/4/08 - Added a dump for wt i.e. sqrt(B^2)*T^3/2/Z/ne
**********************************************************
*/
//To set up directory structure
int IMPACT_Tree(IMPACT_Config *c)
{
int rank;
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
int result=0;
if (!rank)
{
std::string unix_com = "test -d "+IMPACT_Messages::Data_Directory;
result = system(unix_com.c_str());
if (!result) {
if (!IMPACTA_Version_HPC)
{
std::cout<<"IMPACT: ERROR - Directory structure '" <<IMPACT_Messages::Data_Directory<< "' already exists\n";
std::cout<<"\nOverwrite? (type 'yes' for yes) ";
std::string answer;
std::cin >>answer;
if (!strcmp(answer.c_str(),"yes"))
{
std::string root="rm -r "+IMPACT_Messages::Data_Directory;
result = system(root.c_str());
if (result!=0)
{
std::cout<<"\nCould not remove directory";
IMPACT_Bad_Exit(0);
}
} else {
IMPACT_Bad_Exit(0);
}
} else {
std::cout<<"IMPACT: ERROR - Directory structure '" <<IMPACT_Messages::Data_Directory<< "' already exists\n";
IMPACT_Bad_Exit(0);
}
}
std::string root="mkdir "+IMPACT_Messages::Data_Directory;
result = system(root.c_str());
unix_com=root+IMPACT_Messages::Field_Dir;
result = system(unix_com.c_str());
unix_com=root+IMPACT_Messages::DistFunc_Dir;
result = system(unix_com.c_str());
unix_com=root+IMPACT_Messages::Moment_Dir;
result = system(unix_com.c_str());
unix_com=root+IMPACT_Messages::Constants_Dir;
result = system(unix_com.c_str());
//Copy input deck to directory
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
std::string dateStr=asctime (timeinfo);
unix_com=IMPACT_Messages::Data_Directory+"imstdin--"+dateStr;
for (int i=0; i < (int) unix_com.length(); ++i)
{
if (unix_com[i]==' ') unix_com.replace(i,1,"_");
}
unix_com="cp "+IMPACT_Messages::InDeck
+" "+unix_com;
result = system(unix_com.c_str());
//now put in appropriate directories for the Fields
if(c->NE()>0&&if_dump_switches::dump_E)
for (int x1=1;x1<=c->NE();++x1)
{
unix_com=root+IMPACT_Messages::Field_Dir+"E"+getcoord(x1);
result = system(unix_com.c_str());
}
if(c->NB()>0&&if_dump_switches::dump_B)
for (int x1=3;x1>3-c->NB();--x1)
{
unix_com=root+IMPACT_Messages::Field_Dir+"B"+getcoord(x1);
result = system(unix_com.c_str());
}
// Now the directories for the ions
if (if_dump_switches::dump_ni&&IMPACTA_ions::ion_motion)
{
unix_com=root+IMPACT_Messages::Constants_Dir+"ni";
result = system(unix_com.c_str());
}
if(if_dump_switches::dump_Ci&&IMPACTA_ions::ion_motion)
for (int x1=1;x1<=c->Nf1();++x1)
{
unix_com=root+IMPACT_Messages::Constants_Dir+"C"+getcoord(x1);
result = system(unix_com.c_str());
}
if (if_dump_switches::dump_Z&&(IMPACTA_ions::ion_motion||IMPACTA_ions::ionization_on))
{
unix_com=root+IMPACT_Messages::Constants_Dir+"Z";
result = system(unix_com.c_str());
}
//Now the dirs for the moments
if (if_dump_switches::dump_ne)
{
unix_com=root+IMPACT_Messages::Moment_Dir+"ne";
result = system(unix_com.c_str());
}
if (if_dump_switches::dump_Ue){
unix_com=root+IMPACT_Messages::Moment_Dir+"Ue";
result = system(unix_com.c_str());
}
if (if_dump_switches::dump_Te)
{
unix_com=root+IMPACT_Messages::Moment_Dir+"Te";
result = system(unix_com.c_str());}
if (if_dump_switches::dump_eta)
{
unix_com=root+IMPACT_Messages::Moment_Dir+"eta";
result = system(unix_com.c_str());}
if (if_dump_switches::dump_wt)
{
unix_com=root+IMPACT_Messages::Moment_Dir+"wt";
result = system(unix_com.c_str());}
if(c->Nf1()>0&&if_dump_switches::dump_je)
for (int x1=1;x1<=c->Nf1();++x1)
{
unix_com=root+IMPACT_Messages::Moment_Dir+"j"+getcoord(x1);
result = system(unix_com.c_str());
}
if(c->Nf1()>0&&if_dump_switches::dump_q)
for (int x1=1;x1<=c->Nf1();++x1)
{
unix_com=root+IMPACT_Messages::Moment_Dir+"qT"+getcoord(x1);
result = system(unix_com.c_str());
unix_com=root+IMPACT_Messages::Moment_Dir+"qe"+getcoord(x1);
result = system(unix_com.c_str());
}
if(c->Nf1()>0&&if_dump_switches::dump_VN)
for (int x1=1;x1<=c->Nf1();++x1)
{
unix_com=root+IMPACT_Messages::Moment_Dir+"VN"+getcoord(x1);
result = system(unix_com.c_str());
}
if(c->Nf2()>0&&if_dump_switches::dump_P)
for (int x1=1;x1<=c->N3f2();++x1)
for (int x2=x1;x2<=c->N3f2();++x2)
if (x1+x2<6)
{
unix_com=root+IMPACT_Messages::Moment_Dir+"P"+getcoord(x1)+getcoord(x2);
result = system(unix_com.c_str());
}
//Finally the dirs for the distribution functions
if (if_dump_switches::dump_f0)
{
unix_com=root+IMPACT_Messages::DistFunc_Dir+"f0";
result = system(unix_com.c_str());}
if(if_dump_switches::dump_f1)
{
unix_com=root+IMPACT_Messages::DistFunc_Dir+"f1";
result = system(unix_com.c_str());
}
if(if_dump_switches::dump_f2)
{
unix_com=root+IMPACT_Messages::DistFunc_Dir+"f2";
result = system(unix_com.c_str());
}
/* if(if_dump_switches::dump_f3)
{
unix_com=root+IMPACT_Messages::DistFunc_Dir+"f3";
result = system(unix_com.c_str());
}*/
}
return result;
}
void IMPACT_ferr(const char * file)
{
std::cout<< "IMPACT: ERROR - file "<<file<<" not found"<<std::endl;
chkMPI();
}
std::string IMPACT_Out(std::string file)
{
//Output data to IMPACT_Messages::Data_Directory
std::string name;
std::string dir = IMPACT_Messages::Data_Directory;
name=dir+file;
/*std::ofstream fileout;
fileout.open(name.c_str());
if (!fileout) IMPACT_ferr(name.c_str());*/
return name.c_str();
}
std::string IMPACT_In(std::string file)
{
//Open files from IMPACT_Messages::Input_Directory
std::string name;
std::string dir = IMPACT_Messages::Input_Directory;
name=dir+file;
return name.c_str();
}
std::string IMPACT_Out(std::string dir,std::string file,int index)
{
//Open files from IMPACT_Messages::Input_Directory
std::ostringstream numtemp;
numtemp<<index;
std::string number;
if (index<10) number='0';
if (index<100) number+='0';
number+=numtemp.str();
std::string name = dir+file+number+".imd";
return name.c_str();
}
//Output data to IMPACT_Messages::Data_Directory
void IMPACT_Write(struct IMPACT_Moment * M, std::string str)
{
std::ofstream outfile;
std::string name = IMPACT_Out(str);
outfile.open(name.c_str());
if (!outfile) IMPACT_ferr(name.c_str());
outfile<<M;
outfile.close();
}
//This format automatically outputs a .imd - so no need to add extension
void IMPACT_Write(struct IMPACT_Moment * M, std::string str,int index)
{
std::ofstream outfile;
std::ostringstream numtemp;
numtemp<<index;
std::string number;
if (index<10) number='0';
if (index<100) number+='0';
number+=numtemp.str();
std::string name = IMPACT_Out(str)+number+".imd";
outfile.open(name.c_str());
if (!outfile) IMPACT_ferr(name.c_str());
outfile<<M;
outfile.close();
}
//Open files from IMPACT_Messages::Input_Directory
void IMPACT_Read(struct IMPACT_Moment * M, std::string str)
{
std::ifstream infile;
std::string name = IMPACT_In(str);
infile.open(name.c_str());
if (!infile) IMPACT_ferr(name.c_str());
infile>>M;
infile.close();
}
void IMPACT_Write(struct IMPACT_Moment * M, std::string str, std::string dir)
{
std::ofstream outfile;
std::string name = dir+str;
outfile.open(name.c_str());
if (!outfile) IMPACT_ferr(name.c_str());
outfile<<M;
outfile.close();
}
//Open files from IMPACT_Messages::Input_Directory
void IMPACT_Read(struct IMPACT_Moment * M, std::string str, std::string dir)
{
std::ifstream infile;
std::string name = dir+str;
infile.open(name.c_str());
if (!infile) IMPACT_ferr(name.c_str());
infile>>M;
infile.close();
}
void IMPACT_Write(struct IMPACT_Moment * M, std::string str, std::string dir,int timestep)
{
std::ofstream outfile;
std::string name = IMPACT_Out(dir,str,timestep);
outfile.open(name.c_str());
if (!outfile) IMPACT_ferr(name.c_str());
outfile<<M;
outfile.close();
}
void IMPACT_WriteInt(std::string str, std::string dir,int timestep)
{
std::ofstream outfile;
std::string name = IMPACT_Out(dir,str,timestep);
outfile.open(name.c_str());
if (!outfile) IMPACT_ferr(name.c_str());
//outfile<<M;
IMPACT_Heating::i_mat.Print(outfile);
outfile.close();
}
void IMPACT_Write(IMPACT_Dist * M, std::string str, std::string dir,int timestep)
{
std::ofstream outfile;
std::string name = IMPACT_Out(dir,str,timestep);
outfile.open(name.c_str());
if (!outfile) IMPACT_ferr(name.c_str());
outfile<<M;
outfile.close();
}
// To dump all the data at a timestep we use....
void IMPACT_Dump(IMPACT_Config *c, IMPACT_MPI_Config *MPIc,IMPACT_ParVec *v, IMPACT_Var *f0,IMPACT_Var *f1,IMPACT_Var *f2,IMPACT_Var *f3,IMPACT_Var *E,IMPACT_Var *B, int timestep)
{
// If new T normalization invoked, need to change all vals
IMPACTA_Rescale_T(c,MPIc,v,f0,f1,f2,f3,E,B,1.0/equation_switches::NEW_T_NORM);
//easy way of checking whether this timestep should be dumped...
const int ifdumpfields = (timestep % c->N_Dump());
const int ifdumpdists = (timestep % (if_dump_switches::f_ndump*c->N_Dump()));
std::ostringstream Imessage;
if ((!ifdumpfields||timestep==c->n_max())&&if_dump_switches::ifdumpall==1)
{
clock_t timestart,timeend; //for timing
timestart=clock();
if (!MPIc->rank())
{
Imessage<<"\n"<<ENDFORMAT<<"IMPACT: Writing data\n|<";
int total=(2+2*c->Nf1()+c->Nf2()+c->NE()+c->NB())-2;
for (int i=0;i<total;++i)
Imessage<<"--";
Imessage<<">|\n";
std::cout<<Imessage.str();
}
std::string dir;
std::string name;
struct IMPACT_Moment ZM;
new_Constant(&Initial_Conditions::Z,c,MPIc,&ZM,"Z");
if (!timestep&&!MPIc->rank())
{
struct IMPACT_Moment niM;
new_Constant(&Initial_Conditions::ni,c,MPIc,&niM,"ni");
dir=IMPACT_Messages::Data_Directory+IMPACT_Messages::Constants_Dir;
if(if_dump_switches::dump_Z)
IMPACT_Write(&ZM,"Z_",dir,timestep);
if(if_dump_switches::dump_ni&&!IMPACTA_ions::ion_motion)
IMPACT_Write(&niM,"ni_",dir,timestep);
}
if (IMPACTA_ions::ion_motion&&!MPIc->rank())
{
struct IMPACT_Moment CiM;
for (int direc=0;direc<c->Nf1();++direc)
{
name = "C"; name+=getcoord(direc+1);
new_Constant(&Initial_Conditions::C_i[direc],c,MPIc,&CiM,name);
dir=IMPACT_Messages::Data_Directory+
IMPACT_Messages::Constants_Dir+name+"/";
name+="_";
if(if_dump_switches::dump_Ci)
IMPACT_Write(&CiM,name,dir,timestep);
}
struct IMPACT_Moment niM;
new_Constant(&Initial_Conditions::ni,c,MPIc,&niM,"ni");
dir=IMPACT_Messages::Data_Directory+
IMPACT_Messages::Constants_Dir+"ni/";
if(if_dump_switches::dump_ni)
IMPACT_Write(&niM,"ni_",dir,timestep);
struct IMPACT_Moment ZM;
new_Constant(&Initial_Conditions::Z,c,MPIc,&ZM,"Z");
dir=IMPACT_Messages::Data_Directory+
IMPACT_Messages::Constants_Dir+"Z/";
if(if_dump_switches::dump_Z)
IMPACT_Write(&ZM,"Z_",dir,timestep);
}
if (IMPACTA_ions::ionization_on&& !MPIc->rank()&&!IMPACTA_ions::ion_motion)
{
struct IMPACT_Moment ZM;
new_Constant(&Initial_Conditions::Z,c,MPIc,&ZM,"Z");
dir=IMPACT_Messages::Data_Directory+
IMPACT_Messages::Constants_Dir+"Z/";
if(if_dump_switches::dump_Z)
IMPACT_Write(&ZM,"Z_",dir,timestep);
}
//________________________________________________________________
//First output Moments
MPI::COMM_WORLD.Barrier();
struct IMPACT_Moment ne;
MPI::COMM_WORLD.Barrier();
new_ne(v,f0,c,MPIc,&ne);
struct IMPACT_Moment Ue;
MPI::COMM_WORLD.Barrier();
new_Ue(v,f0,c,MPIc,&Ue);
struct IMPACT_Moment Te=Divide(&Ue,&ne);
for (int i=1;i<=c->Nx();++i)
for (int j=1;j<=c->Ny();++j)
Te.values.set(i,j,Te.values.get(i,j)*2.0/3.0);
struct IMPACT_Moment eta;
MPI::COMM_WORLD.Barrier();
new_eta(v,f0,c,MPIc,&eta);
MPI::COMM_WORLD.Barrier();
struct IMPACT_Moment m05;
MPI::COMM_WORLD.Barrier();
new_m0five(v,f0,c,MPIc,&m05);
MPI::COMM_WORLD.Barrier();
struct IMPACT_Moment m03;
MPI::COMM_WORLD.Barrier();
new_m0three(v,f0,c,MPIc,&m03);
if (!MPIc->rank())
{
dir = IMPACT_Messages::Data_Directory+IMPACT_Messages::Moment_Dir;
if (if_dump_switches::dump_ne)
IMPACT_Write(&ne,"ne_",dir+"ne/",timestep);
std::cout<<BRED<<"[]";
if (if_dump_switches::dump_Ue)
IMPACT_Write(&Ue,"Ue_",dir+"Ue/",timestep);
std::cout<<BRED<<"[]";
IMPACT_Write(&m05,"m05_",dir+"Ue/",timestep);
IMPACT_Write(&m03,"m03_",dir+"Ue/",timestep);
if (if_dump_switches::dump_Te)
{
strcpy(Te.name,"T_e");
IMPACT_Write(&Te,"Te_",dir+"Te/",timestep);
// Ray Tracing Output
IMPACT_WriteInt("Int_",dir+"Te/",timestep);
}
if (if_dump_switches::dump_eta)
{
strcpy(eta.name,"eta");
IMPACT_Write(&eta,"eta_",dir+"eta/",timestep);
}
}
struct IMPACT_Moment je[3], q[3], VN[3];
if (c->Nf1()>0)
for (IMPACT_Dim x1=1;x1<=c->Nf1();++x1)
{
MPI::COMM_WORLD.Barrier();
new_je(v,f1,c,MPIc,&je[x1.get()-1],&x1);
name = "j"; name+=getcoord(x1.get());
if (!MPIc->rank())
{
if (if_dump_switches::dump_je)
IMPACT_Write(&je[x1.get()-1],name+"_",dir+name+"/",timestep);
std::cout<<BRED<<"[]";
}
MPI::COMM_WORLD.Barrier();
// Total heat flow
new_qT(v,f1,c,MPIc,&q[x1.get()-1],&x1);
name = "qT"; name+=getcoord(x1.get());
if (!MPIc->rank())
{
if (if_dump_switches::dump_q)
IMPACT_Write(&q[x1.get()-1],name+"_",dir+name+"/",timestep);
std::cout<<BRED<<"[]";
}
// Now dump intrinsic heat flow
for (int i=1;i<=c->Nx();++i)
for (int j=1;j<=c->Ny();++j)
q[x1.get()-1].values.set(i,j,q[x1.get()-1].values.get(i,j)
+1.25*je[x1.get()-1].values.get(i,j));
// end of loop!
name = "qe"; name+=getcoord(x1.get());
if (!MPIc->rank())
{
if (if_dump_switches::dump_q)
IMPACT_Write(&q[x1.get()-1],name+"_",dir+name+"/",timestep);
std::cout<<BRED<<"[]";
}
MPI::COMM_WORLD.Barrier();
// ve is electron flow velocity
struct IMPACT_Moment ve=Divide(&je[x1.get()-1],&ne);
MPI::COMM_WORLD.Barrier();
new_VN(v,f0,f1,c,MPIc,&VN[x1.get()-1],&x1);
for (int i=1;i<=c->Nx();++i)
for (int j=1;j<=c->Ny();++j){
VN[x1.get()-1].values.set(i,j,VN[x1.get()-1].values.get(i,j)+ve.values.get(i,j));
}
// end of loop!
name = "VN"; name+=getcoord(x1.get());
if (!MPIc->rank())
{
if (if_dump_switches::dump_VN)
IMPACT_Write(&VN[x1.get()-1],name+"_",dir+name+"/",timestep);
std::cout<<BRED<<"[]";
}
}
struct IMPACT_Moment P[5];
for (IMPACT_Dim x1=1;x1<=c->N3f2();++x1)
for (IMPACT_Dim x2=x1.get();x2<=c->N3f2();++x2)
if (x1.get()+x2.get()<6)
{
MPI::COMM_WORLD.Barrier();
new_P(v,f2,c,MPIc,&P[x1.get()+x2.get()-2],&x1,&x2);
name = "P"; name+=getcoord(x1.get());name+=getcoord(x2.get());
if (!MPIc->rank())
{
if (if_dump_switches::dump_P)
IMPACT_Write(&P[x1.get()+x2.get()-2],name+"_",dir+name+"/",timestep);
std::cout<<BRED<<"[]";
}
//________________________________________________________________
// NEW bit AGRT 2012 - eventually include in input deck but for now....
// This outputs nonlocal version of divP term in Ohm's law
std::string name2;
MPI::COMM_WORLD.Barrier();
new_divP(v,f0,f2,c,MPIc,&P[x1.get()+x2.get()-2],&x1,&x2);
name2 = "divP"; name2+=getcoord(x1.get());name2+=getcoord(x2.get());
if (!MPIc->rank())
{
if (if_dump_switches::dump_P)
IMPACT_Write(&P[x1.get()+x2.get()-2],name2+"_",dir+name+"/",timestep);
std::cout<<BRED<<"[]";
}
//________________________________________________________________
}
//________________________________________________________________
//Now output fields
dir = IMPACT_Messages::Data_Directory+IMPACT_Messages::Field_Dir;
struct IMPACT_Moment EM[3], BM[3];
if(c->NE()>0)
for (IMPACT_Dim x1=1;x1<=c->NE();++x1)
{
MPI::COMM_WORLD.Barrier();
new_E(v,E,c,MPIc,&EM[x1.get()-1],&x1);
name = "E"; name+=getcoord(x1.get());
if (!MPIc->rank())
{
if (if_dump_switches::dump_E)
IMPACT_Write(&EM[x1.get()-1],name+"_",dir+name+"/",timestep);
if (!MPIc->rank()) std::cout<<BRED<<"[]";
}
}
struct IMPACT_Moment wt;
double wt_temp=0.0;
if(c->NB()>0)
{
for (IMPACT_Dim x1=3;x1>3-c->NB();--x1)
{
MPI::COMM_WORLD.Barrier();
new_B(v,B,c,MPIc,&BM[x1.get()-1],&x1);
name = "B"; name+=getcoord(x1.get());
if (!MPIc->rank())
{
if (if_dump_switches::dump_B)
IMPACT_Write(&BM[x1.get()-1],name+"_",dir+name+"/",timestep);
if (!MPIc->rank()) std::cout<<BRED<<"[]";
}
}
if (if_dump_switches::dump_wt)
{
name = "wt";
IMPACT_Dim x1_temp(1);
new_B(v,B,c,MPIc,&wt,&x1_temp);
strcpy(wt.name,name.c_str());
dir = IMPACT_Messages::Data_Directory+IMPACT_Messages::Moment_Dir;
for (int i=1;i<=c->Nx();++i)
for (int j=1;j<=c->Ny();++j)
{
wt_temp=0.0;
for (IMPACT_Dim x1=3;x1>3-c->NB();--x1)
wt_temp+=BM[x1.get()-1].values.get(i,j)
*BM[x1.get()-1].values.get(i,j);
wt_temp=sqrt(wt_temp)/ne.values.get(i,j)/ZM.values.get(i,j);
wt_temp*=pow(Te.values.get(i,j),1.5)*3.0/4.0*sqrt(globalconsts::pi);
wt.values.set(i,j,wt_temp);
}
if (!MPIc->rank())
{
IMPACT_Write(&wt,name+"_",dir+name+"/",timestep);
}
}
}
// ****************************************
// New - now output complete distribution functions
if (!ifdumpdists) {
dir = IMPACT_Messages::Data_Directory+IMPACT_Messages::DistFunc_Dir;
if(if_dump_switches::dump_f0)
{
MPI::COMM_WORLD.Barrier();
IMPACT_Dist f0_out(c,0);
f0_out.fill(v,c,MPIc);
name = "f0";
if (!MPIc->rank())
{
IMPACT_Write(&f0_out,name+"_",dir+name+"/",timestep);}
}
if(if_dump_switches::dump_f1&&c->Nf1()>0)
{
MPI::COMM_WORLD.Barrier();
IMPACT_Dist f1_out(c,1);
f1_out.fill(v,c,MPIc);
name = "f1";
if (!MPIc->rank())
{
IMPACT_Write(&f1_out,name+"_",dir+name+"/",timestep);}
}
if(if_dump_switches::dump_f2&&c->Nf2()>0)
{
MPI::COMM_WORLD.Barrier();
IMPACT_Dist f2_out(c,2);
f2_out.fill(v,c,MPIc);
name = "f2";
if (!MPIc->rank())
{
IMPACT_Write(&f2_out,name+"_",dir+name+"/",timestep);}
}
}
// ****************************************
timeend=clock();
std::ostringstream Imessage2;
Imessage2<<"\n"<<ENDFORMAT<<"\nIMPACT: Data dump - Total time = "<<double(timeend-timestart)/CLOCKS_PER_SEC<<" s"<<std::endl<<ULINE;
if (!MPIc->rank()) std::cout<< Imessage2.str();
}
// Put back quantities to original values
IMPACTA_Rescale_T(c,MPIc,v,f0,f1,f2,f3,E,B,equation_switches::NEW_T_NORM);
}
<file_sep>/install.sh
#!/bin/sh
mkdir bin
mkdir tmp
printf "IMPACTA version control: \n\n" > version.txt
git log --pretty=format:'%h : %s' --graph >> version.txt
printf "\n\n (Archis made this)" >> version.txt
cd setup
make debug<file_sep>/include/impacta_functions/impacta_form_sparse.h
/*
**********************************************************
Fills sparse matrix from equations in IMPACTA code
Including boundary conditions and differential info
Version 1.0
AGRT
12/2/07
Notes:
20/2/07
Would be good to improve way matrix is packed - at the moment rudimentary
process of filling in row ParVec, then counting non zeros and
putting in sparse matrix
(see Matrix.h also)
22/2
"count" version counts number of non-zero elements
5/3
The count version should be eliminated at some point to make it
simpler to add in other equations - the outer equation form
can do the job easily enough, if modified.
8/3 Count made more efficient - so unlikely to b e able to eliminate
So much more efficient!! - in comparison, 0.9 s with new algorith,
I'm still waiting for the old one to finish under the same conditions!
9/4 - added switches to switch on and off different equations
these have required the addition of functions to ParSpa
12/4/07 - made slightly more efficient
15/4/07 - added IMPACT_Switch_Elements, which switches
off the diagonal elements in the solution matrix (for
switching off d/dt terms)
23/8/07 - Messages updated so that only the rank 0 processor counts.
25/9/07 - f1 equation RHS has grad f0 term added from gradn and T z
1/10/07 f0 equation RHS has grad f1 term added for self consistancy
6/10/07 - changed so that istart and iend cells are not at boundaries
- trying to solve boundary problems!
Note both these terms are from formula with no inertia terms
and ignoring f2
11/2/08 - minor change so that f2 depends on f0 through IB heating
13/3/08 - curl b term corrected on n side of equation
2/7/08 - Fixed boundaries implimented so that if chosen, don't
evolve relevent boundaries
jan 2011 - fixed bounds adjusted so that a bit more correct -
now boundary taken in 1 so effectively have ghost cells
**********************************************************
*/
// Check fixed boundaries,
inline int check_fixed(IMPACT_Config *c, int *boundx,int *boundy)
{
int answer=0;
if (*boundx>-1)
{
answer+=IMPACT_Boundaries::fixed_any[*boundx];
}
if (*boundy>-1)
{
answer+=IMPACT_Boundaries::fixed_any[*boundy];
}
return answer;
}
inline void equations_outer(IMPACT_Config *config1,IMPACT_ParVec *vlagged, IMPACT_ParVec *vtemp,IMPACT_ParSpa *S,IMPACT_StenOps * O, IMPACT_Var* f0,IMPACT_Var* f1,IMPACT_Var* f2,IMPACT_Var* f3,IMPACT_Var* E,IMPACT_Var* B,int *i,int *j, int *kmin,int *kmax);
//The code for equations inside boundaries
inline void equations_inner(IMPACT_Config *config1, IMPACT_ParVec *vlagged,IMPACT_ParVec *vtemp, IMPACT_ParSpa *S,IMPACT_StenOps * O, IMPACT_Var* f0,IMPACT_Var* f1,IMPACT_Var* f2,IMPACT_Var* f3,IMPACT_Var* E,IMPACT_Var* B,int *i,int *j)
{
int bx=-1,by=-1;
if (*i==2) bx = 0;
if (*i==(config1->Nx()-1)) bx = 1;
if (*j==2) by = 2;
if (*j==(config1->Ny()-1)) by = 3;
if (!check_fixed(config1,&bx,&by))
{
//___________________________________________________________
if (equation_switches::f0_equation_on)
for (int k=2;k<config1->Nv();++k)
{
f0equation_inner(config1,vlagged,vtemp,O,f0,E,B,f1,i,j,&k);
f0equation_Pack_inner(vtemp,S, config1,f0,f1,E,B,i,j,&k);
f0equation_clean_inner(vtemp, config1,O,f0,E,B,f1,i,j,&k);
}
else for (int k=2;k<config1->Nv();++k)
S->nullequation(config1,0,f0->getrow(i,j,&k));
//____________________________________________________________
//f1 equation now
if (config1->Nf1()>0)
for (IMPACT_Dim x1=1;x1<=config1->Nf1();++x1)
{
if (equation_switches::f1_equation_on)
for (int k=2;k<config1->Nv();++k)
{
f1equation_inner(config1,vlagged,vtemp,O,f0,E,B,f1,f2,i,j,&k,&x1);
f1equation_Pack_inner(vtemp,S, config1,f0,f1,f2,E,B,i,j,&k,&x1);
//This packs the completed ParVec
f1equation_clean_inner(vtemp, config1,O,f0,E,B,f1,f2,i,j,&k,&x1);
}
else for (int k=2;k<config1->Nv();++k)
S->nullequation(config1,1,f1->getrow(i,j,&k,&x1));
}
// f2 equation.....
if (config1->Nf2()>0)
for (IMPACT_Dim x1=1;x1<=config1->N3f2();++x1)
for (IMPACT_Dim x2=x1.get();x2<=config1->N3f2();++x2)
if (x1.get()+x2.get()<6)
{
if (equation_switches::f2_equation_on)
for (int k=2;k<config1->Nv();++k)
{
f2equation_inner(config1,vlagged,vtemp,O,f0,f1,f2,f3,E,B,
i,j,&k,&x1,&x2);
f2equation_Pack_inner(vtemp,S, config1,f0,f1,f2,f3,E,B,
i,j,&k,&x1,&x2);
//This packs the completed ParVec
f2equation_clean_inner(vtemp,config1,O,E,B,f0,f1,f2,f3,
i,j,&k,&x1,&x2);
}
else for (int k=2;k<config1->Nv();++k)
S->nullequation(config1,2,f2->getrow(i,j,&k,&x1,&x2));
}
//E equation now
if (config1->NE()>0)
for (IMPACT_Dim x1=1;x1<=config1->NE();++x1)
{
if (equation_switches::E_equation_on)
{
Eequation_inner(config1,vlagged,vtemp,O,E,B,f1,i,j,&x1);
Eequation_Pack_inner(vtemp,S, config1,f1,E,B,i,j,&x1);
//This packs the completed ParVec
vtemp->reset();
Eequation_clean_inner(vtemp, config1,O,E,B,f1,i,j,&x1);
}
else S->nullequation(config1,4,E->getrow(i,j,&x1));
}
//___________________________________________________________
// finally B equation.
if (config1->NB()>0)
for (IMPACT_Dim x1=3;x1>3-config1->NB();--x1)
{
if (equation_switches::B_equation_on)
{
Bequation_inner(config1,vlagged,vtemp,O,E,B,i,j,&x1);
Bequation_Pack_inner(vtemp,S, config1,E,B,i,j,&x1);
//S->Pack(vtemp,rownumber); //This packs the completed ParVec
Bequation_clean_inner(vtemp, config1,O,E,B,i,j,&x1);
}
else S->nullequation(config1,5,B->getrow(i,j,&x1));
}
//____________________________________________________________
} else {
int kmin=1;
int kmax=config1->Nv();
equations_outer(config1,vlagged, vtemp,S, O, f0,f1, f2, f3,E,B,i,j,&kmin,&kmax);
}
}
inline void equations_outer(IMPACT_Config *config1,IMPACT_ParVec *vlagged, IMPACT_ParVec *vtemp,IMPACT_ParSpa *S,IMPACT_StenOps * O, IMPACT_Var* f0,IMPACT_Var* f1,IMPACT_Var* f2,IMPACT_Var* f3,IMPACT_Var* E,IMPACT_Var* B,int *i,int *j, int *kmin,int *kmax)
{
int bx=-1,by=-1;
if (*i==1) bx = 0;
if (*i==config1->Nx()) bx = 1;
if (*j==1) by = 2;
if (*j==config1->Ny()) by = 3;
//___________________________________________________________
if (equation_switches::f0_equation_on&&!check_fixed(config1,&bx,&by))
for (int k = *kmin;k<=*kmax;++k)
{
f0equation_outer(config1,vlagged,vtemp,O,f0,E,B,f1,i,j,&k);
//S->Pack(vtemp,rownumber); //This packs the completed ParVec
f0equation_Pack_outer(vtemp,S, config1,f0,f1,E,B,i,j,&k);
f0equation_clean_outer(vtemp, config1,O,f0,E,B,f1,i,j,&k);
}
else for (int k = *kmin;k<=*kmax;++k)
S->nullequation(config1,0,f0->getrow(i,j,&k));
//____________________________________________________________
//f1 and E equations now
if (config1->Nf1()>0)
for (IMPACT_Dim x1=1;x1<=config1->Nf1();++x1)
{
if (equation_switches::f1_equation_on&&!check_fixed(config1,&bx,&by))
for (int k = *kmin;k<=*kmax;++k)
{
f1equation_outer(config1,vlagged,vtemp,O,f0,E,B,f1,f2,i,j,&k,&x1);
f1equation_Pack_outer(vtemp,S, config1,f0,f1,f2,E,B,i,j,&k,&x1);
//This packs the completed ParVec
f1equation_clean_outer(vtemp, config1,O,f0,E,B,f1,f2,i,j,&k,&x1);
}
else for (int k = *kmin;k <= *kmax;++k)
S->nullequation(config1,1,f1->getrow(i,j,&k,&x1));
}
// f2 equation.....
if (config1->Nf2()>0)
for (IMPACT_Dim x1=1;x1<=config1->N3f2();++x1)
for (IMPACT_Dim x2=x1.get();x2<=config1->N3f2();++x2)
if (x1.get()+x2.get()<6)
{
if (equation_switches::f2_equation_on&&!check_fixed(config1,&bx,&by))
for (int k = *kmin;k<=*kmax;++k)
{
f2equation_outer(config1,vlagged,vtemp,O,f0,f1,f2,f3,E,B,
i,j,&k,&x1,&x2);
f2equation_Pack_outer(vtemp,S, config1,f0,f1,f2,f3,E,B,
i,j,&k,&x1,&x2);
//This packs the completed ParVec
f2equation_clean_outer(vtemp,config1,O,E,B,f0,f1,f2,f3,
i,j,&k,&x1,&x2);
}
else for (int k = *kmin;k <= *kmax;++k)
S->nullequation(config1,2,f2->getrow(i,j,&k,&x1,&x2));
}
if (config1->NE()>0)
for (IMPACT_Dim x1=1;x1<=config1->NE();++x1)
{
if (equation_switches::E_equation_on&&!check_fixed(config1,&bx,&by))
{
Eequation_outer(config1,vlagged,vtemp,O,E,B,f1,i,j,&x1);
Eequation_Pack_outer(vtemp,S, config1,f1,E,B,i,j,&x1);
//This packs the completed ParVec
vtemp->reset();
Eequation_clean_outer(vtemp, config1,O,E,B,f1,i,j,&x1);
}
else S->nullequation(config1,4,E->getrow(i,j,&x1));
}
//___________________________________________________________
// finally B equation.
if (config1->NB()>0)
for (IMPACT_Dim x1=3;x1>3-config1->NB();--x1)
{
if (equation_switches::B_equation_on&&!check_fixed(config1,&bx,&by))
{
Bequation_outer(config1,vlagged,vtemp,O,E,B,i,j,&x1);
Bequation_Pack_outer(vtemp,S, config1,E,B,i,j,&x1);
//This packs the completed ParVec
Bequation_clean_outer(vtemp, config1,O,E,B,i,j,&x1);
}
else S->nullequation(config1,5,B->getrow(i,j,&x1));
}
//____________________________________________________________
}
inline void IMPACT_Form_Sparse(IMPACT_Config *config1, IMPACT_MPI_Config * MPIc,IMPACT_ParVec *vlagged, IMPACT_ParSpa *S,IMPACT_StenOps * O, IMPACT_Var* f0,IMPACT_Var* f1,IMPACT_Var* f2,IMPACT_Var* f3,IMPACT_Var* E,IMPACT_Var* B)
{
//vlagged - ParVec containing lagged data, S- sparse matrix
/*
This function packs the parts of the sparse
matrix S which are f0 equations
*/
int rank=MPIc->rank(),numprocs=MPIc->size();
double itemp;
int checker=1;
int istart=MPIc->istart();
int iend=MPIc->iend();
std::ostringstream Imessage("");
IMPACT_ParVec *vtemp; // temporary store of row elements
vtemp = new IMPACT_ParVec(vlagged->start(),vlagged->end()); // i.e. as long as the side of the matrix
vtemp->reset(); //This cleans up the temporary vectro for next use
/* _________________________________________________________
INNER CELLS
_________________________________________________________
simple - just doesn't test whether i-1 etc is outside area
*/
clock_t timestart_inner,timeend_inner; //for timing matrix count.
timestart_inner=clock();
MPI::COMM_WORLD.Barrier();
if (iend-istart>3&&!rank) Imessage<<ENDFORMAT<<"\nIMPACT: Building Sparse Matrix";
if (iend-istart>3&&numprocs==1) Imessage<<" (Inner loop)\n|<---------------->|";
if (!rank) Imessage<<'\n';
std::cout<<Imessage.str();
int mystart=istart,myend=iend;
if (rank==0) ++mystart;
if (rank==numprocs-1) --myend;
if (config1->Ny()>2&&config1->Nx()>2&&config1->Nv()>2)
for (int i=mystart;i<=myend;++i)
{
// No communication needed for these cells
for (int j=2;j<config1->Ny();++j)
{
equations_inner(config1, vlagged, vtemp, S, O, f0,f1, f2, f3,E,B,&i,&j);
}
itemp=(double) (i-istart)/(iend-istart-1)*10.1;
if ((int)itemp==checker&&numprocs==1)
{std::cout<<BRED<<"[]"<<ENDFORMAT;++checker;}
}
timeend_inner=clock();
/* _________________________________________________________
BOUNDARY CELLS
_________________________________________________________
Now we do boundary cells: These form a 3D box shell around
the inner cells. We will do first each plane A (6 planes), then the
wireframe line B (12 lines). (i.e. initially missing out the edge of
each plane) Then finally do the corner cells C (6 of them)
______
|\ \
| \ _____\ <- C
| | |
\ | A |<- B
\|______|
update 19/2/07
now the planes at i=1 and Nx are large (go to edges)
then j planes goes stops at i=2
FINALLY k planes stop at i=2 and j=2
*/
/*
first the i boundary planes
5/10/07 - Now not used!
*/
clock_t timestart_outer,timeend_outer; //for timing matrix count.
int kmin,kmax;
if (iend-istart>3&&numprocs==1) std::cout<<ENDFORMAT<<"\nIMPACT: Building Sparse Matrix (Outer loop)\n|<-->|\n";
else if (numprocs==1) std::cout<<ENDFORMAT<<"\nIMPACT: Building Sparse Matrix\n|<-->|\n";
timestart_outer=clock();
if (config1->Ny()>2&&config1->Nx()>2&&config1->Nv()>2)
{
if(rank==0||rank==numprocs-1)
for (int j=2;j<config1->Ny();++j)
{
kmin=1; kmax=config1->Nv();
if (rank==0)
{
int i=istart;
equations_outer(config1,vlagged, vtemp,S, O, f0,f1, f2, f3,
E,B,&i,&j,&kmin,&kmax);
}
if (rank==numprocs-1)
{
int i=iend;
equations_outer(config1,vlagged, vtemp,S, O, f0,f1, f2, f3,
E,B,&i,&j,&kmin,&kmax);
}
}
if (numprocs==1) std::cout<<BRED<<"[]"<<ENDFORMAT;
/*
now the j boundary planes
*/
for (int i=istart;i<=iend;++i)
{
kmin=1; kmax=config1->Nv();
int j=1;
equations_outer(config1,vlagged, vtemp,S, O, f0,f1, f2, f3,
E,B,&i,&j,&kmin,&kmax);
j=config1->Ny();
equations_outer(config1,vlagged, vtemp,S, O, f0,f1, f2, f3,
E,B,&i,&j,&kmin,&kmax);
}
if (numprocs==1) std::cout<<BRED<<"[]"<<ENDFORMAT;
/*
now the k boundary planes
*/
for (int i=istart;i<=iend;++i)
for (int j=2;j<config1->Ny();++j)
{
kmax=kmin=1;
equations_outer(config1,vlagged, vtemp,S, O, f0,f1, f2, f3,
E,B,&i,&j,&kmin,&kmax);
kmin=kmax=config1->Nv();
equations_outer(config1,vlagged, vtemp,S, O, f0,f1, f2, f3,
E,B,&i,&j,&kmin,&kmax);
}
if (numprocs==1) std::cout<<BRED<<"[]"<<ENDFORMAT;
}
if (config1->Ny()<3||config1->Nx()<3||config1->Nv()<3)
{
for (int i=istart;i<=iend;++i)
for (int j=1;j<=config1->Ny();++j)
{
kmin=1;
kmax=config1->Nv();
equations_outer(config1,vlagged, vtemp,S, O, f0,f1, f2, f3,
E,B,&i,&j,&kmin,&kmax);
}
}
delete vtemp;
timeend_outer=clock();
// MESSAGES
if (numprocs==1)
{
std::cout<< std::endl <<"IMPACT: Matrix Build - Inner Loop took "<<IMPACT_GetTime(double(timeend_inner-timestart_inner)/CLOCKS_PER_SEC)<<std::endl;
std::cout<<" Outer Loop took "<<IMPACT_GetTime(double(timeend_outer-timestart_outer)/CLOCKS_PER_SEC)<<std::endl;
std::cout<<ULINE;
}
std::ostringstream Imessage2;
Imessage2<<BYELLOW<<"\nIMPACT: Processor "<<rank<<" of "<<numprocs<<" Matrix Build - Total time = "<<IMPACT_GetTime(double(timeend_outer-timestart_inner)/CLOCKS_PER_SEC)<<ENDFORMAT;
if (!rank) Imessage2<<'\n'<<ULINE;
if (equation_switches::Cee0_on&&!rank)
{
Imessage2<<"\n(Average Chang-Cooper delta iterations = "<<IMPACT_Diagnostics::total_delta_its/IMPACT_Diagnostics::delta_times<<")\n";}
std::cout<<Imessage2.str();
IMPACT_Diagnostics::total_delta_its=IMPACT_Diagnostics::delta_times=0.0;
}
/*
This version of the function counts the non-zero elements to initialize the
sparse matrix
*/
inline void IMPACT_Form_Sparse_count(IMPACT_Config *config1, IMPACT_MPI_Config * MPIc,IMPACT_ParVec *vlagged, IMPACT_ParSpa *S,IMPACT_StenOps * O, IMPACT_Var* f0,IMPACT_Var* f1,IMPACT_Var* f2,IMPACT_Var* f3,IMPACT_Var* E,IMPACT_Var* B)
{
clock_t timestart,timeend; //for timing matrix count.
timestart=clock();
IMPACT_ParVec *vtemp; // temporary store of row elements
vtemp = new IMPACT_ParVec(vlagged->start(),vlagged->end()); // i.e. as long as the side of the matrix
vtemp->reset();
double itemp;
int checker=1;
int istart=MPIc->istart();
int iend=MPIc->iend();
int rank = MPIc->rank();
int numprocs=MPIc->size();
std::ostringstream Imessage("");
//As this only needs to
//int rownumber;
MPI::COMM_WORLD.Barrier();
if (!rank) Imessage<<ENDFORMAT<<"\nIMPACT: Counting maximum elements\n";
if (numprocs==1) Imessage<<"|<---------------->|\n";
std::cout<<Imessage.str();
for (int i=istart;i<=iend;++i)
{
for (int j=1;j<=config1->Ny();++j)
{
if (equation_switches::f0_equation_on)
{
//IMPACT_Update_Cee0_BC(config1,vlagged,f0,&i,&j);
for (int k=1;k<=config1->Nv();++k)
{
//___________________________________________________________
//f0 equation
f0equation_outer(config1,vlagged,vtemp,O,f0,E,B,f1,&i,&j,&k);
f0equation_count(vtemp,S,config1,f0,E,B,f1,&i,&j,&k);
f0equation_clean_outer(vtemp, config1,O,f0,E,B,f1,&i,&j,&k);
//____________________________________________________________
}
}
else for (int k=1;k<=config1->Nv();++k)
S->count_nullequation(config1,f0->getrow(&i,&j,&k));
//f1 and E equations now
if (config1->Nf1()>0)
for (IMPACT_Dim x1=1;x1<=config1->Nf1();++x1)
{
if (equation_switches::f1_equation_on)
for (int k=1;k<=config1->Nv();++k)
{
f1equation_outer(config1,vlagged,vtemp,O,f0,E,B,f1,f2,&i,&j,&k,&x1);
f1equation_count(vtemp,S,config1,f0,E,B,f1,f2,&i,&j,&k,&x1);
f1equation_clean_outer(vtemp, config1,O,f0,E,B,f1,f2,&i,&j,&k,&x1);
}
else for (int k=1;k<=config1->Nv();++k)
S->count_nullequation(config1,f1->getrow(&i,&j,&k,&x1));
}
//f2 equation
if (config1->Nf2()>0)
for (IMPACT_Dim x1=1;x1<=config1->N3f2();++x1)
for (IMPACT_Dim x2=x1.get();x2<=config1->N3f2();++x2)
if (x1.get()+x2.get()<6)
{
if (equation_switches::f2_equation_on)
for (int k=1;k<=config1->Nv();++k)
{
f2equation_outer(config1,vlagged,vtemp,O,f0,f1,f2,f3,E,B,
&i,&j,&k,&x1,&x2);
f2equation_count(vtemp,S,config1,f0,f1,E,B,f2,f3,&i,&j,&k,
&x1,&x2);
f2equation_clean_outer(vtemp,config1,O,E,B,f0,f1,f2,f3,
&i,&j,&k,&x1,&x2);
}
else for (int k=1;k<=config1->Nv();++k)
S->count_nullequation(config1,f2->getrow(&i,&j,&k,&x1,&x2));
}
if (config1->NE()>0)
for (IMPACT_Dim x1=1;x1<=config1->NE();++x1)
{
if (equation_switches::E_equation_on)
{
Eequation_outer(config1,vlagged,vtemp,O,E,B,f1,&i,&j,&x1);
Eequation_count(vtemp,S,config1,E,B,f1,&i,&j,&x1);
Eequation_clean_outer(vtemp, config1,O,E,B,f1,&i,&j,&x1);
vtemp->reset();
}
else S->count_nullequation(config1,E->getrow(&i,&j,&x1));
}
//___________________________________________________________
//finally B equation.
if (config1->NB()>0)
for (IMPACT_Dim x1=3;x1>3-config1->NB();--x1)
{
if (equation_switches::B_equation_on)
{
Bequation_outer(config1,vlagged,vtemp,O,E,B,&i,&j,&x1);
Bequation_count(vtemp,S,config1,E,B,&i,&j,&x1);
Bequation_clean_outer(vtemp, config1,O,E,B,&i,&j,&x1);
}
else S->count_nullequation(config1,B->getrow(&i,&j,&x1));
}
//____________________________________________________________
}
itemp=(double) (i-istart)/(iend-istart)*10.1;
if ((int)itemp==checker&&numprocs==1) {std::cout<<BRED<<"[]"<<ENDFORMAT;++checker;}
}
delete vtemp;
S->Resize(); //THIS IS IMPORTANT. Resizes the S vector and sorts out rowvector
timeend=clock();
// MESSAGES
std::ostringstream Imessage2("");
Imessage2<<ENDFORMAT<<"\nIMPACT: Processor "<<rank<<" of "<<numprocs<<" - Element Count took "<<IMPACT_GetTime(double(timeend-timestart)/CLOCKS_PER_SEC)<<" ";
Imessage2<<"-- Sparse Matrix memory reserved for "<<S->getSl()<<" elements";
if (!rank) Imessage2<<'\n';
std::cout<<Imessage2.str();
}
<file_sep>/include/impacta_equations/impacta_ionmotion.h
/*
**********************************************************
Ion motion package for IMPACT
Version 1.1
AGRT
2/7/08 - Fixed boundaries for ions added
22/2/08
jan 2011 - Added DCbyDt function - RHS of
DC/Dt in hydrodynamic equations, also used
in RHS of main kinetic equations (refer to
Thomas JCP 2011)
march 2011 - Added dZbydt - Z has to move too!
july 2011 - Added ion pressure to equation of motion!
**********************************************************
*/
void IMPACTA_Set_Ci(IMPACT_Config *c,double value)
{
if (IMPACTA_ions::ion_motion)
{
for (int i=(1+IMPACT_Boundaries::fixed_any[0]);i<=(c->Nx()-IMPACT_Boundaries::fixed_any[1]);++i)
for (int j=(1+IMPACT_Boundaries::fixed_any[2]);j<=(c->Ny()-IMPACT_Boundaries::fixed_any[3]);++j){
for (int dir=0;dir<3;++dir)
{
Initial_Conditions::C_i[dir].set(i,j,value);
}
Initial_Conditions::DivC_i.set(i,j,value);
}
}
}
void IMPACTA_Multiply_Ci(IMPACT_Config *c,double value)
{
if (IMPACTA_ions::ion_motion)
{
for (int i=(1+IMPACT_Boundaries::fixed_any[0]);i<=(c->Nx()-IMPACT_Boundaries::fixed_any[1]);++i)
for (int j=(1+IMPACT_Boundaries::fixed_any[2]);j<=(c->Ny()-IMPACT_Boundaries::fixed_any[3]);++j)
for (int dir=0;dir<3;++dir)
Initial_Conditions::C_i[dir].set(i,j,value*Initial_Conditions::C_i[dir].get(&i,&j));
}
}
void IMPACTA_Update_DivCi(IMPACT_Config *c, IMPACT_MPI_Config *M,
IMPACT_StenOps *O)
{
MPI::COMM_WORLD.Barrier();
//Now update DivC
int direc=0,iplus=0,iminus=0,jplus=0,jminus=0;
IMPACT_stencil temp_sten;
int istart=M->istart();
int iend=M->iend();
// New -> correct istart and iend for fixed boundaries:
if (istart==1) {
istart=(1+IMPACT_Boundaries::fixed_any[0]);
}
if (iend==c->Nx()) {
iend=(c->Nx()-IMPACT_Boundaries::fixed_any[1]);
}
bool uw = 0;
if (IMPACTA_ions::ion_motion)
for (int i=istart;i<=iend;++i)
for (int j=(1+IMPACT_Boundaries::fixed_any[2]);j<=(c->Ny()-IMPACT_Boundaries::fixed_any[3]);++j)
{
double divC=0.0;
for (IMPACT_Dim x1=1;x1<=3;++x1)
{
iplus=i+1,iminus=i-1,jplus=j+1,jminus=j-1;
direc=x1.get()-1;
uw = Initial_Conditions::C_i[direc].sign(&i,&j);
// temp_sten = (*O->ddxi_uw(&i,&j,&x1,uw));
temp_sten = (*O->ddxi(&i,&j,&x1));
IMPACT_Ci_bound(&temp_sten,c->Nx(),c->Ny(),&iplus,
&iminus,&jplus,&jminus,&x1);
divC+=Initial_Conditions::C_i[direc].get(&i,&j)
*temp_sten(0);
divC+=Initial_Conditions::C_i[direc].get(&iplus,&j)
*temp_sten(1);
divC+=Initial_Conditions::C_i[direc].get(&iminus,&j)
*temp_sten(2);
divC+=Initial_Conditions::C_i[direc].get(&i,&jplus)
*temp_sten(3);
divC+=Initial_Conditions::C_i[direc].get(&i,&jminus)
*temp_sten(4);
}
Initial_Conditions::DivC_i.set(i,j,divC);
}
MPI::COMM_WORLD.Barrier();
IMPACTA_Share_Moment(c,M, &Initial_Conditions::DivC_i);
}
// this is RHS of DU/Dt equation - refer to Thomas JCP 2011
double IMPACTA_DUbyDt(IMPACT_Config *c, IMPACT_MPI_Config *M,IMPACT_ParVec *v,
IMPACT_StenOps *O, IMPACT_Var *f0,IMPACT_Var *f1,
IMPACT_Var *f2,IMPACT_Var *E, IMPACT_Var *B,
int i, int j,IMPACT_Dim x1, int n_adjusted)
{
IMPACT_stencil temp_sten;
double gradp=0.0,jxb=0.0,EZnimne=0.0;
int dir=0;
double loc_ni=Initial_Conditions::ni.get(&i,&j);
double loc_Z=Initial_Conditions::Z.get(&i,&j);
int iplus=i+1,iminus=i-1,jplus=j+1,jminus=j-1;
int iplusni=iplus,iminusni=iminus; // these added because periodic conditions different for f and e.g. n,T,Z grids!!!
IMPACT_Dim x2,x3;
bool uw;
//-------------------------------------------------------
// +Grad p_e
uw = Initial_Conditions::C_i[x1.get()-1].sign(&i,&j);
// temp_sten = (*O->ddxi_uw(&i,&j,&x1,uw));
temp_sten = (*O->ddxi(&i,&j,&x1));
IMPACT_f0_bound(&temp_sten,c->Nx(),c->Ny(),&iplus,
&iminus,&jplus,&jminus);
IMPACT_ni_bound(&temp_sten,c->Nx(),c->Ny(),&iplusni,
&iminusni,&jplus,&jminus);
// here - added ion pressure also!
/*gradp=(Local_pe(v,f0,c,&i,&j)+IMPACTA_ions::ion_temperature*Initial_Conditions::ni.get(&i,&j))*temp_sten(0);
gradp+=(Local_pe(v,f0,c,&iplus,&j)+IMPACTA_ions::ion_temperature*Initial_Conditions::ni.get(&iplusni,&j))*temp_sten(1);
gradp+=(Local_pe(v,f0,c,&iminus,&j)+IMPACTA_ions::ion_temperature*Initial_Conditions::ni.get(&iminusni,&j))*temp_sten(2);
gradp+=(Local_pe(v,f0,c,&i,&jplus)+IMPACTA_ions::ion_temperature*Initial_Conditions::ni.get(&i,&jplus))*temp_sten(3);
gradp+=(Local_pe(v,f0,c,&i,&jminus)+IMPACTA_ions::ion_temperature*Initial_Conditions::ni.get(&i,&jminus))*temp_sten(4);
*/
gradp=(Local_pe(v,f0,c,&i,&j))*temp_sten(0);
gradp+=(Local_pe(v,f0,c,&iplus,&j))*temp_sten(1);
gradp+=(Local_pe(v,f0,c,&iminus,&j))*temp_sten(2);
gradp+=(Local_pe(v,f0,c,&i,&jplus))*temp_sten(3);
gradp+=(Local_pe(v,f0,c,&i,&jminus))*temp_sten(4);
//-------------------------------------------------------
// Divergence of anisotropic pressure
if (c->Nf2()>0)
for (IMPACT_Dim xa=1;xa<=3;++xa)
{
iplus=i+1,iminus=i-1,jplus=j+1,jminus=j-1;
// uw = Initial_Conditions::C_i[xa.get()-1].sign(&i,&j);
// temp_sten = (*O->ddxi_uw(&i,&j,&xa,uw));
temp_sten = (*O->ddxi(&i,&j,&xa));
IMPACT_f2_bound(&temp_sten,c->Nx(),c->Ny(),&iplus,
&iminus,&jplus,&jminus,&x1,&xa);
gradp+=Local_Pi(v,f2,c,&i,&j,&x1,&xa)*temp_sten(0);
gradp+=Local_Pi(v,f2,c,&iplus,&j,&x1,&xa)*temp_sten(1);
gradp+=Local_Pi(v,f2,c,&iminus,&j,&x1,&xa)*temp_sten(2);
gradp+=Local_Pi(v,f2,c,&i,&jplus,&x1,&xa)*temp_sten(3);
gradp+=Local_Pi(v,f2,c,&i,&jminus,&x1,&xa)*temp_sten(4);
}
//-------------------------------------------------------
if (dir==2)
{
gradp=(Local_Te(v,f0,c,&i,&j)*IMPACT_Heating::Dnz_xy.get(&i,&j)
*IMPACT_Heating::Dnz_t.Get(n_adjusted)
+Local_ne(v,f0,c,&i,&j)*IMPACT_Heating::DTz_xy.get(&i,&j)
*IMPACT_Heating::DTz_t.Get(n_adjusted));
}
//-------------------------------------------------------
//// +J x B
/// NEW 2011 AGRT -> +jxB instead of curl BxB
GetOrthogonal(&x1,&x2,&x3);
if (x3>3-c->NB()) {
jxb+=B->get(v,&i,&j,&x3)*Local_je(v,f1,c,&i,&j,&x2);
}
if (x2>3-c->NB()) {
jxb-=B->get(v,&i,&j,&x2)*Local_je(v,f1,c,&i,&j,&x3);
}
//-------------------------------------------------------
// +E(Zni-ne)
if (x1<=c->NE()) {
EZnimne=E->get(v,&i,&j,&x1)*(loc_Z*loc_ni-Local_ne(v,f0,c,&i,&j));
}
//-------------------------------------------------------
return (IMPACTA_ions::alpha_ion/loc_ni)*(EZnimne+jxb-gradp);
/*
old (pre 2011)
(((gradp+EZnimne)
+gradBsquared*IMPACTA_ions::a2bar)
*Initial_Conditions::Z.get(&i,&j));*/
}
void IMPACTA_Ci_Smooth(IMPACT_Config *c, IMPACT_MPI_Config *M,IMPACT_StenOps *O, int direc);
int IMPACTA_Update_Ci(IMPACT_Config *c, IMPACT_MPI_Config *M,IMPACT_ParVec *v,
IMPACT_StenOps *O, IMPACT_Var *f0,IMPACT_Var *f1,
IMPACT_Var *f2, IMPACT_Var *E, IMPACT_Var *B,int *n)
{
int istart=M->istart();
int iend=M->iend();
// New -> correct istart and iend for fixed boundaries:
if (istart==1) {
istart=(1+IMPACT_Boundaries::fixed_any[0]);
}
if (iend==c->Nx()) {
iend=(c->Nx()-IMPACT_Boundaries::fixed_any[1]);
}
IMPACT_stencil temp_sten;
int dir=0,fixcheck=0;
int n_adjusted=*n;
if (n_adjusted<1) n_adjusted=1;
double DUbyDt=0.0;
int iplus=2,iminus=0,jplus=2,jminus=0;
IMPACT_Dim x2,x3;
// First update C due to effects of thermal and magnetic pressure:
//________________________________________________________________________
// Contains smoothing effect!!!
if(!IMPACTA_ions::ion_motion) return 0;
for (dir=0;dir<3;++dir)
{
Initial_Conditions::C_istar[dir].copy(&Initial_Conditions::C_i[dir]);
}
for (IMPACT_Dim x1=1;x1<=3;++x1)
{
dir=x1.get()-1;
for (int i=istart;i<=iend;++i)
for (int j=(1+IMPACT_Boundaries::fixed_any[2]);j<=(c->Ny()-IMPACT_Boundaries::fixed_any[3]);++j)
{
fixcheck=0;
// check fixed bounds
if (i==1) fixcheck+=(IMPACT_Boundaries::fix_Ci[0]!=0.0);
if (i==c->Nx()) fixcheck+=(IMPACT_Boundaries::fix_Ci[1]!=0.0);
if (j==1) fixcheck+=(IMPACT_Boundaries::fix_Ci[2]!=0.0);
if (j==c->Ny()) fixcheck+=(IMPACT_Boundaries::fix_Ci[3]!=0.0);
DUbyDt = IMPACTA_DUbyDt(c,M,v,O,f0,f1,f2,E,B,i,j,x1,n_adjusted);
if (!fixcheck)
Initial_Conditions::C_istar[dir].set
(i,j,Initial_Conditions::C_i[dir].get(&i,&j)
+DUbyDt*c->dt());
else
Initial_Conditions::C_istar[dir].set
(i,j,Initial_Conditions::C_i[dir].get(&i,&j));
}
}
for (dir=0;dir<3;++dir)
{
Initial_Conditions::C_i[dir].copy(&Initial_Conditions::C_istar[dir]);
MPI::COMM_WORLD.Barrier();
IMPACTA_Share_Moment(c,M, &Initial_Conditions::C_i[dir]);
}
//________________________________________________________________________
// Next - advection at the bulk flow velocity
double deltaCistar=0.0;
int dirj=0;
bool uw;
for (IMPACT_Dim x1i=1;x1i<=3;++x1i)
{
dir=x1i.get()-1;
for (int i=istart;i<=iend;++i)
for (int j=(1+IMPACT_Boundaries::fixed_any[2]);j<=(c->Ny()-IMPACT_Boundaries::fixed_any[3]);++j)
{
fixcheck=0;
// check fixed bounds
if (i==1) fixcheck+=(IMPACT_Boundaries::fix_Ci[0]!=0.0);
if (i==c->Nx()) fixcheck+=(IMPACT_Boundaries::fix_Ci[1]!=0.0);
if (j==1) fixcheck+=(IMPACT_Boundaries::fix_Ci[2]!=0.0);
if (j==c->Ny()) fixcheck+=(IMPACT_Boundaries::fix_Ci[3]!=0.0);
deltaCistar=0.0;
for (IMPACT_Dim x1j=1;x1j<=3;++x1j)
{
iplus=i+1,iminus=i-1,jplus=j+1,jminus=j-1;
dirj=x1j.get()-1;
uw = Initial_Conditions::C_i[dir].sign(&i,&j);
//temp_sten = (*O->ddxi_uw(&i,&j,&x1j,uw));
temp_sten = (*O->ddxi(&i,&j,&x1j));
IMPACT_Ci_bound(&temp_sten,c->Nx(),c->Ny(),&iplus,
&iminus,&jplus,&jminus,&x1j);
deltaCistar+=Initial_Conditions::C_i[dir].get(&i,&j)
*Initial_Conditions::C_i[dirj].get(&i,&j)*temp_sten(0);
deltaCistar+=Initial_Conditions::C_i[dir].get(&i,&j)
*Initial_Conditions::C_i[dirj].get(&iplus,&j)*temp_sten(1);
deltaCistar+=Initial_Conditions::C_i[dir].get(&i,&j)
*Initial_Conditions::C_i[dirj].get(&iminus,&j)*temp_sten(2);
deltaCistar+=Initial_Conditions::C_i[dir].get(&i,&j)
*Initial_Conditions::C_i[dirj].get(&i,&jplus)*temp_sten(3);
deltaCistar+=Initial_Conditions::C_i[dir].get(&i,&j)
*Initial_Conditions::C_i[dirj].get(&i,&jminus)*temp_sten(4);
}//end of xj loop
if (!fixcheck)
Initial_Conditions::C_istar[dir].set
(i,j,Initial_Conditions::C_i[dir].get(&i,&j)-deltaCistar*c->dt());
else
Initial_Conditions::C_istar[dir].set
(i,j,Initial_Conditions::C_i[dir].get(&i,&j));
}//end of j loop
} // end of xi loop
for (dir=0;dir<3;++dir)
{
Initial_Conditions::C_i[dir].copy(&Initial_Conditions::C_istar[dir]);
MPI::COMM_WORLD.Barrier();
IMPACTA_Share_Moment(c,M, &Initial_Conditions::C_i[dir]);
}
/*// smooth Ci
for (int dir=0;dir<3;++dir)
{
IMPACTA_Ci_Smooth(c,M,O,dir);
}*/
//Finally update div Ci
IMPACTA_Update_DivCi(c,M,O);
return 0;
}// end of function
int IMPACTA_Update_ni(IMPACT_Config *c, IMPACT_MPI_Config *M,IMPACT_ParVec *v,
IMPACT_StenOps *O, IMPACT_Var *f0,int *n)
{
int istart=M->istart();
int iend=M->iend();
// New -> correct istart and iend for fixed boundaries:
if (istart==1) {
istart=(1+IMPACT_Boundaries::fixed_any[0]);
}
if (iend==c->Nx()) {
iend=(c->Nx()-IMPACT_Boundaries::fixed_any[1]);
}
int iplus=2,iminus=0,jplus=2,jminus=0,direc=0;
double gradni=0.0,divC=0.0,Citemp=0.0;
IMPACT_stencil temp_sten;
int fixcheck=0;
int n_adjusted=*n;
if (n_adjusted<1) n_adjusted=1;
if (!IMPACTA_ions::ion_motion) return 0;
Initial_Conditions::C_istar[0].copy(&Initial_Conditions::ni);
if (IMPACTA_ions::quasin_on) {
for (int i=istart;i<=iend;++i)
for (int j=(1+IMPACT_Boundaries::fixed_any[2]);j<=(c->Ny()-IMPACT_Boundaries::fixed_any[3]);++j)
{
//-------------------------------------------------------
// C.Grad ni
gradni=0.0;
fixcheck=0;
// check fixed bounds
if (i==1) fixcheck+=IMPACT_Boundaries::fix_ni[0];
if (i==c->Nx()) fixcheck+=IMPACT_Boundaries::fix_ni[1];
if (j==1) fixcheck+=IMPACT_Boundaries::fix_ni[2];
if (j==c->Ny()) fixcheck+=IMPACT_Boundaries::fix_ni[3];
Initial_Conditions::ni.set(i,j,Local_ne(v,f0,c,&i,&j)/Initial_Conditions::Z.get(&i,&j));
}
}
else
{
for (int i=istart;i<=iend;++i){
for (int j=(1+IMPACT_Boundaries::fixed_any[2]);j<=(c->Ny()-IMPACT_Boundaries::fixed_any[3]);++j)
{
//-------------------------------------------------------
// C.Grad ni
gradni=0.0;
fixcheck=0;
// check fixed bounds
if (i==1) fixcheck+=IMPACT_Boundaries::fix_ni[0];
if (i==c->Nx()) fixcheck+=IMPACT_Boundaries::fix_ni[1];
if (j==1) fixcheck+=IMPACT_Boundaries::fix_ni[2];
if (j==c->Ny()) fixcheck+=IMPACT_Boundaries::fix_ni[3];
for (IMPACT_Dim x1=1;x1<=3;++x1)
{
direc=x1.get()-1;
iplus=i+1,iminus=i-1,jplus=j+1,jminus=j-1;
temp_sten = (*O->ddxi(&i,&j,&x1));
IMPACT_ni_bound(&temp_sten,c->Nx(),c->Ny(),&iplus,
&iminus,&jplus,&jminus);
Citemp=Initial_Conditions::C_i[direc].get(&i,&j);
gradni+=Citemp*Initial_Conditions::ni.get(&i,&j)*temp_sten(0);
gradni+=Citemp*Initial_Conditions::ni.get(&iplus,&j)*temp_sten(1);
gradni+=Citemp*Initial_Conditions::ni.get(&iminus,&j)*temp_sten(2);
gradni+=Citemp*Initial_Conditions::ni.get(&i,&jplus)*temp_sten(3);
gradni+=Citemp*Initial_Conditions::ni.get(&i,&jminus)*temp_sten(4);
if (direc==2)
{
gradni=Citemp*IMPACT_Heating::Dnz_xy.get(&i,&j)
*IMPACT_Heating::Dnz_t.Get(n_adjusted);
}
}
//-------------------------------------------------------
// ni div C
divC=Initial_Conditions::DivC_i.get(&i,&j)
*Initial_Conditions::ni.get(&i,&j);
//-------------------------------------------------------
//using C_istar as a temporary store
if (!fixcheck)
Initial_Conditions::C_istar[0].set
(i,j,Initial_Conditions::ni.get(&i,&j)-(gradni+divC)*c->dt());
else
Initial_Conditions::C_istar[0].set
(i,j,Initial_Conditions::ni.get(&i,&j));
}
}
Initial_Conditions::ni.copy(&Initial_Conditions::C_istar[0]);
}
MPI::COMM_WORLD.Barrier();
IMPACTA_Share_Moment(c,M, &Initial_Conditions::ni);
return 0;
}
// This advects the charge state (but assumes Z is incompressible quantity - dZ/dt=0
int IMPACTA_Update_Z(IMPACT_Config *c, IMPACT_MPI_Config *M,IMPACT_ParVec *v,
IMPACT_StenOps *O, IMPACT_Var *f0,int *n)
{
int istart=M->istart();
int iend=M->iend();
// New -> correct istart and iend for fixed boundaries:
if (istart==1) {
istart=(1+IMPACT_Boundaries::fixed_any[0]);
}
if (iend==c->Nx()) {
iend=(c->Nx()-IMPACT_Boundaries::fixed_any[1]);
}
int iplus=2,iminus=0,jplus=2,jminus=0,direc=0;
double gradni=0.0,Citemp=0.0;
IMPACT_stencil temp_sten;
int fixcheck=0;
int n_adjusted=*n;
if (n_adjusted<1) n_adjusted=1;
if (!IMPACTA_ions::ion_motion) return 0;
Initial_Conditions::C_istar[0].copy(&Initial_Conditions::Z);
for (int i=istart;i<=iend;++i)
for (int j=(1+IMPACT_Boundaries::fixed_any[2]);j<=(c->Ny()-IMPACT_Boundaries::fixed_any[3]);++j)
{
//-------------------------------------------------------
// C.Grad ni
gradni=0.0;
fixcheck=0;
// check fixed bounds
if (i==1) fixcheck+=IMPACT_Boundaries::fix_ni[0];
if (i==c->Nx()) fixcheck+=IMPACT_Boundaries::fix_ni[1];
if (j==1) fixcheck+=IMPACT_Boundaries::fix_ni[2];
if (j==c->Ny()) fixcheck+=IMPACT_Boundaries::fix_ni[3];
bool uw;
for (IMPACT_Dim x1=1;x1<=3;++x1)
{
direc=x1.get()-1;
iplus=i+1,iminus=i-1,jplus=j+1,jminus=j-1;
uw = Initial_Conditions::C_i[direc].sign(&i,&j);
// temp_sten = (*O->ddxi_uw(&i,&j,&x1,uw));
temp_sten = (*O->ddxi(&i,&j,&x1));
IMPACT_ni_bound(&temp_sten,c->Nx(),c->Ny(),&iplus,
&iminus,&jplus,&jminus);
Citemp=Initial_Conditions::C_i[direc].get(&i,&j);
gradni+=Citemp*Initial_Conditions::Z.get(&i,&j)*temp_sten(0);
gradni+=Citemp*Initial_Conditions::Z.get(&iplus,&j)*temp_sten(1);
gradni+=Citemp*Initial_Conditions::Z.get(&iminus,&j)*temp_sten(2);
gradni+=Citemp*Initial_Conditions::Z.get(&i,&jplus)*temp_sten(3);
gradni+=Citemp*Initial_Conditions::Z.get(&i,&jminus)*temp_sten(4);
if (direc==2)
{
gradni=Citemp*IMPACT_Heating::Dnz_xy.get(&i,&j)
*IMPACT_Heating::Dnz_t.Get(n_adjusted);
}
}
//-------------------------------------------------------
//using C_istar as a temporary store
if (!fixcheck)
Initial_Conditions::C_istar[0].set
(i,j,Initial_Conditions::Z.get(&i,&j)-(gradni)*c->dt());
else
Initial_Conditions::C_istar[0].set
(i,j,Initial_Conditions::Z.get(&i,&j));
}
Initial_Conditions::Z.copy(&Initial_Conditions::C_istar[0]);
MPI::COMM_WORLD.Barrier();
IMPACTA_Share_Moment(c,M, &Initial_Conditions::Z);
return 0;
}
void IMPACTA_Ci_Smooth(IMPACT_Config *c, IMPACT_MPI_Config *M,
IMPACT_StenOps *O, int direc)
{
MPI::COMM_WORLD.Barrier();
//Now update DivC
int iplus=0,iminus=0,jplus=0,jminus=0;
IMPACT_stencil temp_sten;
int istart=M->istart();
int iend=M->iend();
// New -> correct istart and iend for fixed boundaries:
if (istart==1) {
istart=(1+IMPACT_Boundaries::fixed_any[0]);
}
if (iend==c->Nx()) {
iend=(c->Nx()-IMPACT_Boundaries::fixed_any[1]);
}
IMPACT_Dim x1(direc);
if (IMPACTA_ions::ion_motion)
{
for (int i=istart;i<=iend;++i)
for (int j=(1+IMPACT_Boundaries::fixed_any[2]);j<=(c->Ny()-IMPACT_Boundaries::fixed_any[3]);++j)
{
double divC=0.0;
iplus=i+1,iminus=i-1,jplus=j+1,jminus=j-1;
temp_sten = LAX;
IMPACT_Ci_bound(&temp_sten,c->Nx(),c->Ny(),&iplus,
&iminus,&jplus,&jminus,&x1);
divC+=Initial_Conditions::C_i[direc].get(&i,&j)
*temp_sten(0);
divC+=Initial_Conditions::C_i[direc].get(&iplus,&j)
*temp_sten(1);
divC+=Initial_Conditions::C_i[direc].get(&iminus,&j)
*temp_sten(2);
divC+=Initial_Conditions::C_i[direc].get(&i,&jplus)
*temp_sten(3);
divC+=Initial_Conditions::C_i[direc].get(&i,&jminus)
*temp_sten(4);
Initial_Conditions::C_istar[direc].set(i,j,divC);
}
MPI::COMM_WORLD.Barrier();
IMPACTA_Share_Moment(c,M, &Initial_Conditions::C_istar[direc]);
Initial_Conditions::C_i[direc].copy(&Initial_Conditions::C_istar[direc]);
}
}
<file_sep>/include/impacta_functions/impacta_cleanvector.h
/*
**********************************************************
Code for setting appropriate elements in v to zero
NOTE -WHEN f2 added need to modify f1 clean equation!!!
Version IMPACTA 1.1
AGRT
6/3/07
8/3/07 - Updated so that there exists a zero checking version
for debugging - it checks that v really has been zeroed.
13/3/07 - Boundary code updated in line for the parallel version.
11/2/08 - updated to include IB heating in f2 equation
24/2/08 - updated to include ion motion in f0 equation
**********************************************************
*/
// EFFICIENT ZEROING OF MATRIX ELEMENTS
inline void IMPACT_Var::clean(IMPACT_ParVec * v,IMPACT_Config *config1, IMPACT_StenOps * O,int *i, int *j, int *k) // for f0
{
int iplus=*i+1,iminus=*i-1,jplus=*j+1,jminus=*j-1;
for (int kk=*k-1;kk<=*k+1;++kk)
{
// int kk=*k;
set(v,0.0,&iplus,j,&kk);
set(v,0.0,&iminus,j,&kk);
set(v,0.0,i,&jplus,&kk);
set(v,0.0,i,&jminus,&kk);
}
for (int kk=1;kk<=config1->Nv();++kk)
set(v,0.0,i,j,&kk);
}
inline void IMPACT_Var::clean(IMPACT_ParVec * v,IMPACT_Config *config1, IMPACT_StenOps * O,int *i, int *j, int *k, IMPACT_Dim * x1) //for f1
{
int iplus=*i+1,iminus=*i-1,jplus=*j+1,jminus=*j-1;
set(v,0.0,&iplus,j,k,x1);
set(v,0.0,&iminus,j,k,x1);
set(v,0.0,i,&jplus,k,x1);
set(v,0.0,i,&jminus,k,x1);
for (int kk=1;kk<=config1->Nv();++kk)
set(v,0.0,i,j,&kk,x1);
}
inline void IMPACT_Var::clean(IMPACT_ParVec * v,IMPACT_Config *config1, IMPACT_StenOps * O,int *i, int *j, IMPACT_Dim* x1) // for E/B
{
int iplus=*i+1,iminus=*i-1,jplus=*j+1,jminus=*j-1;
set(v,0.0,i,j,x1);
set(v,0.0,&iplus,j,x1);
set(v,0.0,&iminus,j,x1);
set(v,0.0,i,&jplus,x1);
set(v,0.0,i,&jminus,x1);
}
inline void IMPACT_Var::clean(IMPACT_ParVec * v,IMPACT_Config *config1, IMPACT_StenOps * O,int *i, int *j, int *k, int *index) //for f2
{
int iplus=*i+1,iminus=*i-1,jplus=*j+1,jminus=*j-1;
set(v,0.0,&iplus,j,k,index);
set(v,0.0,&iminus,j,k,index);
set(v,0.0,i,&jplus,k,index);
set(v,0.0,i,&jminus,k,index);
set(v,0.0,i,j,k,index);
}
inline void IMPACT_Var::clean(IMPACT_ParVec * v,IMPACT_Config *config1, IMPACT_StenOps * O,int *i, int *j, int *k, IMPACT_Dim *x1, IMPACT_Dim *x2) //for f2
{
int iplus=*i+1,iminus=*i-1,jplus=*j+1,jminus=*j-1;
set(v,0.0,&iplus,j,k,x1,x2);
set(v,0.0,&iminus,j,k,x1,x2);
set(v,0.0,i,&jplus,k,x1,x2);
set(v,0.0,i,&jminus,k,x1,x2);
set(v,0.0,i,j,k,x1,x2);
}
inline void IMPACT_Var::cleanouter(IMPACT_ParVec * v,IMPACT_Config *config1, IMPACT_StenOps * O,int *i, int *j, int *k) // for f0
{
int iplus=*i+1,iminus=*i-1,jplus=*j+1,jminus=*j-1,kplus=*k+1,kminus=*k-1;
//chk_ij(c,&iplus,&jplus);
//chk_ij(c,&iminus,&jminus);
chk_j(config1,&jplus,&jminus);
if (kminus<1) ++kminus;
if (kplus>config1->Nv()) --kplus;
for (int kk=kminus;kk<=kplus;++kk)
{
//int kk=*k;
set(v,0.0,&iplus,j,&kk);
set(v,0.0,&iminus,j,&kk);
set(v,0.0,i,&jplus,&kk);
set(v,0.0,i,&jminus,&kk);
}
for (int kk=1;kk<=config1->Nv();++kk)
set(v,0.0,i,j,&kk);
}
inline void IMPACT_Var::cleanouter(IMPACT_ParVec * v,IMPACT_Config *config1, IMPACT_StenOps * O,int *i, int *j, int *k, IMPACT_Dim * x1) //for f1
{
int iplus=*i+1,iminus=*i-1,jplus=*j+1,jminus=*j-1;
//chk_ij(c,&iplus,&jplus);
//chk_ij(c,&iminus,&jminus);
chk_j(config1,&jplus,&jminus);
set(v,0.0,&iplus,j,k,x1);
set(v,0.0,&iminus,j,k,x1);
set(v,0.0,i,&jplus,k,x1);
set(v,0.0,i,&jminus,k,x1);
for (int kk=1;kk<=config1->Nv();++kk)
set(v,0.0,i,j,&kk,x1);
}
inline void IMPACT_Var::cleanouter(IMPACT_ParVec * v,IMPACT_Config *config1, IMPACT_StenOps * O,int *i, int *j, IMPACT_Dim* x1) // for E/B
{
int iplus=*i+1,iminus=*i-1,jplus=*j+1,jminus=*j-1;
//chk_ij(c,&iplus,&jplus);
//chk_ij(c,&iminus,&jminus);
chk_j(config1,&jplus,&jminus);
set(v,0.0,i,j,x1);
set(v,0.0,&iplus,j,x1);
set(v,0.0,&iminus,j,x1);
set(v,0.0,i,&jplus,x1);
set(v,0.0,i,&jminus,x1);
set(v,0.0,&iplus,&jplus,x1);
set(v,0.0,&iminus,&jplus,x1);
set(v,0.0,&iplus,&jminus,x1);
set(v,0.0,&iminus,&jminus,x1);
}
inline void IMPACT_Var::cleanouter(IMPACT_ParVec * v,IMPACT_Config *config1,
IMPACT_StenOps * O,int *i, int *j, int *k,
int *index) //for f2
{
int iplus=*i+1,iminus=*i-1,jplus=*j+1,jminus=*j-1;
chk_j(config1,&jplus,&jminus);
set(v,0.0,&iplus,j,k,index);
set(v,0.0,&iminus,j,k,index);
set(v,0.0,i,&jplus,k,index);
set(v,0.0,i,&jminus,k,index);
set(v,0.0,i,j,k,index);
// New bits for Weibel damping
set(v,0.0,&iplus,&jplus,k,index);
set(v,0.0,&iminus,&jplus,k,index);
set(v,0.0,&iplus,&jminus,k,index);
set(v,0.0,&iminus,&jminus,k,index);
}
inline void IMPACT_Var::cleanouter(IMPACT_ParVec * v,IMPACT_Config *config1, IMPACT_StenOps * O,int *i, int *j, int *k, IMPACT_Dim *x1, IMPACT_Dim *x2) //for f2
{
int iplus=*i+1,iminus=*i-1,jplus=*j+1,jminus=*j-1;
chk_j(config1,&jplus,&jminus);
set(v,0.0,&iplus,j,k,x1,x2);
set(v,0.0,&iminus,j,k,x1,x2);
set(v,0.0,i,&jplus,k,x1,x2);
set(v,0.0,i,&jminus,k,x1,x2);
set(v,0.0,i,j,k,x1,x2);
// New bits for Weibel damping
set(v,0.0,&iplus,&jplus,k,x1,x2);
set(v,0.0,&iminus,&jplus,k,x1,x2);
set(v,0.0,&iplus,&jplus,k,x1,x2);
set(v,0.0,&iminus,&jminus,k,x1,x2);
}
inline void vzerochk(IMPACT_ParVec *v) //checks v is actually zero throughout.
{
double check=fabs(v->VecSum());
if (check>0.0)
{
std::cout<<"IMPACT: ERROR - Vector not correctly zeroed."<<std::endl;
exit(0);
}
}
namespace with_zero_vector_checking
{
int withzerovectorchecking=1;
inline void f0equation_clean_outer(IMPACT_ParVec * vtemp, IMPACT_Config *c, IMPACT_StenOps * O,IMPACT_Var* f0,IMPACT_Var* E,IMPACT_Var * B,IMPACT_Var* f1,int *i,int *j,int *k)
{
f0->cleanouter(vtemp,c,O,i,j,k);
if (c->NE()>0)
for (IMPACT_Dim x1=1;x1<=c->NE();++x1)
E->cleanouter(vtemp,c,O,i,j,&x1);
for (IMPACT_Dim x2=3;x2>3-c->NB();--x2)
B->cleanouter(vtemp,c,O,i,j,&x2);
for (IMPACT_Dim x1=1;x1<=c->Nf1();++x1)
f1->cleanouter(vtemp,c,O,i,j,k,&x1);
vzerochk(vtemp);
}
inline void f0equation_clean_inner(IMPACT_ParVec * vtemp, IMPACT_Config *c, IMPACT_StenOps * O,IMPACT_Var* f0,IMPACT_Var* E,IMPACT_Var * B,IMPACT_Var* f1,int *i,int *j,int *k)
{
f0->clean(vtemp,c,O,i,j,k);
if (c->NE()>0)
for (IMPACT_Dim x1=1;x1<=c->NE();++x1)
E->clean(vtemp,c,O,i,j,&x1);
for (IMPACT_Dim x2=3;x2>3-c->NB();--x2)
B->clean(vtemp,c,O,i,j,&x2);
for (IMPACT_Dim x1=1;x1<=c->Nf1();++x1)
f1->clean(vtemp,c,O,i,j,k,&x1);
vzerochk(vtemp);
}
inline void f1equation_clean_outer(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O, IMPACT_Var* f0,IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f1,IMPACT_Var* f2,int* i,int *j,int *k,IMPACT_Dim *x1)
{
f0->cleanouter(vtemp,c,O,i,j,k);
if (c->NE()>0)
for (IMPACT_Dim x2=1;x2<=c->NE();++x2)
E->cleanouter(vtemp,c,O,i,j,&x2);
for (IMPACT_Dim x2=1;x2<=c->Nf1();++x2)
f1->cleanouter(vtemp,c,O,i,j,k,&x2);
for (IMPACT_Dim x2=3;x2>3-c->NB();--x2)
B->cleanouter(vtemp,c,O,i,j,&x2);
if (c->Nf2()>0)
for (int pos=0;pos<c->Nf2();++pos)
f2->cleanouter(vtemp,c,O,i,j,k,&pos);
vzerochk(vtemp);
}
inline void f1equation_clean_inner(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O, IMPACT_Var* f0,IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f1,IMPACT_Var* f2,int* i,int *j,int *k,IMPACT_Dim *x1)
{
f0->clean(vtemp,c,O,i,j,k);
if (c->NE()>0)
for (IMPACT_Dim x2=1;x2<=c->NE();++x2)
E->clean(vtemp,c,O,i,j,&x2);
for (IMPACT_Dim x2=1;x2<=c->Nf1();++x2)
f1->clean(vtemp,c,O,i,j,k,&x2);
for (IMPACT_Dim x2=3;x2>3-c->NB();--x2)
B->clean(vtemp,c,O,i,j,&x2);
if (c->Nf2()>0)
for (int pos=0;pos<c->Nf2();++pos)
f2->clean(vtemp,c,O,i,j,k,&pos);
vzerochk(vtemp);
}
inline void f2equation_clean_outer(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O, IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f0,IMPACT_Var* f1,IMPACT_Var* f2,IMPACT_Var* f3,int* i,int *j,int *k,IMPACT_Dim *x1,IMPACT_Dim *x2)
{
f0->cleanouter(vtemp,c,O,i,j,k);
if (c->Nf2()>0)
for (int pos=0;pos<c->Nf2();++pos)
f2->cleanouter(vtemp,c,O,i,j,k,&pos);
if (c->Nf1()>0)
for (IMPACT_Dim x3=1;x3<=c->Nf1();++x3)
f1->cleanouter(vtemp,c,O,i,j,k,&x3);
for (IMPACT_Dim x3=1;x3<=c->NE();++x3)
E->cleanouter(vtemp,c,O,i,j,&x3);
for (IMPACT_Dim x3=3;x3>3-c->NB();--x3)
B->cleanouter(vtemp,c,O,i,j,&x3);
vzerochk(vtemp);
}
inline void f2equation_clean_inner(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O, IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f0,IMPACT_Var* f1,IMPACT_Var* f2,IMPACT_Var* f3,int* i,int *j,int *k,IMPACT_Dim *x1,IMPACT_Dim *x2)
{
f0->clean(vtemp,c,O,i,j,k);
if (c->Nf2()>0)
for (int pos=0;pos<c->Nf2();++pos)
f2->cleanouter(vtemp,c,O,i,j,k,&pos);
if (c->Nf1()>0)
for (IMPACT_Dim x3=1;x3<=c->Nf1();++x3)
f1->clean(vtemp,c,O,i,j,k,&x3);
for (IMPACT_Dim x3=1;x3<=c->NE();++x3)
E->clean(vtemp,c,O,i,j,&x3);
for (IMPACT_Dim x3=3;x3>3-c->NB();--x3)
B->clean(vtemp,c,O,i,j,&x3);
vzerochk(vtemp);
}
inline void Bequation_clean_outer(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O,IMPACT_Var* E,IMPACT_Var* B,int* i,int *j,IMPACT_Dim *x1)
{
B->cleanouter(vtemp,c,O,i,j,x1);
if (c->NE()>0)
for (IMPACT_Dim x2=1;x2<=c->NE();++x2)
E->cleanouter(vtemp,c,O,i,j,&x2);
vzerochk(vtemp);
}
inline void Bequation_clean_inner(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O,IMPACT_Var* E,IMPACT_Var* B,int* i,int *j,IMPACT_Dim *x1)
{
B->clean(vtemp,c,O,i,j,x1);
if (c->NE()>0)
for (IMPACT_Dim x2=1;x2<=c->NE();++x2)
E->clean(vtemp,c,O,i,j,&x2);
vzerochk(vtemp);
}
inline void Eequation_clean_outer(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O,IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f1,int* i,int *j,IMPACT_Dim *x1)
{
int ktemp=1;
if (c->NE()>0)
for (IMPACT_Dim x2=1;x2<=c->NE();++x2)
E->cleanouter(vtemp,c,O,i,j,&x2);
f1->cleanouter(vtemp,c,O,i,j,&ktemp,x1);
if (c->NB()>0)
for (IMPACT_Dim x2=3;x2>3-c->NB();--x2)
B->cleanouter(vtemp,c,O,i,j,&x2);
vzerochk(vtemp);
}
inline void Eequation_clean_inner(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O,IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f1,int* i,int *j,IMPACT_Dim *x1)
{
int ktemp=1;
if (c->NE()>0)
for (IMPACT_Dim x2=1;x2<=c->NE();++x2)
E->cleanouter(vtemp,c,O,i,j,&x2);
f1->clean(vtemp,c,O,i,j,&ktemp,x1);
if (c->NB()>0)
for (IMPACT_Dim x2=3;x2>3-c->NB();--x2)
B->clean(vtemp,c,O,i,j,&x2);
vzerochk(vtemp);
}
}
namespace no_zero_vector_checking
{
int withzerovectorchecking=0;
inline void f0equation_clean_outer(IMPACT_ParVec * vtemp, IMPACT_Config *c, IMPACT_StenOps * O,IMPACT_Var* f0,IMPACT_Var* E,IMPACT_Var * B,IMPACT_Var* f1,int *i,int *j,int *k)
{
f0->cleanouter(vtemp,c,O,i,j,k);
if (c->NE()>0)
for (IMPACT_Dim x1=1;x1<=c->NE();++x1)
E->cleanouter(vtemp,c,O,i,j,&x1);
for (IMPACT_Dim x2=3;x2>3-c->NB();--x2)
B->cleanouter(vtemp,c,O,i,j,&x2);
for (IMPACT_Dim x1=1;x1<=c->Nf1();++x1)
f1->cleanouter(vtemp,c,O,i,j,k,&x1);
}
inline void f0equation_clean_inner(IMPACT_ParVec * vtemp, IMPACT_Config *c, IMPACT_StenOps * O,IMPACT_Var* f0,IMPACT_Var* E,IMPACT_Var * B,IMPACT_Var* f1,int *i,int *j,int *k)
{
f0->clean(vtemp,c,O,i,j,k);
if (c->NE()>0)
for (IMPACT_Dim x1=1;x1<=c->NE();++x1)
E->clean(vtemp,c,O,i,j,&x1);
for (IMPACT_Dim x2=3;x2>3-c->NB();--x2)
B->clean(vtemp,c,O,i,j,&x2);
for (IMPACT_Dim x1=1;x1<=c->Nf1();++x1)
f1->clean(vtemp,c,O,i,j,k,&x1);
}
inline void f1equation_clean_outer(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O, IMPACT_Var* f0,IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f1,IMPACT_Var* f2,int* i,int *j,int *k,IMPACT_Dim *x1)
{
f0->cleanouter(vtemp,c,O,i,j,k);
if (c->NE()>0)
for (IMPACT_Dim x2=1;x2<=c->NE();++x2)
E->cleanouter(vtemp,c,O,i,j,&x2);
for (IMPACT_Dim x2=1;x2<=c->Nf1();++x2)
f1->cleanouter(vtemp,c,O,i,j,k,&x2);
for (IMPACT_Dim x2=3;x2>3-c->NB();--x2)
B->cleanouter(vtemp,c,O,i,j,&x2);
if (c->Nf2()>0)
for (int pos=0;pos<c->Nf2();++pos)
f2->cleanouter(vtemp,c,O,i,j,k,&pos);
}
inline void f1equation_clean_inner(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O, IMPACT_Var* f0,IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f1,IMPACT_Var* f2,int* i,int *j,int *k,IMPACT_Dim *x1)
{
f0->clean(vtemp,c,O,i,j,k);
if (c->NE()>0)
for (IMPACT_Dim x2=1;x2<=c->NE();++x2)
E->clean(vtemp,c,O,i,j,&x2);
for (IMPACT_Dim x2=1;x2<=c->Nf1();++x2)
f1->clean(vtemp,c,O,i,j,k,&x2);
for (IMPACT_Dim x2=3;x2>3-c->NB();--x2)
B->clean(vtemp,c,O,i,j,&x2);
if (c->Nf2()>0)
for (int pos=0;pos<c->Nf2();++pos)
f2->clean(vtemp,c,O,i,j,k,&pos);
}
inline void f2equation_clean_outer(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O, IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f0,IMPACT_Var* f1,IMPACT_Var* f2,IMPACT_Var* f3,int* i,int *j,int *k,IMPACT_Dim *x1,IMPACT_Dim *x2)
{
f0->cleanouter(vtemp,c,O,i,j,k);
if (c->Nf2()>0)
for (int pos=0;pos<c->Nf2();++pos)
f2->cleanouter(vtemp,c,O,i,j,k,&pos);
if (c->Nf1()>0)
for (IMPACT_Dim x3=1;x3<=c->Nf1();++x3)
f1->cleanouter(vtemp,c,O,i,j,k,&x3);
for (IMPACT_Dim x3=1;x3<=c->NE();++x3)
E->cleanouter(vtemp,c,O,i,j,&x3);
for (IMPACT_Dim x3=3;x3>3-c->NB();--x3)
B->cleanouter(vtemp,c,O,i,j,&x3);
}
inline void f2equation_clean_inner(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O, IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f0,IMPACT_Var* f1,IMPACT_Var* f2,IMPACT_Var* f3,int* i,int *j,int *k,IMPACT_Dim *x1,IMPACT_Dim *x2)
{
f0->clean(vtemp,c,O,i,j,k);
if (c->Nf2()>0)
for (int pos=0;pos<c->Nf2();++pos)
f2->cleanouter(vtemp,c,O,i,j,k,&pos);
if (c->Nf1()>0)
for (IMPACT_Dim x3=1;x3<=c->Nf1();++x3)
f1->clean(vtemp,c,O,i,j,k,&x3);
for (IMPACT_Dim x3=1;x3<=c->NE();++x3)
E->clean(vtemp,c,O,i,j,&x3);
for (IMPACT_Dim x3=3;x3>3-c->NB();--x3)
B->clean(vtemp,c,O,i,j,&x3);
}
inline void Bequation_clean_outer(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O,IMPACT_Var* E,IMPACT_Var* B,int* i,int *j,IMPACT_Dim *x1)
{
B->cleanouter(vtemp,c,O,i,j,x1);
if (c->NE()>0)
for (IMPACT_Dim x2=1;x2<=c->NE();++x2)
E->cleanouter(vtemp,c,O,i,j,&x2);
}
inline void Bequation_clean_inner(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O,IMPACT_Var* E,IMPACT_Var* B,int* i,int *j,IMPACT_Dim *x1)
{
B->clean(vtemp,c,O,i,j,x1);
if (c->NE()>0)
for (IMPACT_Dim x2=1;x2<=c->NE();++x2)
E->clean(vtemp,c,O,i,j,&x2);
}
inline void Eequation_clean_outer(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O,IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f1,int* i,int *j,IMPACT_Dim *x1)
{
int ktemp=1;
if (c->NE()>0)
for (IMPACT_Dim x2=1;x2<=c->NE();++x2)
E->cleanouter(vtemp,c,O,i,j,&x2);
f1->cleanouter(vtemp,c,O,i,j,&ktemp,x1);
if (c->NB()>0)
for (IMPACT_Dim x2=3;x2>3-c->NB();--x2)
B->cleanouter(vtemp,c,O,i,j,&x2);
}
inline void Eequation_clean_inner(IMPACT_ParVec * vtemp,IMPACT_Config *c, IMPACT_StenOps * O,IMPACT_Var* E,IMPACT_Var* B,IMPACT_Var* f1,int* i,int *j,IMPACT_Dim *x1)
{
int ktemp=1;
if (c->NE()>0)
for (IMPACT_Dim x2=1;x2<=c->NE();++x2)
E->cleanouter(vtemp,c,O,i,j,&x2);
f1->clean(vtemp,c,O,i,j,&ktemp,x1);
if (c->NB()>0)
for (IMPACT_Dim x2=3;x2>3-c->NB();--x2)
B->clean(vtemp,c,O,i,j,&x2);
}
}
<file_sep>/runflux.sh
#!/bin/sh
#PBS -S /bin/sh
#PBS -N gnt
#PBS -l procs=16,walltime=100:00:00
#PBS -l pmem=3800mb
#PBS -A agrt1_flux
#PBS -l qos=flux
#PBS -q flux
#PBS -M <EMAIL>
#PBS -m abe
#PBS -j oe
#PBS -V
echo "I ran on:"
cat $PBS_NODEFILE
#############################################################################################
# EDIT BELOW HERE
#############################################################################################
export ROOT_DIR=/scratch/agrt_flux/archisj/devilray/impray/
export DATA_DIR=/scratch/agrt_flux/archisj/th_out/
export INPUTFILE=imstdin
## OPTIONAL - CAN BE BLANK, no spaces
export RUNTITLE=wtgen
#############################################################################################
export DIR_NAME=impacta_${RUNTITLE}_${PBS_JOBID%.nyx.engin.umich.edu}
mkdir ${DATA_DIR}/${DIR_NAME}
cp -f ${ROOT_DIR}/bin/impacta ${DATA_DIR}/${DIR_NAME}/.
cp -f ${ROOT_DIR}/input/${INPUTFILE} ${DATA_DIR}/${DIR_NAME}/imstdin
#cp -fr ${ROOT_DIR}/bin/impacta_data_in ${DATA_DIR}/${DIR_NAME}/.
# Write down the version
cp ${ROOT_DIR}/version.txt ${DATA_DIR}/${DIR_NAME}/version.txt
# Create root directory
cd ${DATA_DIR}/${DIR_NAME}
# Run code
mpirun -np 16 ./impacta -read imstdin
#-renorm_temp 0.01
<file_sep>/include/impacta_objects/impacta_matrix.h
/*
**********************************************************
IMPACT Version 1.0
Matrix and Sparse matrix classes
Version 1.3
AGRT
19/2/07
Latest notes:
Added method for inserting vector into sparse matrix at
row rownumber
IMPORTANT - this can be made much more efficient possibly in future.
Also - stencil class added - this allows ddx stencils etc.
5/3 - Had to change the count member function. This is because
the order of the rownumber calling was critical previously
!!!IMPORTANT!!!!
Resize MUST be called after all rows have been counted as it now
sorts out the num in rows which WILL BE COMPLETELY WRONG OTHERWISE!!!!
7/3 - New count routines for each equation which count only the relevent
elements
18/4/07 - new added velocity stencil - 3 point for inserting
velocity differentials
8/5 - velocity stencil array added for storing RB coefficents
**********************************************************
*/
class IMPACT_Matrix //matrix class
{
private:
friend class IMPACT_Sparse;
IMPACT_Vector** Matrix;
int N,M; //number of rows/cols
public:
IMPACT_Matrix();
IMPACT_Matrix(int Nin,int Min); //Square Matrix_size - -self explanatory //note - no default constructor!!
IMPACT_Matrix(IMPACT_Config config1); //Square Matrix_size - -self explanatory //note - no default constructor!!
virtual ~IMPACT_Matrix();
double get(int,int);
void set(int,int, double);
void inc(int,int, double);
void setall(double);
void Print();
void Print(std::ofstream& outfile);
void ChangeSize(int new_N,int new_M);
void multiply(double value);
void size(int *Nout, int *Mout);
int chksize(int *Nout, int *Mout);
void reset();
};
inline IMPACT_Matrix::IMPACT_Matrix(){
//(adapted from Vector)
Matrix = new IMPACT_Vector*[1];
Matrix[0]=new IMPACT_Vector();
N=M=1;
}
inline IMPACT_Matrix::IMPACT_Matrix(int Nin, int Min){ //N by M matrix
//(adapted from Vector)
Matrix = new IMPACT_Vector*[Nin];
for (int i=0;i<Nin;i++)
Matrix[i]=new IMPACT_Vector(Min);
N=Nin,M=Min;
}
inline IMPACT_Matrix::IMPACT_Matrix(IMPACT_Config config1)
{
N = (config1.conf_N_f0+config1.conf_N_f1+config1.conf_N_f2+config1.conf_N_f3)*config1.conf_Nv+config1.conf_NE+config1.conf_NB;
M=N=N*config1.conf_Nx*config1.conf_Ny;
Matrix = new IMPACT_Vector*[N];
for (int i=0;i<N;i++)
Matrix[i]=new IMPACT_Vector(N);
}
inline IMPACT_Matrix::~IMPACT_Matrix()
{ //This deallocates memory resources
for (int i=0;i<N;i++)
delete Matrix[i]; //When the object goes out of scope
delete[] Matrix;
}
inline double IMPACT_Matrix::get(int i,int j){ //i and j are from 1 to N not 0 to N-1
double answer;
answer=Matrix[i-1]->Get(j);
return answer;
}
inline void IMPACT_Matrix::set(int i,int j, double value){
//i and j are from 1 to N not 0 to N-1
Matrix[i-1]->Set(j,value);
}
inline void IMPACT_Matrix::inc(int i,int j, double value){
//i and j are from 1 to N not 0 to N-1
Matrix[i-1]->Set(j,value+get(i,j));
}
inline void IMPACT_Matrix::setall(double value)
{
//i and j are from 1 to N not 0 to N-1
for (int i=0;i<N;i++)
Matrix[i]->SetAll(value);
}
inline void IMPACT_Matrix::ChangeSize(int Nin,int Min)
{
//This deallocates memory resources
for (int i=0;i<N;i++)
delete Matrix[i]; //When the object goes out of scope
delete[] Matrix;
Matrix = new IMPACT_Vector*[Nin];
for (int i=0;i<Nin;i++)
Matrix[i]=new IMPACT_Vector(Min);
N=Nin,M=Min;
}
inline void IMPACT_Matrix::multiply(double value)
{
for (int i=1; i<=N;i++)
for (int j=1;j<=M;j++)
set(i,j,value*get(i,j));
}
inline void IMPACT_Matrix::size(int *Nout, int *Mout)
{
*Nout = N;
*Mout = M;
}
inline int IMPACT_Matrix::chksize(int *Nout, int *Mout)
{
int ans=0;
ans+=(*Nout == N);
ans+=(*Mout == M);
ans=ans/2;
return ans;
}
inline void IMPACT_Matrix::Print()
{
//Needs no explanation?
for (int i=1; i<=N;i++)
{
std::cout<<i<<": ";
for (int j=1;j<=M;j++)
{
if (i==j) std::cout<<BCYAN;
else std::cout<<ENDFORMAT;
std::cout << get(i,j) << " ";
}
std::cout << std::endl;
}
std::cout << std::endl<<std::endl<<std::endl;
std::cout<<ENDFORMAT;
}
inline void IMPACT_Matrix::Print(std::ofstream& outfile)
{
//Needs no explanation?
for (int i=1; i<=N;i++)
{
for (int j=1;j<=M;j++)
{
outfile << get(i,j) << " ";
}
outfile << std::endl;
}
outfile << std::endl<<std::endl<<std::endl;
}
inline void IMPACT_Matrix::reset()
{
for (int i=0;i<N;++i)
Matrix[i]->reset();
}
class IMPACT_Sparse
{
//These functions are for efficient counting and packing but need Var
//inputs so have to be outside the class.
/* friend void f0equation_count(IMPACT_ParVec * v, IMPACT_Sparse *S,IMPACT_Config *c, IMPACT_Var * f0,IMPACT_Var * E,IMPACT_Var * f1,int*i,int*j,int*k);
friend void f1equation_count(IMPACT_ParVec * v, IMPACT_Sparse *S,IMPACT_Config *c, IMPACT_Var * f0,IMPACT_Var * E,IMPACT_Var * B,IMPACT_Var * f1,int*i,int*j,int*k,IMPACT_Dim * x1);
friend void Eequation_count(IMPACT_ParVec * v, IMPACT_Sparse *S,IMPACT_Config *c,IMPACT_Var * E,IMPACT_Var *B,IMPACT_Var * f1,int*i,int*j,IMPACT_Dim * x1);
friend void Bequation_count(IMPACT_ParVec * v, IMPACT_Sparse *S,IMPACT_Config *c,IMPACT_Var * E,IMPACT_Var *B,int*i,int*j,IMPACT_Dim * x1);*/
// friend void PackSparse_int(IMPACT_Sparse *S,IMPACT_ParVec *v,int packstart,int packend,int *runningtotal);
// friend void PackSparse(IMPACT_Sparse *S,IMPACT_ParVec *v,int i,int *runningtotal);
// friend void chksparse_chk(IMPACT_Sparse *S, int *rownumber,int *runningtotal);
private:
IMPACT_Vector *values; //the values to be input
int *numinrows; //array of the start of the rowsin the matrix
int *colnums;// the column labels
int N; // the dimensions of the NxN matrix
int sparselength;//length of the sparse matrix
public:
IMPACT_Sparse()
{
values = new IMPACT_Vector(1);
numinrows = new int[2];
colnums = new int[1];
sparselength=1;
N=1;
}
virtual ~IMPACT_Sparse()
{
delete values;
delete[] numinrows;
delete[] colnums;
}
IMPACT_Sparse(IMPACT_Config config1)
{
N = (config1.conf_N_f0+config1.conf_N_f1+config1.conf_N_f2+config1.conf_N_f3)*config1.conf_Nv+config1.conf_NE+config1.conf_NB;
N*=config1.conf_Nx*config1.conf_Ny;
numinrows=new int[N+1];
colnums = new int[1];
values = new IMPACT_Vector(1);
sparselength=1;
}
IMPACT_Sparse(IMPACT_Config config1,int slength)//the length of sparse is defined
{
N = (config1.conf_N_f0+config1.conf_N_f1+config1.conf_N_f2+config1.conf_N_f3)*config1.conf_Nv+config1.conf_NE+config1.conf_NB;
N*=config1.conf_Nx*config1.conf_Ny;
numinrows=new int[N+1];
colnums = new int[slength];
values = new IMPACT_Vector(slength);
sparselength=slength;
}
//This next one is to enable the parallel sparse matrix
IMPACT_Sparse(int rowlength)
//the length of the rowvector is defined
{
N=rowlength;
numinrows=new int[rowlength+1];
colnums = new int[1];
values = new IMPACT_Vector(1);
sparselength=1;
}
inline int getN()
{
return N;
}
inline int getSl()
{
return sparselength;
}
void printvals()
{
values->PrintArray();
}
void printrows()
{
for (int i=0;i<N;i++) std::cout<<"("<< i+1<<","<<numinrows[i]<<"),";std::cout<<std::endl;
}
void printvalsbyrow()
{
for (int i=0;i<N;i++)
{ std::cout<<"Row "<<i+1<<": ";
for (int j=numinrows[i];j<numinrows[i+1];j++)
std::cout<< values->Get(j)<<",";
std::cout<<std::endl;
}
std::cout<<std::endl;
}
void printelembyrow()
{
for (int i=0;i<N;i++)
{ std::cout<<"Row "<<i+1<<": ";
for (int j=numinrows[i];j<numinrows[i+1];j++)
std::cout<< j<<",";
std::cout<<std::endl;
}
std::cout<<std::endl;
}
void printcols()
{
for (int i=0;i<sparselength;i++) std::cout<< colnums[i]<<",";std::cout<<std::endl;
}
void printcolsbyrow()
{
for (int i=0;i<N;i++)
{ std::cout<<"Row "<<i+1<<": ";
for (int j=numinrows[i];j<numinrows[i+1];j++)
std::cout<< colnums[j-1]<<",";
std::cout<<std::endl;
}
std::cout<<std::endl;
}
inline int getrow(int index)//returns value in row index
{
//error checking
// if(index<1||index>N+1){std::cout<<"in Sparse getrow - index outside max value"<<std::endl<<"element = "<< index<<std::endl;exit(0);}
return numinrows[index-1];
}
inline int getrow_nocheck(int index)//returns value in row index
{
//error checking
// if(index<0||index>N+1){std::cout<<"in Sparse getrow - index outside max value"<<std::endl<<"element = "<< index<<std::endl;exit(0);}
return numinrows[index-1];
}
inline void setrow(int index,int value)//sends value to row index
{
//error checking
// if(index<1||index>N+1){std::cout<<"in Sparse setrow - index outside max value"<<std::endl<<"element = "<< index<<std::endl;exit(0);}
numinrows[index-1]=value;
}
inline void incrow(int index,int value)//sends value incrimentally to row index
{
//error checking
// if(index<1||index>N+1){std::cout<<"in Sparse incrow - index outside max value"<<std::endl<<"element = "<< index<<std::endl;exit(0);}
numinrows[index-1]+=value;
}
inline int getcol(int index)//returns value in col index
{
//error checking
// if(index<1||index>sparselength){std::cout<<"in Sparse getcol - index outside max value"<<std::endl<<"element = "<< index<<std::endl;exit(0);}
return colnums[index-1];
}
inline int * getcol_add(int index)//returns value in col index
{
//error checking
// if(index<1||index>sparselength){std::cout<<"in Sparse getcol - index outside max value"<<std::endl<<"element = "<< index<<std::endl;exit(0);}
return &colnums[index-1];
}
inline void setcol(int index,int value)//sends value to col index
{
//if(index<1||index>sparselength){std::cout<<"in Sparse setcol - index outside max value"<<std::endl<<"element = "<< index<<std::endl;exit(0);}
colnums[index-1]=value;
}
inline double getval(int index)//returns value in val index
{
//error checking
// if(index<1||index>sparselength){std::cout<<"in Sparse getval - index outside max value"<<std::endl<<"element = "<< index<<std::endl;exit(0);}
return values->Get(index);
}
inline double * getval_add(int index)
{
//error checking
//if(index<1||index>sparselength){std::cout<<"in Sparse getval - index outside max value"<<std::endl<<"element = "<< index<<std::endl;exit(0);}
return values->Get_add(index);
}
inline void setval(int index,double value)//sends value to val index
{
// if(index<1||index>sparselength){std::cout<<"in Sparse setval - index outside max value"<<std::endl<<"element = "<< index<<std::endl;exit(0);}
values->Set(index,value);
}
inline void Pack(IMPACT_Matrix* M) //pack a matrix into the sparse matrix
{
if (N!=M->N) //If Matrix dimensions do not agree then
{
N=M->N; // resize sparse
delete[] numinrows;
numinrows=new int[N+1];
}
//
double zerothresh=zerotolerance::zerothreshold;
double val;
int total=0;
numinrows[0]=1;//first element is at 1!
for (int i=1;i<=N;++i) //This bit counts non-zeros
{
numinrows[i]=numinrows[i-1];
for (int j=1;j<=N;++j)
{
val=M->get(i,j);
if(fabs(val)>zerothresh)
++numinrows[i];
}
total+=(numinrows[i]-numinrows[i-1]);
}
//Now we can make new vectors for values and colnums
if (total!=sparselength){
sparselength=total;
delete[] colnums;
values->ChangeSize(total);
colnums = new int[total];}
int runningtotal=0; //to keep tabs of the
for (int i=1;i<=N;++i) //Now pack sparse matrix
{
for (int j=1;j<=N;++j)
{
val=M->get(i,j);
if(val>zerothresh)
{
values->Set(runningtotal+1,val);
colnums[runningtotal]=j;
runningtotal++;}
}//j
}//i
}
inline void reset() //this makes everything zero EXCEPT the rownums
{
for(int i=1;i<=sparselength;++i)
{colnums[i-1]=0;
values->Set(i,0.0);}
}
inline int getfree(int rownumber)
// finds free spot in sparse matrix at row rownumber
{
int freespot=0;
int ii=getrow(rownumber);
while (freespot==0)
{
if (getcol(ii)==0) freespot=ii;
//if (ii>S->getrow(rownumber+1))
// {std::cout<<"Error, no free space in sparse matrix";exit(0);}
++ii;
}
return freespot;
}
//_________________________________________________________________
//Counts non zeros in a row and packs them:
inline void Pack(IMPACT_ParVec *v, int rownumber)
{
int index = getrow(rownumber);
double zerothresh=zerotolerance::zerothreshold;
double val;
int runningtotal=index-1; //to keep tabs of the
for (int i=1;i<=v->length();++i) //Now pack sparse matrix
{
val=v->Get(i);
if(fabs(val)>zerothresh)
{
values->Set(runningtotal+1,val);
colnums[runningtotal]=i;
runningtotal++;
}
}//i
}
//this counts the non-zero elements in *v and resizes accordingly
// NB!!! Probably needs a reset after to set to zero
inline void Count(IMPACT_ParVec *v, int rownumber)
{
double zerothresh=zerotolerance::zerothreshold;
double val;
//store old rowcount
numinrows[rownumber]=0;//numinrows[rownumber-1];
/*
NOTE NOTE NOTE This means numinrows is WRONG until
Resize is called!!
*/
for (int j=1;j<=N;++j)
{ //cycle through and count
val=v->Get(j);
if(fabs(val)>zerothresh)
++numinrows[rownumber];
}
}
inline void Resize() // after count, resizes column and row vectors
{
numinrows[0]=1;//first element is at 1!
for (int j=0;j<N;++j)
{
numinrows[j+1]+=numinrows[j]; // adds rows correctly
}
sparselength=(numinrows[N]-1); //-1 as next(non-existent) row would be at N
//updates length of sparse vector
delete[] colnums;
values->ChangeSize(sparselength);
colnums = new int[sparselength];
}
};
IMPACT_Matrix S2M(IMPACT_Sparse *S)//for checking
{
int N=S->getN();
IMPACT_Matrix M(N,N);
for (int i=1;i<=N;++i)
for(int j=S->getrow(i);j<S->getrow(i+1);++j){
if(S->getcol(j)!=0) M.set(i,S->getcol(j),S->getval(j));
}
return M;
}
int getfree(int rownumber,IMPACT_Sparse *S)
// finds free spot in sparse matrix at row rownumber
{
int freespot=0;
int ii=S->getrow(rownumber);
while (freespot==0)
{
if (S->getcol(ii)==0) freespot=ii;
//if (ii>S->getrow(rownumber+1))
// {std::cout<<"Error, no free space in sparse matrix";exit(0);}
++ii;
}
return freespot;
}
/*
This next class has 5 components (can obviously be extended if required)
These represent a point in x,y space and the neighbouring points.
e.g. (x,y),(x+1,y),(x-1,y), (x,y+1),(x,y-1)
*/
class IMPACT_stencil
{
private:
double stencil[5]; // (x,y),(x+1,y),(x-1,y), (x,y+1),(x,y-1);
public:
IMPACT_stencil()
{
for (int i=0;i<5;++i)
{
stencil[i]=0;
}
}
~IMPACT_stencil()
{ }
IMPACT_stencil(double s1,double s2,double s3,double s4,double s5)
{
stencil[0]=s1;
stencil[1]=s2;
stencil[2]=s3;
stencil[3]=s4;
stencil[4]=s5;
}
/* IMPACT_stencil(double s1,double s2,double s3,double s4,double s5,double m)
{
stencil[0]=s1;
stencil[1]=s2;
stencil[2]=s3;
stencil[3]=s4;
stencil[4]=s5;
multiplier=m;
}*/
/* IMPACT_stencil(double * s,double m)
{
for (int i=0;i<5;++i)
{
stencil[i]=s[i];
}
multiplier=m;
}*/
inline double operator ()(int index)
{
return stencil[index];
}
inline double get(int index)
{
return stencil[index];
}
inline void set(int index, double val)
{
stencil[index]=val;
}
inline void invert(int index)
{
stencil[index]=-stencil[index];
}
inline IMPACT_stencil operator * (double m) // updates the multiplier
//returns a stencil so that it can be used
{
//multiplier=m;
IMPACT_stencil answer(stencil[0]*m,stencil[1]*m,stencil[2]*m,stencil[3]*m,stencil[4]*m);
return answer;
}
inline IMPACT_stencil operator + (IMPACT_stencil toadd) // adds stencils
{
IMPACT_stencil answer(get(0)+toadd.get(0),get(1)+toadd.get(1),get(2)+toadd.get(2),get(3)+toadd.get(3),get(4)+toadd.get(4));
return answer;
}
inline void flip(IMPACT_Dim *x1)
{
double tempstore;
switch (x1->get())
{
case 1:
tempstore=stencil[1];
stencil[1]=stencil[2];
stencil[2]=tempstore;
break;
case 2:
tempstore=stencil[3];
stencil[3]=stencil[4];
stencil[4]=tempstore;
break;
}
}
void print()
{
for (int i=0;i<5;++i)
std::cout<<stencil[i]<<',';
std::cout<<'\n';
}
};
class IMPACT_Vel_Sten //velocity space stencil
{
private:
double stencil[3]; // (v-1,v,v+1)
public:
IMPACT_Vel_Sten()
{
stencil[0] =stencil[1]=stencil[2]= 0.0;
}
~IMPACT_Vel_Sten()
{}
IMPACT_Vel_Sten(double s1,double s2, double s3)
{
stencil[0] = s1;
stencil[1] = s2;
stencil[2] = s3;
}
inline double get(int index)
{
return stencil[index];
}
inline void set(int index, double val)
{
stencil[index]=val;
}
inline void inc(int index, double val)
{
stencil[index]+=val;
}
inline void operator +=(IMPACT_Vel_Sten toadd)
{
stencil[0] = toadd.get(0);
stencil[1] = toadd.get(1);
stencil[2] = toadd.get(2);
}
inline void operator *(double value)
{
for (int i=0;i<3;++i)
stencil[i]*= value;
}
inline void printelements()
{
std::cout<<"("<<stencil[0]<<','<<stencil[1]<<','<<stencil[2]<<")\n";
}
};
class IMPACT_VS_Array //velocity space stencil ARRAY
{
private:
IMPACT_Vel_Sten ****VSten;
int Ny,Nv,xstart,Nx; // as parallel=>x start to end
public:
IMPACT_VS_Array()
{
Ny=Nv=xstart=Nx=1;
VSten = new IMPACT_Vel_Sten***[Nx]; //x
for (int i=0;i<Nx;++i)
{
VSten[i] = new IMPACT_Vel_Sten**[Ny+1];
for (int j=0;j<=Ny;++j)
{
VSten[i][j] = new IMPACT_Vel_Sten*[Nv+1];
for (int k=0;k<=Nv;++k)
VSten[i][j][k] = new IMPACT_Vel_Sten(0.0,0.0,0.0);
}
}
}
~IMPACT_VS_Array()
{
delete[] VSten;
}
IMPACT_VS_Array(IMPACT_Config *c, IMPACT_MPI_Config *M)
{
Ny=c->Ny();
Nv=c->Nv();
xstart=M->istart();
Nx=M->iend()+1-xstart;
VSten = new IMPACT_Vel_Sten***[Nx]; //x
for (int i=0;i<Nx;++i)
{
VSten[i] = new IMPACT_Vel_Sten**[Ny+1];
for (int j=0;j<=Ny;++j)
{
VSten[i][j] = new IMPACT_Vel_Sten*[Nv+1];
for (int k=0;k<=Nv;++k)
VSten[i][j][k] = new IMPACT_Vel_Sten(0.0,0.0,0.0);
}
}
}
void set(IMPACT_Vel_Sten *vs,int *i,int *j,int *k)
{
for (int u=0;u<3;++u)
VSten[*i-xstart][*j][*k]->set(u,vs->get(u));
}
void inc(IMPACT_Vel_Sten *vs,int *i,int *j,int *k)
{
for (int u=0;u<3;++u)
VSten[*i-xstart][*j][*k]->inc(u,vs->get(u));
}
void inc_kminus(IMPACT_Vel_Sten *vs,int *i,int *j,int *k)
{
for (int u=1;u<3;++u)
VSten[*i-xstart][*j][*k]->inc(u,vs->get(u-1));
}
void multiply(double *value, int *i, int *j, int *k)
{
for (int u=0;u<3;++u)
VSten[*i-xstart][*j][*k]->set(u,VSten[*i-xstart][*j][*k]->get(u)*(*value));
}
IMPACT_Vel_Sten * get(int *i,int *j, int *k)
{
return VSten[*i-xstart][*j][*k];
}
};
class IMPACT_IMatrix : public IMPACT_Matrix
{
private:
double constvalue;
int ifconst;
public:
IMPACT_IMatrix() : IMPACT_Matrix()
{
constvalue=1;
ifconst=1;
}
IMPACT_IMatrix(double value) : IMPACT_Matrix()
{
constvalue=value;
ifconst=1;
}
IMPACT_IMatrix(double* gridx, double* gridy,int Nx,int Ny) : IMPACT_Matrix(Nx,Ny)
{
constvalue=0;
ifconst=0;
double tempinsert;
for (int i=0;i<Nx;++i)
for(int j=0;j<Ny;++j)
{
tempinsert=gridx[i]*gridy[j];
IMPACT_Matrix::set(i+1,j+1,tempinsert);
}
}
void copy(IMPACT_IMatrix *IM)
{
int Nin,Min;
IM->size(&Nin,&Min);
if (Nin*Min==1) setc(IM->get(&Nin,&Min));
else
{
ifconst=0;
if (!chksize(&Nin,&Min)) IMPACT_Matrix::ChangeSize(Nin,Min);
for (int i=1;i<=Nin;++i)
for (int j=1;j<=Min;++j)
IMPACT_Matrix::set(i,j,IM->get(&i,&j));
}
/*if (Nin*Min==1) {ifconst=1; constvalue=IM->get(&Nin,&Min);}
else
{
ifconst=0;
IMPACT_Matrix::ChangeSize(Nin,Min);
for (int i=1;i<=Nin;++i)
for (int j=1;j<=Min;++j)
set(i,j,IM->get(&i,&j));}*/
}
void copy(IMPACT_Matrix *IM)
{
int Nin,Min;
IM->size(&Nin,&Min);
if (Nin*Min==1) setc(IM->get(Nin,Min));
else
{
ifconst=0;
if (!chksize(&Nin,&Min)) IMPACT_Matrix::ChangeSize(Nin,Min);
for (int i=1;i<=Nin;++i)
for (int j=1;j<=Min;++j)
IMPACT_Matrix::set(i,j,IM->get(i,j));
}
/*if (Nin*Min==1) {ifconst=1; constvalue=IM->get(&Nin,&Min);}
else
{
ifconst=0;
IMPACT_Matrix::ChangeSize(Nin,Min);
for (int i=1;i<=Nin;++i)
for (int j=1;j<=Min;++j)
set(i,j,IM->get(&i,&j));}*/
}
void setc(double value) //set a constant value
{
constvalue=value;
ifconst=1;
}
void setg(double* gridx, double* gridy,int Nx,int Ny)
{
constvalue=0;
ifconst=0;
double tempinsert;
IMPACT_Matrix::ChangeSize(Nx,Ny);
for (int i=0;i<Nx;++i)
for(int j=0;j<Ny;++j)
{
tempinsert=gridx[i]*gridy[j];
IMPACT_Matrix::set(i+1,j+1,tempinsert);
}
}
double get(int *i, int *j)
{
double result = constvalue;
if (!ifconst) result = IMPACT_Matrix::get(*i,*j);
return result;
}
void Iset(double value,int *i, int *j)
{
constvalue=value;
if (!ifconst) IMPACT_Matrix::set(*i,*j,value);
}
void multiplyall(double value)
{
if (ifconst) constvalue*=value;
if (!ifconst) IMPACT_Matrix::multiply(value);
}
void Print()
{
if (!ifconst) IMPACT_Matrix::Print();
if (ifconst) std::cout<<constvalue<<'\n';
}
void Printf(std::ofstream& outfile)
{
if (!ifconst) IMPACT_Matrix::Print(outfile);
if (ifconst) std::cout<<constvalue<<'\n';
}
void SwitchOffConst()
{
ifconst=0;
}
void SwitchOffConst(int Nxin,int Nyin)
{
if(ifconst){
ifconst=0;
ChangeSize(Nxin,Nyin);
for (int i=1;i<=Nxin;++i)
for (int j=1;j<=Nyin;++j)
Iset(constvalue,&i,&j);
}
}
void SwitchOnConst()
{
ifconst=1;
}
bool sign(int *i, int *j)
{
return (get(i,j) >= 0.0);
}
};
void IMPACTA_Share_Moment(IMPACT_Config *c, IMPACT_MPI_Config *M,
IMPACT_IMatrix *Moment)
{
if (M->size()>1){
double *jstring;
jstring = new double[c->Ny()];
for (int i=1;i<=c->Nx();++i)
{
MPI::COMM_WORLD.Barrier();
for (int j=1;j<=c->Ny();++j) jstring[j-1]=Moment->get(&i,&j);
MPI::COMM_WORLD.Bcast(jstring,c->Ny(),MPI::DOUBLE,M->rank(&i));
for (int j=1;j<=c->Ny();++j) Moment->set(i,j,jstring[j-1]);
}
delete[] jstring;
}
}<file_sep>/include/impacta_io/impacta_moments.h
/*
**********************************************************
Obtain moments of the equations
Version 2.4
AGRT
23/3/07 - the first set of functions turn a ParVec into
a Moment, the second set do the reverse
4/6/07 - pressure tensor (f2) term added
21/8/07 - Average value member added
5/5/08 - Anisotrpic Pressure now 2* origninal -> because
of normalization
30/6/08 - Local anisotropic pressure function added
**********************************************************
*/
inline double Local_pe(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Config *c,
int *i,int *j);
inline double Local_je(IMPACT_ParVec * v, IMPACT_Var * f1, IMPACT_Config *c,
int *i,int *j,IMPACT_Dim *x1);
inline double Local_ne(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Config *c,
int *i,int *j);
// First get moments from parallel vectors
//This is a moment...
struct IMPACT_Moment
{
char name[LenName]; // the name of the moment
int Nx, Ny;
char coords[Ncoords]; //what is the coordinate system
IMPACT_Vector xaxis; //xaxis labels
IMPACT_Vector yaxis; //yaxis labels
IMPACT_Matrix values; //the Matrix of moment values
double average;
};
/*
Output format is like:
IMPACT
<Moment name>
<coords> - either xy, rz or r0
<Nx> <TAB> <Ny>
<xaxis values>
<yaxis values>
<matrix of data>
*/
struct IMPACT_Moment Duplicate(struct IMPACT_Moment *M1)
{
struct IMPACT_Moment M2;
for (int i=0;i<20;++i)
M2.name[i]=M1->name[i];
M2.Nx=M1->Nx;
M2.Ny=M1->Ny;
M2.coords[0]=M1->coords[0];
M2.coords[1]=M1->coords[1];
M2.xaxis.ChangeSize(M1->Nx);
M2.yaxis.ChangeSize(M1->Ny);
M2.values.ChangeSize(M1->Nx,M1->Ny);
M2.average=M1->average;
for (int i=1;i<=M1->Nx;++i)
M2.xaxis.Set(i,M1->xaxis.Get(i));
for (int i=1;i<=M1->Ny;++i)
M2.yaxis.Set(i,M1->yaxis.Get(i));
for (int i=1;i<=M1->Nx;++i)
for (int j=1;j<=M1->Ny;++j)
M2.values.set(i,j,M1->values.get(i,j));
return M2;
}
struct IMPACT_Moment Divide(struct IMPACT_Moment *M1,struct IMPACT_Moment *M3)
{
struct IMPACT_Moment M2;
M2.Nx=M1->Nx;
M2.Ny=M1->Ny;
M2.coords[0]=M1->coords[0];
M2.coords[1]=M1->coords[1];
M2.xaxis.ChangeSize(M1->Nx);
M2.yaxis.ChangeSize(M1->Ny);
M2.values.ChangeSize(M1->Nx,M1->Ny);
for (int i=1;i<=M1->Nx;++i)
M2.xaxis.Set(i,M1->xaxis.Get(i));
for (int i=1;i<=M1->Ny;++i)
M2.yaxis.Set(i,M1->yaxis.Get(i));
for (int i=1;i<=M1->Nx;++i)
for (int j=1;j<=M1->Ny;++j)
M2.values.set(i,j,M1->values.get(i,j)/M3->values.get(i,j));
return M2;
}
inline void GetGrid(IMPACT_Config *c, struct IMPACT_Moment *M)
{
M->xaxis.ChangeSize(c->Nx());
M->yaxis.ChangeSize(c->Ny());
for (int i=1;i<=c->Nx();++i)
M->xaxis.Set(i,c->xpos(i));
for (int i=1;i<=c->Ny();++i)
M->yaxis.Set(i,c->ypos(i));
}
inline void new_Constant(IMPACT_IMatrix *Const, IMPACT_Config *c,
IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer,
std::string name1)
{
int Nx=c->Nx();
int Ny=c->Ny();
strncpy(answer->name,name1.c_str(),LenName);
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
double totalsum=0.0;
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j){
answer->values.set(i,j,Const->get(&i,&j));
totalsum+=Const->get(&i,&j);
}
answer->average=totalsum/Nx/Ny;
GetGrid(c,answer); // gets x and y axis
}
inline void new_ne(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer)
{
int Nx=c->Nx();
int Ny=c->Ny();
strcpy(answer->name,"n_e");
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
int Nv=c->Nv();
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum;
double totalsum=0.0;
for (int i=1;i<=Nx;++i)
{
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
// for (int k=1;k<=Nv;++k)
// rowsum+=fourpi*f0->get(&gatheredvector,&i,&j,&k)*c->v2(&k)*c->dv(&k);
for (int k=1;k<=Nv;++k)
rowsum+=fourpi*data[k-1]*c->dv(&k)*c->v2(&k);
answer->values.set(i,j,rowsum);
totalsum+=rowsum;
}
}
answer->average=totalsum/Nx/Ny;
GetGrid(c,answer); // gets x and y axis
delete[] data;
}
//the next is for quickeness - no update of grid, just values.
inline void get_ne(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer)
{
int Nx=c->Nx();
int Ny=c->Ny();
int Nv=c->Nv();
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum;
for (int i=1;i<=Nx;++i)
{
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
// for (int k=1;k<=Nv;++k)
// rowsum+=fourpi*f0->get(&gatheredvector,&i,&j,&k)*c->v2(&k)*c->dv(&k);
for (int k=1;k<=Nv;++k)
rowsum+=fourpi*data[k-1]*c->dv(&k)*c->v2(&k);
answer->values.set(i,j,rowsum);
}
}
delete[] data;
}
inline void new_Ue(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer)
{
int Nx=c->Nx();
int Ny=c->Ny();
strcpy(answer->name,"U_e");
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
int Nv=c->Nv();
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum,totalsum=0.0;
for (int i=1;i<=Nx;++i)
{
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+= twopi*e_mass*data[k-1]*c->v2(&k)*c->v2(&k)*c->dv(&k);
//for (int k=1;k<=Nv;++k)
//rowsum+= twopi*e_mass*f0->get(&gatheredvector,&i,&j,&k)*c->v2(&k)*c->v2(&k)*c->dv(&k); // 4pi /2
answer->values.set(i,j,rowsum);
totalsum+=rowsum;
}
}
answer->average=totalsum/Nx/Ny;
GetGrid(c,answer); // gets x and y axis
delete[] data;
}
inline void new_m0five(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer)
{
int Nx=c->Nx();
int Ny=c->Ny();
strcpy(answer->name,"m05");
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
int Nv=c->Nv();
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum,totalsum=0.0;
for (int i=1;i<=Nx;++i)
{
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+= twopi*e_mass*data[k-1]*c->v3(&k)*c->v2(&k)*c->v2(&k)*c->dv(&k);
//for (int k=1;k<=Nv;++k)
//rowsum+= twopi*e_mass*f0->get(&gatheredvector,&i,&j,&k)*c->v2(&k)*c->v2(&k)*c->dv(&k); // 4pi /2
answer->values.set(i,j,rowsum);
totalsum+=rowsum;
}
}
answer->average=totalsum/Nx/Ny;
GetGrid(c,answer); // gets x and y axis
delete[] data;
}
inline void new_m0three(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer)
{
int Nx=c->Nx();
int Ny=c->Ny();
strcpy(answer->name,"m03");
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
int Nv=c->Nv();
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum,totalsum=0.0;
for (int i=1;i<=Nx;++i)
{
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+= twopi*e_mass*data[k-1]*c->v2(&k)*c->v3(&k)*c->dv(&k);
//for (int k=1;k<=Nv;++k)
//rowsum+= twopi*e_mass*f0->get(&gatheredvector,&i,&j,&k)*c->v2(&k)*c->v2(&k)*c->dv(&k); // 4pi /2
answer->values.set(i,j,rowsum);
totalsum+=rowsum;
}
}
answer->average=totalsum/Nx/Ny;
GetGrid(c,answer); // gets x and y axis
delete[] data;
}
//the next is for quickeness - no update of grid, just values.
inline void get_Ue(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer)
{
int Nx=c->Nx();
int Ny=c->Ny();
int Nv=c->Nv();
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum;
for (int i=1;i<=Nx;++i)
{
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+= twopi*e_mass*data[k-1]*c->v2(&k)*c->v2(&k)*c->dv(&k);
//for (int k=1;k<=Nv;++k)
//rowsum+= twopi*e_mass*f0->get(&gatheredvector,&i,&j,&k)*c->v2(&k)*c->v2(&k)*c->dv(&k);// 4pi /2
answer->values.set(i,j,rowsum);
}
}
delete[] data;
}
inline void new_je(IMPACT_ParVec * v, IMPACT_Var * f1, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer,IMPACT_Dim *x1)
{
int Nx=c->Nx();
int Ny=c->Ny();
int x1_int=x1->get();
char dimension='x';
switch (x1_int)
{
case 1:
dimension='x';
break;
case 2:
dimension='y';
break;
case 3:
dimension='z';
break;
}
char nametemp[10]={'j','_',dimension};
strcpy(answer->name,nametemp);
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
int Nv=c->Nv();
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum;
int kstart=x1_int*Nv-1; //if 1 - just skip f0, if 2 skip f0 and f1x1 etc.
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+=fourthirdspi*e_charge*data[k+kstart]*c->v3(&k)*c->dv(&k);
/* for (int k=1;k<=Nv;++k)
{
rowsum+=fourthirdspi*e_charge*f1->get(&gatheredvector,&i,&j,&k,x1)*c->v3(&k)*c->dv(&k); // 4pi/3 e int f1v^3 dv*/
answer->values.set(i,j,rowsum);
//}
}
GetGrid(c,answer); // gets x and y axis
delete[] data;
}
inline void new_Te(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer)
{
int Nx=c->Nx();
int Ny=c->Ny();
strcpy(answer->name,"T_e");
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
struct IMPACT_Moment Ue,ne;
new_Ue(v,f0,c,MPIc,&Ue);
new_ne(v,f0,c,MPIc,&ne);
struct IMPACT_Moment Te=Divide(&Ue,&ne);
for (int i=1;i<=c->Nx();++i)
for (int j=1;j<=c->Ny();++j)
answer->values.set(i,j,Te.values.get(i,j)*2.0/3.0);
answer->average=2.0/3.0*Ue.average/ne.average;
}
inline void new_eta(IMPACT_ParVec * v, IMPACT_Var * f0,IMPACT_Config *c,IMPACT_MPI_Config *MPIc,
struct IMPACT_Moment * answer)
{
int Nx=c->Nx();
int Ny=c->Ny();
int Nv=c->Nv();
double *data;
data = new double[c->cellpoints()];
double rowsum,totalsum=0.0;
strcpy(answer->name,"eta");
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
double netemp;
// f0 MOMENT
//************************************************************
for (int i=1;i<=Nx;++i)
{
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
netemp = 0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+= data[k-1]*c->v2(&k)*c->v3(&k)*c->dv(&k);
for (int k=1;k<=Nv;++k)
netemp+=data[k-1]*c->dv(&k)*c->v2(&k); // get ne
answer->values.set(i,j,0.5*Initial_Conditions::Z.get(&i,&j)*netemp/rowsum);
totalsum+=rowsum;
}
}
answer->average=totalsum/Nx/Ny;
GetGrid(c,answer); // gets x and y axis
delete[] data;
}
// - vector quants
inline void get_je(IMPACT_ParVec * v, IMPACT_Var * f1, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer,IMPACT_Dim *x1)
{
int Nx=c->Nx();
int Ny=c->Ny();
int Nv=c->Nv();
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum;
int x1_int=x1->get();
int kstart=x1_int*Nv-1; //if 1 - just skip f0, if 2 skip f0 and f1x1 etc.
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+=fourthirdspi*e_charge*data[k+kstart]*c->v3(&k)*c->dv(&k);
/* for (int k=1;k<=Nv;++k)
{
rowsum+=fourthirdspi*e_charge*f1->get(&gatheredvector,&i,&j,&k,x1)*c->v3(&k)*c->dv(&k); // 4pi/3 e int f1v^3 dv*/
answer->values.set(i,j,rowsum);
//}
}
delete[] data;
}
inline void new_qT(IMPACT_ParVec * v, IMPACT_Var * f1, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer,IMPACT_Dim *x1)
{
int Nx=c->Nx();
int Ny=c->Ny();
int x1_int=x1->get();
char dimension='x';
switch (x1_int)
{
case 1:
dimension='x';
break;
case 2:
dimension='y';
break;
case 3:
dimension='z';
break;
}
char nametemp[10]={'q','_',dimension};
strcpy(answer->name,nametemp);
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
int Nv=c->Nv();
double *data;
data = new double[c->cellpoints()];
double rowsum;
int kstart=x1_int*Nv-1; //if 1 - just skip f0, if 2 skip f0 and f1x1 etc.
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+=fourthirdspi*data[k+kstart]*c->v3(&k)*c->v2(&k)*c->dv(&k);
answer->values.set(i,j,rowsum/2.0);
}
GetGrid(c,answer); // gets x and y axis
delete[] data;
}
inline void new_VN(IMPACT_ParVec * v, IMPACT_Var * f0,IMPACT_Var * f1,IMPACT_Config *c,IMPACT_MPI_Config *MPIc,
struct IMPACT_Moment * answer,IMPACT_Dim *x1)
{
int Nx=c->Nx();
int Ny=c->Ny();
int Nv=c->Nv();
int x1_int=x1->get();
char dimension='x';
double *data;
data = new double[c->cellpoints()];
double rowsum,totalsum=0.0;
char nametemp[10]={'V','_','N',dimension};
strcpy(answer->name,nametemp);
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
double jtemp,ptemp;
// f0 MOMENT
//************************************************************
for (int i=1;i<=Nx;++i)
{
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+= data[k-1]*c->v2(&k)*c->v3(&k)*c->dv(&k);
answer->values.set(i,j,rowsum);
totalsum+=rowsum;
}
}
answer->average=totalsum/Nx/Ny;
GetGrid(c,answer); // gets x and y axis
// f1 MOMENT -> M3
//************************************************************
switch (x1_int)
{
case 1:
dimension='x';
break;
case 2:
dimension='y';
break;
case 3:
dimension='z';
break;
}
// double data2[c->cellpoints()];
int kstart=x1_int*Nv-1; //if 1 - just skip f0, if 2 skip f0 and f1x1 etc.
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
//jtemp = 0.0;
//ptemp=1.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+=data[k+kstart]*c->v3(&k)*c->v3(&k)*c->dv(&k);
//-------------------------------------------------------------
// get current
//for (int k=1;k<=Nv;++k)
//jtemp+=fourthirdspi*e_charge*data[k+kstart]*c->v3(&k)*c->dv(&k);
//-------------------------------------------------------------
// ptemp=Local_pe(v,f0,c,&i,&j);
answer->values.set(i,j,(oneover6*rowsum/(answer->values.get(i,j))));//+jtemp/ptemp);
}
// GetGrid(c,answer); // gets x and y axis
delete[] data;
}
inline void get_q(IMPACT_ParVec * v, IMPACT_Var * f1, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer,IMPACT_Dim *x1)
{
int Nx=c->Nx();
int Ny=c->Ny();
int Nv=c->Nv();
int x1_int=x1->get();
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum;
int kstart=x1_int*Nv-1; //if 1 - just skip f0, if 2 skip f0 and f1x1 etc.
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+=fourthirdspi*data[k+kstart]*c->v3(&k)*c->v2(&k)*c->dv(&k);
answer->values.set(i,j,rowsum/2.0);
}
delete[] data;
}
//anisotropic pressure
inline void new_P(IMPACT_ParVec * v, IMPACT_Var * f2, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer,IMPACT_Dim *x1,IMPACT_Dim *x2)
{
int Nx=c->Nx();
int Ny=c->Ny();
int x1_int=x1->get();
int x2_int=x2->get();
if (x1_int<3) x1_int--;
if (x2_int<3) x2_int--; //similar to the system in IMPACT_Var
char dimension[2]={'e','e'};
switch (x1_int+x2_int)
{
case 0:
dimension[0]='x';
dimension[1]='x';
break;
case 1:
dimension[0]='x';
dimension[1]='y';
break;
case 2:
dimension[0]='y';
dimension[1]='y';
break;
case 3:
dimension[0]='x';
dimension[1]='z';
break;
case 4:
dimension[0]='y';
dimension[1]='z';
break;
}
char nametemp[10]={'P','_',dimension[0],'_',dimension[1]};
strcpy(answer->name,nametemp);
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
int Nv=c->Nv();
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum;
int kstart=(x1_int+x2_int+c->Nf1()+1)*Nv-1; //skip f0 and f1
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+=data[k+kstart]*c->v2(&k)*c->v2(&k)*c->dv(&k);
answer->values.set(i,j,2.0/5.0*fourthirdspi*rowsum);
}
GetGrid(c,answer); // gets x and y axis
delete[] data;
}
//anisotropic pressure term in Ohm's law
inline void new_divP(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Var * f2, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer,IMPACT_Dim *x1,IMPACT_Dim *x2)
{
int Nx=c->Nx();
int Ny=c->Ny();
int x1_int=x1->get();
int x2_int=x2->get();
if (x1_int<3) x1_int--;
if (x2_int<3) x2_int--; //similar to the system in IMPACT_Var
char dimension[2]={'e','e'};
switch (x1_int+x2_int)
{
case 0:
dimension[0]='x';
dimension[1]='x';
break;
case 1:
dimension[0]='x';
dimension[1]='y';
break;
case 2:
dimension[0]='y';
dimension[1]='y';
break;
case 3:
dimension[0]='x';
dimension[1]='z';
break;
case 4:
dimension[0]='y';
dimension[1]='z';
break;
}
char nametemp[10]={'D','_',dimension[0],'_',dimension[1]};
strcpy(answer->name,nametemp);
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
int Nv=c->Nv();
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum;
int kstart=(x1_int+x2_int+c->Nf1()+1)*Nv-1; //skip f0 and f1
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+=data[k+kstart]*c->v2(&k)*c->v2(&k)*c->dv(&k)*(c->v2(&k)*c->v(&k)); // M2(3)
answer->values.set(i,j,(2.0/15.0)*rowsum);
}
GetGrid(c,answer); // gets x and y axis
//************************************************************
// Now take gradient
int iplus,iminus,jplus,jminus;
double **answermethis;
answermethis=new double*[Nx];
for (int i=0;i<Nx;++i) {
answermethis[i]=new double[Ny];
}
if ((*x1)<3) {
for (int i=1;i<=Nx;++i)
{
for (int j=1;j<=Ny;++j)
{
iplus=i+1;
iminus=i-1;
jplus=j+1;
jminus=j-1;
//temp_sten =(*O->ddxi(i,j,x1))
IMPACT_stencil temp_sten(0.0,(0.5/c->dx(&i)),-(0.5/c->dx(&i)),(0.5/c->dy(&j)),-(0.5/c->dy(&j)));
IMPACT_f2_bound(&temp_sten,Nx,Ny,&iplus,&iminus,&jplus,&jminus,x1,x2);
// fix for periodic bounds
if (iplus>Nx) { iplus =1;}
if (iminus<1) { iminus =Nx;}
if (jplus>Ny) { jplus =1;}
if (jminus<1) { jminus =Ny;}
if (*x1==1) {
answermethis[i-1][j-1]=answer->values.get(iplus,j)*temp_sten(1);
answermethis[i-1][j-1]+=answer->values.get(iminus,j)*temp_sten(2);
}
if (*x1==2) {
answermethis[i-1][j-1]=answer->values.get(i,jplus)*temp_sten(3);
answermethis[i-1][j-1]+=answer->values.get(i,jminus)*temp_sten(4);
}
}// i
}//j
}
// f0 MOMENT
//************************************************************
for (int i=1;i<=Nx;++i)
{
for (int j=1;j<=Ny;++j)
{
rowsum=0.0;
Gather_kstring(v,c,MPIc,&i,&j,data);
for (int k=1;k<=Nv;++k)
rowsum+= data[k-1]*c->v2(&k)*c->v3(&k)*c->dv(&k);
answer->values.set(i,j,answermethis[i-1][j-1]/(2.0*rowsum));
//totalsum+=rowsum;
}
}
//answer->average=totalsum/Nx/Ny;
GetGrid(c,answer); // gets x and y axis
//************************************************************
delete[] data;
}
inline void new_E(IMPACT_ParVec * v, IMPACT_Var * E, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer,IMPACT_Dim *x1)
{
int Nx=c->Nx();
int Ny=c->Ny();
int x1_int=x1->get();
char dimension='x';
switch (x1_int)
{
case 1:
dimension='x';
break;
case 2:
dimension='y';
break;
case 3:
dimension='z';
break;
}
char nametemp[10]={'E','_',dimension};
strcpy(answer->name,nametemp);
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
int Epos=c->cellpoints()-c->NB()-c->NE()+x1_int-1;
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum;
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
Gather_kstring(v,c,MPIc,&i,&j,data);
rowsum=data[Epos];//E->get(&gatheredvector,&i,&j,x1);
answer->values.set(i,j,rowsum);
}
GetGrid(c,answer); // gets x and y axis
delete[] data;
}
inline void get_E(IMPACT_ParVec * v, IMPACT_Var * E, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer,IMPACT_Dim *x1)
{
int Nx=c->Nx();
int Ny=c->Ny();
int x1_int=x1->get();
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum;
int Epos=c->cellpoints()-c->NB()-c->NE()+x1_int-1;
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
Gather_kstring(v,c,MPIc,&i,&j,data);
rowsum=data[Epos];//E->get(&gatheredvector,&i,&j,x1);
answer->values.set(i,j,rowsum);
}
delete[] data;
}
inline void new_B(IMPACT_ParVec * v, IMPACT_Var * B, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer,IMPACT_Dim *x1)
{
int Nx=c->Nx();
int Ny=c->Ny();
int x1_int=x1->get();
char dimension='x';
switch (x1_int)
{
case 1:
dimension='x';
break;
case 2:
dimension='y';
break;
case 3:
dimension='z';
break;
}
char nametemp[10]={'B','_',dimension};
strcpy(answer->name,nametemp);
strncpy(answer->coords,IMPACT_Coords,Ncoords);
answer->Nx=Nx;
answer->Ny=Ny;
answer->values.ChangeSize(Nx,Ny);
int Bpos=c->cellpoints()-4+x1_int;
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum,totalsum=0.0;
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
Gather_kstring(v,c,MPIc,&i,&j,data);
rowsum=data[Bpos];//E->get(&gatheredvector,&i,&j,x1);
answer->values.set(i,j,rowsum);
totalsum+=rowsum;
}
answer->average=totalsum/Nx/Ny;
GetGrid(c,answer); // gets x and y axis
delete[] data;
}
inline void get_B(IMPACT_ParVec * v, IMPACT_Var * B, IMPACT_Config *c,IMPACT_MPI_Config *MPIc, struct IMPACT_Moment * answer,IMPACT_Dim *x1)
{
int Nx=c->Nx();
int Ny=c->Ny();
int x1_int=x1->get();
int Bpos=c->cellpoints()-4+x1_int;
//IMPACT_ParVec gatheredvector=Gather(v,c,MPIc);
double *data;
data = new double[c->cellpoints()];
double rowsum;
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
Gather_kstring(v,c,MPIc,&i,&j,data);
rowsum=data[Bpos];//E->get(&gatheredvector,&i,&j,x1);
answer->values.set(i,j,rowsum);
}
delete[] data;
}
//________________________________________________________________________
// Local moments;
inline double Local_Te(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Config *c,
int *i,int *j)
{
int Nv=c->Nv();
double rowsum=0.0;
double answer=0.0;
for (int k=1;k<=Nv;++k)
rowsum+=f0->get(v,i,j,&k)*c->v2(&k)*c->v2(&k)*c->dv(&k);
answer=rowsum;
rowsum=0.0;
for (int k=1;k<=Nv;++k)
rowsum+=f0->get(v,i,j,&k)*c->v2(&k)*c->dv(&k);
answer=2.0/3.0*answer/rowsum;
return answer;
}
inline double Local_ne(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Config *c,
int *i,int *j)
{
int Nv=c->Nv();
double rowsum=0.0;
double answer=0.0;
for (int k=1;k<=Nv;++k)
rowsum+=f0->get(v,i,j,&k)*c->v2(&k)*c->dv(&k);
answer=fourpi*rowsum;
return answer;
}
inline double Local_pe(IMPACT_ParVec * v, IMPACT_Var * f0, IMPACT_Config *c,
int *i,int *j)
{
double answer=Local_Te(v,f0,c,i,j)*Local_ne(v,f0,c,i,j);
return answer;
}
/*
Local anisotropic part of pressure tensor
*/
inline double Local_Pi(IMPACT_ParVec * v, IMPACT_Var * f2, IMPACT_Config *c,
int *i,int *j,IMPACT_Dim *x1,IMPACT_Dim *x2)
{
int Nv=c->Nv();
double rowsum=0.0;
double answer=0.0;
rowsum=0.0;
for (int k=1;k<=Nv;++k)
rowsum+=f2->get(v,i,j,&k,x1,x2)*c->v2(&k)*c->v2(&k)*c->dv(&k);
answer=2.0/5.0*fourthirdspi*rowsum;
return answer;
}
inline double Local_je(IMPACT_ParVec * v, IMPACT_Var * f1, IMPACT_Config *c,
int *i,int *j,IMPACT_Dim *x1)
{
int Nv=c->Nv();
double rowsum=0.0;
double answer=0.0;
for (int k=1;k<=Nv;++k)
rowsum+=f1->get(v,i,j,&k,x1)*c->v2(&k)*c->v(&k)*c->dv(&k);
answer=e_charge*fourthirdspi*rowsum;
return answer;
}
inline double Local_qT(IMPACT_ParVec * v, IMPACT_Var * f1, IMPACT_Config *c,
int *i,int *j,IMPACT_Dim *x1)
{
int Nv=c->Nv();
double rowsum=0.0;
double answer=0.0;
for (int k=1;k<=Nv;++k)
rowsum+=f1->get(v,i,j,&k,x1)*c->v2(&k)*c->v3(&k)*c->dv(&k);
answer=fourthirdspi*rowsum*0.5;
return answer;
}
<file_sep>/include/impacta_extpks/impacta_matrix_solver.h
/*
**********************************************************
The Matrix solver - takes an IMPACT_Sparse and converts
to a PETSc AIJ sparse. Solves locally and returns vector.
Version 2.9
AGRT
15/3/07
15/4/07 - NB NB NB!!! vin is RHS (n) vector, vout is LHS (n+1)
25/10/07 - Update! Uses explicit soln as possible start solution
29/10/07 - Explicit soln needs rethinking but importantly the
rtol value for the solver previously = rtol(specified)/N
This was obviously unnecessary and also probably doesn't
helpt with convergence very much
1/2/08 Major Development!!!!!
----------------------------------------------------------
New iterative method of solving matrix. For scalar n,
equation
Ax=b
can be solved in the following way for x
(A+I)x=c
c = Ax+x = b+x
A+I = D
if we solve
D^-1 c = x
We can get x, but c=b+x. Can converge on solution with
x_(i+1) = D^-1 (b+x_i)
This is now implemented.
----------------------------------------------------------
**********************************************************
*/
static char help[] = "Matrix solver which takes IMPACT_Sparse and IMPACT_Vector forms and converts them to Petsc objects before solving the matrix equation";
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Input arguments for matrix solve:
argc - number of commandline flags
args - array of flags (strings)
Ain - input Sparse matrix, A[0][Nz], A[1][N+1], A[2][Nz]
bin - solution vector
uin - vector to solve via u=(A)^(-1)b
Nin - number of rows of Ain
Nzin - number of non-zero entries in Ain - no! agrt291106
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*
Yale Sparse Matrix Format:
Matrix Aij is represented by 3 vectors:
A - The nonzero values in a long column
I - The position of the first entry of row i in vector A
J - The column values for the entries in vector A
Then to extract Aij from the three vectors, for value Aij
cycle over rows i, then cycle from j=I(i) to I(i+1)
Then extract A(j) and J(j)
*/
inline int MatrixSolve(IMPACT_Config *c,IMPACT_MPI_Config *M, IMPACT_ParSpa *IMPACT_S,IMPACT_ParVec *IMPACT_vin,IMPACT_ParVec *IMPACT_vout,int argc,char **args,int *lagged)
{
Vec PETSC_vin,PETSC_vout; //Petsc Vectors
/* approx solution, RHS, exact solution */ //no x now agrt251106
Mat PETSC_S; /* PETSC Sparse matrix */
KSP ksp; /* linear solver context */
PetscInt Istart,Iend, N,n,its;//N is size of Matrix n is local length
// its - iteration numebr
PetscErrorCode ierr;
PetscLogDouble time1,time2; //for recording the time!
PC pc; //preconditioner
//PetscScalar v; //reusable double for inserting values
//int *d_nnz,*o_nnz; //These will be arrays for preallocation of memory
PetscScalar iteratematrixscalar = zerotolerance::iterate_matrix;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int rank,size;
int badreturn=0;
// Step 1 - set relevent values from MPI_Config:
rank=M->rank();
size=M->size();
Istart=M->start()-1;
Iend=M->end()-1;
N=c->totalpoints();
n=M->N();
if (rank==0) std::cout<<"\n";
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Step 2 - initialize Matrix solver:
PetscInitialize(&argc,&args,(char *)0,help);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Compute the matrix and right-hand-side vector that define
the linear system, Ax = b.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*
(Petsc notes...)
Create parallel matrix, specifying only its global dimensions.
When using MatCreate(), the matrix format can be specified at
runtime. Also, the parallel partitioning of the matrix is
determined by PETSc at runtime.
Performance tuning note: For problems of substantial size,
preallocation of matrix memory is crucial for attaining good
performance. See the matrix chapter of the users manual for details.
*/
// Step 3 - preallocate memory
MPI::COMM_WORLD.Barrier();
// We will first use the numinrows only -> can be improved later:
PetscInt *preall;
preall = new PetscInt[n];
PetscInt columntemp; //needed because petsc goes from 0 to n-1
double IfZeroRow; //needed if whole row is zero - set diag to 1
PetscScalar one = 1.0;
for (int i=0;i<n;++i)
preall[i]=IMPACT_S->getrow(i+Istart+2)-IMPACT_S->getrow(i+Istart+1);
startofmatrixsolve:
MatCreateAIJ(PETSC_COMM_WORLD,n,n,N,N,0,preall,0,preall,&PETSC_S);
// MatCreateMPIAIJ(PETSC_COMM_WORLD,n,n,N,N,0,preall,0,preall,&PETSC_S);
ierr = MatSetOption(PETSC_S,MAT_IGNORE_ZERO_ENTRIES,PETSC_TRUE); CHKERRQ(ierr); // PETSC TRUE added for PETSC 3.0.0
//____________________________________________________________________________
/*
Step 4 -Insert Matrix elements from Yale Sparse Matrix Format
Remember IMPACT is from 1 to N whereas PETSC is from 0 to N-1
//_____________________________________________________________________________
*/
ierr = PetscGetTime(&time1);CHKERRQ(ierr); //get time
for (int rowcount=Istart;rowcount<=Iend;++rowcount)
{
IfZeroRow=0.0;
for (int subrowcount=IMPACT_S->getrow(rowcount+1);
subrowcount<IMPACT_S->getrow(rowcount+2);++subrowcount)
{
IfZeroRow+=IMPACT_S->getval(subrowcount);
columntemp=IMPACT_S->getcol(subrowcount)-1;
ierr = MatSetValues(PETSC_S,1,&rowcount,1,&columntemp,
IMPACT_S->getval_add(subrowcount),
INSERT_VALUES);CHKERRQ(ierr);
}
if (IfZeroRow==0.0)
ierr = MatSetValues(PETSC_S,1,&rowcount,1,&rowcount,
&one, INSERT_VALUES);
}
/*
Assemble matrix, using the 2-step process:
MatAssemblyBegin(), MatAssemblyEnd()
Computations can be done while messages are in transition
by placing code between these two statements.
*/
ierr = MatAssemblyBegin(PETSC_S,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyEnd(PETSC_S,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = PetscGetTime(&time2);CHKERRQ(ierr);
std::ostringstream Imess1("");
Imess1<< "\nRank "<<rank<<": Sparse matrix transfer IMPACT->PETSC took - " <<IMPACT_GetTime(time2-time1);
if (if_dump_switches::view_matrix)
MatView(PETSC_S,PETSC_VIEWER_DRAW_WORLD);
/*
Create parallel vectors.
- We form 1 vector from scratch and then duplicate as needed.
- When using VecCreate(), VecSetSizes and VecSetFromOptions()
in this example, we specify only the
vector's global dimension; the parallel partitioning is determined
at runtime.
- When solving a linear system, the vectors and matrices MUST
be partitioned accordingly. PETSc automatically generates
appropriately partitioned matrices and vectors when MatCreate()
and VecCreate() are used with the same communicator.
- The user can alternatively specify the local vector and matrix
dimensions when more sophisticated partitioning is needed
(replacing the PETSC_DECIDE argument in the VecSetSizes() statement
below).
*/
//Step 5 - create vector from impact vector
ierr = PetscGetTime(&time1);CHKERRQ(ierr); //get time
VecCreateMPI(MPI_COMM_WORLD,n,N,&PETSC_vin);
ierr = VecDuplicate(PETSC_vin,&PETSC_vout);CHKERRQ(ierr);
//Insert values for vector PETSC_vin
for (int i=Istart;i<=Iend;i++)
{
ierr=VecSetValues(PETSC_vin,1,&i,IMPACT_vin->Get_add(i+1)
,INSERT_VALUES);CHKERRQ(ierr);
ierr=VecSetValues(PETSC_vout,1,&i,IMPACT_vout->Get_add(i+1)
,INSERT_VALUES);CHKERRQ(ierr);
}
VecAssemblyBegin(PETSC_vin); VecAssemblyBegin(PETSC_vout);
VecAssemblyEnd(PETSC_vin); VecAssemblyEnd(PETSC_vout);
ierr = PetscGetTime(&time2);CHKERRQ(ierr);
Imess1<< "\nRank "<<rank<<": Vector transfer IMPACT->PETSC took - " <<IMPACT_GetTime(time2-time1);
if(!rank) Imess1<<'\n';
std::cout<<Imess1.str();
MPI::COMM_WORLD.Barrier();
/* _-----------------------------------------------------------------
step 5b - If user requests, find explicit solution of equation
to act as rhs vector as a preconditioner.
We do two half time steps to get soln
-> Didn't work very well
Try linear soln as start point:
Single step explicit:
*/
if (zerotolerance::explicit_PC)
{
PetscScalar idt = c->idt(), dt=c->dt(), Nsteps=1.0;
// These two operations are equivalent to M = 2/dtI - M;
ierr = MatScale(PETSC_S,-1.0);CHKERRQ(ierr);
ierr = MatShift(PETSC_S,idt);CHKERRQ(ierr); //gets rid of diagonal elem
ierr = MatScale(PETSC_S,dt/Nsteps*0.5);CHKERRQ(ierr);
ierr = MatShift(PETSC_S,1.0/Nsteps);CHKERRQ(ierr); // adds diagonal
// Now get solution M v_in = v_out
ierr = MatMult(PETSC_S,PETSC_vin,PETSC_vout);CHKERRQ(ierr);
/*
Vec PETSC_vout_temp;
ierr = VecDuplicate(PETSC_vout,&PETSC_vout_temp);CHKERRQ(ierr);
for (int step =1;step<Nsteps;++step)
{
VecCopy(PETSC_vout,PETSC_vout_temp);
ierr = MatMult(PETSC_S,PETSC_vout_temp,PETSC_vout);CHKERRQ(ierr);
}
VecDestroy(PETSC_vout_temp);
*/
// now revert Matrix to original form:
ierr = MatShift(PETSC_S,-1.0/Nsteps);CHKERRQ(ierr); // adds diagonal
ierr = MatScale(PETSC_S,idt*Nsteps*2.0);CHKERRQ(ierr);
ierr = MatShift(PETSC_S,-idt);CHKERRQ(ierr);
ierr = MatScale(PETSC_S,-1.0);CHKERRQ(ierr);
// Fiinally multiply by dt
//ierr = VecScale(PETSC_vout,dt);CHKERRQ(ierr);
}
/* _-----------------------------------------------------------------
step 5b - If user requests, iterate towards solution using previous
close solution
*/
if (iteratematrixscalar>0.0)
{
iteratematrixscalar=zerotolerance::iterate_matrix;
if (!rank) std::cout<<"\nIterating matrix:\nShifting matrix elements...";
ierr = MatShift(PETSC_S,iteratematrixscalar); CHKERRQ(ierr);
if (!rank) std::cout<<"Finished\nMultiplying through...";
ierr = VecAXPY(PETSC_vin,iteratematrixscalar,PETSC_vout);
if (!rank) std::cout<<"Finished\n";
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
step 6 - Create the linear solver and set various options
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*
Create linear solver context
*/
ierr = PetscGetTime(&time1);CHKERRQ(ierr); //get time
ierr = KSPCreate(MPI_COMM_WORLD,&ksp);CHKERRQ(ierr);
KSPSetType(ksp,KSPBCGS); //Set method of ksp -biconjugate gradient stabilized
/*
Set operators. Here the matrix that defines the linear system
also serves as the preconditioning matrix.
*/
ierr = KSPSetOperators(ksp,PETSC_S,PETSC_S,DIFFERENT_NONZERO_PATTERN);
CHKERRQ(ierr);
/*
Set linear solver defaults for this problem (optional).
- By extracting the KSP and PC contexts from the KSP context,
we can then directly call any KSP and PC routines to set
various options.
- The following two statements are optional; all of these
parameters could alternatively be specified at runtime via
KSPSetFromOptions(). All of these defaults can be
overridden at runtime, as indicated below.
*/
// Also on first loop, rtol can be 1e-2
if (!*lagged&&zerotolerance::on_first_lag_low_rtol)
ierr = KSPSetTolerances(ksp,zerotolerance::low_rtol,
zerotolerance::KSP_atol,
zerotolerance::KSP_dtol,
zerotolerance::MatrixSolver_ItMax);
else if (*lagged==1&&zerotolerance::on_first_lag_low_rtol)
ierr = KSPSetTolerances(ksp,zerotolerance::low_rtol/10,
zerotolerance::KSP_atol,
zerotolerance::KSP_dtol,
zerotolerance::MatrixSolver_ItMax);
else
ierr = KSPSetTolerances(ksp,zerotolerance::KSP_rtol,
zerotolerance::KSP_atol,
zerotolerance::KSP_dtol,
zerotolerance::MatrixSolver_ItMax);
CHKERRQ(ierr);
//ierr = PCSetType(pc,PCASM); CHKERRQ(ierr);
//ierr = PCSetType(pc,PCILU); CHKERRQ(ierr);
/*
Set runtime options, e.g.,
-ksp_type <type> -pc_type <type> -ksp_monitor -ksp_rtol <rtol>
These options will override those specified above as long as
KSPSetFromOptions() is called _after_ any other customization
routines.
*/
ierr = KSPSetFromOptions(ksp);CHKERRQ(ierr);
ierr = KSPSetInitialGuessNonzero(ksp,PETSC_TRUE);CHKERRQ(ierr);
ierr = KSPGetPC(ksp,&pc); CHKERRQ(ierr);
ierr = PCFactorSetZeroPivot(pc,1e-50); CHKERRQ(ierr);
// ierr = PCFactorSetShiftType(pc,MAT_SHIFT_POSITIVE_DEFINITE); CHKERRQ(ierr);
// ierr = PCFactorSetShiftAmount(pc,PETSC_DECIDE); CHKERRQ(ierr);
// ierr = PCFactorSetShiftPd(pc,PETSC_TRUE); CHKERRQ(ierr);
// ierr = PCFactorSetShiftNonzero(pc,PETSC_DECIDE); CHKERRQ(ierr);
ierr = PetscGetTime(&time2);CHKERRQ(ierr);
std::ostringstream Imess2;
Imess2<<"\nPETSC: Processor "<<rank<<" of "<<size<<" - KSP solver setup took - " <<time2-time1<<" s";
//if(!rank) Imess2<<'\n';
std::cout<<Imess2.str();
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Step 7 - Solve the linear system
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
MPI::COMM_WORLD.Barrier();
if (!rank) std::cout<<"\n\n";
ierr = PetscGetTime(&time1);CHKERRQ(ierr); //get time
// ierr = KSPView(ksp,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
ierr = KSPSolve(ksp,PETSC_vin,PETSC_vout);
if (ierr>0)
{
//this changed to help converge matrix
if(zerotolerance::iterate_matrix==0.0)
zerotolerance::iterate_matrix=zerotolerance::init_matrix_it;
else zerotolerance::iterate_matrix*=zerotolerance::matrix_it_multiplier;
if (zerotolerance::iterate_matrix>0.01)
{
if (!rank) std::cout<<BRED<<"IMPACTA: Matrix error - can't fix\n Exiting...\n"<<ENDFORMAT;
exit(0);
}
else{
if (rank==0) {
std::cout<<BRED<<"Matrix error (probably zero pivot or zero on the diagonal)\n"<<ENDFORMAT<<"\nChanging matrix iteration tolerance to "
<< zerotolerance::iterate_matrix
<< " and retrying matrix solve\n";
}
MPI::COMM_WORLD.Barrier();
ierr = VecDestroy(&PETSC_vout);CHKERRQ(ierr);
ierr = KSPDestroy(&ksp);CHKERRQ(ierr);
ierr = VecDestroy(&PETSC_vin);CHKERRQ(ierr);
ierr = MatDestroy(&PETSC_S);CHKERRQ(ierr);
goto startofmatrixsolve;
// IMPACT_Soft_Exit(M,1);
}
}
CHKERRQ(ierr);
//KSPTrueMonitor(ksp,its,converg,PETSC_NULL);
KSPGetIterationNumber(ksp,&its); CHKERRQ(ierr);
//for diagnostics....
IMPACT_Diagnostics::total_nl_its+=its;
IMPACT_Diagnostics::nl_times+=1.0;
//
KSPConvergedReason reason;
KSPGetConvergedReason(ksp,&reason);
// PetscScalar converg; //convergence info
ierr = PetscGetTime(&time2);CHKERRQ(ierr);
if (rank==0){
std::ostringstream Imess3;
Imess3<<ULINE<<BYELLOW<<"PETSC: Matrix Solver - " <<its<<" iteration(s)";
Imess3<<" took - " <<IMPACT_GetTime(time2-time1)<<std::endl<<ENDFORMAT<<ULINE;
std::cout<<Imess3.str();
}
if (reason > 0)
{
if (rank==0)
PetscPrintf(MPI_COMM_WORLD,"Linear solve converged due to %s\n",
KSPConvergedReasons[reason]);
}
else
{
//this changed to help converge matrix
if(zerotolerance::iterate_matrix==0.0)
zerotolerance::iterate_matrix=zerotolerance::init_matrix_it;
else zerotolerance::iterate_matrix*=zerotolerance::matrix_it_multiplier;
if (zerotolerance::iterate_matrix>1.0)
{
zerotolerance::adaptive_timesteps*=zerotolerance::adaptive_multiplier;
badreturn=1;
++zerotolerance::adaptivetimes;
}
else{
if (rank==0) {
std::cout<<BRED;
PetscPrintf(MPI_COMM_WORLD,"Linear solve did not converge due to %s\n",
KSPConvergedReasons[reason]);
std::cout<<ENDFORMAT<<"\nChanging matrix iteration tolerance to "
<< zerotolerance::iterate_matrix
<< " and retrying matrix solve\n";
}
MPI::COMM_WORLD.Barrier();
ierr = VecDestroy(&PETSC_vout);CHKERRQ(ierr);
ierr = KSPDestroy(&ksp);CHKERRQ(ierr);
ierr = VecDestroy(&PETSC_vin);CHKERRQ(ierr);
ierr = MatDestroy(&PETSC_S);CHKERRQ(ierr);
goto startofmatrixsolve;
// IMPACT_Soft_Exit(M,1);
}
}
//__________________________________________________
if (!badreturn)
{
PetscScalar *vec_arr; //pointer to array
//Step 8 - Return vector
ierr = VecGetArray(PETSC_vout,&vec_arr); CHKERRQ(ierr); //This gets the elements
for (int i=0; i<n; ++i)
if (fabs(vec_arr[i])>zerotolerance::zerothreshold)
IMPACT_vout->Set(i+1+Istart,vec_arr[i]); // This locally updates vout
ierr = VecRestoreArray(PETSC_vout,&vec_arr); CHKERRQ(ierr);
}
//__________________________________________________
//
//Step 9 -Clean up the PETSC objects
//
ierr = VecDestroy(&PETSC_vout);CHKERRQ(ierr);
ierr = KSPDestroy(&ksp);CHKERRQ(ierr);
ierr = VecDestroy(&PETSC_vin);CHKERRQ(ierr);
ierr = MatDestroy(&PETSC_S);CHKERRQ(ierr);
delete[] preall;
//This line leads to readjusting the timestep if things get easier
if (zerotolerance::iterate_matrix<1.0/zerotolerance::matrix_it_multiplier
&&zerotolerance::adaptivetimes>0) --zerotolerance::adaptivetimes;
zerotolerance::iterate_matrix=zerotolerance::iterate_matrix_orig_val;
return badreturn;
}
<file_sep>/include/impacta_io/impacta_input.h
/*
**********************************************************
IMPACTA
Function for reading input deck and setting up new
config object from it
Version 1.2
AGRT
30/3/07
11/2/08
Unbelievably badly written code - very sorry about that
**********************************************************
*/
std::string StringToUpper(std::string myString);
//Input and initial messages
IMPACT_Config IMPACT_Input(int *argnum, char **argstr)
{
int rank;
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
// First open inputdeck
/*int dircheck=0;
for (int i=0;i<*argnum;++i)
if (!strcmp(argstr[i], "-rd")) {dircheck=i;argstr[i]=NULL;}
if (dircheck>0)
{argstr[dircheck+1]; argstr[dircheck+1]=NULL;}*/
//First sort out file management
//*************************************************************
IMPACT_Messages::Root_Dir= IMPACT_Get_CmdLine(argnum, argstr,"-rd");
if (!strcmp(IMPACT_Messages::Root_Dir.c_str(), "*nofield*"))
IMPACT_Messages::Root_Dir="";
else IMPACT_Messages::Root_Dir = IMPACT_Messages::Root_Dir+"/";
IMPACT_Messages::Data_Directory=IMPACT_Messages::Root_Dir+"IMPACTA_Data/";
IMPACT_Messages::Input_Directory=IMPACT_Messages::Root_Dir+"IMPACTA_Data_In/";
if_dump_switches::ifdumpall=1-IMPACT_Cmp_CmdLine(*argnum, argstr,"-no_dump");
//no xnbody wanted:
IMPACT_Diagnostics::noxnbody=1-IMPACT_Cmp_CmdLine(*argnum, argstr,"-using_xnbody");
IMPACT_Messages::InDeck= IMPACT_Get_CmdLine(argnum, argstr,"-read");
if (!strcmp(IMPACT_Messages::InDeck.c_str(), "*nofield*"))
IMPACT_Messages::InDeck="imstdin";
IMPACT_Messages::InDeck=IMPACT_Messages::Root_Dir+IMPACT_Messages::InDeck;
std::string filename = IMPACT_Messages::InDeck;
std::ifstream infile(filename.c_str());
if (!infile) IMPACT_ferr(filename.c_str());
//*************************************************************
std::string input_para; //input string from infile
std::string old_para=""; // for storing the previous string of the loop
char comment_char[200]; //for reading comments
int stringlength=30;
char *input_char;
input_char=new char[stringlength+1]; //for storing data
int currentvar=0; //for indexing what we are looking for
int grid_err=1;
//*************************************************************
// Get some command line instructions!
int probecheck = IMPACT_Cmp_CmdLine(*argnum, argstr, "-probe_input");
IMPACT_Diagnostics::divcheck = !IMPACT_Cmp_CmdLine(*argnum, argstr, "-no_div_check");
if (!IMPACT_Diagnostics::divcheck&&!rank) std::cout<<"Ignoring divergence in Picard iteration\n";
if (IMPACT_Cmp_CmdLine(*argnum, argstr, "-echo_infuncs"))
IMPACT_Messages::if_show_function_input=1;
std::string truth; //for testing truth
std::istringstream Bimptemp;
Bimptemp.str(IMPACT_Get_CmdLine(argnum, argstr,"-B_implicit_frac"));
if (strcmp(Bimptemp.str().c_str(),"*nofield*")) {
Bimptemp>>globalconsts::Bimp;
if (globalconsts::Bimp<0.0||globalconsts::Bimp>1.0){
std::cout<<"IMPACT: ERROR - Not a valid value for B implicit fraction\n";
exit(0);
}
}
// For initial DLM Distribution
std::istringstream DLMtemp;
DLMtemp.str(IMPACT_Get_CmdLine(argnum, argstr,"-init_DLM_order"));
if (strcmp(DLMtemp.str().c_str(),"*nofield*")) {
DLMtemp>>equation_switches::Gamma_A;
if (equation_switches::Gamma_A<2.0){
std::cout<<"IMPACT: ERROR - Not a valid value for DLM order\n";
std::cout<<equation_switches::Gamma_A<<'\n';
exit(0);
}
}
// dEbydtfix fraction
std::istringstream Efixtemp;
Efixtemp.str(IMPACT_Get_CmdLine(argnum, argstr,"-Fix_dE/dt"));
if (strcmp(Efixtemp.str().c_str(),"*nofield*")) {
Efixtemp>>equation_switches::dEbydtfix;
if (equation_switches::dEbydtfix<0.0||equation_switches::dEbydtfix>1.0){
std::cout<<"IMPACT: ERROR - Not a valid value for dE/dt fix\n";
exit(0);
}
}
// Iterate the picard iteration
std::istringstream PCITMATtemp;
PCITMATtemp.str(IMPACT_Get_CmdLine(argnum, argstr,"-max_picard_its"));
if (strcmp(PCITMATtemp.str().c_str(),"*nofield*")) {
PCITMATtemp>>zerotolerance::max_picard_its;
if (zerotolerance::iterate_matrix<0){
std::cout<<"IMPACT: ERROR - Not a valid value for max picard its\n";
exit(0);
}
}
// Change temperature normalization
std::istringstream Tnormtemp;
Tnormtemp.str(IMPACT_Get_CmdLine(argnum, argstr,"-renorm_temp"));
if (strcmp(Tnormtemp.str().c_str(),"*nofield*")) {
Tnormtemp>>equation_switches::NEW_T_NORM;
if (equation_switches::NEW_T_NORM<0){
std::cout<<"IMPACT: ERROR - Not a valid value for temperature normalization\n";
exit(0);
}
}
// Iterate the matrix
std::istringstream ITMATtemp;
ITMATtemp.str(IMPACT_Get_CmdLine(argnum, argstr,"-iterate_matrix"));
if (strcmp(ITMATtemp.str().c_str(),"*nofield*")) {
ITMATtemp>>zerotolerance::iterate_matrix;
if (zerotolerance::iterate_matrix<0.0){
std::cout<<"IMPACT: ERROR - Not a valid value for matrix iteration coefficient\n";
exit(0);
}
}
zerotolerance::iterate_matrix_orig_val=zerotolerance::iterate_matrix;
if_dump_switches::view_matrix=IMPACT_Cmp_CmdLine(*argnum, argstr,"-view_matrix");
zerotolerance::linear_solution_PC=IMPACT_Cmp_CmdLine(*argnum, argstr,"-LPC");
zerotolerance::explicit_PC=IMPACT_Cmp_CmdLine(*argnum, argstr,"-EPC");
zerotolerance::on_first_lag_low_rtol=IMPACT_Cmp_CmdLine(*argnum, argstr,"-KSP_lower_initial_rtol");
equation_switches::Bimp_in_E_equation=1.0-IMPACT_Cmp_CmdLine(*argnum, argstr,"-B_explicit");
if (equation_switches::Bimp_in_E_equation==0.0) equation_switches::dEbydtfix=0.0;
if(IMPACT_Cmp_CmdLine(*argnum, argstr,"-time_centering"))
{
equation_switches::Bimp_in_E_equation=0.5;
equation_switches::jimp_in_E_equation=0.5; //remember - can't be zero
equation_switches::Eimp_in_B_equation=0.5;
}
//*************************************************************
//Critical information....
int nprocs=0; //number of processors
int nmax = 0;
double dt=-1;
int Nx=0,Ny=0,Nv=0;
int NB=-1,EOn=-1,f1On=-1,f2On=-1,f3On=-1;
for (int i=0;i<IMPACT_Input_Deck::MAXVAR;++i)
IMPACT_Input_Deck::Var_check[i]=0;
int loopcheck=0;
//-1 so we can check it has been specified
char coords[3]={0,0,0};
double *xgrid,*ygrid,*vgrid, *xtemp,*ytemp, *ttemp;
ttemp = new double[nmax+2];
for (int i=0;i<nmax+2;++i) ttemp[i]=1.0*i;
//non-critical information
double *Z_gridx,*Z_gridy,*ne_gridx,*ne_gridy,*ni_gridx,*ni_gridy;
double *Te_gridx,*Te_gridy,*B_gridx,*B_gridy;
double *heating_x,*heating_y,*heating_t;
double *Dnz_x,*Dnz_y,*dnz_t,*DTz_x,*DTz_y,*dTz_t;
double Bhat[3]={0,0,0};
double xmin = 0.0,ymin = 0.0; //where the simulation lower bound is
double T0 = 0.0;
int Ndump=1;
double wpeovernuei,vteoverc;
int grd_val=0;
double gridval=0.0;
char temptruth;
while(infile>>input_para&¤tvar<IMPACT_Input_Deck::MAXVAR-1)
{
std::ostringstream numtemp(""); //for storing data
std::istringstream inumtemp(""); //for outputting data
for (int k=0;k<stringlength;++k)
input_char[k]=0; //reset input_char
if (input_para.c_str()[0]=='%') //to deal with comments
{
infile.getline(comment_char,200,'\n');
input_para="";
}
//now check if there is an = sign...
int length = strlen(input_para.c_str());
for (int i=0;i<length;++i)
if (input_para.c_str()[i]=='=') //to deal with either spaces or not
{ //between = sign and parameter
//first make it uppercase to get rid of ambiguity
if (!i) //(if = is the first character)
{
for (int j=0;j<(int)strlen(old_para.c_str());++j)
{
input_char[j] = (char)toupper(old_para.c_str()[j]);
}
}
else
{
for (int j=0;j<i;++j)
input_char[j] = (char)toupper(input_para.c_str()[j]);
}
if (i<length-1) //(if = is not the last character)
{ //the procedure is to get the string after the =
char tempstore; //and turn it into a number
for (int m=0;m<length-i-1;++m)
{
tempstore=input_para.c_str()[m+i+1];
if (tempstore==',') break;
numtemp<<tempstore;
inumtemp.str(numtemp.str());
}
}
else
{
infile>>input_para;
inumtemp.str(input_para);
}
}
old_para=input_para;
/*
next comes the easy part - the istringstream object is
emptied of its information depending on the previous
string name - e.g. if the string before the = is
xmin - then the data is put into xmin.
*/
std::string grid_temp=""; grid_err=1;// for extracting grid info;
std::string dirtemp="";
loopcheck=0;
int endcheck=IMPACT_Input_Deck::MAXVAR-currentvar;
if (endcheck>4) endcheck=4;
for (int i=0;i<endcheck;++i)
if(!strcmp(input_char,IMPACT_Input_Deck::Var_names[currentvar+i]))
{loopcheck=1; currentvar+=i;break;}
if (loopcheck)
{
switch (currentvar)
{
case 0:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>dirtemp;
IMPACT_Messages::Data_Directory =
IMPACT_Messages::Root_Dir+dirtemp+"/"; break;
case 1:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>dirtemp;
IMPACT_Messages::Input_Directory =
IMPACT_Messages::Root_Dir+dirtemp+"/"; break;
case 2:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>nprocs; break;
case 3:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>nmax; break;
case 4:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>dt;
ttemp = new double[nmax+2];
for (int i=0;i<nmax+2;++i) ttemp[i]=dt*i;
break;
case 5:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>Ndump; break;
case 6:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>T0; break;
case 7:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>Nx; break;
case 8:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>Ny; break;
case 9:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>Nv; break;
case 10:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>coords; break;
case 11:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>xmin; break;
case 12:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>ymin;
break;
case 13:
IMPACT_Input_Deck::Var_check[currentvar]=1;
xgrid= new double[Nx+2];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"dx:\t\t";
grid_err = IMPACT_Make_Axis(infile, grid_temp,xgrid,Nx,xmin,1);
//now make xvalues...
xtemp= new double[Nx+2];
xmin+=0.5*xgrid[1];
xtemp[1]=xmin;
// std::cout<<"xtemp[0]: " << xtemp[0] <<" xgrid[0]: " << xgrid[0] << "\n";
// std::cout<<"xtemp[1]: " << xtemp[1] <<" xgrid[1]: " << xgrid[1] << "\n";
for (int i=2;i<Nx+2;++i)
xtemp[i]=xtemp[i-1]+0.5*(xgrid[i-1]+xgrid[i]);
// std::cout<<"xtemp[i]: " << xtemp[i] <<" xgrid[i]: " << xgrid[i] << "\n";}
break;
case 14:
IMPACT_Input_Deck::Var_check[currentvar]=1;
ygrid= new double[Ny+2];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"dy:\t\t";
grid_err = IMPACT_Make_Axis(infile, grid_temp,ygrid,Ny,ymin,2);
//now make y values
ytemp= new double[Ny+2];
ymin+=0.5*ygrid[1];
ytemp[1]=ymin;
for (int i=2;i<Ny+2;++i)
ytemp[i]=ytemp[i-1]+0.5*(ygrid[i-1]+ygrid[i]);
break;
case 15:
IMPACT_Input_Deck::Var_check[currentvar]=1;
vgrid= new double[Nv+2];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"dv:\t\t";
grid_err = IMPACT_Make_Axis(infile, grid_temp,vgrid,Nv,0.0,3);
vgrid[0]=vgrid[1];
vgrid[Nv+1]=vgrid[Nv];
break;
case 16:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>NB; break;
case 17:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
EOn=IMPACT_truth(truth); break;
case 18:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
f1On=IMPACT_truth(truth); break;
case 19:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
f2On=IMPACT_truth(truth); break;
case 20:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
f3On=IMPACT_truth(truth); break;
case 21:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>zerotolerance::zerothreshold; break;
case 22:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>zerotolerance::laggedtolerance; break;
case 23:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>zerotolerance::KSP_atol; break;
case 24:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>zerotolerance::KSP_rtol; break;
case 25:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>zerotolerance::KSP_dtol; break;
case 26:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>zerotolerance::MatrixSolver_ItMax; break;
case 27:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
IMPACT_strcpy(argstr[*argnum-IMPACT_Input_Deck::Extra_cmdln]
,"-pc_type");
IMPACT_strcpy(argstr[*argnum-IMPACT_Input_Deck::Extra_cmdln+1]
,truth);
break;
case 28:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
IMPACT_strcpy(argstr[*argnum-IMPACT_Input_Deck::Extra_cmdln+2]
,"-ksp_type");
IMPACT_strcpy(argstr[*argnum-IMPACT_Input_Deck::Extra_cmdln+3]
,truth);
break;
case 29:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if (IMPACT_truth(truth))
IMPACT_strcpy(argstr[*argnum-IMPACT_Input_Deck::Extra_cmdln+4]
,"-ksp_monitor");
break;
case 30:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>IMPACTA_ions::atomic_mass_number;
break;
case 31:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>globalconsts::oneover_atomic_Z;
globalconsts::oneover_atomic_Z=1.0/globalconsts::oneover_atomic_Z;
break;
case 32:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>IMPACTA_ions::ion_temperature;
break;
case 33:
for (int i=0;i<3;++i)
IMPACT_Input_Deck::Var_check[currentvar+i]=1;
currentvar+=2;
inumtemp>>grid_temp;
grid_err =IMPACT_Make_Function2D(infile,grid_temp,&Initial_Conditions::Z,
xtemp,ytemp,Nx,Ny);
Z_gridx= new double[1];
Z_gridy= new double[1];
break;
case 34:
IMPACT_Input_Deck::Var_check[currentvar]=1;
IMPACT_Input_Deck::Var_check[currentvar-1]=1;
Z_gridx= new double[Nx];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"Z(x):\t\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,Z_gridx,xtemp,Nx);
break;
case 35:
IMPACT_Input_Deck::Var_check[currentvar]=1;
Z_gridy= new double[Ny];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"Z(y):\t\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,Z_gridy,ytemp,Ny);
//this must be parallelized at some point
IMPACT_Make_2DGrid(&Initial_Conditions::Z,Z_gridx,Z_gridy,Nx,Ny);
break;
case 36:
for (int i=0;i<3;++i)
IMPACT_Input_Deck::Var_check[currentvar+i]=1;
currentvar+=2;
inumtemp>>grid_temp;
grid_err =IMPACT_Make_Function2D(infile,grid_temp,&Initial_Conditions::ne,
xtemp,ytemp,Nx,Ny);
ne_gridx= new double[1];
ne_gridy= new double[1];
break;
case 37:
IMPACT_Input_Deck::Var_check[currentvar]=1;
IMPACT_Input_Deck::Var_check[currentvar-1]=1;
ne_gridx= new double[Nx];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"ne(x):\t\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,ne_gridx,xtemp,Nx);
break;
case 38:
IMPACT_Input_Deck::Var_check[currentvar]=1;
ne_gridy= new double[Ny];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"ne(y):\t\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,ne_gridy,ytemp,Ny);
IMPACT_Make_2DGrid(&Initial_Conditions::ne,ne_gridx,ne_gridy,Nx,Ny);
break;
case 39:
for (int i=0;i<3;++i)
IMPACT_Input_Deck::Var_check[currentvar+i]=1;
currentvar+=2;
inumtemp>>grid_temp;
grid_err =IMPACT_Make_Function2D(infile,grid_temp,&Initial_Conditions::ni,
xtemp,ytemp,Nx,Ny);
ni_gridx= new double[1];
ni_gridy= new double[1];
break;
case 40:
IMPACT_Input_Deck::Var_check[currentvar]=1;
IMPACT_Input_Deck::Var_check[currentvar-1]=1;
ni_gridx= new double[Nx];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"ni(x):\t\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,ni_gridx,xtemp,Nx);
break;
case 41:
IMPACT_Input_Deck::Var_check[currentvar]=1;
ni_gridy= new double[Ny];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"ni(y):\t\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,ni_gridy,ytemp,Ny);
IMPACT_Make_2DGrid(&Initial_Conditions::ni,ni_gridx,ni_gridy,Nx,Ny);
break;
case 42:
for (int i=0;i<3;++i)
IMPACT_Input_Deck::Var_check[currentvar+i]=1;
currentvar+=2;
inumtemp>>grid_temp;
grid_err =IMPACT_Make_Function2D(infile,grid_temp,
&Initial_Conditions::Te,
xtemp,ytemp,Nx,Ny);
Te_gridx= new double[1];
Te_gridy= new double[1];
break;
case 43:
IMPACT_Input_Deck::Var_check[currentvar]=1;
IMPACT_Input_Deck::Var_check[currentvar-1]=1;
Te_gridx= new double[Nx];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"Te(x):\t\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,Te_gridx,xtemp,Nx);
break;
case 44:
IMPACT_Input_Deck::Var_check[currentvar]=1;
Te_gridy= new double[Ny];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"Te(y):\t\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,Te_gridy,ytemp,Ny);
IMPACT_Make_2DGrid(&Initial_Conditions::Te,Te_gridx,Te_gridy,Nx,Ny);
break;
case 45:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>grid_temp;
grid_err =IMPACT_Make_Function2D(infile,grid_temp,
&Initial_Conditions::B[0],
xtemp,ytemp,Nx,Ny);
break;
case 46:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>grid_temp;
grid_err =IMPACT_Make_Function2D(infile,grid_temp,
&Initial_Conditions::B[1],
xtemp,ytemp,Nx,Ny);
break;
case 47:
for (int i=0;i<4;++i)
IMPACT_Input_Deck::Var_check[currentvar+i]=1;
inumtemp>>grid_temp;
currentvar+=3;
grid_err =IMPACT_Make_Function2D(infile,grid_temp,
&Initial_Conditions::B[2],
xtemp,ytemp,Nx,Ny);
B_gridx= new double[1];
B_gridy= new double[1];
break;
case 48:
for (int i=0;i>-4;--i)
IMPACT_Input_Deck::Var_check[currentvar+i]=1;
inumtemp>>grid_temp;
grid_err = IMPACT_Get_Bhat(infile, grid_temp,Bhat);
break;
case 49:
IMPACT_Input_Deck::Var_check[currentvar]=1;
B_gridx= new double[Nx];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"B_0(x):\t\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,B_gridx,xtemp,Nx);
break;
case 50:
IMPACT_Input_Deck::Var_check[currentvar]=1;
B_gridy= new double[Ny];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"B_0(y):\t\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,B_gridy,ytemp,Ny);
for (int i=0;i<3;++i)
{
IMPACT_Make_2DGrid(&Initial_Conditions::B[i],
B_gridx,B_gridy,Nx,Ny);
Initial_Conditions::B[i].multiplyall(Bhat[i]);
//normalize to the unit vector Bhat
}
break;
case 51:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>wpeovernuei;
break;
case 52:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>vteoverc;
break;
case 53:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::f0_equation_on=IMPACT_truth(truth);
if (!strcmp(truth.c_str(),"EXMX"))
{
equation_switches::evolvef0=1;
equation_switches::f0_equation_on=0;
}
break;
case 54:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::f1_equation_on=IMPACT_truth(truth); break;
case 55:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::f2_equation_on=IMPACT_truth(truth); break;
case 56:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::f3_equation_on=IMPACT_truth(truth); break;
case 57:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::E_equation_on=IMPACT_truth(truth); break;
case 58:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::B_equation_on=IMPACT_truth(truth); break;
case 59:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::df0_by_dt_on=(double)IMPACT_truth(truth);
break;
case 60:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::inf0_grad_f1_on=(double)IMPACT_truth(truth);
break;
case 61:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::inf0_Edf1dv_on=(double)IMPACT_truth(truth);
break;
case 62:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::Cee0_on=(double)IMPACT_truth(truth);
break;
case 63:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::e_inert_on=(double)IMPACT_truth(truth);
break;
case 64:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::inf1_vgradf0_on=(double)IMPACT_truth(truth);
break;
case 65:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::inf1_Edf0dv_on=(double)IMPACT_truth(truth);
break;
case 66:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::inf1_f1xB_on=(double)IMPACT_truth(truth);
break;
case 67:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::Cei_on=(double)IMPACT_truth(truth);
break;
case 68:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::Cee1_on=IMPACT_truth(truth);
break;
case 69:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::e_viscosity_on=(double)IMPACT_truth(truth);
break;
case 70:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::df3_by_dt_on=(double)IMPACT_truth(truth);
break;
case 71:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::disp_j_on=(double)IMPACT_truth(truth);
break;
case 72:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
equation_switches::relaxtoeq=IMPACT_truth(truth);
if (!strcmp(truth.c_str(),"f1only"))
equation_switches::relaxtoeq=2;
break;
case 73:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>zerotolerance::equil_percent;
break;
case 74:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>zerotolerance::RB_D_tolerance; break;
case 75:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>zerotolerance::RB_D_itmax;
break;
case 76:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
zerotolerance::RB_iterate=IMPACT_truth(truth);
break;
case 77:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if (!strcmp(truth.c_str(),"IB"))
IMPACT_Heating::IB_type_on=1.0;
if (!strcmp(truth.c_str(),"MX"))
IMPACT_Heating::MX_type_on=1.0;
break;
case 78:
for (int i=0;i<3;++i)
IMPACT_Input_Deck::Var_check[currentvar+i]=1;
currentvar+=2;
if (IMPACT_Heating::IB_type_on==1.0
||IMPACT_Heating::MX_type_on==1.0)
{
inumtemp>>grid_temp;
grid_err=IMPACT_Make_Function2D(infile,grid_temp,
&IMPACT_Heating::Heating_xy
,xtemp,ytemp,Nx,Ny);
heating_x= new double[1];
heating_y= new double[1];
}
break;
case 79:
IMPACT_Input_Deck::Var_check[currentvar]=1;
IMPACT_Input_Deck::Var_check[currentvar-1]=1;
if (IMPACT_Heating::IB_type_on==1.0
||IMPACT_Heating::MX_type_on==1.0)
{
heating_x= new double[Nx];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"Heating(x):\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,heating_x,xtemp,Nx);
}
break;
case 80:
IMPACT_Input_Deck::Var_check[currentvar]=1;
if (IMPACT_Heating::IB_type_on==1.0
||IMPACT_Heating::MX_type_on==1.0)
{
heating_y= new double[Ny];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"Heating(y):\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,heating_y,ytemp,Ny);
IMPACT_Make_2DGrid(&IMPACT_Heating::Heating_xy,heating_x,heating_y,Nx,Ny);
}
break;
case 81:
IMPACT_Input_Deck::Var_check[currentvar]=1;
heating_t= new double[nmax];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"Heating(t):\t";
grid_err=IMPACT_Make_Grid(infile, grid_temp,heating_t,ttemp,nmax);
break;
case 82:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>> IMPACT_Heating::vosc_squared;
IMPACT_Heating::vosc_squared*=IMPACT_Heating::vosc_squared;
break;
case 83:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>> IMPACT_Heating::polarization;
break;
case 84:
for (int i=0;i<3;++i)
IMPACT_Input_Deck::Var_check[currentvar+i]=1;
currentvar+=2;
inumtemp>>grid_temp;
grid_err=IMPACT_Make_Function2D(infile,grid_temp,
&IMPACT_Heating::Dnz_xy
,xtemp,ytemp,Nx,Ny);
Dnz_x= new double[1];
Dnz_y= new double[1];
break;
case 85:
IMPACT_Input_Deck::Var_check[currentvar]=1;
IMPACT_Input_Deck::Var_check[currentvar-1]=1;
Dnz_x= new double[Nx];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"dn/dz/n(x):\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,Dnz_x,xtemp,Nx);
break;
case 86:
IMPACT_Input_Deck::Var_check[currentvar]=1;
Dnz_y= new double[Ny];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"dn/dz/n(y):\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,Dnz_y,ytemp,Ny);
IMPACT_Make_2DGrid(&IMPACT_Heating::Dnz_xy,Dnz_x,Dnz_y,Nx,Ny);
break;
case 87:
IMPACT_Input_Deck::Var_check[currentvar]=1;
dnz_t= new double[nmax];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"dn/dz/n(t):\t";
grid_err=IMPACT_Make_Grid(infile, grid_temp,dnz_t,ttemp,nmax);
break;
case 88:
for (int i=0;i<3;++i)
IMPACT_Input_Deck::Var_check[currentvar+i]=1;
currentvar+=2;
inumtemp>>grid_temp;
grid_err=IMPACT_Make_Function2D(infile,grid_temp,
&IMPACT_Heating::DTz_xy
,xtemp,ytemp,Nx,Ny);
DTz_x= new double[1];
DTz_y= new double[1];
break;
case 89:
IMPACT_Input_Deck::Var_check[currentvar]=1;
IMPACT_Input_Deck::Var_check[currentvar-1]=1;
DTz_x= new double[Nx];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"dT/dz/T(x):\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,DTz_x,xtemp,Nx);
break;
case 90:
IMPACT_Input_Deck::Var_check[currentvar]=1;
DTz_y= new double[Ny];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"dT/dz/T(y):\t";
grid_err = IMPACT_Make_Grid(infile, grid_temp,DTz_y,ytemp,Ny);
IMPACT_Make_2DGrid(&IMPACT_Heating::DTz_xy,DTz_x,DTz_y,Nx,Ny);
break;
case 91:
IMPACT_Input_Deck::Var_check[currentvar]=1;
dTz_t= new double[nmax];
inumtemp>>grid_temp;
if (IMPACT_Messages::if_show_function_input)
std::cout<<"dT/dz/T(t):\t";
grid_err=IMPACT_Make_Grid(infile, grid_temp,dTz_t,ttemp,nmax);
break;
case 92:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_ne=IMPACT_truth(truth); break;
case 93:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_ni=IMPACT_truth(truth); break;
case 94:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_Ci=IMPACT_truth(truth); break;
case 95:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_Z=IMPACT_truth(truth); break;
case 96:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_Te=IMPACT_truth(truth); break;
case 97:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_Ue=IMPACT_truth(truth); break;
case 98:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_je=IMPACT_truth(truth); break;
case 99:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_q=IMPACT_truth(truth); break;
case 100:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_P=IMPACT_truth(truth); break;
case 101:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_E=IMPACT_truth(truth); break;
case 102:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_B=IMPACT_truth(truth); break;
case 103:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_wt=IMPACT_truth(truth); break;
case 104:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_VN=IMPACT_truth(truth); break;
case 105:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_eta=IMPACT_truth(truth); break;
case 106:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_f0=IMPACT_truth(truth); break;
case 107:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_f1=IMPACT_truth(truth); break;
case 108:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
if_dump_switches::dump_f2=IMPACT_truth(truth); break;
case 109:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>if_dump_switches::f_ndump; break;
case 110:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>temptruth;
switch (temptruth)
{
case 'p':
IMPACT_Boundaries::boundary_type=0;
break;
case 'r':
IMPACT_Boundaries::boundary_type=1;
break;
case 'b':
IMPACT_Boundaries::boundary_type=2;
break;
case 'R':
IMPACT_Boundaries::boundary_type=4;
break;
case 'o':
IMPACT_Boundaries::boundary_type=3;
break;
case 'P':
IMPACT_Boundaries::boundary_type=5;
break;
default:
std::cout<<"\nIMPACTA: ERROR - In input deck, unknown boundaries\n";
exit(0);
}
break;
case 111:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>temptruth;
switch (temptruth)
{
case 'p':
IMPACT_Boundaries::boundary_type+=0;
break;
case 'r':
IMPACT_Boundaries::boundary_type+=10;
break;
case 'b':
IMPACT_Boundaries::boundary_type+=20;
break;
case 'o':
IMPACT_Boundaries::boundary_type+=30;
break;
default:
std::cout<<"\nIMPACTA: ERROR - In input deck, unknown boundaries\n";
exit(0);
}
break;
case 112:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>grd_val;
IMPACT_Boundaries::fix_f0.set(0,grd_val);
for (int i=1;i<4;++i)
{
infile >> grd_val;
if (grd_val==1||grd_val==0)
IMPACT_Boundaries::fix_f0.set(i,grd_val);
else
{
std::cout<<"\nIMPACTA: ERROR - In input deck, fixed boundaries\n";
exit(0);
}
}
break;
case 113:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>grd_val;
IMPACT_Boundaries::fix_f1_E.set(0,grd_val);
for (int i=1;i<4;++i)
{
infile >>grd_val;
if (grd_val==1||grd_val==0)
IMPACT_Boundaries::fix_f1_E.set(i,grd_val);
else
{
std::cout<<"\nIMPACTA: ERROR - In input deck, fixed boundaries\n";
exit(0);
}
}
break;
case 114:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>grd_val;
IMPACT_Boundaries::fix_f2.set(0,grd_val);
for (int i=1;i<4;++i)
{
infile >>grd_val;
if (grd_val==1||grd_val==0)
IMPACT_Boundaries::fix_f2.set(i,grd_val);
else
{
std::cout<<"\nIMPACTA: ERROR - In input deck, fixed boundaries\n";
exit(0);
}
}
break;
case 115:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>grd_val;
IMPACT_Boundaries::fix_B.set(0,grd_val);
for (int i=1;i<4;++i)
{
infile >>grd_val;
if (grd_val==1||grd_val==0)
IMPACT_Boundaries::fix_B.set(i,grd_val);
else
{
std::cout<<"\nIMPACTA: ERROR - In input deck, fixed boundaries\n";
exit(0);
}
}
break;
case 116:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>grd_val;
IMPACT_Boundaries::fix_ni.set(0,grd_val);
for (int i=1;i<4;++i)
{
infile >>grd_val;
if (grd_val==1||grd_val==0)
IMPACT_Boundaries::fix_ni.set(i,grd_val);
else
{
std::cout<<"\nIMPACTA: ERROR - In input deck, fixed boundaries\n";
exit(0);
}
}
break;
case 117:
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>gridval;
IMPACT_Boundaries::fix_Ci.set(0,grd_val);
for (int i=1;i<4;++i)
{
infile >>gridval;
IMPACT_Boundaries::fix_Ci.set(i,grd_val);
}
break;
case 118:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>gridval;
IMPACTA_smoothing::smooth_kernel[0]=gridval;
double smoothtemp=IMPACTA_smoothing::smooth_kernel[0];
//std::cout << IMPACTA_smoothing::smooth_kernel[0] << "\n";
for (int i=1;i<5;++i)
{
infile >>gridval;
IMPACTA_smoothing::smooth_kernel[i]=gridval;
smoothtemp+=IMPACTA_smoothing::smooth_kernel[i];
//std::cout << IMPACTA_smoothing::smooth_kernel[i] << "\n"; std::cout << smoothtemp << "\n";
}
if ( !((smoothtemp-1.0)<1e-6) )
{
std::cout<<"\nIMPACTA: ERROR - In input deck, smoothing kernel must sum to 1.0!\n";
exit(0);
}
break;
}
case 119:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
std::cout<<"ionization = "<<truth<<'\n';
truth=StringToUpper(truth); // make uppercase
if (!strcmp(truth.c_str(),"NONE"))
IMPACTA_ions::ionization_on=0;
if (!strcmp(truth.c_str(),"SAHA"))
IMPACTA_ions::ionization_on=1;
if (!strcmp(truth.c_str(),"TF"))
IMPACTA_ions::ionization_on=2;
break;
}
case 120:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp>>truth;
IMPACTA_ions::quasin_on=IMPACT_truth(truth);
break;
}
case 121:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >>truth;
equation_switches::tr_bool=IMPACT_truth(truth);
break;
}
case 122:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >>gridval;
IMPACT_Heating::beam_width=gridval;
break;
}
case 123:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >>gridval;
IMPACT_Heating::beam_res=gridval;
break;
}
case 124:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >> truth;
truth=StringToUpper(truth); // make uppercase
if (!strcmp(truth.c_str(),"X"))
IMPACT_Heating::direction=0;
if (!strcmp(truth.c_str(),"Y"))
IMPACT_Heating::direction=1;
break;
}
case 125:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >> truth;
truth=StringToUpper(truth); // make uppercase
if (!strcmp(truth.c_str(),"U"))
IMPACT_Heating::shape=0;
if (!strcmp(truth.c_str(),"S"))
IMPACT_Heating::shape=1;
if (!strcmp(truth.c_str(),"G"))
IMPACT_Heating::shape=2;
break;
}
case 126:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >>gridval;
IMPACT_Heating::n_c=gridval;
break;
}
case 127:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >>gridval;
IMPACT_Heating::ray_x0=gridval;
break;
}
case 128:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >>gridval;
IMPACT_Heating::ray_y0=gridval;
break;
}
case 129:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >>gridval;
IMPACT_Heating::theta=gridval*globalconsts::pi/180.0;
break;
}
case 130:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >>gridval;
IMPACT_Heating::dtheta = gridval*globalconsts::pi/180.0;
break;
}
case 131:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >>gridval;
IMPACT_Heating::ds=gridval;
break;
}
case 132:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >>gridval;
IMPACT_Heating::diffsteps=gridval;
break;
}
case 133:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >>gridval;
Initial_Conditions::T_mult =gridval;
break;
}
case 134:
{
IMPACT_Input_Deck::Var_check[currentvar]=1;
inumtemp >>gridval;
Initial_Conditions::f0delta =gridval;
break;
}
}
inumtemp.clear();
if (probecheck)
std::cout<<"->"<<IMPACT_Input_Deck::Var_names[currentvar]<<'\n';
++currentvar;
}
//Now check we haven't missed one
// if(!strcmp(input_char,IMPACT_Input_Deck::Var_names[currentvar+1]))
if (currentvar>1)
if (!IMPACT_Input_Deck::Var_check[currentvar-1])
{
std::cout<<"\nIMPACT: ERROR - Input deck is missing parameter or is out of order\n\n";
std::cout<<"Error at "<< currentvar << " "<< IMPACT_Input_Deck::Var_names[currentvar-1]<<'\n';
exit(0);
}
}
infile.close();
/*
finally we have to check the values are sensible
note that don't need to check the switches EOn etc
as an error would lead them to be off.
*/
if (!grid_err) IMPACT_InputDeckError("grid error");
if (Nx<1||Ny<1||Nv<1) IMPACT_InputDeckError("Nx or Ny or Nv less than 1");
if (NB<0||NB>3||NB==2) IMPACT_InputDeckError("only 0, 1 or 3 B components allowed");
if (dt<0.0) IMPACT_InputDeckError("dt must be positive"); //can't have time running backwards!
if (nmax<1) IMPACT_InputDeckError("more than 1 timestep needed!");
if (EOn<0||f1On<0||f2On<0||f3On<0) IMPACT_InputDeckError("E, f1, f2 components must be 0 or 1" );
if (coords[0]!='x'||coords[1]!='y') IMPACT_InputDeckError("Coordinate error");
//if (currentvar< IMPACT_Input_Deck::MAXVAR-1) IMPACT_InputDeckError("");
// check parameters all present (input deck not missing field)
int ifanymissing=0;
for (int i=0;i<IMPACT_Input_Deck::MAXVAR-1;++i){
if (!IMPACT_Input_Deck::Var_check[i]){
std::cout<<"IMPACTA: ERROR - input deck missing parameter/statement '"<<IMPACT_Input_Deck::Var_names[i]<<"'\n";
ifanymissing++;
}
}
if (ifanymissing) {
std::cout<<"input deck out of date or incorrect, please check. Exiting...\n";
exit(0);
}
// check for negative temperature or density or Z
int ne_error=0;
std::string ne_errormessage="";
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
if(Initial_Conditions::Z.get(&i,&j)<0.0){ne_errormessage="Z";ne_error=1;}
if(Initial_Conditions::ne.get(&i,&j)<0.0){ne_errormessage="ne";ne_error=1;}
if(Initial_Conditions::ni.get(&i,&j)<0.0){ne_errormessage="ni";ne_error=1;}
if(Initial_Conditions::Te.get(&i,&j)<0.0){ne_errormessage="Te";ne_error=1;}
}
if (ne_error)
{
std::cout<< "IMPACT: ERROR - in input deck, "<<ne_errormessage<<" is less than zero on at least one gridcell\n";
exit(0);
}
// Now output all this information to the screen so it can be seen
//
double xmax=xmin+xgrid[1]*0.5,ymax=ymin+ygrid[1]*0.5,vmax=0.0;
for (int i=1;i<Nx-1;++i) xmax+=0.5*(xgrid[i+1]+xgrid[i]);
for (int i=1;i<Ny-1;++i) ymax+=0.5*(ygrid[i+1]+ygrid[i]);
for (int i=1;i<=Nv;++i) vmax+=0.5*(vgrid[i+1]+vgrid[i]);
xmax+=0.5*xgrid[Nx-1];
ymax+=0.5*ygrid[Ny-1];
if (!rank)
if (IMPACT_Cmp_CmdLine(*argnum, argstr, "-echo_input"))
{
std::cout<<'\n'<<"From Input Deck:\nNt = "<<nmax<<"\nNx = "<<Nx<<"\nNy = "<<Ny<<"\nNv = "<<Nv<<'\n';
std::cout<<"t = ("<<T0<<":"<<dt*nmax<<")\nx = ("<<xmin-.5*xgrid[1]<<":"<<xmax+.5*xgrid[Nx]<<")\ny = ("<<ymin-.5*ygrid[1]<<":"<<ymax+.5*ygrid[Ny]<<")\nv = (0:"<<vmax<<")";
std::cout<<BWHITE<<"\nf0: equation is "
<<BGREEN<<onoroff(equation_switches::f0_equation_on);
std::cout<<BWHITE<<"\nf1: elements are "<< BGREEN
<<onoroff(f1On)<<BWHITE", equation is "<<BGREEN
<<onoroff(equation_switches::f1_equation_on);
std::cout<<BWHITE<<"\nf2: elements are "<<BGREEN<<onoroff(f2On)
<<BWHITE<<", equation is "
<<BGREEN<<onoroff(equation_switches::f2_equation_on);
std::cout<<BWHITE<<"\nf3: elements are "<<BGREEN<<onoroff(f3On)
<<BWHITE<<", equation is "<<BGREEN
<<onoroff(equation_switches::f3_equation_on);
std::cout<<BWHITE<<"\nE: elements are "<<BGREEN<<onoroff(EOn)
<<BWHITE<<", equation is "<<BGREEN
<<onoroff(equation_switches::E_equation_on);
std::cout<<'\n'<<BGREEN<<NB<<BWHITE
<<" B-field components, B equation is "<<BGREEN
<<onoroff(equation_switches::B_equation_on)<<'\n'
<<ENDFORMAT;
std::cout<<"Ndump = "<<Ndump<<'\n';
std::cout<<"zero tolerance = "<<zerotolerance::zerothreshold<<'\n';
std::cout<<"lagged tolerance = "<<zerotolerance::laggedtolerance<<'\n';
std::cout<<"KSP atol = "<<zerotolerance::KSP_atol<<'\n';
std::cout<<"KSP rtol = "<<zerotolerance::KSP_rtol<<'\n';
std::cout<<"KSP dtol = "<<zerotolerance::KSP_dtol<<'\n';
std::cout<<"KSP max iterations = "<<zerotolerance::MatrixSolver_ItMax<<'\n';
std::cout<<"w_pe over nu_ei = "<< wpeovernuei<<'\n';
std::cout<<"v_te over c = "<< vteoverc<<'\n';
std::cout<<"delta^2 = "<<globalconsts::c_L*globalconsts::c_L
/globalconsts::omega_p_nuei_n/globalconsts::omega_p_nuei_n<<'\n';
std::cout<<ULINE<<'\n';
}
IMPACT_Diagnostics::output_precision=nprocs;
//Make grids by multipling the one d functions
//MAKE HEATING GRIDS
IMPACT_Heating::Heating_t.ChangeSize(nmax);
IMPACT_Heating::DTz_t.ChangeSize(nmax);
IMPACT_Heating::Dnz_t.ChangeSize(nmax);
for (int i=0;i<nmax;++i)
{
IMPACT_Heating::Heating_t.Set(i+1,heating_t[i]);
IMPACT_Heating::Dnz_t.Set(i+1,dnz_t[i]);
IMPACT_Heating::DTz_t.Set(i+1,dTz_t[i]);
}
if (IMPACT_Heating::IB_type_on==1.0||IMPACT_Heating::MX_type_on==1.0)
{
/* for (int i=0;i<Nx;++i)
heating_x[i]*=Z_gridx[i]*Z_gridx[i]*ni_gridx[i]*oneover6;
for (int i=0;i<Ny;++i)
heating_y[i]*=Z_gridy[i]*Z_gridy[i]*ni_gridy[i]*oneover6;
IMPACT_Make_2DGrid(&IMPACT_Heating::Heating_xy,heating_x,heating_y,Nx,Ny);
double heating_val=0.0;
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
heating_val=Initial_Conditions::Z.get(&i,&j)*
Initial_Conditions::Z.get(&i,&j)*
Initial_Conditions::ni.get(&i,&j)*oneover6;
********************************************
This now moved into the collision update
********************************************
//IMPACT_Heating::Heating_xy.Iset(IMPACT_Heating::Heating_xy.get(&i,&j)
// *heating_val,&i,&j);
}*/
/*
for polarization dependence, the matrix elements are the combo EE-1/3I
E = cos theta_p xhat + sin theta_p yhat
*/
/*if (!getcoord(IMPACT_Heating::polarization))
for (int i=1;i<=3;++i)
IMPACT_Heating::vosc_hat.set(i,i,0.0);
else
{
if (getcoord(IMPACT_Heating::polarization)==4)
{
// Circularly polarized case
IMPACT_Heating::vosc_hat.set(1,1,2.0*oneover3);
IMPACT_Heating::vosc_hat.set(2,2,2.0*oneover3);
IMPACT_Heating::vosc_hat.set(3,3,-oneover3);
}
else
{
if (getcoord(IMPACT_Heating::polarization)==5)
{
// Polarized at 45 degrees to x and y axis
IMPACT_Heating::vosc_hat.set(1,1,0.5*oneover3);
IMPACT_Heating::vosc_hat.set(2,2,0.5*oneover3);
IMPACT_Heating::vosc_hat.set(1,2,0.5);
IMPACT_Heating::vosc_hat.set(2,1,0.5);
IMPACT_Heating::vosc_hat.set(3,3,-oneover3);
}
else
{
for (int i=1;i<=3;++i)
IMPACT_Heating::vosc_hat.set(i,i,-oneover3);
IMPACT_Heating::vosc_hat.set(getcoord(IMPACT_Heating::polarization),getcoord(IMPACT_Heating::polarization),2.0*oneover3);
}
}
}*/
double Elaser[3]={0.0,0.0,0.0}; //unit vectors for laser
double p=0.0; //0.0 for circular, 1.0 for linear polarization
switch (IMPACT_Heating::polarization)
{
case 'x':
Elaser[0]=1.0; p=1.0;
break;
case 'y':
Elaser[1]=1.0; p=1.0;
break;
case 'z':
Elaser[2]=1.0; p=1.0;
break;
case 'c':
p=0.0;
break;
case 'd':
Elaser[0]=1.0/sqrt(2.0); Elaser[1]=1.0/sqrt(2.0); p=1.0;
break;
default:
break;
}
// FORM POLARIZATION MATRICES
for (int i=1;i<=3;++i)
for (int j=1;j<=3;++j)
IMPACT_Heating::vosc_hat.set(i,j,Elaser[i-1]*Elaser[j-1]);
IMPACT_Heating::vosc_hat.inc(1,1,(1.0-p));
IMPACT_Heating::vosc_hat.inc(2,2,(1.0-p));
// subtract 1/3 I
for (int i=1;i<=3;++i)
IMPACT_Heating::vosc_hat.inc(i,i,-oneover3);
IMPACT_Heating::Total_heating_contribution.copy(&IMPACT_Heating::Heating_xy);
// NOW FORM B-FEEDBACK MATRICES
//-----------------------------------------------------
if (NB>0)
{
if (NB>1)
{
IMPACT_Heating::vosc_hat_Bx.set(1,2,-0.5*Elaser[0]*Elaser[2]);
IMPACT_Heating::vosc_hat_Bx.set(2,1,-0.5*Elaser[0]*Elaser[2]);
IMPACT_Heating::vosc_hat_Bx.set(1,3,0.5*Elaser[0]*Elaser[1]);
IMPACT_Heating::vosc_hat_Bx.set(3,1,0.5*Elaser[0]*Elaser[1]);
IMPACT_Heating::vosc_hat_Bx.set(2,2,-Elaser[1]*Elaser[2]);
IMPACT_Heating::vosc_hat_Bx.set(2,3,0.5*((1.0-p)+Elaser[1]*Elaser[1]
-Elaser[2]*Elaser[2]));
IMPACT_Heating::vosc_hat_Bx.set(3,2,0.5*((1.0-p)+Elaser[1]*Elaser[1]
-Elaser[2]*Elaser[2]));
IMPACT_Heating::vosc_hat_Bx.set(3,3,Elaser[1]*Elaser[2]);
//*******************************************************
IMPACT_Heating::vosc_hat_By.set(1,1,Elaser[0]*Elaser[2]);
IMPACT_Heating::vosc_hat_By.set(1,2,0.5*Elaser[1]*Elaser[2]);
IMPACT_Heating::vosc_hat_By.set(2,1,0.5*Elaser[1]*Elaser[2]);
IMPACT_Heating::vosc_hat_By.set(1,3,0.5*(-(1.0-p)+Elaser[2]*Elaser[2]
-Elaser[0]*Elaser[0]));
IMPACT_Heating::vosc_hat_By.set(3,1,0.5*(-(1.0-p)+Elaser[2]*Elaser[2]
-Elaser[0]*Elaser[0]));
IMPACT_Heating::vosc_hat_By.set(2,3,-0.5*Elaser[0]*Elaser[1]);
IMPACT_Heating::vosc_hat_By.set(3,2,-0.5*Elaser[0]*Elaser[1]);
IMPACT_Heating::vosc_hat_By.set(3,3,-Elaser[0]*Elaser[2]);
}
//*******************************************************
IMPACT_Heating::vosc_hat_Bz.set(1,1,-Elaser[0]*Elaser[1]);
IMPACT_Heating::vosc_hat_Bz.set(1,2,0.5*(Elaser[0]*Elaser[0]
-Elaser[1]*Elaser[1]));
IMPACT_Heating::vosc_hat_Bz.set(2,1,0.5*(Elaser[0]*Elaser[0]
-Elaser[1]*Elaser[1]));
IMPACT_Heating::vosc_hat_Bz.set(1,3,-0.5*Elaser[1]*Elaser[2]);
IMPACT_Heating::vosc_hat_Bz.set(3,1,-0.5*Elaser[1]*Elaser[2]);
IMPACT_Heating::vosc_hat_Bz.set(2,2,Elaser[0]*Elaser[1]);
IMPACT_Heating::vosc_hat_Bz.set(2,3,0.5*Elaser[0]*Elaser[2]);
IMPACT_Heating::vosc_hat_Bz.set(3,2,0.5*Elaser[0]*Elaser[2]);
}
//-----------------------------------------------------
}
/* IMPACT_Heating::vosc_hat.Print();
IMPACT_Heating::vosc_hat_Bx.Print();
IMPACT_Heating::vosc_hat_By.Print();
IMPACT_Heating::vosc_hat_Bz.Print();
exit(0);*/
//-----------------------------------------------------
if (omega_p_nuei_n<1.0&&!equation_switches::disp_j_on){
std::cout << BRED<<"IMPACT: Warning - omega_p over nu_ei is less than 1 and displacement current is switched off\n (Matrix solve error may occur)\n";
std::cout<<ENDFORMAT<<"Switch on dE/dt? ";
std::string answer;
std::cin>>answer;
if (!strcmp(answer.c_str(),"yes") ) equation_switches::disp_j_on=1.0;
}
/*
Setting of global consts
These have been altered to include temperature normalization
*/
globalconsts::c_L=fabs(1.0/vteoverc)/sqrt(equation_switches::NEW_T_NORM);
globalconsts::omega_p_nuei_n = fabs(wpeovernuei)*pow(equation_switches::NEW_T_NORM,1.5);
IMPACT_Heating::vosc_squared/=equation_switches::NEW_T_NORM;
//-----------------------------------------------------
globalconsts::deltasquared=globalconsts::c_L*globalconsts::c_L/globalconsts::omega_p_nuei_n/globalconsts::omega_p_nuei_n;
/*
IMPACTA_ions::a1bar=me_over_mp/(2.0*oneover_atomic_Z*IMPACTA_ions::atomic_mass_number);
IMPACTA_ions::a2bar=IMPACTA_ions::a1bar*c_L*c_L/omega_p_lambda_n/omega_p_lambda_n;
*/
IMPACTA_ions::alpha_ion = (me_over_mp/IMPACTA_ions::atomic_mass_number
/(globalconsts::oneover_atomic_Z));
/* if (!equation_switches::disp_j_on) {equation_switches::disp_j_on+=
globalconsts::omega_p_lambda_n*
globalconsts::omega_p_lambda_n*
zerotolerance::dispj_off_frac;
// if (equation_switches::disp_j_on<1e-12) equation_switches::disp_j_on=1e-12;
} */
IMPACT_Config config(Nx,Ny,Nv,xgrid,ygrid,vgrid,dt,1,f1On,f2On,f3On,EOn,NB);
/* Cee0_flux_store::flux = new IMPACT_Vel_Sten*[Nv+1];
for (int kk=0;kk<=Nv;++kk)
Cee0_flux_store::flux[kk]= new IMPACT_Vel_Sten(0.0,0.0,0.0);*/
config.set_xmin(xmin);
config.set_ymin(ymin);
config.set_nmax(nmax);
config.set_ndump(Ndump);
if (!config.Nf1()) equation_switches::f1_equation_on=0;
if (!config.Nf2()) equation_switches::f2_equation_on=0;
if (!config.Nf3()) equation_switches::f3_equation_on=0;
if (!config.NE()) equation_switches::E_equation_on=0;
if (!config.NB()) equation_switches::B_equation_on=0;
/* if (!IMPACT_Cmp_CmdLine(*argnum, argstr, "-no_calc_ni"))
{
Initial_Conditions::ni.SwitchOffConst();
Initial_Conditions::ni.ChangeSize(Nx,Ny);
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
Initial_Conditions::ni.set(i,j,Initial_Conditions::ne.get(&i,&j)/
Initial_Conditions::Z.get(&i,&j));
}*/
// FOR ION MOTION
//__________________________________________________________________________
Initial_Conditions::ni.SwitchOffConst(Nx,Ny);
IMPACTA_ions::ion_motion=!IMPACT_Cmp_CmdLine(*argnum, argstr, "-static_ions");
if (IMPACTA_ions::ion_motion)
{
for (int dir=0;dir<3;++dir)
{
Initial_Conditions::C_i[dir].SwitchOffConst();
Initial_Conditions::C_i[dir].ChangeSize(Nx,Ny);
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
Initial_Conditions::C_i[dir].set(i,j,0.0);
Initial_Conditions::C_istar[dir].SwitchOffConst();
Initial_Conditions::C_istar[dir].ChangeSize(Nx,Ny);
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
Initial_Conditions::C_istar[dir].set(i,j,0.0);
}
Initial_Conditions::DivC_i.SwitchOffConst();
Initial_Conditions::DivC_i.ChangeSize(Nx,Ny);
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
Initial_Conditions::DivC_i.set(i,j,0.0);
}
else
{
for (int dir=0;dir<3;++dir)
{
Initial_Conditions::C_i[dir].setc(0.0);
Initial_Conditions::C_istar[dir].setc(0.0);
}
Initial_Conditions::DivC_i.setc(0.0);
}
//__________________________________________________________________________
//For ionization
Initial_Conditions::Z.SwitchOffConst(Nx,Ny);
// C_istar is used to smooth Z
if (IMPACTA_ions::ionization_on&&!IMPACTA_ions::ion_motion){
for (int dir=0;dir<3;++dir) {
Initial_Conditions::C_istar[dir].SwitchOffConst();
Initial_Conditions::C_istar[dir].ChangeSize(Nx,Ny);
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
Initial_Conditions::C_istar[dir].set(i,j,0.0);
}
}
//__________________________________________________________________________
if (IMPACT_Cmp_CmdLine(*argnum, argstr, "-show_all_initial"))
{
std::cout<< BPURPLE<<"Z\n"<<YELLOW;
Initial_Conditions::Z.Print();
std::cout<< BPURPLE<<"ni\n"<<YELLOW;
Initial_Conditions::ni.Print();
std::cout<< BPURPLE<<"ne\n"<<YELLOW;
Initial_Conditions::ne.Print();
std::cout<< BPURPLE<<"Te\n"<<YELLOW;
Initial_Conditions::Te.Print();
for (int dim=0;dim<3;++dim)
{
std::cout<< BPURPLE<< "B_x"<<dim+1<<'\n'<<YELLOW;
Initial_Conditions::B[dim].Print();
}
std::cout<<ENDFORMAT;
}
//For dbydz grids
IMPACT_Heating::DTbydzgrid.SwitchOffConst(Nx,Ny);
IMPACT_Heating::Dnbydzgrid.SwitchOffConst(Nx,Ny);
Initial_Conditions::ne.SwitchOffConst(Nx,Ny);
Initial_Conditions::Te.SwitchOffConst(Nx,Ny);
double gridtemp=0.0;
for (int i=1;i<=Nx;++i)
for (int j=1;j<=Ny;++j)
{
gridtemp=IMPACT_Heating::Dnz_xy.get(&i,&j)
*IMPACT_Heating::Dnz_t.Get(1)
/Initial_Conditions::ne.get(&i,&j);
IMPACT_Heating::Dnbydzgrid.Iset(gridtemp,&i,&j);
gridtemp=IMPACT_Heating::DTz_xy.get(&i,&j)
*IMPACT_Heating::DTz_t.Get(1)/Initial_Conditions::Te.get(&i,&j);
IMPACT_Heating::DTbydzgrid.Iset(gridtemp,&i,&j);
}
for (int i=0;i<4;++i)
{
IMPACT_Boundaries::fixed_any.inc(i,IMPACT_Boundaries::fix_f0[i]);
IMPACT_Boundaries::fixed_any.inc(i,IMPACT_Boundaries::fix_f1_E[i]);
IMPACT_Boundaries::fixed_any.inc(i,IMPACT_Boundaries::fix_f2[i]);
IMPACT_Boundaries::fixed_any.inc(i,IMPACT_Boundaries::fix_B[i]);
IMPACT_Boundaries::fixed_any.inc(i,IMPACT_Boundaries::fix_ni[i]);
IMPACT_Boundaries::fixed_any.inc(i,(IMPACT_Boundaries::fix_Ci[i]!=0.0));
if (IMPACT_Boundaries::fixed_any[i]) {
IMPACT_Boundaries::fixed_any.set(i,1);
} else {
IMPACT_Boundaries::fixed_any.set(i,0);
}
}
// set smoothing kernel
for (int i=0;i<5;++i){
LAX.set(i,IMPACTA_smoothing::smooth_kernel[i]);
}
//for diagnosis
IMPACT_Diagnostics::showmatrix=
IMPACT_Cmp_CmdLine(*argnum,argstr,"-show_matrix");
IMPACT_Diagnostics::showvector=
IMPACT_Cmp_CmdLine(*argnum,argstr,"-show_vector");
IMPACT_strcpy(argstr[*argnum-IMPACT_Input_Deck::Extra_cmdln+5]
,"-mat_view_info");
delete[] xgrid;
delete[] ygrid;
delete[] vgrid;
delete[] xtemp;
delete[] ytemp;
delete[] ttemp;
delete[] Z_gridx;
delete[] Z_gridy;
delete[] ne_gridx;
delete[] ne_gridy;
delete[] ni_gridx;
delete[] ni_gridy;
delete[] Te_gridx;
delete[] Te_gridy;
delete[] B_gridx;
delete[] B_gridy;
if ( IMPACT_Heating::IB_type_on==1.0||IMPACT_Heating::MX_type_on==1.0)
{
delete[] heating_x;
delete[] heating_y;
delete[] heating_t;
}
delete[] input_char;
return config;
}
//Routine for uppercasing string
std::string StringToUpper(std::string myString)
{
const int length = myString.length();
for(int i=0; i!=length ; ++i)
{
myString[i] = std::toupper(myString[i]);
}
return myString;
}
<file_sep>/include/impacta_environment.h
/*
**********************************************************
Enviroment settings for IMPACTA code
Including boundary conditions and differential info
1
AGRT
22/2/08 - Ion motion added
12/2/07
12/3/07 - The boundary condition stuff in here doesn't
really do anything. The code is in the operators .h file
The other namespaces do though.
200 - MPI messages communicating ParVecs.
17/4/07 - more changes - diagnostic variables
3/5/07 - vector checking code inserted at end
27/7/07 Many small additions
15/10/07 - MPIChunkSize added as constant
feb 08 - iterations for matrix added
1/7/08 - Fixed boundaries changed to simpler algorithm
**********************************************************
*/
/*
Later need to read some of these namespaces from a file.
These are namespaces for different differential types
The name is fairly self explanatory
the codes are
diff_type
20 - centred - (as in Roberts paper 12/2/07)
10 - upwind (won't work yet 23/1/07)
coords
0 - x-y cartesian
1 - r-theta cylindrical
2 - r-z cylindrical
In the transformation the coordinates
x -> r
y -> theta/z
*/
/*There will be a lot of these - one for each boundary (4-6)
for each component (f0,f1....B - 6) yielding something like
32 separate boundary variables.
*/
//Definitions
#define ULINE "----------------------------------------------------------"<<std::endl
#define T_ULINE "**********************************************************"<<std::endl
#define TAB '\t'
//Color definitions - using ANSI codes - may not be portable
#ifndef IMPACTAWITHCOLOUR
#define RED "" // makes text red
#define GREEN "" // makes text green
#define YELLOW "" // makes text yellow
#define BLUE "" // makes text blue
#define PURPLE "" // makes text purple
#define CYAN "" // makes text cyan
#define WHITE "" // makes text white
#define BRED "" // makes text red
#define BGREEN "" // makes text green
#define BYELLOW "" // makes text yellow
#define BBLUE "" // makes text blue
#define BPURPLE "" // makes text purple
#define BCYAN "" // makes text cyan
#define BWHITE "" // makes text white
#define ENDFORMAT "" // ends text formatting
#else
#define RED "\033[0;"<<31<<"m" // makes text red
#define GREEN "\033[0;"<<32<<"m" // makes text green
#define YELLOW "\033[0;"<<33<<"m" // makes text yellow
#define BLUE "\033[0;"<<34<<"m" // makes text blue
#define PURPLE "\033[0;"<<35<<"m" // makes text purple
#define CYAN "\033[0;"<<36<<"m" // makes text cyan
#define WHITE "\033[0;"<<37<<"m" // makes text white
#define BRED "\033[1;"<<31<<"m" // makes text red
#define BGREEN "\033[1;"<<32<<"m" // makes text green
#define BYELLOW "\033[1;"<<33<<"m" // makes text yellow
#define BBLUE "\033[1;"<<34<<"m" // makes text blue
#define BPURPLE "\033[1;"<<35<<"m" // makes text purple
#define BCYAN "\033[1;"<<36<<"m" // makes text cyan
#define BWHITE "\033[1;"<<37<<"m" // makes text white
#define ENDFORMAT "\033[0m" // ends text formatting
#endif
/*
jan 2011 - added switch-array, this can be switched on and off
*/
class IMPACTA_Switch_Array
{
private:
double *myarray;
double *otherarray;
int Nel;
public:
IMPACTA_Switch_Array()
{
myarray=new double[1];
otherarray=new double[1];
myarray[0]=0.0;
otherarray[0]=0.0;
Nel=1;
}
IMPACTA_Switch_Array(int numberofelements)
{
myarray=new double[numberofelements];
otherarray=new double[numberofelements];
Nel=numberofelements;
for (int i=0;i<numberofelements;++i)
{
myarray[i]=0.0;
otherarray[i]=0.0;
}
}
IMPACTA_Switch_Array(int numberofelements,int value)
{
myarray=new double[numberofelements];
otherarray=new double[numberofelements];
Nel=numberofelements;
for (int i=0;i<numberofelements;++i)
{
myarray[i]=value;
otherarray[i]=0.0;
}
}
//*************************************
//Access methods
//*************************************
double get(int el)
{
return myarray[el];
}
double operator[](int el)
{
return myarray[el];
}
void set(int el,int val)
{
myarray[el]= (double) val;
}
void set(int el,double val)
{
myarray[el]=val;
}
void inc(int el,double val)
{
myarray[el]+=val;
}
void switch_off()
{
int summation=0;
for (int i=0;i<Nel;++i)
summation+=myarray[i];
if (summation) {
double *temp;
temp=myarray;
myarray=otherarray;
otherarray=temp;
}
}
void switch_on()
{
int summation=0;
for (int i=0;i<Nel;++i)
summation+=myarray[i];
if (!summation) {
double *temp;
temp=myarray;
myarray=otherarray;
otherarray=temp;
}
}
};
namespace IMPACT_Boundaries
{
// {xlower, xupper, ylower, yupper}
IMPACTA_Switch_Array fix_f0(4);
IMPACTA_Switch_Array fix_f1_E(4);
IMPACTA_Switch_Array fix_f2(4);
IMPACTA_Switch_Array fix_B(4);
IMPACTA_Switch_Array fix_ni(4);
IMPACTA_Switch_Array fix_Ci(4);
IMPACTA_Switch_Array fixed_any(4);
int ifboundBx=0;
int ifboundBy=0;
int boundary_type=0;
}
/* These are namespaces for warnings*/
namespace warnings
{
const int IMPACT_nowarnings=0;
}
namespace IMPACTA_smoothing
{
double smooth_kernel[5]={1.0,0.0,0.0,0.0,0.0};
}
namespace zerotolerance
{
double zerothreshold=1.e-25;
double laggedtolerance=1.e-12;
//for the next three, see Petsc manual
double KSP_atol= 1.e-50; // default 1.e-50
double KSP_rtol= 1.e-4; //default 1.e-2
double KSP_dtol= 1.e5; //default 1.e5
int MatrixSolver_ItMax=5000; // max number of iterations default 10^5
int linear_solution_PC=0;
int explicit_PC=0;
int on_first_lag_low_rtol=0;
double low_rtol=1e-2;
// double dispj_off_frac=1e-12;
// These are for converging the matrix efficiently
double iterate_matrix=0.0;
double init_matrix_it=1e-3; //this is the initial matrix iteration
//value taken if matrix does not converge
double matrix_it_multiplier=10.0; //what the iteration value changes by
double iterate_matrix_orig_val=0.0;
double minimum_it_matrix_val=1e-10; //to prevent accidental appearance of 0 on diagonal
double picard_divergence=1.0;//whether picard iterations diverge or not.
int max_picard_its = 100; // maximum number of picard iterations
int adaptive_timesteps=1; // for adaptive timestep iteration
int adaptive_multiplier=2;
int adaptivetimes=5;// times the matrix solve should be good before
int adaptivetimesoriginal=5;// the adaptive_timestep number reduces
double equil_percent=1.0e-6;
double RB_D_tolerance = 1e-6;
double CD_tolerance = 1e-12;
double CD_frac_tol = 1e-7;
int RB_D_itmax = 50;
int RB_iterate = 1;
}
namespace equation_switches
{
//These switch whole equations and parts of equations on or off
int f0_equation_on = 1;
int evolvef0 = 0;
int f1_equation_on = 1;
int f2_equation_on = 0;
int f3_equation_on = 0;
int E_equation_on = 1;
int B_equation_on = 1;
//components of the f0eqn
double df0_by_dt_on = 1.0;
double inf0_grad_f1_on = 1.0;
double inf0_Edf1dv_on = 1.0;
double Cee0_on = 1.0;
//f1 eqn
double e_inert_on=1.0;
double inf1_vgradf0_on = 1.0;
double inf1_Edf0dv_on = 1.0;
double inf1_f1xB_on = 1.0;
double Cei_on = 1.0;
int Cee1_on = 1;
//E eqn
double disp_j_on = 1.0;
//
double e_viscosity_on=1.0;
double df3_by_dt_on=1.0; // This is actually now for Weibel damping f3
//
int relaxtoeq=1;
//
double Bimp_in_E_equation=1.0; //rememver - if zero affects dEbydtfix
double jimp_in_E_equation=1.0; //remember - can't be zero
double Eimp_in_B_equation=1.0;
double dEbydtfix=0.5; //1e-8;
double Gamma_A=2.0; // for initializing distribution
// This helps fix matrix solve problems
double NEW_T_NORM=1.0;
// Ray tracing
bool tr_bool;
}
namespace if_dump_switches
{
int ifdumpall=1;
int dump_ne=1;
int dump_ni=0;
int dump_Ci=0;
int dump_Z=0;
int dump_Te=1;
int dump_Ue=1;
int dump_je=1;
int dump_q=1;
int dump_P=1;
int dump_Q=1;
int dump_E=1;
int dump_B=1;
int dump_wt=1;
int dump_VN=1;
int dump_eta=1;
int dump_f0=0;
int dump_f1=0;
int dump_f2=0;
int f_ndump=1;
int view_matrix=0;
}
/* Following are the values of global constants etc.*/
double Calculate_Lambda();
namespace globalconsts
{
double Y=1.0;
const double pi=3.141592653589793238;
const double twopi=2.0*pi;
const double fourpi=4.0*pi;
const double fourthirdspi=4.0*pi/3.0;
const double fourthirds=4.0/3.0;
const double oneover3 = 1.0/3.0;
const double oneover6 = 1.0/6.0;
const double pibysix=pi/6.0;
const double sqrt2 = sqrt(2.0);
double oneover_atomic_Z = 0.1;
double c_L = 10;//3e8; // speed of light over v electron thermal
double epsilon0=1.0;//8.85e-12;
double e_charge = -1.0; //1.6e-19 // electron charge.
double e_mass = 1; //9.11e-31 //electron mass
double me_over_mp = 0.000544617024;
double omega_p_nuei_n = 10; //w0*ln
const int LenName=20;
const int Ncoords=2;
char IMPACT_Coords[Ncoords]={'x','y'};
double deltasquared=1.0;
double Bimp=1.0;
// conversion of T in keV to normalized units
const double keVnorm = 511.0; //to be multiplied by v^2/c^2
// Actual value of density!
// collision frequency in units of 1/s
double Lambda_ei = Calculate_Lambda();
double logLambda = log( Lambda_ei);
double N_par_Debye = Lambda_ei/(9.0*oneover_atomic_Z);
double real_T_J = 9.11e-31/c_L/c_L*2.998e8*2.998e8; // real temperature in J
double ne24 = 16.0/9.0*pi*pi*pow(8.85e-12/1.602e-19/1.602e-19,3)/N_par_Debye/N_par_Debye*real_T_J*real_T_J*real_T_J/1.0e6/1.0e24;
double real_wp = sqrt(1.602e-19*1.602e-19*ne24*1.0e6*1.0e24/8.85e-12/9.11e-31);
double nuei = sqrt(2.0/pi)*logLambda/ Lambda_ei*real_wp;
// I don't take into account Z or T dependance as is logarithmic anyway,
// and calculation would really slow things down
double ionize_coll_log = log(1e5/c_L/c_L*oneover_atomic_Z)/logLambda; // normalized collision logarithm from Bethe formula
double laser_frequency = 1.78e15; // angular frequency of laser
const double Z_minimum=1e-3; // minimum ionization state.
int MPIChunkSize = 1;//10000;
std::string initial_time_str="";
// For input maths
const int nsymbols=5;
const int nfuncs=9;
std::string IMPACTA_symbols[nsymbols]={"+","-","*","/","^"};
std::string IMPACTA_funcs[nfuncs]={"(","COS(","SIN(","TAN(","EXP(",
"TANH(","SINH(","COSH(","LOG("};
//numbers as strings useful
const int nnumbers=16;
std::string IMPACTA_numbers[nnumbers]={"1","2","3","4","5","6","7","8","9","0"
,".", "LX","LY","PI","X","Y"};
}
namespace IMPACTA_ions
{
int ionization_on=0;
bool quasin_on=false;
std::string ionization_model[3] = {"off","Saha","Thomas-Fermi"};
int ion_motion=0;
// double a1bar=0.00544617024;
//double a2bar=a1bar;
double atomic_mass_number=10.0;
double ion_temperature=1.0;
double alpha_ion = (globalconsts::me_over_mp/atomic_mass_number
/(globalconsts::oneover_atomic_Z));
double ionization_time_frequency = 4.11e16/globalconsts::nuei; // omega_a normalized to e-i collision time
double ionization_v_osc = 0.168 *(1.78e15/globalconsts::laser_frequency)*globalconsts::c_L; // 0.168 is a0 for 1 micron laser.
const int N_Z_smooth = 10; //number of steps between smoothing of Z
}
namespace VISIT_PARAMS
{
const int data_id0=0;//NONE
const int data_id1=1;//ne
const int data_id2=2;//ni
const int data_id3=3;//Te
const int data_id4=4;//Bz
const int data_id5=5;
const int data_id6=6;
const int data_id7=7;
const int data_id8=8;
const int vec_id1=0; //E field
const int vec_id2=1; //B field
const int vec_id3=2; // j
const int vec_id4=3; // q
}
namespace IMPACT_Diagnostics
{
double init_start_time=0.0,init_end_time=0.0;//to measure initialization time
double n_start_time=0.0,n_end_time=0.0; //to measure timestep CPU time
double start_time=0.0,end_time=0.0; //to measure total CPU time
double total_nl_its=0.0,nl_times=0.0; //to measure ave nonlinear iterations
double total_picard_its=0.0,picard_times=0.0; //to measure
const int graphbars=50;
double timegraph[graphbars+1];
double total_delta_its=0.0,delta_times=0.0; //to measure delta in RB coeffs
int showmatrix=0;
int showvector=0;
int noxnbody=0;
int divcheck=1; // Check for diveregnce in Picard iteration
int output_precision=10; //number of digits precision for output
}
std::string IMPACT_GetTime(double time)
{
std::ostringstream outtime;
int days,hours,mins;
double secs=time;
days=int (secs)/86400;
secs-=86400.0*days;
hours=int (secs)/3600;
secs-=3600.0*hours;
mins=int (secs)/60;
secs-=60.0*mins;
if (days==1) outtime<<days<<" day, ";
if (hours==1) outtime<<hours<<" hour, ";
if (mins==1) outtime<<mins<<" min, ";
if (days>1) outtime<<days<<" days, ";
if (hours>1) outtime<<hours<<" hours, ";
if (mins>1) outtime<<mins<<" mins, ";
outtime<<secs<<" s";
return outtime.str();
}
//Using this namespace means that space will be saved in
//the matrix for the components present in Robs version
//of IMPACT.
namespace IMPACT_Original
{
int f0_on=1,f1_on=1,f2_on=0,f3_on=0,E_on=1,num_B=3;
}
namespace IMPACT_Messages
{
char Version[20]="Wolfhound Alpha";
char Date[11]="01/06/2012";
char DataHeader[2][200]= {"IMPACTA Moment Data file (.imd)\nAGRT07\nNotes:\nThe data can be returned into an IMPACT_Moment structure\nby using the << operator.","IMPACTA Distribution Data file (.imd)\nAGRT07\nNotes:\nThe data can be returned into an IMPACT_Dist class\nby using the << operator."};
std::string Root_Dir = "";
std::string Data_Directory=Root_Dir+"impacta_data/";
std::string Input_Directory=Root_Dir+"impacta_data_in/";
std::string Field_Dir="FLD/";
std::string DistFunc_Dir="DST/";
std::string Moment_Dir="MNT/";
std::string Constants_Dir="ION/";
std::string InDeck=Root_Dir+"imstdin";
int if_show_function_input=0;
}
namespace IMPACT_Input_Deck
{
const int Extra_cmdln=6;
const int MAXVAR=136; //maximum number of variable names for input deck +1
const int MAXLEN = 22; //maximum length of variable name
int Var_check[MAXVAR];
char Var_names[MAXVAR][MAXLEN]=
{
"OUT_DIR", //1
"IN_DIR",
"OUT_DIGS",
"N_MAX",
"DT",
"NDUMP",
"T0",
"NX",
"NY",
"NV", //10
"COORDINATES",
"XMIN",
"YMIN",
"DXGRID",
"DYGRID",
"DVGRID",
"NUM_B",
"E_ON",
"F1_ON",
"F2_ON", // 20
"F3_ON",
"ZERO_TOL",
"LAG_TOL",
"KSP_ATOL", "KSP_RTOL","KSP_DTOL",
"KSP_MAX_IT","KSP_PC_TYPE","KSP_METHOD","KSP_MONITOR", //30
"A","Z0","TI",
"Z(X,Y)","Z(X)", "Z(Y)", // 36
"NE(X,Y)","NE(X)", "NE(Y)",
"NI(X,Y)","NI(X)", "NI(Y)", // 42
"TE(X,Y)","TE(X)", "TE(Y)",
"BX(X,Y)","BY(X,Y)","BZ(X,Y)", // 48
"B0HAT","B0(X)", "B0(Y)",
"W_PE_OVER_NU_EI",
"V_TE_OVER_C",
"F0_EQUATION",
"F1_EQUATION", //55
"F2_EQUATION",
"F3_EQUATION",
"E_EQUATION",
"B_EQUATION",
"DF0/DT", "INF0_GRAD_F1","INF0_EDF1DV","CEE0", // 63
"DF1/DT","INF1_VGRADF0","INF1_EDF0DV","INF1_F1XB","CEI","CEE1", // 69
"DF2/DT","DAMP_WEIBEL","DISP_J", // 72
"INITIAL_CONDITION","INITIAL_STEP_DT_FRAC", // 74
"RB_D_IT_TOL", "RB_D_IT_MAX", "RB_ITERATE", // 77
"HEAT_SOURCE","HEATING(X,Y)","HEATING(X)","HEATING(Y)", //80
"HEATING(T)","VOSC","POLARIZATION", //83
"GRADN_Z(X,Y)/N","GRADN_Z(X)/N","GRADN_Z(Y)/N","GRADN_Z(T)/N", //87
"GRADT_Z(X,Y)/T","GRADT_Z(X)/T","GRADT_Z(Y)/T","GRADT_Z(T)/T", //91
"IF_DUMP_NE","IF_DUMP_NI","IF_DUMP_CI","IF_DUMP_Z", //95
"IF_DUMP_TE","IF_DUMP_UE","IF_DUMP_JE","IF_DUMP_Q","IF_DUMP_P", //100
"IF_DUMP_E","IF_DUMP_B","IF_DUMP_WT","IF_DUMP_VN","IF_DUMP_ETA", // 105
"IF_DUMP_F0","IF_DUMP_F1","IF_DUMP_F2","F_NDUMP", //109
"X_BOUND","Y_BOUND", //111
"FIX_F0","FIX_F1_E","FIX_F2","FIX_B","FIX_NI","FIX_CI", // 117
"SMOOTHING_KERNEL","IONIZATION_MODEL","QUASINEUTRALITY", // 120
"TR_BOOL","BEAM_WIDTH","BEAM_RES","BOUNDARY","SHAPE",
"N_C","X_0","Y_0","THETA","DTHETA", // 130
"DS","INTENSITY_DIFF_STEPS","TEMP_MULTIPLIER","FRACTION",
"END"}; // END goes at the end..
}
//________________________________________________________________
// Useful functions
//
//This function compares the given string with the commandline arguments
// and returns true(1) or false(0)
int IMPACT_Cmp_CmdLine(int argnum, char **argstr, std::string string)
{
int result=0;
char null[3]="";
for (int i = 0; i<argnum;++i)
if (!strcmp(argstr[i],string.c_str()))
{
result = 1;
argstr[i]=null;
}
return result;
}
std::string IMPACT_Get_CmdLine(int *argnum, char **argstr, std::string string)
{
int dircheck=0;
char null[3]="";
std::string answer;
for (int i=0;i<*argnum;++i)
if (!strcmp(argstr[i], string.c_str())) {dircheck=i;argstr[i]=null;}
if (dircheck>0)
{answer= argstr[dircheck+1]; argstr[dircheck+1]=null;}
else answer = "*nofield*";
return answer;
}
// list of known functions
int IMPACT_isFunc(char * func)
{
char func3[4]="";
char func4[5]="";
for (int i=0;i<5;++i)
func[i]=toupper(func[i]);
for (int i=0;i<3;++i)
func3[i]=toupper(func[i+1]);
for (int i=0;i<4;++i)
func4[i]=toupper(func[i+1]);
int result =0;
//note the numbers correspond to dofunction
if(!strcmp(func4,"TANH")) result = 6;
if (!result){
if(!strcmp(func3,"SIN")) result = 1;
if(!strcmp(func3,"COS")) result = 2;
if(!strcmp(func3,"TAN")) result = 3;
if(!strcmp(func3,"EXP")) result = 4;
if(!strcmp(func3,"LOG")) result = 5;
}
return result;
}
double IMPACT_function(double value,int result)
{
double answer=0.0;
switch (result)
{
case 1:
answer = sin(value);
break;
case 2:
answer = cos(value);
break;
case 3:
answer = tan(value);
break;
case 4:
answer = exp(value);
break;
case 5:
answer = log(value);
break;
case 6:
answer = tanh(value);
break;
}
return answer;
}
//executes the given function
void IMPACT_dofunction(double *gridtemp,int N,int result)
{
for (int i=0;i<N;++i) gridtemp[i] = IMPACT_function(gridtemp[i],result);
}
double IMPACT_isConst(char* number, double max,int N)
{
int length=strlen(number);
std::istringstream numtemp;
numtemp.str(number);
for (int i=0;i<length;++i)
number[i]=toupper(number[i]);
double result =0;
if(!strcmp(number,"PI")) result = globalconsts::pi;
if (!strcmp(number,"MAX"))
{
if (max==0.0) {std::cout<< "IMPACT: ERROR - in input deck, max requested but max - min = 0.0\n"; exit(0);}
result = max*(double)N/(double)(N-1);
}
if (!result) numtemp>>result;
return result;
}
double IMPACT_isConst2D(char* number, double imax,double jmax,int Nx,int Ny)
{
int length=strlen(number);
std::istringstream numtemp;
numtemp.str(number);
for (int i=0;i<length;++i)
number[i]=toupper(number[i]);
double result =0;
if(!strcmp(number,"PI")) result = globalconsts::pi;
if (!strcmp(number,"ILIM"))
{
if (imax==0.0) {std::cout<< "IMPACT: ERROR - in input deck, max requested but max - min = 0.0\n"; exit(0);}
result = imax*(double)Nx/(double)(Nx-1);
}
if (!strcmp(number,"JLIM"))
{
if (jmax==0.0) {std::cout<< "IMPACT: ERROR - in input deck, max requested but max - min = 0.0\n"; exit(0);}
result = jmax*(double)Ny/(double)(Ny-1);
}
if (!result) numtemp>>result;
return result;
}
void chk()
{
std::cout<<"EXIT OK"<<std::endl;exit(0);}
void chk(int check)
{
std::cout<<"EXIT OK - "<< check<<std::endl;exit(0);}
void chk(double check)
{
std::cout<<"EXIT OK - "<< check<<std::endl;exit(0);}
void chkns(int check)
{
std::cout<<"OK - "<< check<<std::endl;}
void chkns(double check)
{
std::cout<<"OK - "<< check<<std::endl;}
void chkMPI()
{
int rank;
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
if (rank==0)std::cout<<"EXIT OK"<<std::endl;MPI_Finalize();exit(0);}
/* for (int i = 31; i <= 37; i++)
{
std::cout << "\033[0;" << i << "mHello!\033[0m" << std::endl;
std::cout << "\033[1;" << i << "mHello!\033[0m" << std::endl;
}*/
//_____________________________________________
//Error handling - exit if alocation is outside range
namespace no_vec_err_checking
{
int vecerrchkon=0;
inline void Vec_check_err(int *element, int *size)
{
}
}
namespace with_vec_err_checking
{
int vecerrchkon=1;
inline void Vec_check_err(int *element,int *size)
{
try {if (*element>*size || *element<1) throw 10;}
catch (int err)
{if (err==10)
{std::cout << std::endl<<"Exiting - Tried to access non-existent vector element";
std::cout<<std::endl;
std::cout<<"element="<<*element<<std::endl;
exit(0);}
}
}
}
<file_sep>/include/impacta_equations/impacta_f0equation.h
/*
**********************************************************
f0 equation IMPACTA code for inner and outer cells
Version 1.2
1
AGRT
20/2/07
24/2/08 - updated to include simple ion model
**********************************************************
*/
//code for inner cells of f0 equation - i.e. not at boundaries
void f0equation_inner(IMPACT_Config *c, IMPACT_ParVec *vlagged,IMPACT_ParVec *vtemp, IMPACT_StenOps * O,IMPACT_Var* f0,IMPACT_Var* E,IMPACT_Var * B,IMPACT_Var* f1,int *i,int *j,int *k)
{
/*
**********************************************************
INSERT f0 Equation terms CODE HERE
**********************************************************
*/
f0->set(vtemp,equation_switches::df0_by_dt_on*c->idt(),i,j,k);
// set f0 n+1 element to 1.0
IMPACT_Dim coord_1(1);
IMPACT_Dim coord_2(2);
// v/3 div.f1
double vover3=c->v(k)*oneover3*equation_switches::inf0_grad_f1_on;
//i.e. v/3
IMPACT_stencil temp_sten = (*O->ddx(i))*vover3;
f1->insert(&temp_sten,vtemp,i,j,k,&coord_1); // x part of div
temp_sten = (*O->ddy(j))*vover3;
f1->insert(&temp_sten,vtemp,i,j,k,&coord_2); // y part of div
//ai/v^2 dv^2f1i/fv
double oneover3v2=-1.0*oneover3/c->v2(k); // 1/v squared
for (IMPACT_Dim x1=1;x1<=c->NE();++x1)
E->inc(vtemp,oneover3v2*f1->ddv_v2(vlagged, c,i,j,k,&x1)
*equation_switches::inf0_Edf1dv_on,i,j,&x1); //E element
//e-e collision term Cee0
int kminus=*k-1;
double Cee0_const = -1.0/c->v2(k)*c->idv(k);
IMPACT_Vel_Sten Fk(0.0,0.0,0.0);
Fk.inc(0,-Cee0_flux_store::flux->get(i,j,&kminus)->get(1));
Fk.inc(1,-Cee0_flux_store::flux->get(i,j,&kminus)->get(2)
+Cee0_flux_store::flux->get(i,j,k)->get(1));
Fk.inc(2,Cee0_flux_store::flux->get(i,j,k)->get(2));
Fk*Cee0_const;
f0->insert(&Fk,vtemp,i,j,k);
bool uw;
int dir;
if (IMPACTA_ions::ion_motion)
{
// ION Motion terms...
// + C.grad f0
for (IMPACT_Dim x1=1;x1<=c->Nf1();++x1)
{
temp_sten = (*O->ddxi(i,j,&x1))*
Initial_Conditions::C_i[x1.get()-1].get(i,j);
// Upwind
/*
dir = x1.get()-1;
uw = Initial_Conditions::C_i[dir].sign(i,j);
temp_sten = (*O->ddxi_uw(i,j,&x1,uw))*
Initial_Conditions::C_i[x1.get()-1].get(i,j);*/
f0->insert(&temp_sten,vtemp,i,j,k);
}
// Removed as not included in f2 and f1 agrt 2011 -- readded May 2011
// - v/3df0/dvdivCi
kminus=*k-1;
int kplus=*k+1;
double vover3deltav=-c->v(k)*oneover3/(c->dv(&kminus)+c->dv(&kplus));
f0->inc(vtemp,vover3deltav*Initial_Conditions::DivC_i.get(i,j),i,j,&kplus);
f0->inc(vtemp,-vover3deltav*Initial_Conditions::DivC_i.get(i,j),i,j,&kminus);
}
// Diffusion
// double Dtimesdt = -1.0e-3;
// temp_sten = (O->Laplacian(i,j)*Dtimesdt);
// f0->insert(&temp_sten,vtemp,i,j,k);
}
//code for outer cells of f0 equation - i.e. boundaries
void f0equation_outer(IMPACT_Config *c, IMPACT_ParVec *vlagged,IMPACT_ParVec * vtemp, IMPACT_StenOps * O, IMPACT_Var* f0,IMPACT_Var* E,IMPACT_Var * B,IMPACT_Var* f1,int *i,int *j,int *k)
{
/*
**********************************************************
INSERT f0 Equation terms CODE HERE - BC versions
**********************************************************
*/
f0->set(vtemp,equation_switches::df0_by_dt_on*c->idt(),i,j,k);
IMPACT_Dim coord_1(1);
IMPACT_Dim coord_2(2);
// v/3 div.f1
double vover3=c->v(k)*oneover3*equation_switches::inf0_grad_f1_on;
//i.e. v/3
IMPACT_stencil temp_sten = (*O->ddx(i))*vover3;
f1->insert_f1BC(&temp_sten,vtemp,i,j,k,&coord_1); // x part of div
temp_sten = (*O->ddy(j))*vover3;
f1->insert_f1BC(&temp_sten,vtemp,i,j,k,&coord_2); // y part of div
//ai/v^2 dv^2f1i/fv
double oneover3v2=-1.0*oneover3/c->v2(k); // 1/v squared
for (IMPACT_Dim x1=1;x1<=c->NE();++x1)
E->inc(vtemp,oneover3v2*f1->ddv_v2_BC(vlagged, c,i,j,k,&x1)
*equation_switches::inf0_Edf1dv_on,i,j,&x1);
//e-e collision term Cee0
int kminus=*k-1;
double Cee0_const = -1.0/c->v2(k)*c->idv(k);
IMPACT_Vel_Sten Fk(0.0,0.0,0.0);
Fk.inc(0,-Cee0_flux_store::flux->get(i,j,&kminus)->get(1));
Fk.inc(1,-Cee0_flux_store::flux->get(i,j,&kminus)->get(2)
+Cee0_flux_store::flux->get(i,j,k)->get(1));
Fk.inc(2,Cee0_flux_store::flux->get(i,j,k)->get(2));
Fk*Cee0_const;
f0->insert(&Fk,vtemp,i,j,k);
bool uw;
int dir;
if (IMPACTA_ions::ion_motion)
{
// ION Motion terms...
// C.grad f0
for (IMPACT_Dim x1=1;x1<=c->Nf1();++x1)
{
temp_sten = (*O->ddxi(i,j,&x1))*
Initial_Conditions::C_i[x1.get()-1].get(i,j);
// Upwind
/*dir = x1.get()-1;
uw = Initial_Conditions::C_i[dir].sign(i,j);
temp_sten = (*O->ddxi_uw(i,j,&x1,uw))*
Initial_Conditions::C_i[dir].get(i,j);*/
f0->insert_BC(&temp_sten,vtemp,i,j,k);
}
// Removed as not included in f2 and f1 agrt 2011 -- readded May 2011
//v/3df0/dvdivCi
kminus=*k-1;
int kplus=*k+1;
if (kminus<1) kminus=1;
if (kminus>c->Nv()) kplus=c->Nv();
double vover3deltav=-c->v(k)*oneover3/(c->dv(&kminus)+c->dv(&kplus));
f0->inc(vtemp,-vover3deltav*Initial_Conditions::DivC_i.get(i,j),i,j,&kminus);
f0->inc(vtemp,vover3deltav*Initial_Conditions::DivC_i.get(i,j),i,j,&kplus);
}
// Diffusion
// double Dtimesdt = -1.0e-3;
// temp_sten = (O->Laplacian(i,j)*Dtimesdt);
// f0->insert_BC(&temp_sten,vtemp,i,j,k);
}
| c2c0383cd4eb14ff3d54336a861f819400f477c9 | [
"C",
"C++",
"Shell"
] | 16 | C++ | lsahdjf/EagleRay-Imp | 915f9c8678272eef09b1370b6050a29741115146 | 95b0eac73313cf5d38adf67abb6b93667bdc3b17 |
refs/heads/master | <file_sep>#!/bin/bash
if [ $# -ne 2 ] || [ $1 = "-h" ]
then
echo "backupme is to backup any file or directory easily to a destination.";
echo "";
echo "USAGE:";
echo "-------------------------------------";
echo "$0 source destination";
echo "-------------------------------------";
echo "";
exit;
fi
#$1 source (dir or file)
#$2 destination
e=`date +%Y%m%d`; #get the date formatted
back=$2/$1"_"$e.bac;
#copy source to the destination
cp -R $1 $back #copy source to the backup directory
#check if the source is a directory. if a directory find all files and directories and rename them
if [ -d "$1" ]
then
#find each file and rename
for file in `find $back -type f`; do
mv $file $file"_"$e.bac
done
#find each directory and rename
for file in `find $back/* -type d`; do
mv $file $file"_"$e.bac
done
fi
echo "Successfully backed up";
<file_sep># Shell Scripts
Simple and useful shell scripts that can be used with your daily work
* Before executing any command, make sure to give neccessary permissions to corresponding script files.
## Backupme [backupme.sh]
1. Choose a directory/file to backup. Eg. directory called 'source'
2. Choose a directory to store the backup. Eg. directory called 'dest'
3. Make sure the script 'backupme.sh' has neccessary permissions to execute.
4. run the script
```
./backupme.sh source dest
```
| c9175357e9e0da45464a20b4c02f7724e2311295 | [
"Markdown",
"Shell"
] | 2 | Shell | prabushitha/Shell-Scripts | 33bbc79083a4946f9a586d33c09bdcd9cb317d5f | 866ba1b51f0e00e7d039e635ccdcf2d8dcc6e6f1 |
refs/heads/master | <repo_name>sushimadeeasy/FriendFinder<file_sep>/app/routing/apiRoutes.js
var fs = require("fs");
module.exports = function(app) {
app.post("/api/friends", function(req, res) {
console.log(req.body['scores[]'])
var input = req.body['scores[]']
fs.readFile("app/data/users.JSON", "utf8", function(error, data) {
var match = JSON.parse(data)
var least;
for (var i = 0; i < match.length; i++) {
var diff = 0;
console.log(match[i].scores)
for (var j = 0; j < input.length; j++) {
diff += Math.abs(parseInt(input[j]) - match[i].scores[j]);
}
match[i].diff = diff;
console.log(match[i]);
if (!least) {
least = match[i].diff
} else if (least > match[i].diff) {
least = match[i].diff
}
}
console.log(least);
for (var i = 0; i < match.length; i++) {
if (match[i].diff == least) {
console.log(match[i])
res.json(match[i])
}
}
});
});
app.get("/api/friends", function(req, res) {
fs.readFile("app/data/users.JSON", "utf8", function(error, data) {
res.json(JSON.parse(data))
console.log(data)
});
});
}
<file_sep>/README.md
# Friend-Finder
A compatibility-based "FriendFinder" application -- Find the best matches based on personalities. This full-stack site takes in results of your users' surveys (10 questions, on a scale of 1-5), then compare their answers with those from other "users". The app will then display the name and picture of the opposite sex with the best overall match.
The server and routing is built on Express.
### Overview
1. The user answers 10 questions that evaluate various character traits. Each answer is a number on a scale of 1 to 5 based on how much the user agrees or disagrees with the question.
2. The user's results are converted into a simple array of numbers (ex: `[5, 1, 4, 4, 5, 1, 2, 5, 4, 1]`).
* The array is used to compare the user's scores against those from other users, question by question. The sum of the differences calculates the `totalDifference`.
* Example:
* You: `[5, 1, 4, 4, 5, 1, 2, 5, 4, 1]`
* Celebrity: `[3, 2, 6, 4, 5, 1, 2, 5, 4, 1]`
* Total Difference: 2 + 1 + 2 + 0 + 0 + 0 + 0 + 0 + 0 + 0 = 5
* The closest match will be the user with the least amount of difference.
3. Once the app finds the current user's most compatible friend, the result is displayed as a modal pop-up.
* The modal displays both the name and picture of the closest opposite sex match.
<file_sep>/server.js
var express = require("express");
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var path = require("path");
var fs = require("fs");
var app = express();
var port = process.env.PORT || 3000;
// Serve static content for the app from the "public" directory in the application directory.
app.use(express.static(__dirname + "/app"));
// Parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
require("./app/routing/apiRoutes")(app);
require("./app/routing/htmlRoutes")(app);
app.listen(port);
| c08dcc85747186fe359856342bd2fc5c6d0efa0c | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | sushimadeeasy/FriendFinder | ce4df28896922b1e7e384dc55e4e64d70fccf47f | 809cd88bfc63762468dbe7e14500afd67d205dce |
refs/heads/master | <file_sep># JS-Form Homework
A Pen created on CodePen.io. Original URL: [https://codepen.io/handeyildirim/pen/xxwvvGK](https://codepen.io/handeyildirim/pen/xxwvvGK).
<file_sep># JavaScript-Form-Homework-for-Interactivity-With-JavaScript
Writing codes needed to enable auto-complete on this form. Whenever the checkbox is checked, the code automatically copies the values from Shipping Name and Shipping Zip into the Billing Name and Billing Zip. If the checkbox is unchecked, the Billing Name and Billing Zip go blank.
<file_sep>/*Add the JavaScript here for the function billingFunction(). It is responsible for setting and clearing the fields in Billing Information */
function billingFunction(){ if(document.querySelector("#same").checked){
var name = document.querySelector("#shippingName").value; //copying for the value entered by user in shippingName
var zip = document.querySelector("#shippingZip").value; //copying for the value entered by user in shippingZip
document.querySelector("#billingName").value = name; //copying the initialised variables to billing address and zip
document.querySelector("#billingZip").value = zip;
}
else{
document.querySelector("#billingName").value="";
document.querySelector("#billingZip").value="";
}
} | ba1e3e47d4102ff836a47f18c6fe266e1f94a90e | [
"Markdown",
"JavaScript"
] | 3 | Markdown | handeyildirim/JavaScript-Form-Homework-for-Interactivity-With-JavaScript | 150058c1d2e379b36b5f92e34ae5eddde52bd1ff | 8a2fef33af5e4f56ec7091fd5ff765d7654c7bd6 |
refs/heads/master | <file_sep>#coding: utf-8
from PyQt4.QtGui import *
import BaseShape
class RectEditor(QDialog):
def __init__(self, ShapeObj, parent=None):
self.m_ShapeObj = ShapeObj
QWidget.__init__(self, parent)
self.setWindowTitle(u'矩形状态编辑框')
grid = QGridLayout()
labelObj = QLabel(u'状态名')
grid.addWidget(labelObj, 1, 1)
self.m_Combo = QComboBox()
for (key, value) in BaseShape.BaseShape.s_dState.items():
self.m_Combo.addItem(value)
self.m_Combo.setCurrentIndex(self.m_ShapeObj.GetStateId())
grid.addWidget(self.m_Combo, 1, 2)
self.setLayout(grid)
def closeEvent(self, event):
self.m_ShapeObj.SetStateId(self.m_Combo.currentIndex())
print u'矩形状态编辑框关闭'
class LineEditor(QDialog):
def __init__(self, ShapeObj, parent = None):
self.m_ShapeObj = ShapeObj
QWidget.__init__(self, parent)
self.setWindowTitle(u'线段编辑框')
self.m_lCombo = []
lLabels = []
for i in range(len(self.m_ShapeObj.m_lCondition) + 2):
lLabels.append(u'条件' + str(i))
grid = QGridLayout()
for i in range(len(lLabels)):
labelObj = QLabel(lLabels[i])
grid.addWidget(labelObj, i + 1, 1)
comboObj = QComboBox()
for (key, value) in BaseShape.BaseShape.s_dCondition.items():
comboObj.addItem(value)
comboObj.setCurrentIndex(self.m_ShapeObj.GetCondiction(i))
grid.addWidget(comboObj, i + 1, 2)
self.m_lCombo.append(comboObj)
self.setLayout(grid)
def closeEvent(self, event):
lCondition = []
for ComboObj in self.m_lCombo:
nIndex = ComboObj.currentIndex()
if nIndex != 0:
lCondition.append(nIndex)
self.m_ShapeObj.SetCondition(lCondition)
print 'update condictions',lCondition,self.m_ShapeObj.m_lCondition
print u'线段状态编辑框关闭'
<file_sep>#coding: utf-8
import copy
g_lStack = []
def Push(lShape):
g_lStack.append(copy.deepcopy(lShape))
print 'push history', 'stack size', len(g_lStack)
def Pop(lShape):
nLen = len(g_lStack)
if nLen > 0:
print 'pop history', 'stack size', len(g_lStack)
lRet = g_lStack[nLen - 1]
del g_lStack[nLen - 1]
return lRet
else:
print 'pop history fail', 'stack size is empty'
Push(lShape)
return lShape
<file_sep>#coding: utf-8
g_dState = {
0:u"start",
1:u"BornState(出生状态)",
2:u"NormalState(非战斗状态)",
3:u"IdleState(Idle状态)",
4:u"ReturnState(返回状态)",
5:u"FightState(战斗状态)",
6:u"ControlState(受控状态)",
7:u"DeadState(死亡状态)",
8:u"end"
}
g_dCondition = {
0 : u"",
1 : u"new",
2 : u"eGMSG_CreateCompleted,創建完成",
3 : u"close_idle, 关闭了IDLE开关时",
4 : u"open_idle, 开启了IDLE开关时",
5 : u"eGMSG_DestroyMySelf,无法被玩家看到",
6 : u"eGMSG_InitMySelf,被玩家看到",
7 : u"eGMSG_GetControl, 被强控",
8 : u"eGMSG_OnDamage, 受到损害",
9 : u"eGMSG_FoundTarget, 发现可攻击目标",
10: u"eGMSG_MoveEnded, 到达返回点",
11: u"eGMSG_OnDead, 死亡",
12: u"eGMSG_OnTargetLost, 所有可攻击目标丢失",
13: u"eGMSG_OnDead, 死亡",
14: u"eGMSG_DisControl, 强制结束"
}<file_sep>#coding: utf-8
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import PaintWidget
import BaseShape
import json
import History
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self, windowTitle=u"状态机编辑器")
self.m_PaintWidget = PaintWidget.PaintWidget()
self.m_PaintWidget.Update()
#菜单栏
FileMemu = self.menuBar().addMenu(u"菜单")
SaveAction = QAction(u"保存", FileMemu)
SaveAction.triggered.connect(self.Save)
ReadAction = QAction(u"读取", FileMemu)
ReadAction.triggered.connect(self.Read)
FileMemu.addAction(SaveAction)
FileMemu.addAction(ReadAction)
#工具栏
EditorToolBar = QToolBar()
#画线
self.addToolBar(Qt.TopToolBarArea,EditorToolBar)
self.m_DrawLineAction = QAction("Line", EditorToolBar)
self.m_DrawLineAction.triggered.connect(self.DrawLineActionTriggered)
self.m_DrawLineAction.setText(u'线')
self.m_DrawLineAction.setCheckable(True)
EditorToolBar.addAction(self.m_DrawLineAction)
#画矩形
self.m_DrawRectAction = QAction("Rect", EditorToolBar)
self.m_DrawRectAction.triggered.connect(self.DrawRectActionTriggered)
self.m_DrawRectAction.setText(u'矩形')
self.m_DrawRectAction.setCheckable(True)
EditorToolBar.addAction(self.m_DrawRectAction)
#画菱形
self.m_DrawDiamondAction = QAction("Diamond", EditorToolBar)
self.m_DrawDiamondAction.triggered.connect(self.DrawDiamondActionTriggered)
self.m_DrawDiamondAction.setText(u"菱形")
self.m_DrawDiamondAction.setCheckable(True)
EditorToolBar.addAction(self.m_DrawDiamondAction)
#画布
self.m_PaintWidget.setMinimumSize(2000, 2000)
Scroll = QScrollArea()
Scroll.setWidget(self.m_PaintWidget)
Scroll.setAutoFillBackground(True)
Scroll.setWidgetResizable(True)
self.setCentralWidget(Scroll)
def DrawLineActionTriggered(self):
self.m_DrawRectAction.setChecked(False)
self.m_DrawDiamondAction.setChecked(False)
self.m_PaintWidget.setCurrentShape(BaseShape.BaseShape.s_Line, self.m_DrawLineAction)
def DrawRectActionTriggered(self):
self.m_DrawLineAction.setChecked(False)
self.m_DrawDiamondAction.setChecked(False)
self.m_PaintWidget.setCurrentShape(BaseShape.BaseShape.s_Rect, self.m_DrawRectAction)
def DrawDiamondActionTriggered(self):
self.m_DrawLineAction.setChecked(False)
self.m_DrawRectAction.setChecked(False)
self.m_PaintWidget.setCurrentShape(BaseShape.BaseShape.s_Diamond, self.m_DrawDiamondAction)
def Save(self):
fileDialog = QFileDialog(self)
fileDialog.setWindowTitle(u'保存状态图')
fileDialog.setDirectory('.')
fileDialog.setFilter("Image Files(*.json)")
path = ''
if fileDialog.exec_() == QDialog.Accepted:
path = fileDialog.selectedFiles()[0]
QMessageBox.information(None, u"路径", u"保存目录为:" + path)
jsonFile = {}
for shape in self.m_PaintWidget.m_lShape:
jsonFile[shape.m_nId] = {}
jsonFile[shape.m_nId] = shape.ToJson()
jsonFile['s_curId'] = BaseShape.BaseShape.s_curId
print json.dumps(jsonFile)
with open(path, 'w') as outfile:
json.dump(jsonFile, outfile)
else:
QMessageBox.information(None, u"路径", u"你没有选中任何文件")
print u'保存状态图'
def BuildNet(self):
for CommentObj in self.m_PaintWidget.m_lShape:
if CommentObj.isComment():
for LineObj in self.m_PaintWidget.m_lShape:
if LineObj.isLine():
if LineObj.m_nCommentId == CommentObj.m_nId:
CommentObj.m_LineObj = LineObj
print 'build net'
def Read(self):
fileDialog = QFileDialog(self)
fileDialog.setWindowTitle(u'读取状态图')
fileDialog.setDirectory('.')
fileDialog.setFilter("Image Files(*.json)")
if fileDialog.exec_() == QDialog.Accepted:
path = fileDialog.selectedFiles()[0]
QMessageBox.information(None, u"路径", u"读取目录为:" + path)
jsonFile = {}
with open(path, 'r') as outfile:
jsonFile = json.load(outfile)
print jsonFile
self.m_PaintWidget.m_lShape = []
for (key,value) in jsonFile.items():
if key == "s_curId":
continue
if value['m_bLine'][0] == True:
shape = BaseShape.Line()
elif value['m_bRect'][0] == True:
shape = BaseShape.Rect()
elif value['m_bDiamond'][0] == True:
shape = BaseShape.Diamond()
elif value['m_bComment'][0] == True:
shape = BaseShape.Comment(QPoint(int(value['m_start'][0]), int(value['m_start'][1])), None)
shape.InitFromJson(key, value)
if shape.m_color == True:
self.m_PaintWidget.m_chooseShape = shape
self.m_PaintWidget.m_lShape.append(shape)
BaseShape.BaseShape.s_curId = jsonFile['s_curId']
self.BuildNet()
self.m_PaintWidget.m_lShape.sort(lambda x,y:cmp(x.m_bLine, y.m_bLine))
self.m_PaintWidget.update()
History.Push(self.m_PaintWidget.m_lShape)
else:
QMessageBox.information(None, u"路径", u"你没有选中任何文件")
print u'读取状态图'
if __name__ == "__main__" :
q = QApplication(sys.argv)
w = MainWindow()
w.setWindowTitle(u"状态机编辑器")
w.resize(1600, 800)
w.show()
q.exec_()<file_sep>#coding: utf-8
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import Geometry
class EllipseMoveAction(object):
def __init__(self, StartQPointObj, EndQPointObj, CallBackFuntion):
self.m_StartQPointObj = StartQPointObj
self.m_EndQPointObj = EndQPointObj
#算出单位向量
self.m_UnitVectorObj = Geometry.GetUnitVector(EndQPointObj - StartQPointObj)
self.m_CallBackFuntion = CallBackFuntion
return
def IsFinish(self):
nLen = Geometry.GetDistance(self.m_StartQPointObj, self.m_EndQPointObj)
if nLen < 5:
self.m_CallBackFuntion()
print 'is finish'
return True
else:
return False
def Move(self):
if self.IsFinish() == True:
return
nStep = 30
self.m_StartQPointObj += nStep * self.m_UnitVectorObj
def paint(self,painter):
pen = QPen()
pen.setWidth(2)
pen.setColor(QColor(0,255,0))
painter.setPen(pen)
painter.drawEllipse(self.m_StartQPointObj, 5, 5)
return
class Animation(object):
def __init__(self):
self.m_lAction = []
def Push(self, ActionObj):
self.m_lAction.append(ActionObj)
def Remove(self, ActionObj):
nLen = len(self.m_lAction)
for i in range(nLen):
if self.m_lAction[i] == ActionObj:
del self.m_lAction[i]
return
def Update(self, painter):
for ActionObj in self.m_lAction:
ActionObj.Move()
ActionObj.paint(painter)
lTmp = []
for ActionObj in self.m_lAction:
if ActionObj.IsFinish() == False:
lTmp.append(ActionObj)
self.m_lAction = lTmp
#QTimer.singleShot(100, self.Update)
<file_sep>#coding: utf-8
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import Geometry
import BaseShape
import math
import Editor
import copy
import History
import AnimationFactory
class PaintWidget(QWidget):
def __init__(self):
QWidget.__init__(self)
self.m_curShapeCode = -1
self.m_shape = None
self.m_perm = True
self.m_lShape = []
self.m_curAction = None
self.m_chooseShape = None
self.m_prePoint = QPoint()
self.m_curPoint = QPoint()
self.setFocusPolicy(Qt.ClickFocus)
self.m_bMoving = False
self.m_AnimationObj = AnimationFactory.Animation()
#ActionObj = AnimationFactory.EllipseMoveAction(QPoint(1,1), QPoint(1600, 800), self.AfterAction)
#self.m_AnimationObj.Push(ActionObj)
self.m_dTips = {}
def setCurrentShape(self, s, action):
self.m_curAction = action
if s != self.m_curShapeCode:
self.m_curShapeCode = s
def GetSpacePoint(self):
nX = 0
nY = 0
for shape in self.m_lShape:
if shape.m_start.x() > nX:
nX = shape.m_start.x()
if shape.m_end.x() > nX:
nX = shape.m_end.x()
if shape.m_start.y() > nY:
nY = shape.m_start.y()
if shape.m_end.y() > nY:
nY = shape.m_start.y()
print 'GetSpacePoint',QPoint(nX, nY)
return QPoint(nX, nY)
def AddComment(self):
for shape in self.m_lShape:
if shape.isLine():
if len(shape.m_lCondition) > 0 and shape.m_nCommentId == -1:
#算出最合適的start點
CommentObj = BaseShape.Comment(self.GetSpacePoint(), shape)
self.m_lShape.append(CommentObj)
shape.m_nCommentId = CommentObj.m_nId
#刪除非法的注釋
while self.CheckErrorCommment() != -1:
for i in range(len(self.m_lShape)):
if self.m_lShape[i].isLine():
if len(self.m_lShape[i].m_lCondition) == 0 and self.m_lShape[i].m_nCommentId != -1:
self.RemoveComment(self.m_lShape[i].m_nCommentId)
break
def RemoveComment(self, nId):
for i in range(len(self.m_lShape)):
if self.m_lShape[i].m_nId == nId:
del self.m_lShape[i]
return
for shape in self.m_lShape:
if shape.isLine():
if shape.m_nCommentId == nId:
shape.m_nCommentId = -1
def CheckErrorCommment(self):
for shape in self.m_lShape:
if shape.isLine():
if len(shape.m_lCondition) == 0 and shape.m_nCommentId != -1:
return shape.m_nCommentId
return -1
def paintEvent(self, event):
painter = QPainter(self)
painter.setBrush(Qt.white)
painter.drawRect(0, 0, self.width(), self.height())
self.AddComment()
#self.m_AnimationObj.Update(painter)
for shape in self.m_lShape:
shape.paint(painter)
if self.m_shape != None:
self.m_shape.paint(painter)
#AnimationFactory.AnimationSingleton().Update()
def Update(self):
self.update()
QTimer.singleShot(50, self.Update)
def AfterAction(self):
print 'after action'
def mouseDoubleClickEvent(self, event):
#鼠标双击操作,弹出属性框编辑
if self.m_chooseShape != None:
if self.m_chooseShape.isRect() == True:
editor = Editor.RectEditor(self.m_chooseShape)
editor.exec_()
print 'Double click ',self.m_chooseShape.GetStateDescribe()
elif self.m_chooseShape.isLine() == True:
editor = Editor.LineEditor(self.m_chooseShape)
editor.exec_()
print 'Double click ',self.m_chooseShape.GetStateDescribe()
def PressChooseShape(self, event):
if self.m_chooseShape != None:
self.m_chooseShape.setColor(False)
self.m_chooseShape.m_curConner = - 1
self.m_chooseShape = None
self.update()
for shape in self.m_lShape:
if shape.isRect() == True:
if self.inRect(event.pos(), shape):
self.m_bMoving = True
print 'choose Rect', shape.m_nId
self.m_chooseShape = shape
self.m_chooseShape.setColor(True)
self.update()
return
elif shape.isLine() == True and shape.isRing() == False:
#求出点到直线的距离
p1 = Geometry.PointToLineInterPoint(shape.m_start, shape.m_end, event.pos())
p2 = event.pos()
x1 = p1.x() - p2.x()
y1 = p1.y() - p2.y()
len = math.sqrt( 1.0 * x1 * x1 + y1 * y1)
if len <= 3 and self.inRect(p1, shape):
self.m_bMoving = True
print 'choose Line', shape.m_nId
self.m_chooseShape = shape
self.m_chooseShape.setColor(True)
self.update()
return
elif shape.isLine() == True and shape.isRing() == True:
print 'choose Ring', shape.m_nId
startPoint = QPoint(shape.m_start.x() + (shape.m_end.x() - shape.m_start.x()) / 4, shape.m_start.y())
startPoint += QPoint(0.0, (shape.m_start.y() - shape.m_end.y()) / 2)
end = QPoint(shape.m_start.x() + (shape.m_end.x() - shape.m_start.x()) / 4 * 3, shape.m_start.y())
tmp = BaseShape.Rect()
tmp.m_start = startPoint
tmp.m_end = end
if self.inRect(event.pos(), tmp):
self.m_bMoving = True
self.m_chooseShape = shape
self.m_chooseShape.setColor(True)
self.update()
return
elif shape.isDiamond() == True:
if self.inRect(event.pos(), shape):
self.m_bMoving = True
print 'choose Diamond', shape.m_nId
self.m_chooseShape = shape
self.m_chooseShape.setColor(True)
self.update()
return
elif shape.isComment() == True:
if shape.InComment(event.pos()):
self.m_bMoving = True
print 'choose Comment', shape.m_nId
self.m_chooseShape = shape
self.m_chooseShape.setColor(True)
self.update()
return
def mousePressEvent(self, event):
print 'press'
self.m_prePoint = event.pos()
#已经有被选中的矩形或线条,判断是是否需要编辑
if self.m_chooseShape != None:
if self.m_chooseShape.getCorner(event.pos()) != -1:
return
#没有画图任务,这里触发一个选中操作
if self.m_curShapeCode == -1:
self.PressChooseShape(event)
print 'choose shape code',self.m_curShapeCode
return
#新建线条
if self.m_curShapeCode == BaseShape.BaseShape.s_Line:
self.m_shape = BaseShape.Line()
#新建矩形
elif self.m_curShapeCode == BaseShape.BaseShape.s_Rect:
self.m_shape = BaseShape.Rect()
#新建菱形
elif self.m_curShapeCode == BaseShape.BaseShape.s_Diamond:
self.m_shape = BaseShape.Diamond()
self.m_perm = False
self.m_shape.setStart(event.pos())
self.m_shape.setEnd(event.pos())
if self.m_chooseShape != None:
self.m_chooseShape.setColor(False)
self.m_chooseShape = None
def MoveReShape(self, event):
if self.m_chooseShape.isRect() == True:
self.m_curPoint = event.pos()
if self.m_chooseShape.CanReshap(self.m_curPoint - self.m_prePoint):
#先对线进行移动
for shape in self.m_lShape:
if shape.isLine() == True:
shape.followRect(self.m_chooseShape, self.m_curPoint - self.m_prePoint)
#重新画矩形
self.m_chooseShape.reShape(self.m_curPoint - self.m_prePoint)
self.m_prePoint = self.m_curPoint
elif self.m_chooseShape.isLine() == True:
if self.m_chooseShape.hasCorner() != -1:
self.m_curPoint = event.pos()
self.m_chooseShape.reShape(self.m_curPoint - self.m_prePoint)
self.m_prePoint = self.m_curPoint
elif self.m_chooseShape.isDiamond() == True:
if self.m_chooseShape.hasCorner() != -1:
self.m_curPoint = event.pos()
if self.m_chooseShape.CanReshap(self.m_curPoint - self.m_prePoint):
self.m_chooseShape.reShape(self.m_curPoint - self.m_prePoint)
self.m_prePoint = self.m_curPoint
for shape in self.m_lShape:
if shape.isLine() == True:
shape.FollowDiamond(self.m_chooseShape)
self.update()
def mouseMoveEvent(self, event):
if self.m_chooseShape != None and self.m_chooseShape.hasCorner() != -1:
self.MoveReShape(event)
return
#处理被选中的物体的拖动,这里线是不能被拖动的
DeltaMoveObj = QPoint()
if self.m_chooseShape != None and (self.m_chooseShape.isRect() == True or self.m_chooseShape.isDiamond() == True or self.m_chooseShape.isComment() == True):
if self.m_bMoving == True:
self.m_bMoving = False
self.m_chooseShape.setColor(False)
History.Push(self.m_lShape)
self.m_chooseShape.setColor(True)
self.m_curPoint = event.pos()
DeltaMoveObj = self.m_curPoint - self.m_prePoint
self.m_chooseShape.move(DeltaMoveObj)
#所有线段检查是否和这个矩形有关系,如果有,移动
for shape in self.m_lShape:
if shape.isLine() == True:
shape.move(DeltaMoveObj, self.m_chooseShape.m_nId)
self.m_prePoint = self.m_curPoint
self.update()
return
if self.m_shape and self.m_perm == False:
self.m_shape.setEnd(event.pos())
self.update()
return
def keyPressEvent(self, event):
if event.key() == Qt.Key_Delete:
if self.m_chooseShape !=None:
self.m_chooseShape.setColor(False)
print 'key delete'
History.Push(self.m_lShape)
if self.m_chooseShape.isRect() or self.m_chooseShape.isDiamond():
self.RemoveRect(self.m_chooseShape.m_nId)
elif self.m_chooseShape.isLine():
self.RemoveLine(self.m_chooseShape.m_nId)
self.m_chooseShape = None
self.update()
elif event.modifiers() == (Qt.ControlModifier) and event.key() == Qt.Key_Z:
self.m_lShape = History.Pop(self.m_lShape)
self.update()
if self.m_chooseShape == True:
self.m_chooseShape.setColor(False)
self.m_chooseShape = None
self.m_shape = None
self.m_perm = True
if self.m_curAction != None:
self.m_curAction.setChecked(False)
self.m_curAction = None
self.m_curShapeCode = -1
def RemoveLine(self, nId):
nCommentId = 0
for i in range(len(self.m_lShape)):
if self.m_lShape[i].m_nId == nId:
nCommentId = self.m_lShape[i].m_nCommentId
del self.m_lShape[i]
break
for i in range(len(self.m_lShape)):
if self.m_lShape[i].m_nId == nCommentId:
del self.m_lShape[i]
break
def RemoveRect(self, nId):
for i in range(len(self.m_lShape)):
if self.m_lShape[i].m_nId == nId:
del self.m_lShape[i]
break
self.RemoveErrorLine(nId)
def RemoveErrorLine(self, nId):
while True:
flag = self.CheckErrorLine(nId);
if flag == -1:
break;
else:
self.RemoveLine(self.m_lShape[flag].m_nId)
def CheckErrorLine(self, nId):
for i in range(len(self.m_lShape)):
if self.m_lShape[i].m_left == nId or self.m_lShape[i].m_right == nId:
return i
return -1
#重新編輯圖元結束
def ReleaseReshape(self, event):
History.Push(self.m_lShape)
if self.m_chooseShape.isRect() == True or self.m_chooseShape.isDiamond() == True:
self.m_chooseShape.m_curConner = -1
elif self.m_chooseShape.isLine() == True:
self.m_curPoint = event.pos()
self.m_chooseShape.reShape(self.m_curPoint - self.m_prePoint)
self.m_prePoint = self.m_curPoint
for i in range(len(self.m_lShape)):
if self.m_lShape[i] == self.m_chooseShape:
del self.m_lShape[i]
break
self.m_shape = self.m_chooseShape
self.m_chooseShape.m_curConner = -1
self.m_curShapeCode = BaseShape.BaseShape.s_Line
self.ReleaseCreate(event)
#創建新的圖元
def ReleaseCreate(self, event):
#如果是直线,需要判断前后是否落在两个方框内
History.Push(self.m_lShape)
if self.m_shape.isLine():
if self.checkLineLegal() == True:
self.m_lShape.append(self.m_shape)
elif self.m_shape.isRect():
x1 = self.m_shape.m_start.x() - self.m_shape.m_end.x()
y1 = self.m_shape.m_start.x() - self.m_shape.m_end.y()
if math.fabs(x1) > 10 and math.fabs(y1) > 10:
self.m_lShape.append(self.m_shape)
elif self.m_shape.isDiamond():
x1 = self.m_shape.m_start.x() - self.m_shape.m_end.x()
y1 = self.m_shape.m_start.x() - self.m_shape.m_end.y()
if math.fabs(x1) > 10 and math.fabs(y1) > 10:
self.m_lShape.append(self.m_shape)
self.m_perm = True
self.m_shape = None
if self.m_curAction != None:
self.m_curAction.setChecked(False)
self.m_curAction = None
self.m_curShapeCode = -1
self.update()
def mouseReleaseEvent(self, event):
if self.m_chooseShape != None and self.m_chooseShape.hasCorner() != -1:
self.ReleaseReshape(event)
return
if self.m_curShapeCode != -1:
self.ReleaseCreate(event)
return
#线段的起点和终点必须在矩形的内部
def checkLineLegal(self):
flag1 = -1
flag2 = -1
for i in range(len(self.m_lShape)):
if self.m_lShape[i].isLine():
continue;
if self.m_lShape[i].isRect():
if self.m_lShape[i].InRect(self.m_shape.m_start):
flag1 = i
if self.m_lShape[i].InRect(self.m_shape.m_end):
flag2 = i
if self.m_lShape[i].isDiamond():
if self.m_lShape[i].InDiamond(self.m_shape.m_start):
flag1 = i
if self.m_lShape[i].InDiamond(self.m_shape.m_end):
flag2 = i
if flag1 != -1 and flag2 != -1:
#重複的邊
for ShapeObj in self.m_lShape:
if ShapeObj.isLine():
if ShapeObj.m_left == self.m_lShape[flag1].m_nId and ShapeObj.m_right == self.m_lShape[flag2].m_nId:
return False
#非環
if flag1 != flag2:
start = QPoint()
if self.m_lShape[flag1].isRect():
start = self.GetRectVLineInterPoint(self.m_lShape[flag1], self.m_shape.m_start, self.m_shape.m_end)
elif self.m_lShape[flag1].isDiamond():
start = self.m_lShape[flag1].GetInterPoint(self.m_shape.m_start)
end = QPoint()
if self.m_lShape[flag2].isRect():
end = self.GetRectVLineInterPoint(self.m_lShape[flag2], self.m_shape.m_start, self.m_shape.m_end)
elif self.m_lShape[flag2].isDiamond():
end = self.m_lShape[flag2].GetInterPoint(self.m_shape.m_end)
if start == None:
start = copy.deepcopy(self.m_shape.m_start)
if end == None:
end = copy.deepcopy(self.m_shape.m_end)
self.m_shape.m_start = start
self.m_shape.m_end = end
self.m_shape.m_left = self.m_lShape[flag1].m_nId
self.m_shape.m_right = self.m_lShape[flag2].m_nId
return True
#環
else:
#菱形不能有環
if self.m_lShape[flag1].isDiamond():
return False
self.m_shape.m_start = copy.deepcopy(self.m_lShape[flag1].m_start)
self.m_shape.m_end = copy.deepcopy(self.m_lShape[flag1].m_end)
self.m_shape.m_left = copy.deepcopy(self.m_lShape[flag1].m_nId)
self.m_shape.m_right = copy.deepcopy(self.m_lShape[flag1].m_nId)
return True
else:
return False
#判断一个点是否在矩形中
def inRect(self, point, rect):
x = point.x()
y = point.y()
flag1 = False
flag2 = False
if rect.m_start.x() <= x and x <= rect.m_end.x():
flag1 = True
if rect.m_end.x() <= x and x <= rect.m_start.x():
flag1 = True
if rect.m_start.y() <= y and y <= rect.m_end.y():
flag2 = True
if rect.m_end.y() <= y and y <= rect.m_start.y():
flag2 = True
if flag1 == True and flag2 == True:
return True
else:
return False
def GetRectVLineInterPoint(self, rect, p1, p2):
a1 = QPoint(rect.m_start.x(), rect.m_end.y())
a2 = QPoint(rect.m_end.x(), rect.m_start.y())
a3 = rect.m_start
a4 = rect.m_end
if Geometry.IsSegmentIntersect(a3, a1, p1, p2):
return Geometry.InterPoint(a3, a1, p1, p2)
elif Geometry.IsSegmentIntersect(a3, a2, p1, p2):
return Geometry.InterPoint(a3, a2, p1, p2)
elif Geometry.IsSegmentIntersect(a4, a1, p1, p2):
return Geometry.InterPoint(a4, a1, p1, p2)
elif Geometry.IsSegmentIntersect(a4, a2, p1, p2):
return Geometry.InterPoint(a4, a2, p1, p2)
| 3355894844ac1fca7815f198bd60200428dd18fa | [
"Python"
] | 6 | Python | zhxfl/StateMachine | e77e486874d7d2541e0cd2ca07fa2a1ece3afc5e | 4d7a6cffbacc45c22f669313ab2fcf0ea8fd4e07 |
refs/heads/master | <file_sep>from django.shortcuts import render
from django.http import HttpResponse
from pendientes.models import Tarea # Importamos la clase Tarea de models.py
from random import randint
# Create your views here.
def index(request):
listita = Tarea.objects.all() #consultamos la BD y guardamos todos
# los registros de la tabla Tarea
persona = { # como objetos y guardamos en listita
"nombre" : "Marce",
"edad":33,
"hobbies": ["rugby","comer pan","cortar patas de dinos","comer chocolate","jugar pool"],
"lista_tareas": listita, # agregamos la clave lista_tareas
} # al diccionario de contenido con la
# lista de tareas p/ mandar al template
return render(request, 'inicio.html', persona)
def tarea(request):
numero = str(randint(500,999))
print("Hola!!!!!", numero)
return HttpResponse("Hola soy la vista tarea" + numero)
def aleatorio(request):
numero = str(randint(1,999))
respuesta = "El numero ganador es: " + numero
return HttpResponse(respuesta)
# Crear la vista/funcion tarea y conectar con la direccion
# /tareas en el archivo urls.py
# despues ir al navegador y abrir http:....../tareas
# Crear una vista respuestas que retorne un texto cuando
# en el navegador entremos a http:...../info
# Pista crear la funcion/vista en views.py y conectar en
# urls.py usando path(.....) | e88e6f695bb792b6e0bba1bb56e8058c4874d44d | [
"Python"
] | 1 | Python | melizeche/django_bootcamp4 | 4136875face8864ea9d3d2ba006d659c8fceaa7d | 21b8b212575d624959f96bb842e24216a8c5f43c |
refs/heads/master | <repo_name>JianYiJi/ProgrammingAssignment2<file_sep>/cachematrix.R
##This function creates a special "matrix" object that can cache its inverse
makeCacheMatrix <- function(x = matrix()) {
i <- NULL ##The inverse of the matrix
set <- function(y){
x <<- y
i <<- NULL
}
get <- function()x
##this function set the inverse of the matrix x
setInverse <- function(Inverse) i <- Inverse
##this function return the inverse of the matrix x
getInverse <- function()i
##return a list of functions that creat in this function
list(set = set,get = get,setInverse = setInverser,getInverse = getInverse)
}
##This function return a matrix that is the inverse of 'x'
cacheSolve <- function(x, ...) {
## get the inverse from x
i <- x$getInverse()
## check that if the inverse i is null,if it is not,
##then return the inverse i
if(!is.null(i)){
message("getting cached data")
return(i)
}
## when the inverse is null,the we should compute the inverse of x
## get the matrix x
data <- x$get()
##compute the inverse of the matrix x
i <- solve(x)
x$setInverse(i)
i
}
| b951039ebb9f131eda6226513c2958b0c1de152c | [
"R"
] | 1 | R | JianYiJi/ProgrammingAssignment2 | 85bc92db3c2ac576c6520ebc6c4740ec2b56333e | 027e33c2510dfbf3d16b9688b29118d497732406 |
refs/heads/master | <repo_name>cephasax/MLDesktop<file_sep>/src/br/ufrn/imd/domain/DiabetsClasses.java
package br.ufrn.imd.domain;
public enum DiabetsClasses {
//it's only a fake for put
NULL("tested_negative");
private String info;
DiabetsClasses(String info){
this.info = info;
}
public String getInfo(){
return this.info;
}
}
<file_sep>/src/br/ufrn/imd/domain/MachineLearningModel.java
package br.ufrn.imd.domain;
import weka.classifiers.Classifier;
import weka.core.SerializationHelper;
/**
* @author cephas
*
*/
public class MachineLearningModel {
private Classifier cls;
private String modelName;
public MachineLearningModel(String fileName) {
this.modelName = new String(fileName);
}
public void loadModel() {
try {
this.cls = (Classifier) SerializationHelper.read(modelName);
} catch (Exception e) {
System.out.println("Unable to load model - reason: \n");
e.printStackTrace();
}
}
public Classifier getCls() {
return cls;
}
public void setCls(Classifier cls) {
this.cls = cls;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
}
<file_sep>/src/br/ufrn/imd/domain/DiabetsUtils.java
package br.ufrn.imd.domain;
import java.util.ArrayList;
import java.util.List;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
/**
*
* @author Cephas
*
* @see this class works like an interface between iris objects in Java and Weka instance needed
* by classification method. it is a bit more than a parser but it function is restricted to build and
* allow the classification with Weka ".model" file loaded.
*
*/
public class DiabetsUtils {
private Instances dataset;
private ArrayList<Attribute> attributes;
public DiabetsUtils() {
createInstances();
}
private void createInstances() {
this.dataset = new Instances("dataset", createAttributesToDiabets(), 0);
this.dataset.setClassIndex(this.dataset.numAttributes() - 1);
;
}
private ArrayList<Attribute> createAttributesToDiabets() {
this.attributes = new ArrayList<Attribute>();
attributes.add(new Attribute("preg"));
attributes.add(new Attribute("plas"));
attributes.add(new Attribute("pres"));
attributes.add(new Attribute("skin"));
attributes.add(new Attribute("insu"));
attributes.add(new Attribute("mass"));
attributes.add(new Attribute("pedi"));
attributes.add(new Attribute("age"));
// Create Class Attribute
attributes.add(new Attribute("diabetsClass", createValuesForClass()));
return attributes;
}
private List<String> createValuesForClass() {
List<String> classValues = new ArrayList<String>();
classValues.add(new String("tested_negative"));
classValues.add(new String("tested_positive"));
return classValues;
}
public Instance diabetsToWekaInstance(Diabets diabets) {
double[] values = new double[dataset.numAttributes()];
values[0] = diabets.getPreg();
values[1] = diabets.getPlas();
values[2] = diabets.getPres();
values[3] = diabets.getSkin();
values[4] = diabets.getInsu();
values[5] = diabets.getMass();
values[6] = diabets.getPedi();
values[7] = diabets.getAge();
values[8] = dataset.attribute(8).indexOfValue(diabets.getDiabetsClass());
Instance instance = new DenseInstance(1, values);
return instance;
}
public Instances getDataset() {
return dataset;
}
public void setDataset(Instances dataset) {
this.dataset = dataset;
}
}
<file_sep>/src/br/ufrn/imd/domain/DiabetsItem.java
package br.ufrn.imd.domain;
import java.util.ArrayList;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
//SOME S*** HERE, but I needed to solve problem fastly
public class DiabetsItem {
private SimpleDoubleProperty preg;
private SimpleDoubleProperty plas;
private SimpleDoubleProperty pres;
private SimpleDoubleProperty skin;
private SimpleDoubleProperty insu;
private SimpleDoubleProperty mass;
private SimpleDoubleProperty pedi;
private SimpleDoubleProperty age;
private SimpleStringProperty diabetsClass;
public DiabetsItem() {
this.preg = new SimpleDoubleProperty();
this.plas = new SimpleDoubleProperty();
this.pres = new SimpleDoubleProperty();
this.skin = new SimpleDoubleProperty();
this.insu = new SimpleDoubleProperty();
this.mass = new SimpleDoubleProperty();
this.pedi = new SimpleDoubleProperty();
this.age = new SimpleDoubleProperty();
this.diabetsClass = new SimpleStringProperty("?");
}
public Double getPreg() {
return preg.get();
}
public void setPreg(double preg) {
this.preg.set(preg);
}
public Double getPlas() {
return plas.get();
}
public void setPlas(double plas) {
this.plas.set(plas);
}
public Double getPres() {
return pres.get();
}
public void setPres(double pres) {
this.pres.set(pres);
}
public Double getSkin() {
return skin.get();
}
public void setSkin(double skin) {
this.skin.set(skin);
}
public Double getInsu() {
return insu.get();
}
public void setInsu(double insu) {
this.insu.set(insu);
}
public Double getMass() {
return mass.get();
}
public void setMass(double mass) {
this.mass.set(mass);
}
public Double getPedi() {
return pedi.get();
}
public void setPedi(double pedi) {
this.pedi.set(pedi);
}
public Double getAge() {
return age.get();
}
public void setAge(double age) {
this.age.set(age);
}
public String getDiabetsClass() {
return diabetsClass.get();
}
public void setDiabetsClass(String diabetsClass) {
this.diabetsClass.set(diabetsClass);
}
public static ArrayList<DiabetsItem> diabetsItensFromDiabetsList(ArrayList<Diabets> data) {
ArrayList<DiabetsItem> dt = new ArrayList<DiabetsItem>();
for (int i = 0; i < data.size(); i++) {
DiabetsItem dItem = new DiabetsItem();
dItem.preg.setValue(data.get(i).getPreg());
dItem.plas.setValue(data.get(i).getPlas());
dItem.pres.setValue(data.get(i).getPres());
dItem.skin.setValue(data.get(i).getSkin());
dItem.insu.setValue(data.get(i).getInsu());
dItem.mass.setValue(data.get(i).getMass());
dItem.pedi.setValue(data.get(i).getPedi());
dItem.age.setValue(data.get(i).getAge());
dItem.diabetsClass.setValue(data.get(i).getDiabetsClass());
dt.add(dItem);
}
return dt;
}
}
<file_sep>/src/br/ufrn/imd/utils/DiabetsParser.java
package br.ufrn.imd.utils;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import br.ufrn.imd.domain.Diabets;
import br.ufrn.imd.domain.DiabetsItem;
import javafx.collections.ObservableList;
public class DiabetsParser {
public static List<Diabets> csvToDiabetsData(String filePath) throws IOException{
//Create the CSVFormat object
CSVFormat format = CSVFormat.RFC4180.withHeader().withDelimiter(',');
CSVParser parser = new CSVParser(new FileReader(filePath), format);
List<Diabets> diabetsData = new ArrayList<Diabets>();
for(CSVRecord record : parser){
Diabets diabets = new Diabets();
diabets.setPreg(Double.valueOf(record.get("preg")));
diabets.setPlas(Double.valueOf(record.get("plas")));
diabets.setPres(Double.valueOf(record.get("pres")));
diabets.setSkin(Double.valueOf(record.get("skin")));
diabets.setInsu(Double.valueOf(record.get("insu")));
diabets.setMass(Double.valueOf(record.get("mass")));
diabets.setPedi(Double.valueOf(record.get("pedi")));
diabets.setAge(Double.valueOf(record.get("age")));
diabets.setDiabetsClass("?");
diabetsData.add(diabets);
}
//close the parser
parser.close();
return diabetsData;
}
public static ArrayList<Diabets> DiabetsItensToDiabets(ObservableList<DiabetsItem> dtis){
ArrayList<Diabets> diabetsData = new ArrayList<Diabets>();
for(DiabetsItem di: dtis){
Diabets diabets = new Diabets();
diabets.setPreg(di.getPreg());
diabets.setPlas(di.getPlas());
diabets.setPres(di.getPres());
diabets.setSkin(di.getSkin());
diabets.setInsu(di.getInsu());
diabets.setMass(di.getMass());
diabets.setPedi(di.getPedi());
diabets.setAge(di.getAge());
diabets.setDiabetsClass("?");
diabetsData.add(diabets);
}
return diabetsData;
}
}
| e5b14a5ffae505588230a7b8e1008e01b0810530 | [
"Java"
] | 5 | Java | cephasax/MLDesktop | 5bf474810b05108baa65adfff61ce55ba7559aa5 | d9efac4d48fb7a5412edc7667f03f2f464bcef83 |
refs/heads/master | <file_sep>class User < ActiveRecord::Base
has_many :articles, dependent: :destroy
before_save { self.email = email.downcase }
validates :username, presence: true, length: {minimum: 3, maximum: 20 }
validates :email, presence: true, length: {minimum: 6, maximum: 100 }
has_secure_password
end | f15e858df21bec0f0dbcba3b2c6f73693ab0ee7e | [
"Ruby"
] | 1 | Ruby | peterosipov/my_blog | 370cb82839ed1887ed2dd0f4ac37e7ebc9d93650 | 31d1e7338c1968bd2bc8c1d55ad5dd30ebb78545 |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package carrera;
import java.util.Random;
import java.util.Scanner;
/**
*
* @author <NAME>
*/
public class Carrera {
// static int[] lanzamiento() {
//
// int[] resultados = new int[2]; //Se tiran tres dados
//
// resultados[0] = (int) (Math.random() * 6 + 1); //Primer dado
// resultados[1] = (int) (Math.random() * 6 + 1); //Segundo dado
//
// return resultados;
// }
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// TODO code application logic here
System.out.println("Digite la cantidad de jugadores Minimo 2 maximo 4");
int n = Integer.parseInt(sc.nextLine());
int num = n;
while (num < 2 || num > 4) {
System.out.println("ERROR Digite la cantidad de jugadores Minimo 2 maximo 4");
num = Integer.parseInt(sc.nextLine());
}
System.out.println("====================================================================");
System.out.println("Elija un nivel de tablero");
System.out.println("1. Nivel básico (Tablero de 20 posiciones)");
System.out.println("2. Nivel intermedio (Tablero de 30 posiciones)");
System.out.println("3. Nivel avanzado (Tablero de 50 posiciones)");
System.out.println("====================================================================");
int table = Integer.parseInt(sc.nextLine());
int tab=table;
while (tab != 1 && tab != 2 && tab != 3) {
System.out.println("ERROR Digite un nivel de tablero valido(1,2 o 3)");
tab = Integer.parseInt(sc.nextLine());
}
int opcion = 0;
if (tab == 1 || tab == 2 || tab == 3) {
switch (tab) {
case 1:
opcion = 20;
break;
case 2:
opcion = 30;
break;
case 3:
opcion = 50;
break;
case 4:
System.exit(0);
break;
}
}
System.out.println("====================================================================");
System.out.println("EL JUEGO HA COMENZADO");
int[] puntaje = new int[n];
int[] pares = new int[n];
int i = 0;
while (puntaje[i] < opcion || pares[i] == 3) {
System.out.println("====================================================================");
System.out.println("*Se lanzan los dados*");
int dado1 = (int) (Math.random() * 6 + 1);
int dado2 = (int) (Math.random() * 6 + 1);
if (dado1 == dado2) {
pares[i]++;
} else {
pares[i] = 0;
}
puntaje[i] += dado1 + dado2;
System.out.println("Jugador " + (i + 1) + " esta en la posicion:" + puntaje[i]);
System.out.println("====================================================================");
if (puntaje[i] < opcion) {
i++;
}
if (i == puntaje.length) {
i = 0;
}
}
System.out.println("EL JUGADOR NUMERO: " + (i + 1) + " ES EL GANADOR");
System.out.println("====================================================================");
System.out.println("====================================================================");
System.out.println("====================================================================");
System.out.println("DESEAS JUGAR DE NUEVO? s/n");
String f=sc.nextLine();
if(f.equals("s")){
Carrera.main (null);
System.out.print("\f");
}else if(f.equals("n")){
System.exit(0);
}
}
}
| 7c11a756e48ebd64d023a7fc8d1a3bd447474417 | [
"Java"
] | 1 | Java | xtedor/Carrera | f78e78194f14aa62cde6715a967fff558dd7ab8e | 12ca0772d876518da1efa2e725fdcc9893ed7ebe |
refs/heads/master | <file_sep>hacktoberfest
All contributions to hacktoberfest are welcome.
<file_sep>#include<stdio.h>
void main()
{
int n;
float avg_wt,avg_tat;
printf("Enter number of process: ");
scanf("%d",&n);
int processes[n],burst_time[n],wt[n],tat[n],i,j,total_wt=0,total_tat=0,temp;
for(int k=0;k<n;k++)
{
printf("Enter process id and burst time of process %d: ",(k+1));
scanf("%d",&processes[k]);
scanf("%d",&burst_time[k]);
}
//Bubble sort to sort burst time
for(i = 0; i < n-1; i++) {
for(j = 0; j < n-1-i; j++) {
if(burst_time[j] > burst_time[j+1]) {
temp = burst_time[j];
burst_time[j] = burst_time[j+1];
burst_time[j+1] = temp;
}
}
}
wt[0]=0;
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=burst_time[j];
total_wt=total_wt+wt[i];
}
avg_wt=(float)total_wt/n;
printf("Processes\tBurst Time\tWaiting Time\tTurn-Around Time \n");
for(i=0;i<n;i++)
{
tat[i]=burst_time[i]+wt[i];
total_tat+=tat[i];
printf("%d\t\t%d\t\t%d\t\t%d",processes[i],burst_time[i],wt[i],tat[i]);
printf("\n");
}
avg_tat=(float)total_tat/n; //average turnaround time
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f\n",avg_tat);
}
| c63849822a633528c5d90b9e23e2ca4e3d2a9917 | [
"Markdown",
"C"
] | 2 | Markdown | hp72535/Code | 0a4c256dbd72130641ad32d462fb4d3e1014036a | 6d871254fcd287ce974e004911807430d6784229 |
refs/heads/main | <repo_name>Bolajiomo99/-Dev-Challenge-Todos<file_sep>/src/App.js
// import logo from "./logo.svg";
import "./App.css";
import Todos from "./components/Todos";
function App() {
return (
<>
<h1 className="text-center mt-4 mb-4">#todo</h1>
<Todos />
</>
);
}
export default App;
<file_sep>/README.md
# Todo App (persisting state with Local Storage)
This project/webpage was developed using `React` v "^17.0.2", `Bootstrap` v "4.6.0" (cdn) and `Font-Awesome Icons` v "^5.10" (cdn) libraries.
Deployed with `Netlify` link [here](https://todo-adeoluwa.netlify.app/).
Figma design link [here](https://www.figma.com/file/SClDA1weEGA3Mo8Is8Sbf2/todo?node-id=0%3A1).
Figma design was provided by [devChallenges.io](https://devchallenges.io/).
You can clone project and customise at your end.
| 94fafe074b8df50782decd8193eee7bce7858342 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Bolajiomo99/-Dev-Challenge-Todos | a7142c9d08235e27cf3e88c3b1fc869dbb1ee3d4 | d0edfa6aa87a33fa70a90882f9377a7a922f6f98 |
refs/heads/main | <file_sep>-- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jul 27, 2021 at 11:12 PM
-- Server version: 10.4.19-MariaDB
-- PHP Version: 7.4.20
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `to-do`
--
-- --------------------------------------------------------
--
-- Table structure for table `tasks`
--
CREATE TABLE `tasks` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`is_complete` tinyint(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `tasks`
--
INSERT INTO `tasks` (`id`, `name`, `is_complete`) VALUES
(1, 'task one updatedaaaaa', 1),
(4, 'task2', 0),
(6, 'task4', 1);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tasks`
--
ALTER TABLE `tasks`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tasks`
--
ALTER TABLE `tasks`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
session_start();
require_once '../../includes/DbConnection.php';
if (isset($_POST['task-name']) && !empty($_POST['task-name']) && isset($_POST['task-id']) && !empty($_POST['task-id'])) {
// update task
$updateTaskStmt = $db->prepare("UPDATE `tasks` SET `name`=:task_name WHERE id= :task_id");
$updateTaskStmt->execute([
':task_name' => $_POST['task-name'],
':task_id' => $_POST['task-id']
]);
if ($updateTaskStmt->rowCount()) {
$_SESSION['update'] = true;
header("location: ../../index.php");
} else {
$_SESSION['update'] = false;
header("location: ../../index.php");
}
} else {
require_once '../../includes/header.php';
?>
<body>
<div class="container mt-5">
<p class="lead">Unknown Error, Please Try Again</p>
</div>
</body>
</html>
<?php
}
<file_sep><?php
require_once '../../includes/header.php';
?>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-md-6 mx-auto">
<h3>Create Task</h3>
</div>
</div>
<div class="row mt-5">
<div class="col-md-6 mx-auto">
<form method="POST" action="../../controllers/Tasks/create.php">
<div class="mb-3">
<label for="taskName" class="form-label" style="font-weight: bold;">Task Name: </label>
<input type="text" class="form-control" id="taskName" name="task-name" placeholder="please enter task name">
</div>
<button type="submit" class="btn btn-primary">Add </button>
</form>
</div>
</div>
<div class="row mt-3">
<div class="col-md-6 mx-auto">
<a href="../../index.php" class="btn btn-primary">Home </a>
</div>
</div>
</div>
</body>
</html><file_sep><?php
if (isset($_SESSION['added']) && $_SESSION['added'] === true) {
?>
<div class="row">
<div class="col-md-6">
<div class="alert alert-success" role="alert">
Task has been added successfully
</div>
</div>
</div>
<?php
// unset($_SESSION['added']);
session_unset();
} elseif (isset($_SESSION['added']) && $_SESSION['added'] === false) {
?>
<div class="row">
<div class="col-md-6">
<div class="alert alert-danger" role="alert">
Task has Not been added
</div>
</div>
</div>
<?php
session_unset();
} elseif (isset($_SESSION['update']) && $_SESSION['update'] === true) {
?>
<div class="row">
<div class="col-md-6">
<div class="alert alert-success" role="alert">
Task has been updated successfully
</div>
</div>
</div>
<?php
session_unset();
} elseif (isset($_SESSION['update']) && $_SESSION['update'] === false) {
?>
<div class="row">
<div class="col-md-6">
<div class="alert alert-danger" role="alert">
Task has Not been updated
</div>
</div>
</div>
<?php
session_unset();
} elseif (isset($_SESSION['delete']) && $_SESSION['delete'] === true) {
?>
<div class="row">
<div class="col-md-6">
<div class="alert alert-success" role="alert">
Task has been deleted successfully
</div>
</div>
</div>
<?php
session_unset();
} elseif (isset($_SESSION['delete']) && $_SESSION['delete'] === false) {
?>
<div class="row">
<div class="col-md-6">
<div class="alert alert-danger" role="alert">
Task has not been deleted
</div>
</div>
</div>
<?php
session_unset();
} elseif (isset($_SESSION['complete-task']) && $_SESSION['complete-task'] === true) {
?>
<div class="row">
<div class="col-md-6">
<div class="alert alert-success" role="alert">
Task has been Completed successfully
</div>
</div>
</div>
<?php
session_unset();
} elseif (isset($_SESSION['complete-task']) && $_SESSION['complete-task'] === false) {
?>
<div class="row">
<div class="col-md-6">
<div class="alert alert-danger" role="alert">
Task has not been Completed
</div>
</div>
</div>
<?php
session_unset();
}
?><file_sep><?php
require_once '../../includes/DbConnection.php';
session_start();
if (isset($_POST['task-name']) && !empty($_POST['task-name'])) {
$taskName = $_POST['task-name'];
// length validaton
if (strlen($taskName) > 255) {
die('task name should not exceed 255 character');
}
$creatTaskStmt = $db->prepare("INSERT INTO `tasks`(`name`) VALUES (:task_name)");
$creatTaskStmt->execute([
':task_name' => $taskName
]);
if ($creatTaskStmt->rowCount()) {
$_SESSION['added'] = true;
header("location: ../../index.php");
} else {
$_SESSION['added'] = false;
header("location: ../../index.php");
}
} else {
require_once '../../includes/header.php';
?>
<body>
<div class="container mt-5">
<p class="lead">Unknown Error, Please Try Again</p>
</div>
</body>
</html>
<?php
}
<file_sep># to-do-list
A simple to-do list App by native PHP

<file_sep><?php
session_start();
require_once '../../includes/header.php';
if (isset($_SESSION['task-name']) && !empty($_SESSION['task-name']) && isset($_SESSION['task-id']) && !empty($_SESSION['task-id'])) {
$taskName = $_SESSION['task-name']['name'];
$taskId = $_SESSION['task-id'];
?>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-md-6 mx-auto">
<h3>Edit Task</h3>
</div>
</div>
<div class="row mt-5">
<div class="col-md-6 mx-auto">
<form method="POST" action="../../controllers/Tasks/update.php">
<input type="hidden" name="task-id" value="<?php echo $taskId ?>">
<div class="mb-3">
<label for="taskName" class="form-label" style="font-weight: bold;">Task Name: </label>
<input type="text" class="form-control" id="taskName" name="task-name" value="<?php echo $taskName ?>" placeholder="please enter task name">
</div>
<button type="submit" class="btn btn-primary">Update </button>
</form>
</div>
</div>
<div class="row mt-3">
<div class="col-md-6 mx-auto">
<a href="../../index.php" class="btn btn-primary">Home </a>
</div>
</div>
</div>
</body>
</html>
<?php
} else {
?>
<body>
<div class="container mt-5">
<p class="lead">Unknown Error, Please Try Again</p>
</div>
</body>
</html>
<?php
}
<file_sep><?php
session_start();
require_once 'includes/header.php';
?>
<body>
<div class="container mt-5">
<?php require_once 'includes/sessionMessages.php'; ?>
<div class="row">
<div class="col-md-6">
<a href="views/Tasks/create.php" class="btn btn-primary">Add Task</a>
</div>
</div>
<!-- tasks table -->
<div class="row mt-5">
<div class="col-md-8">
<table class="table">
<thead class="table-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Task Name</th>
<th scope="col">Status</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<?php
require_once 'includes/DbConnection.php';
$fetchTasksQuery = $db->query("SELECT * FROM `tasks`");
$allTasks = $fetchTasksQuery->fetchAll(PDO::FETCH_ASSOC);
foreach ($allTasks as $row) {
?>
<tr>
<th scope="row"><?php echo $row['id'] ?></th>
<td><?php echo $row['name'] ?></td>
<td>
<?php if ($row['is_complete'] == 1) {
?>
<div class="alert alert-success" role="alert">
Completed
</div>
<?php
} else {
?>
<div class="alert alert-warning" role="alert">
Not Completed
</div>
<?php
}
?>
</td>
<td>
<a href="controllers/Tasks/edit.php?id=<?php echo $row['id'] ?>" class="btn btn-warning ">Edite</a>
<a href="controllers/Tasks/delete.php?id=<?php echo $row['id'] ?>" class="btn btn-danger ">Delete</a>
<?php
if ($row['is_complete'] == 0) {
?>
<a href="controllers/Tasks/completeTask.php?id=<?php echo $row['id'] ?>" class="btn btn-dark ">Complete task</a>
<?php
}
?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep><?php
try {
//code...
$dsn = "mysql:host=localhost;dbname=to-do";
$user = "root";
$passwd = "";
$db = new PDO($dsn, $user, $passwd);
} catch (\PDOException $th) {
//throw $th;
echo "Error: ", $th->getMessage();
}
<file_sep><?php
require_once '../../includes/DbConnection.php';
session_start();
// var_dump($_GET);
// die;
if (isset($_GET) && !empty($_GET['id'])) {
$taskId = $_GET['id'];
// get task by id
$getTaskStmt = $db->prepare("SELECT `name` FROM `tasks` WHERE id=:task_id");
$getTaskStmt->execute([
':task_id' => $taskId
]);
// if id not exist >>>> error message
if ($getTaskStmt->rowCount()) {
$_SESSION['task-name'] = $getTaskStmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['task-id'] = $taskId;
header("location: ../../views/Tasks/edit.php");
} else {
require_once '../../includes/header.php';
?>
<body>
<div class="container mt-5">
<p class="lead">This Task doesn't exist</p>
</div>
</body>
</html>
<?php
die;
}
} else {
?>
<body>
<div class="container mt-5">
<p class="lead">Unknown Error, Please Try Again</p>
</div>
</body>
</html>
<?php
}
<file_sep><?php
session_start();
require_once '../../includes/DbConnection.php';
if (isset($_GET) && !empty($_GET['id'])) {
$taskId = $_GET['id'];
// ensure that the id is exist
$getTaskStmt = $db->prepare("SELECT `name` FROM `tasks` WHERE id=:task_id");
$getTaskStmt->execute([
':task_id' => $taskId
]);
// if id not exist >>>> error message
if ($getTaskStmt->rowCount()) {
// delete task by id
$completeTaskStmt = $db->prepare("UPDATE `tasks` SET `is_complete`=1 WHERE id=:task_id");
$completeTaskStmt->execute([
':task_id' => $taskId
]);
if ($completeTaskStmt->rowCount()) {
$_SESSION['complete-task'] = true;
header("location: ../../index.php");
} else {
$_SESSION['complete-task'] = false;
header("location: ../../index.php");
}
} else {
require_once '../../includes/header.php';
?>
<body>
<div class="container mt-5">
<p class="lead">This Task doesn't exist</p>
</div>
</body>
</html>
<?php
die;
}
} else {
?>
<body>
<div class="container mt-5">
<p class="lead">Unknown Error, Please Try Again</p>
</div>
</body>
</html>
<?php
}
| 1a29b29b2dbfd6f60c2a5e695a18b8cbf53b2658 | [
"Markdown",
"SQL",
"PHP"
] | 11 | SQL | Elsayed93/to-do-list | 92e1bbfe5891f891cae6997b60f16a474cd6c7b5 | 44f28ecfc3abbee5455934dc4e2a765d92e1d468 |
refs/heads/master | <file_sep>ETHEREUM_RPC_URL=ws://0.0.0.0:8546<file_sep>import { USDC } from 'src/constants'
export const start = async () => {
//TODO: Some app logic
const decimals = await USDC.methods.decimals().call()
const vitalikBalance = await USDC.methods.balanceOf('0x1db3439a222c519ab44bb1144fc28167b4fa6ee6').call()
console.log(`Vitalik has ${vitalikBalance / 10 ** decimals} USDC`)
};
start()<file_sep>require('dotenv').config()
import Web3 from 'web3'
import erc20Abi from '../contracts/erc20.json'
export const web3 = new Web3(process.env.ETHEREUM_RPC_URL)
// @ts-ignore
export const USDC = new web3.eth.Contract(erc20Abi, '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'); | 302a16c53a3f7ab9034f7ae7838c628326e3795d | [
"TypeScript",
"Shell"
] | 3 | Shell | 34x4p08/awesome-typescript-web3-service | 3b4bd1d26e62d2ba92cba9748453b17b89f8c50c | 3b7aeb0d4894cc65e53f1c8b540faa1f70f78b17 |
refs/heads/master | <repo_name>thunguyen5885/HTVRacing<file_sep>/HTVRacing/app/src/main/java/htv/racing/layers/ui/fragments/HomeFragment.java
package htv.racing.layers.ui.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import htv.racing.R;
import htv.racing.layers.ui.activities.HomeActivity;
import htv.racing.layers.ui.components.views.foreground.ForegroundRelativeLayout;
/**
* Created by ThuNguyen on 12/11/2014.
*/
public class HomeFragment extends Fragment implements View.OnClickListener{
public interface IHomeItemOnClickListner{
public void onHomeItemDatingManagementClicked();
public void onHomeItemCalendarCreatingClicked();
public void onHomeItemPatientListClicked();
public void onHomeItemStatisticClicked();
}
private View mDatingManagementLayout;
private View mCalendarCreatingLayout;
private View mPatientListLayout;
private View mStatisticLayout;
public HomeFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
mDatingManagementLayout = v.findViewById(R.id.homeItemDatingManagementLayout);
mCalendarCreatingLayout = v.findViewById(R.id.homeItemCalendarCreatingLayout);
mPatientListLayout = v.findViewById(R.id.homeItemPatientListLayout);
mStatisticLayout = v.findViewById(R.id.homeItemStatisticLayout);
// Initialize the home item layout
return v;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
if(getActivity() != null){
((HomeActivity) getActivity()).hideFooterSeparator();
((HomeActivity) getActivity()).hideHeaderBackButton();
}
}
@Override
public void onPause() {
super.onPause();
// if(getActivity() != null){
// ((HomeActivity) getActivity()).showFooterSeparator();
// ((HomeActivity) getActivity()).showHeaderBackButton();
// }
}
@Override
public void onClick(View v) {
int parentViewId = (Integer) v.getTag();
switch(parentViewId){
case R.id.homeItemDatingManagementLayout:
break;
case R.id.homeItemCalendarCreatingLayout:
break;
case R.id.homeItemPatientListLayout:
break;
case R.id.homeItemStatisticLayout:
break;
}
}
private void initHomeItemLayout(View parentView, int titleId, int posterId){
View view = parentView.findViewById(R.id.homeItemLayout);
view.setTag(parentView.getId());
view.setOnClickListener(this);
// Title
TextView tvTitle = (TextView)parentView.findViewById(R.id.tvHomeItemTitle);
tvTitle.setText(titleId);
// Poster
ImageView ivPoster = (ImageView)parentView.findViewById(R.id.ivHomeItemPoster);
ivPoster.setImageResource(posterId);
}
private IHomeItemOnClickListner mHomeItemOnClickListener = new IHomeItemOnClickListner() {
@Override
public void onHomeItemDatingManagementClicked() {
}
@Override
public void onHomeItemCalendarCreatingClicked() {
}
@Override
public void onHomeItemPatientListClicked() {
}
@Override
public void onHomeItemStatisticClicked() {
}
};
}
<file_sep>/HTVRacing/app/src/main/java/htv/racing/layers/services/IWebServiceAccess.java
package htv.racing.layers.services;
import java.util.List;
import java.util.Map;
/**
* Created by phannguyen on 12/7/14.
*/
public interface IWebServiceAccess<T extends IWebServiceModel> {
static final String WEBSERVICE_HOST = "https://easycare.vn/api/";
WSResult<T> executeRequest();
Map<String, List<String>> getHeaders();
void setHeaders(Map<String, List<String>> headers);
}
<file_sep>/HTVRacing/app/src/main/java/htv/racing/layers/ui/base/BaseFragment.java
package htv.racing.layers.ui.base;
import android.app.Fragment;
/**
* Created by phannguyen on 12/7/14.
*/
public class BaseFragment extends Fragment{
}
<file_sep>/HTVRacing/app/src/main/java/htv/racing/layers/ui/fragments/MenuFragment.java
package htv.racing.layers.ui.fragments;
import android.app.Activity;
import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SlidingPaneLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.NetworkImageView;
import htv.racing.R;
import htv.racing.layers.ui.activities.HomeActivity;
public class MenuFragment extends Fragment implements View.OnClickListener{
public interface IOnMenuItemOnClickListener{
public void onMenuItemUserClicked();
public void onMenuItemDatingManagementClicked();
public void onMenuItemCalendarCreatingClicked();
public void onMenuItemCommentClicked();
public void onMenuItemExitClicked();
}
// For layout, control
private View mMenuItemUser;
private View mMenuItemDatingManagement;
private View mMenuItemCalendarCreating;
private View mMenuItemComment;
private View mMenuItemExit;
private View mMenuItemSeletedItem;
// For flags
private boolean mIsItemClicked = false;
// For object
private SlidingPaneLayout mSlidingLayout;
public void setSlidingLayout(SlidingPaneLayout slidingLayout){
mSlidingLayout = slidingLayout;
}
public MenuFragment(){
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_menu, container, false);
mMenuItemUser = v.findViewById(R.id.menuItemUser);
mMenuItemDatingManagement = v.findViewById(R.id.menuItemDatingManagement);
mMenuItemCalendarCreating = v.findViewById(R.id.menuItemCalendarCreating);
mMenuItemComment = v.findViewById(R.id.menuItemComment);
mMenuItemExit = v.findViewById(R.id.menuItemExit);
//initMenuItem(mMenuItemUser, 0, );
// initMenuItem(mMenuItemDatingManagement, R.string.menu_dating_management, R.drawable.ic_menu_dating_management);
// initMenuItem(mMenuItemCalendarCreating, R.string.menu_calendar_creating, R.drawable.ic_menu_calendar_creating);
// initMenuItem(mMenuItemComment, R.string.menu_comment, R.drawable.ic_menu_comment);
// initMenuItem(mMenuItemExit, R.string.menu_exit, R.drawable.ic_menu_exit);
return v;
}
/*ThuNguyen Add 20141022 Start*/
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
}
private void initMenuItem(View rootView, int titleId, int posterId){
View menuItemLayout = rootView.findViewById(R.id.menuItemLayout);
menuItemLayout.setOnClickListener(this);
menuItemLayout.setTag(rootView.getId());
TextView tvTitle = (TextView) rootView.findViewById(R.id.tvMenuItemTitle);
tvTitle.setText(titleId);
NetworkImageView tvPoster = (NetworkImageView) rootView.findViewById(R.id.ivMenuItemPoster);
tvPoster.setDefaultImageResId(posterId);
}
/**
* Update background, text color for selected view
*/
private void updateSelectedView(){
if(mMenuItemSeletedItem != null){
mMenuItemSeletedItem.setBackgroundColor(getResources().getColor(R.color.menu_item_selected_background_color));
TextView tvTitle = (TextView) mMenuItemSeletedItem.findViewById(R.id.tvMenuItemTitle);
tvTitle.setTextColor(getResources().getColor(R.color.white));
}
}
private void resetSelectedView(){
if(mMenuItemSeletedItem != null){
mMenuItemSeletedItem.setBackgroundColor(Color.TRANSPARENT);
TextView tvTitle = (TextView) mMenuItemSeletedItem.findViewById(R.id.tvMenuItemTitle);
tvTitle.setTextColor(getResources().getColor(R.color.textview_color_grey));
}
}
@Override
public void onClick(View v) {
if(mSlidingLayout != null && mSlidingLayout.isOpen() &&
!mIsItemClicked) {
// Not permit 2 items run at the same time
mIsItemClicked = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mIsItemClicked = false;
}
}, 500);
// Reset the selected view before
resetSelectedView();
int selectedId = (Integer) v.getTag();
switch (selectedId) {
case R.id.menuItemUser:
mMenuItemSeletedItem = mMenuItemUser;
mMenuItemOnClickListener.onMenuItemUserClicked();
break;
case R.id.menuItemDatingManagement:
mMenuItemSeletedItem = mMenuItemDatingManagement;
mMenuItemOnClickListener.onMenuItemDatingManagementClicked();
break;
case R.id.menuItemCalendarCreating:
mMenuItemSeletedItem = mMenuItemCalendarCreating;
mMenuItemOnClickListener.onMenuItemCalendarCreatingClicked();
break;
case R.id.menuItemComment:
mMenuItemSeletedItem = mMenuItemComment;
mMenuItemOnClickListener.onMenuItemCommentClicked();
break;
case R.id.menuItemExit:
mMenuItemSeletedItem = mMenuItemExit;
mMenuItemOnClickListener.onMenuItemExitClicked();
break;
}
updateSelectedView();
}
}
private IOnMenuItemOnClickListener mMenuItemOnClickListener = new IOnMenuItemOnClickListener() {
@Override
public void onMenuItemUserClicked() {
// Go to user info screen
}
@Override
public void onMenuItemDatingManagementClicked() {
// Go to dating management screen
}
@Override
public void onMenuItemCalendarCreatingClicked() {
// Go to calendar creating screen
}
@Override
public void onMenuItemCommentClicked() {
// Go to comment screen
}
@Override
public void onMenuItemExitClicked() {
// Logout, exit here
}
};
}<file_sep>/HTVRacing/app/src/main/java/htv/racing/layers/ui/views/ILoginView.java
package htv.racing.layers.ui.views;
import htv.racing.layers.ui.views.base.IBaseView;
/**
* Created by phannguyen on 12/7/14.
*/
public interface ILoginView extends IBaseView {
void LoginOK(String message);
void LoginFail(String message);
void ShowIncorrectAccountInfoMessage(String errorMessage);
}
<file_sep>/HTVRacing/app/src/main/java/htv/racing/utils/AppConstants.java
package htv.racing.utils;
/**
* Created by phan on 12/9/2014.
*/
public class AppConstants {
public static final int UNDEFINED_ID = -1;
public static enum WSMethod {
GET, POST, PUT, DELETE
}
public static enum EXAMINATION_STATUS {
WAITING, ACCEPTED, CANCEL
}
public static final String DEFAULT_ENCODING = "UTF-8";
}
<file_sep>/HTVRacing/app/src/main/java/htv/racing/layers/services/concretes/LoginWSAccess.java
package htv.racing.layers.services.concretes;
import java.net.URI;
import htv.racing.layers.services.AbstractWSAccess;
import htv.racing.layers.services.WSRequest;
import htv.racing.layers.services.models.AuthorizationWSModel;
/**
* Created by phan on 12/9/2014.
*/
public class LoginWSAccess extends AbstractWSAccess<AuthorizationWSModel> {
private static final URI LOGIN_URI = URI.create(WEBSERVICE_HOST + "/login");
@Override
protected WSRequest buildRequest() {
return null;
}
@Override
protected AuthorizationWSModel parseResponseBody(String responseBody) throws Exception {
return null;
}
}
| 14a70124bfc042fa6a121faca1b8cb979060c98e | [
"Java"
] | 7 | Java | thunguyen5885/HTVRacing | 6b80f9a0e9b34a53a91c47bf6f7cd8355614d236 | d4a0121d0d03ec949378b25b3c38b61d258bd59e |
refs/heads/master | <file_sep>#include "udpdata.h"
UDPData::UDPData(int headLen, int bodyLen)
{
this->headLength = headLen;
this->bodyLength = bodyLen;
this->head = NULL;
this->body = NULL;
}
UDPData::UDPData(const UDPData& other)
{
headLength = other.headLength;
bodyLength = other.bodyLength;
head = new char[headLength];
memcpy(head, other.head, headLength);
body = new char[bodyLength];
memcpy(body, other.body, bodyLength);
}
UDPData::~UDPData()
{
if (NULL != this->head)
{
delete[] this->head;
this->head = NULL;
}
if (NULL != this->body)
{
delete[] this->body;
this->body = NULL;
}
}
int UDPData::getHeadLength()
{
return this->headLength;
}
int UDPData::getBodyLength()
{
return this->bodyLength;
}
int UDPData::getLength()
{
return this->headLength + this->bodyLength;
}
bool UDPData::setHead(char *head, int len)
{
if (head == NULL)
{
printf("ERROR [UDPData:setHead] Parameter \"head\" is null.");
return false;
}
if (0 != len)
this->headLength = len;
if (NULL == this->head)
this->head = new char[this->headLength];
memcpy(this->head, head, this->headLength);
return true;
}
bool UDPData::setiHead(int i, char data)
{
if (this->head == NULL)
{
printf("ERROR [UDPData:setiHead] \"head\" is null.");
return false;
}
if (i >= getHeadLength())
{
printf("ERROR [UDPData:setiHead] Parameter \"i\" %d is bigger than head length.", i);
return false;
}
head[i] = data;
return true;
}
bool UDPData::setBody(char *body, int len)
{
if (body == NULL)
{
printf("ERROR [UDPData:setBody] Parameter \"body\" is null.");
return false;
}
if (0 != len)
this->bodyLength = len;
if(NULL == this->body)
this->body = new char[this->bodyLength];
memcpy(this->body, body, this->bodyLength);
return true;
}
bool UDPData::setiBody(int i, char data)
{
if (this->body == NULL)
{
printf("ERROR [UDPData:setiBody] \"body\" is null.");
return false;
}
if (i >= getBodyLength())
{
printf("ERROR [UDPData:setiBody] Parameter \"i\" %d is bigger than body length.", i);
return false;
}
body[i] = data;
return true;
}
bool UDPData::getData(char *data)
{
if (NULL == data || NULL == this->head || NULL == this->body)
return false;
char *src = data;
memset(src, 0x00, getLength());
memcpy(src, this->head, getHeadLength());
memcpy(src + getHeadLength(), this->body, getBodyLength());
return true;
}
<file_sep>#pragma once
#define BUFDIM 200
#define _DLLExport __declspec (dllexport)
// =================== export below funcions to Unity 3D =================== //
extern "C" _DLLExport unsigned int* BridgeGetLedBuffer();
extern "C" _DLLExport void BridgeSend();
extern "C" _DLLExport void BridgeHandshake();
extern "C" _DLLExport void BridgeConstruct(
int _floorCounter, int _roundsCounter, float _step,
float _distance, float _height, float _pillar, int _len);
extern "C" _DLLExport void BridgeDeConstruct();<file_sep>/*************************************************
作者:李芃 陈纬
时间:2016-03-30
内容:实验室LED灯柱尺寸.xlsx报表的实现。
得到每一个port口上实际使用的灯数
**************************************************/
#ifndef CYLINDERCONF_H
#define CYLINDERCONF_H
#include <cmath>
#include <map>
using std::map;
using std::pair;
const double PI = 3.14159;
class CylinderConf
{
public:
CylinderConf();
CylinderConf(int m_turnNum, int m_rStep, int m_bConsloeType,
int m_verNum, int m_horDistance, int m_verDistance);
~CylinderConf();
void setTurnNum(int m_turnNum);
void setRStep(int m_rStep);
void setBConsloeType(int m_bConsloeType);
void setVerNum(int m_verNum);
void setHorDistance(int m_horDistance);
void setVerDistance(int m_verDistance);
map<int, int> getEachPortLEDNum(); //获得每一个port口上实际使用的灯数
private:
int turnNum; //环幕数(圈数)
int rStep; //半径步长
int bConsloeType; //分控类型
int verNum; //垂直点数
int horDistance; //水平像素点理论间距
int verDistance; //垂直间距
double getPerimeter(int circleNum); //周长
int getLightBarNum(int circleNum); //水平取整后实际点数(半圆理论点数*2)
int getTHorDistance(); //实际水平间距(未实现)
int getEachTurnLedNum(int circleNum); //环幕每层点数
int getEachPortLightBar(); //每个port口控制灯条个数
int getEachTurnPortNum(int circleNum); //分控port口个数
};
#endif // CYLINDERCONF_H
<file_sep>#include "SVG.h"
#include "nanosvg.h"
FILE *pConsole;
NSVGimage* g_image = NULL;
float fx0, fy0, fx1, fy1;
int pathnum;
int pointnum;
int colorbuf[MAXPATH];
int pathbuf[MAXPATH];
float pointbuf[MAXPOINT];
int *getColorbuf() { return colorbuf; }
int *getPathbuf() { return pathbuf; }
float *getPointbuf() { return pointbuf; }
long long dlltest()
{
return 0;
}
void construct()
{
AllocConsole();
freopen_s(&pConsole, "CONOUT$", "wb", stdout);
}
void deconstruct()
{
}
static float distPtSeg(float x, float y, float px, float py, float qx, float qy)
{
float pqx, pqy, dx, dy, d, t;
pqx = qx - px;
pqy = qy - py;
dx = x - px;
dy = y - py;
d = pqx*pqx + pqy*pqy;
t = pqx*dx + pqy*dy;
if (d > 0) t /= d;
if (t < 0) t = 0;
else if (t > 1) t = 1;
dx = px + t*pqx - x;
dy = py + t*pqy - y;
return dx*dx + dy*dy;
}
static void cubicBez(float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4,
float tol, int level)
{
float x12, y12, x23, y23, x34, y34, x123, y123, x234, y234, x1234, y1234;
float d;
if (level > 14) return;
x12 = (x1 + x2)*0.5f;
y12 = (y1 + y2)*0.5f;
x23 = (x2 + x3)*0.5f;
y23 = (y2 + y3)*0.5f;
x34 = (x3 + x4)*0.5f;
y34 = (y3 + y4)*0.5f;
x123 = (x12 + x23)*0.5f;
y123 = (y12 + y23)*0.5f;
x234 = (x23 + x34)*0.5f;
y234 = (y23 + y34)*0.5f;
x1234 = (x123 + x234)*0.5f;
y1234 = (y123 + y234)*0.5f;
d = distPtSeg(x1234, y1234, x1, y1, x4, y4);
if (d > tol*tol) {
cubicBez(x1, y1, x12, y12, x123, y123, x1234, y1234, tol, level + 1);
cubicBez(x1234, y1234, x234, y234, x34, y34, x4, y4, tol, level + 1);
}
else {
pointbuf[pointnum * 2] = x4;
pointbuf[pointnum * 2 + 1] = y4;
pointnum++;
pathbuf[pathnum]++;
if (pointnum == 1)
{
fx0 = fx1 = x4;
fy0 = fy1 = y4;
}
else
{
if (x4 > fx0) { fx0 = x4; }
if (x4 < fx1) { fx1 = x4; }
if (y4 > fy0) { fy0 = y4; }
if (y4 < fy1) { fy1 = y4; }
}
}
}
void drawPath(float* pts, int npts, char closed, float tol)
{
int i;
for (i = 0; i < npts - 1; i += 3) {
float* p = &pts[i * 2];
cubicBez(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], tol, 0);
}
//for (i = 0; i < npts; i ++) {
// float* p = &pts[i * 2];
// pointbuf[pointnum * 2] = p[0];
// pointbuf[pointnum * 2 + 1] = p[1];
// pointnum++;
// pathbuf[pathnum]++;
//}
}
int parse(char *name)
{
pathnum = pointnum = 0;
g_image = nsvgParseFromFile(name, "px", 96.0f);
if (g_image == NULL)
{
printf("error while parsing %s\n", name);
return 0;
}
NSVGshape* shape;
NSVGpath* path;
float px = 1.0f;
int shapenum = 0;
for (shape = g_image->shapes; shape != NULL; shape = shape->next) {
shapenum++;
for (path = shape->paths; path != NULL; path = path->next) {
colorbuf[pathnum] = shape->fill.color;
pathbuf[pathnum] = 0;
drawPath(path->pts, path->npts, path->closed, px);
pathnum++;
}
}
int offsetx = -(fx0 + fx1)/2, offsety = -(fy0 + fy1);
for (int i = 0; i < pointnum; i++)
{
pointbuf[2 * i] += offsetx;
pointbuf[2 * i + 1] += offsety;
}
printf("shapenum %d, pathnum %d, pointnum %d\n", shapenum, pathnum, pointnum);
printf("fx0 %f, fy0 %f, fx1 %f, fy1 %f\n", fx0, fy0, fx1, fy1);
nsvgDelete(g_image);
return pathnum;
}<file_sep>#include "framedata.h"
FrameData::FrameData(int x, int y)
{
this->width = x;
this->height = y;
this->lenth = 0;
this->frameID = 0;
this->dataLen = x * y;
this->data = NULL;
}
FrameData::FrameData(int x, int y, int z)
{
this->width = x;
this->height = y;
this->lenth = z;
this->frameID = 0;
this->dataLen = x * y * z;
this->data = NULL;
}
FrameData::FrameData(const FrameData& other)
{
this->width = other.width;
this->height = other.height;
this->lenth = other.lenth;
this->dataLen = other.dataLen;
this->frameID = other.frameID;
this->data = new int[width * height];
memcpy(this->data, other.data, width * height * 4);
}
FrameData::~FrameData()
{
this->width = 0;
this->height = 0;
this->frameID = 0;
this->dataLen = 0;
if (NULL != this->data)
{
delete[] this->data;
this->data = NULL;
}
}
int FrameData::getWidth()
{
return this->width;
}
int FrameData::getHeight()
{
return this->height;
}
int FrameData::getLen()
{
return this->dataLen;
}
int *FrameData::getData()
{
return this->data;
}
int FrameData::getFrameID()
{
return this->frameID;
}
void FrameData::setWidth(int width)
{
this->width = width;
}
void FrameData::setHeight(int height)
{
this->height = height;
}
void FrameData::setFrameID(int frameID)
{
this->frameID = frameID;
}
bool FrameData::setData(int *data, int len)
{
if (data == NULL)
{
printf("ERROR [FrameData:setData] Parameter \"data\" is null.");
return false;
}
if (0 == len) {
this->data = new int[getLen()];
memcpy(this->data, data, getLen() * 4);
}
else {
this->dataLen = len;
this->data = new int[len];
memcpy(this->data, data, len * 4);
}
return true;
}
//ÕÛ·µ
void FrameData::changeType()
{
int* srcIn = this->data;
int* dstOut = new int[width * height];
int count = 0;
bool isOk = true;
for (int i = 0; i < width; i++) {
if (isOk) {
for (int j = height - 1; j >= 0; j--) {
dstOut[count] = srcIn[i*height + j];
count++;
}
}
else {
for (int j = 0; j < height; j++) {
dstOut[count] = srcIn[i*height + j];
count++;
}
}
isOk = !isOk;
}
memcpy(data, dstOut, width * height * sizeof(int));
delete[] dstOut;
}
//ºáÏò±ä×ÝÏò
void FrameData::changeType2()
{
int* dstOut = new int[width * height];
int k = 0;
for (int i = 0; i < width; i++) {
for (int j = height - 1; j >= 0; j--) {
dstOut[k] = data[i + j * width];
k++;
}
}
memcpy(data, dstOut, width * height * sizeof(int));
delete[] dstOut;
}
<file_sep>#include "bridge.h"
#include "senddata.h"
static SendData *sd = NULL;
static unsigned int data[BUFDIM * BUFDIM * BUFDIM];
static int len = 0;
static FILE * pConsole;
unsigned int* BridgeGetLedBuffer()
{
return data;
}
void BridgeSend()
{
sd->setData((int *)data, len);
sd->send();
}
void BridgeHandshake()
{
printf("BridgeHandshake\n");
sd->send37();
}
void BridgeConstruct(
int _floorCounter, int _roundsCounter, float _step,
float _distance, float _height, float _pillar, int _len)
{
printf("BridgeConstruct\n");
AllocConsole();
freopen_s(&pConsole, "CONOUT$", "wb", stdout);
len = _len;
if (sd) BridgeDeConstruct();
sd = new SendData("192.168.1.90", 60000);
sd->setCylinderConf(_roundsCounter, _step*10, 1024, _floorCounter, _distance*10, _height*10);
}
void BridgeDeConstruct()
{
printf("BridgeDeConstruct\n");
if (sd) delete sd;
sd = NULL;
}<file_sep>/*************************************************
作者:陈纬
时间:2016-01-10
内容:存储帧数据
**************************************************/
#ifndef FRAMEDATA_H
#define FRAMEDATA_H
#include <string.h>
#include <stdio.h>
class FrameData
{
public:
FrameData(int x = 0, int y = 0);
FrameData(int x, int y, int z);
FrameData(const FrameData &other);
~FrameData();
void setWidth(int width); //获取帧的宽度
void setHeight(int height); //获取帧的高度
void setFrameID(int frameID);
bool setData(int *data, int len = 0);//设置帧中的数据
int getWidth(); //获取帧的宽度
int getHeight(); //获取帧的高度
int getLen();
int getFrameID(); //获取帧号
int *getData(); //获取帧中的int数组数据
void changeType(); //折返
void changeType2(); //横向变纵向
private:
int width; //帧的宽度,与LED灯阵的宽度对应
int height; //帧的高度,与LED灯阵的高度对应
int lenth; //帧的长度,与LED灯阵的高度对应
int dataLen; //数据长度
int frameID; //帧号
int *data; //帧中的数据
};
#endif // FRAMEDATA_H
<file_sep>
/*
* 作者:陈纬
* 日期:2016-3-31
* 内容:存储数组(解决了浅拷贝问题)
*/
#ifndef SAVEDATE
#define SAVEDATE
#include <cstring>
#include <WS2tcpip.h>
template<class type> class SaveData
{
public:
SaveData();
SaveData(const SaveData& other);
~SaveData();
bool setData(type* data, int len); //存储数据
type* getData(); //获得数据
int getLen(); //获得数据长度
private:
type* m_data; //数组
int m_len; //指针长度
};
template<class type> SaveData<type>::SaveData()
{
m_data = NULL;
m_len = 0;
}
template<class type> SaveData<type>::SaveData(const SaveData& other)
{
m_len = other.m_len;
m_data = new type[m_len];
memcpy(m_data, other.m_data, m_len * sizeof(type));
}
template<class type> SaveData<type>::~SaveData()
{
if (NULL != m_data)
{
delete[] m_data;
this->m_data = NULL;
}
}
//存储数据
template<class type> bool SaveData<type>::setData(type* data, int len)
{
if (len > 0)
{
this->m_len = len;
if (NULL == this->m_data)
this->m_data = new type[len];
memcpy(this->m_data, data, len * sizeof(type));
return true;
}
return false;
}
//获得数据
template<class type> type* SaveData<type>::getData()
{
return m_data;
}
//获得数据长度
template<class type> int SaveData<type>::getLen()
{
return m_len;
}
#endif // SAVEDATE
<file_sep>#include "senddata.h"
#include "config.h"
SendData::SendData()
{
init();
}
SendData::SendData(string ip, int port)
{
this->data = NULL;
this->dataLength = 0;
setNetworkInfo(ip, port);
init();
}
SendData::SendData(string ip, int port, int * data, int dataLength)
{
setNetworkInfo(ip, port);
setData(data, dataLength);
init();
}
void SendData::init()
{
}
SendData::~SendData()
{
if (NULL != this->data)
{
delete this->data;
this->data = NULL;
}
delete[] this->udp;
delete[] this->saveD;
udpCount = 0;
}
bool SendData::setNetworkInfo(string ip, int port)
{
WORD socketVersion = MAKEWORD(2, 2);
WSADATA wsaData;
if (WSAStartup(socketVersion, &wsaData) != 0)
{
return false;
}
this->client = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
this->sin.sin_family = AF_INET;
this->sin.sin_port = htons(port);
//sin.sin_addr.s_addr = inet_pton(AF_INET,ip.c_str(),&sin.sin_addr);
this->sin.sin_addr.s_addr = inet_addr(ip.c_str());
this->len = sizeof(sin);
return true;
}
//实验室LED灯柱尺寸.xlsx报表的实现。得到每一个port口上实际使用的灯数
void SendData::setCylinderConf(int m_turnNum, int m_rStep, int m_bConsloeType, int m_verNum, int m_horDistance, int m_verDistance)
{
CylinderConf* cyConf = new CylinderConf(m_turnNum, m_rStep, m_bConsloeType, m_verNum, m_horDistance, m_verDistance);
result = cyConf->getEachPortLEDNum();
allocateResources();
}
void SendData::allocateResources()
{
this->eachFrameUdpNum = (result.size() + 2) * 2 * 2; //一帧 udp的个数
this->udp = new UDPData[eachFrameUdpNum];
this->saveD = new SaveData<char>[this->eachFrameUdpNum - 8];
}
bool SendData::setData(int *data, int len)
{
//判断输入的数据是否超过标准
if (0 > len)
{
printf("ERROR [SendData:setData] Data length %d is the wrong size.", len);
return false;
}
this->dataLength = len;
if (NULL == this->data)
this->data = new int[len];
memcpy(this->data, data, len * sizeof(int));
return true;
}
void SendData::setData(FrameData* frame)
{
this->frame = frame;
setData(frame->getData(), frame->getLen());
}
void SendData::send37()
{
// char notice[37] = {
// 0x02, 0x88, 0x02, 0x64, 0x05, 0x88, 0x00, 0x00,
// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// 0x00, 0x00, 0x00, 0x00, 0x00 };
char notice[37] = {
0x02, 0x88, 0x02, 0x64, 0x08, 0x88, 0x88, 0x88,
0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00 };
//ws2811
// char notice[37] = {
// 0x02, 0x19, 0x02, 0x64, 0x0c, 0x19, 0x19, 0x19,
// 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// 0x00, 0x00, 0x00, 0x00, 0x00 };
sendto(client, notice, 37, 0, (sockaddr *)&sin, len);
}
void SendData::send()
{
branchPort();
ToUDPDatas();
char* src = new char[UDP_LEN];
for (int i = 0; i < this->eachFrameUdpNum; i++)
{
this->udp[i].getData(src);
sendto(client, src, UDP_LEN, 0, (sockaddr *)&sin, len);
}
delete[] src;
}
unsigned long SendData::udpCount = 0;
void SendData::ToUDPDatas()
{
//vector<SaveData<char>* > dst = branchPort();//获得char 256*n 是否会自动释放
int UDP_HEAD_LEN = 6;
int UDP_BODY_LEN = 768;
char *colorHead = new char[UDP_HEAD_LEN];
char *colorBody = new char[UDP_BODY_LEN];
memset(colorHead, 0x00, UDP_HEAD_LEN);
memset(colorBody, 0x00, UDP_BODY_LEN);
//head 1
colorHead[0] = 0x03;
//head 2~6
unsigned long temp = udpCount++;
for (int i = 2; i < UDP_HEAD_LEN; i++)
{
colorHead[i] = temp % 256;
temp = temp / 256;
}
for (int udpPort = 0; udpPort < this->eachFrameUdpNum; udpPort++)
{
if (udpPort < 8)
{
//1,2-port1;3,4-port2 端口 0,1,2,3(主控的port)
memset(colorBody, 0x00, UDP_BODY_LEN);
}else
{
int dstLen = udpPort - 8;
memcpy(colorBody, this->saveD[dstLen].getData(), UDP_BODY_LEN);
}
this->udp[udpPort].setHead(colorHead, UDP_HEAD_LEN);
this->udp[udpPort].setBody(colorBody, UDP_BODY_LEN);
if (udpPort%2)
colorHead[1] += 0x01;
}
delete[] colorHead;
delete[] colorBody;
}
/*************************
* 分Port
* 1.分解数组为int 1024*n(根据实际使用的情况,补0)
* 2.继续分解int 256*n
* 3.继续分解char 256*n
************************/
void SendData::branchPort()
{
int type = BRANCH_CONSOLE_TYPE; //分控类型
int udpInt = 256; //一个udp包需要的int个数
int len = type / udpInt; //一个1024数组 = len * 256数组
int ledNum = 0; //每一个port的LED实际使用个数
int point = 0; //记录帧数据数组的指针
int portNum = result.size(); //port口使用个数
int* src = new int[type]; //int 1024
int* src2 = new int[udpInt]; //int 256
char* src3 = new char[udpInt * 3];//char 256
int count = 0;
for (int i = 1; i <= portNum; i++)
{
ledNum = result[i];
memset(src, 0x00, type * sizeof(int));
memcpy(src, data + point, ledNum * sizeof(int));
for (int j = 0; j < len; j++)
{
memcpy(src2, src + (j * udpInt), udpInt * sizeof(int));
IntToChars(src2, src3, udpInt);
this->saveD[count++].setData(src3, udpInt * 3);
}
point += ledNum;
}
delete[] src;
delete[] src2;
delete[] src3;
}
//int 转 char
void SendData::IntToChars(int* src, char* dst, int srcLen)
{
for (int i = 0; i < srcLen; i++)
{
int value = src[i];
*(dst + 3 * i + 0) = (value >> 24) & 0x000000ff;//R
*(dst + 3 * i + 1) = (value >> 16) & 0x000000ff;//G
*(dst + 3 * i + 2) = (value >> 8) & 0x000000ff;//B
}
}
<file_sep>#include "cylinderconf.h"
CylinderConf::CylinderConf()
{
turnNum = 0;
rStep = 0;
bConsloeType = 0;
verNum = 0;
horDistance = 0;
verDistance = 0;
/*现在使用的参数
turnNum = 12;
rStep = 200;
bConsloeType = 1024;
verNum = 133;
horDistance = 200;
verDistance = 60;
*/
}
CylinderConf::CylinderConf(int m_turnNum, int m_rStep, int m_bConsloeType, int m_verNum, int m_horDistance, int m_verDistance)/* :
turnNum(m_turnNum),
rStep(m_rStep),
bConsloeType(m_bConsloeType),
verNum(m_verNum),
horDistance(m_horDistance),
verDistance(m_verDistance)*/
{
turnNum = m_turnNum;
rStep = m_rStep;
bConsloeType = m_bConsloeType;
verNum = m_verNum;
horDistance = m_horDistance;
verDistance = m_verDistance;
}
CylinderConf::~CylinderConf()
{
}
void CylinderConf::setTurnNum(int m_turnNum)
{
turnNum = m_turnNum;
}
void CylinderConf::setRStep(int m_rStep)
{
rStep = m_rStep;
}
void CylinderConf::setBConsloeType(int m_bConsloeType)
{
bConsloeType = m_bConsloeType;
}
void CylinderConf::setVerNum(int m_verNum)
{
verNum = m_verNum;
}
void CylinderConf::setHorDistance(int m_horDistance)
{
horDistance = m_horDistance;
}
void CylinderConf::setVerDistance(int m_verDistance)
{
verDistance = m_verDistance;
}
//周长
double CylinderConf::getPerimeter(int circleNum)
{
if (circleNum < turnNum + 1 && circleNum >= 0)
return 2 * PI * (rStep * circleNum);//2*PI*R
else
return -1;
}
//水平取整后实际点数(半圆理论点数*2)
int CylinderConf::getLightBarNum(int circleNum)
{
if (1 == circleNum)
return (int)floor((getPerimeter(circleNum) / 2) / horDistance) * 2;//舍小数点
else
return (int)ceil((getPerimeter(circleNum) / 2) / horDistance) * 2;//进一位
}
//实际水平间距
int CylinderConf::getTHorDistance()
{
return 0;
}
//环幕每层点数
int CylinderConf::getEachTurnLedNum(int circleNum)
{
return verNum * getLightBarNum(circleNum);
}
//每个port口控制灯条个数
int CylinderConf::getEachPortLightBar()
{
return (int)floor((double)bConsloeType / verNum);
}
//分控port口个数
int CylinderConf::getEachTurnPortNum(int circleNum)
{
return (int)ceil((double)getLightBarNum(circleNum) / getEachPortLightBar());
}
//获得每一个port口上实际使用的灯数
map<int, int> CylinderConf::getEachPortLEDNum()
{
int n = 1;
map<int, int> result;
int ledNumByPort = verNum * getEachPortLightBar();//每个port口上Led个数MAX
for (int i = 1; i < turnNum + 1; i++)
{
int portNum = getEachTurnPortNum(i); //每一圈分控port口个数
int ledNum = getEachTurnLedNum(i); //每一圈的Led个数
while (portNum > 0)
{
if (ledNum > ledNumByPort) //判断每一圈的Led个数 是否大于 每个port口上Led个数MAX
{
result.insert(pair<int, int>(n++, ledNumByPort));
ledNum -= ledNumByPort;
}
else
{
result.insert(pair<int, int>(n++, ledNum));
}
portNum--;
}
}
return result;
}
<file_sep>/*************************************************
作者:陈纬
时间:2016-01-10
内容:通过Udp协议发送数据,并进行封包操作
**************************************************/
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#ifndef SENDDATA_H
#define SENDDATA_H
#include <WinSock2.h>
#include <string>
#include <vector>
#include <map>
#include "framedata.h"
#include "savedate.h"
#include "cylinderconf.h"
#include "udpdata.h"
#pragma comment(lib, "ws2_32.lib")
using std::vector;
using std::map;
using std::string;
/*******************************************************
*
*
* 默认生成的UDPData的头长度为6,数据长度为768
******************************************************/
class SendData
{
public:
SendData();
SendData(string ip, int port);
SendData(string ip, int port, int *data, int dataLength);
~SendData();
//实验室LED灯柱尺寸.xlsx报表的实现。得到每一个port口上实际使用的灯数
void setCylinderConf(int m_turnNum, int m_rStep, int m_bConsloeType, int m_verNum, int m_horDistance, int m_verDistance);
void allocateResources();//分配资源
bool setData(int *data, int len = 0); //设置要发送的数据
void setData(FrameData* frame);
bool setNetworkInfo(string ip, int port);
void send37(); //发送UDP数据
void send(); //发送UDP数据
protected:
static unsigned long udpCount; //udp包总个数/2
private:
SOCKET client = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
sockaddr_in sin;
int len;
int *data; //要发送的数据
int dataLength; //要发送的数据长度
FrameData* frame; //一帧数据(2D or 3D)
map<int, int> result; //存储每个port led灯实际使用个数
int eachFrameUdpNum; //一帧 udp的个数
UDPData* udp;
SaveData<char>* saveD;
void branchPort(); //分Port
void ToUDPDatas(); //装为udp标准发送格式
void IntToChars(int* src, char* dst, int srcLen);//int 转 char
void init();
};
#endif // SENDDATA_H
<file_sep>#include <windows.h>
#include <mmsystem.h>
#include <emmintrin.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include <math.h>
#define _DLLExport __declspec (dllexport)
#define MAXPATH 1<<10
#define MAXPOINT 1<<16
#define NANOSVG_IMPLEMENTATION
typedef void(__stdcall *CPPCallback)(int tick);
extern "C" _DLLExport long long dlltest();
extern "C" _DLLExport void construct();
extern "C" _DLLExport void deconstruct();
extern "C" _DLLExport int parse(char *);
extern "C" _DLLExport int *getColorbuf();
extern "C" _DLLExport int *getPathbuf();
extern "C" _DLLExport float *getPointbuf();
<file_sep>/*************************************************
作者:陈纬
时间:2016-01-10
内容:存储UDP数据包数据
**************************************************/
#ifndef UDPDATA_H
#define UDPDATA_H
#include <string.h>
#include <stdio.h>
class UDPData
{
public:
UDPData(int headLen = 0, int bodyLen = 0);
UDPData(const UDPData& other);
~UDPData();
int getHeadLength(); //获取head的长度
int getBodyLength(); //获取body的长度
int getLength(); //获取UDPData总长度
bool setHead(char *head = NULL, int len = 0); //设置head中的内容
bool setiHead(int i, char data); //设置head中第i位数据
bool setBody(char *body = NULL, int len = 0); //设置body中的内容
bool setiBody(int i, char data); //设置body中第i位数据
bool getData(char * data); //获取UDPData中的数据
private:
char *head; //UDP数据中的头
char *body; //UDP数据中的负载
int headLength; //head长度
int bodyLength; //body长度
};
#endif // UDPDATA_H
| e90c2f6f950c478559fafe84f9f188c311738386 | [
"C",
"C++"
] | 13 | C++ | yqf3139/ledmatrix-unity-plugins-native | 41a88dc21dbe04249c37543f039f6d3674a81d90 | 80ce76a6a951d68a2411733755da78cc095a978f |
refs/heads/master | <file_sep>import React from "react";
import {
Card,
CardHeader,
CardBody,
CardFooter,
CardTitle,
Row,
Col,
UncontrolledDropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
Table
} from "reactstrap";
// react plugin used to create charts
import { Line, Bar } from "react-chartjs-2";
// function that returns a color based on an interval of numbers
import { PanelHeader, Stats, CardCategory, Tasks } from "components";
import {
dashboardPanelChart,
dashboardMonthlyUsers,
dashboardAllTraffic,
dashboardMonthlySales
} from "variables/charts.jsx";
import { tasks } from "variables/general.jsx";
class Dashboard extends React.Component {
render() {
return (
<div>
<PanelHeader
size="lg"
content={
<Line
data={dashboardPanelChart.data}
options={dashboardPanelChart.options}
/>
}
/>
<div className="content">
<Row>
<Col xs={12} md={4}>
<Card className="card-chart">
<CardHeader>
<CardCategory>Users</CardCategory>
<CardTitle tag="h4">Monthly Users</CardTitle>
<UncontrolledDropdown>
<DropdownToggle
className="btn-round btn-simple btn-icon"
color="default"
>
<i className="ground-ui-icons loader_gear" />
</DropdownToggle>
<DropdownMenu right>
<DropdownItem>Action</DropdownItem>
<DropdownItem>Another Action</DropdownItem>
<DropdownItem>Something else here</DropdownItem>
<DropdownItem className="text-danger">
Remove data
</DropdownItem>
</DropdownMenu>
</UncontrolledDropdown>
</CardHeader>
<CardBody>
<div className="chart-area">
<Line
data={dashboardMonthlyUsers.data}
options={dashboardMonthlyUsers.options}
/>
</div>
</CardBody>
<CardFooter>
<Stats>
{[
{
i: "ground-ui-icons arrows-1_refresh-69",
t: "Just Updated"
}
]}
</Stats>
</CardFooter>
</Card>
</Col>
<Col xs={12} md={4}>
<Card className="card-chart">
<CardHeader>
<CardCategory>2018 Traffic</CardCategory>
<CardTitle tag="h4">All Traffic</CardTitle>
<UncontrolledDropdown>
<DropdownToggle
className="btn-round btn-simple btn-icon"
color="default"
>
<i className="ground-ui-icons loader_gear" />
</DropdownToggle>
<DropdownMenu right>
<DropdownItem>Action</DropdownItem>
<DropdownItem>Another Action</DropdownItem>
<DropdownItem>Something else here</DropdownItem>
<DropdownItem className="text-danger">
Remove data
</DropdownItem>
</DropdownMenu>
</UncontrolledDropdown>
</CardHeader>
<CardBody>
<div className="chart-area">
<Line
data={dashboardAllTraffic.data}
options={dashboardAllTraffic.options}
/>
</div>
</CardBody>
<CardFooter>
<Stats>
{[
{
i: "rt-ui-icons arrows-1_refresh-69",
t: "Just Updated"
}
]}
</Stats>
</CardFooter>
</Card>
</Col>
<Col xs={12} md={4}>
<Card className="card-chart">
<CardHeader>
<CardCategory>Monthly Sales</CardCategory>
<CardTitle tag="h4">Sales</CardTitle>
</CardHeader>
<CardBody>
<div className="chart-area">
<Bar
data={dashboardMonthlySales.data}
options={dashboardMonthlySales.options}
/>
</div>
</CardBody>
<CardFooter>
<Stats>
{[{ i: "rt-ui-icons ui-2_time-alarm", t: "Last 7 days" }]}
</Stats>
</CardFooter>
</Card>
</Col>
</Row>
<Row>
<Col xs={12} md={6}>
<Card className="card-tasks">
<CardHeader>
<CardCategory>To Do List</CardCategory>
<CardTitle tag="h4">Today</CardTitle>
</CardHeader>
<CardBody>
<Tasks tasks={tasks} />
</CardBody>
<CardFooter>
<hr />
<Stats>
{[
{
i: "rt-ui-icons loader_refresh spin",
t: "Updated 5 minutes ago"
}
]}
</Stats>
</CardFooter>
</Card>
</Col>
<Col xs={12} md={6}>
<Card>
<CardHeader>
<CardCategory>Countries</CardCategory>
<CardTitle tag="h4">Visitor Stats</CardTitle>
</CardHeader>
<CardBody>
<Table className="table-hover" responsive>
<thead className="text-primary">
<tr>
<th>Country</th>
<th>% of Visitors</th>
<th>Bounce Rate</th>
<th className="text-right">Page View</th>
</tr>
</thead>
<tbody>
<tr>
<td>Australia</td>
<td>6.03% </td>
<td>17.67%</td>
<td className="text-right">67.05</td>
</tr>
<tr>
<td>Canada</td>
<td>13% </td>
<td>23.12% </td>
<td className="text-right">65.00</td>
</tr>
<tr>
<td>United Kingdom</td>
<td>10%</td>
<td>20.43%</td>
<td className="text-right">67.99</td>
</tr>
<tr>
<td>United States</td>
<td>61% </td>
<td>25.87% </td>
<td className="text-right">55.23</td>
</tr>
</tbody>
</Table>
</CardBody>
</Card>
</Col>
</Row>
</div>
</div>
);
}
}
export default Dashboard;
<file_sep># groundctrl-ui
First generation of GroundCTRL UI
<file_sep>import React, { Component } from "react";
import {
Table,
Row,
Col,
Card,
CardBody,
CardHeader,
CardTitle
} from "reactstrap";
import { Button, PanelHeader } from "components";
class TemplatePages extends Component {
render() {
return (
<div>
<PanelHeader size="sm" />
<div className="content">
<Row>
<Col>
<Card>
<CardHeader>
<h3 className="title">Page Title</h3>
<p className="category">
<h4>How up is space? </h4>
</p>
</CardHeader>
<CardBody>
<h4>Don't be a pleb!</h4>
<p>Ray, look at you tucked up in bed, you little bloody Ray! Michael's a douche pot! CHA CHA CHA CHA! Ray, look at you tucked up in bed, you little bloody Ray! OOOOOOOOOOOOOOHHHHHHHHH EHHHHHHHH!!!! Screw you Michael, you pissy little piss pot!</p>
<Table responsive>
<thead>
<tr>
<th />
<th className="text-center">Free</th>
<th className="text-center">Free Free</th>
</tr>
</thead>
<tbody>
<tr>
<td>The sky is bigger than the ground.</td>
<td className="text-center">16</td>
<td className="text-center">160</td>
</tr>
<tr>
<td>The sky is bigger than the ground.</td>
<td className="text-center">5</td>
<td className="text-center">13</td>
</tr>
<tr>
<td>The sky is bigger than the ground.</td>
<td className="text-center">7</td>
<td className="text-center">27</td>
</tr>
<tr>
<td>The sky is bigger than the ground.</td>
<td className="text-center">
<i className="fa fa-check text-success" />
</td>
<td className="text-center">
<i className="fa fa-check text-success" />
</td>
</tr>
<tr>
<td>The sky is bigger than the ground.</td>
<td className="text-center">
<i className="fa fa-check text-success" />
</td>
<td className="text-center">
<i className="fa fa-check text-success" />
</td>
</tr>
<tr>
<td>The sky is bigger than the ground.</td>
<td className="text-center">
<i className="fa fa-times text-danger" />
</td>
<td className="text-center">
<i className="fa fa-check text-success" />
</td>
</tr>
<tr>
<td>The sky is bigger than the ground.</td>
<td className="text-center">
<i className="fa fa-times text-danger" />
</td>
<td className="text-center">
<i className="fa fa-check text-success" />
</td>
</tr>
<tr>
<td />
<td className="text-center">Free</td>
<td className="text-center">Free Free</td>
</tr>
<tr>
<td />
<td className="text-center">
<Button
href="#"
round
fill
disabled
bsStyle="default"
>
Incorrect Version
</Button>
</td>
</tr>
</tbody>
</Table>
</CardBody>
</Card>
</Col>
</Row>
</div>
</div>
);
}
}
export default TemplatePages;<file_sep>import React from "react";
import { Row, Col, Card, CardHeader, CardBody } from "reactstrap";
// react plugin used to create mapbox maps urbica/react-map-gl - github
import MapGL from '@urbica/react-map-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import { PanelHeader } from "components";
const InteractMapBox = {
viewport: {
latitude: -25.047944,
longitude: 134.003347,
zoom: 3
}
};
class FullScreenMap extends React.Component {
render() {
return (
<div>
<PanelHeader size="sm" />
<div className="content">
<Row>
<Col xs={12}>
<Card>
<CardHeader>
<h3 className="title">Maps by Mapbox</h3>
</CardHeader>
<CardBody>
<div id="map" className="map" >
<MapGL
style={{ width: '100%', height: '100%' }}
mapStyle='mapbox://styles/mapbox/streets-v11'
accessToken={'<KEY>'}
latitude={InteractMapBox.viewport.latitude}
longitude={InteractMapBox.viewport.longitude}
zoom={InteractMapBox.viewport.zoom}
onViewportChange={InteractMapBox.viewport}
/>
</div>
</CardBody>
</Card>
</Col>
</Row>
</div>
</div>
);
}
}
export default FullScreenMap;
| 01906fab36be92ec8d8159286295d7d99c43e39b | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | tim-green/groundctrl-ui | 6c1da7daa5839689a97de85e0dca14e73d3d24f1 | 6d0ca4c51dd8722156b27b56fb3fa98c44db747a |
refs/heads/master | <file_sep>package com.banana.textgame;
import java.util.Scanner;
public class Main {
/*
* Главный метод.
* АБДЯЯЯЯЯЯЯдяяяяяlhhhjl
*/
public static void main(String[] args) {
// вызывает метод start()
new Main().start();
}
/*
* Метод с логикой игры.
*/
private void start() {
onStart();
for (int e = 1; e <= 31; e = e + 2) {
onFinish(e);
}
}
/*
* Метод вызывается один раз при старте игры.
*/
void onStart() {
Scanner па = new Scanner(System.in);
System.out.println("Ты кто такой?");
String ответ = па.nextLine();
System.out.println("ПОШЕЛ ВОН!ВИДЕТЬ ТЕБЯ НЕ ХОЧУ!ЗАКРОЙ ЭТО ОКНО,БЫСТРО!" + ответ);
}
int индус = 0;
/*
* Метод вызывается каждый игровый день.ЖЗШ
* Единственный параметр: dayNumber - номер текущеvго игрового дня.
*/
/* void onNewDay(int dayNumber) {
System.out.println("День номер" + dayNumber + "");
Scanner па = new Scanner(System.in);
System.out.println("Ваше действие");
String action = па.nextLine();
if (action.equals("кофе")) {
if (Math.random() > 0.5) {
индус -= 2;
System.out.println("Минус деньги, которые я мог потратить на еду");
} else {
System.out.println("Еще раз, я купил это дешевое кофе");
}
} else if (action.equals("код")) {
System.out.println("Ваш код на сегодня");
String код = па.nextLine();
индус = индус + код.length();
System.out.println("Бабло Индуса:" + dayNumber + "$.");
} else {
System.out.println("Че это такое?");
}
/*
boolean startsWithSpaces = код.startsWith(" ");
boolean endsWithSpaces = код.endsWith(" ");
boolean result = startsWithSpaces && endsWithSpaces;
System.out.println("Халявщик: " + result);
}
/* void onStartP(int dayNumber2) {
System.out.println("День номер" + dayNumber2 + "");
Scanner па = new Scanner(System.in);
System.out.println("Ваше действие");
String action = па.nextLine();
switch (action) {
case "код":
System.out.println("Ваш код на сегодня");
String код = па.nextLine();
индус = индус + код.length();
System.out.println("Бабло Индуса:" + dayNumber2 + "$.");
break;
case "кофе":
индус -= 2;
System.out.println("Минус деньги, которые я мог потратить на еду");
break;
default:
System.out.println("Че это такое?");
}
}
*/
/*
* Метод вызывается по завершению игры.
*/
void onFinish(int dayNumber2) {
System.out.println("День номер" + dayNumber2 + "");
String dollarString = "";
for (int i = 0; i < индус ; i += 1) {
dollarString = dollarString + "$";
}
System.out.println("Вашм бабосики: " + dollarString + ".");
Scanner па = new Scanner(System.in);
System.out.println("Ваше действие");
String action = па.nextLine();
switch (action) {
case "код":
System.out.println("Ваш код на сегодня");
String код = па.nextLine();
индус = индус + код.length();
System.out.println("<NAME>:" + индус + "$.");
break;
case "кофе":
if (Math.random() > 0.5) {
индус -= 2;
System.out.println("Минус деньги, которые я мог потратить на еду");
} else {
System.out.println("Еще раз, я купил это дешевое кофе");
}
break;
default:
System.out.println("Че это такое?");
}
}
}
| dc6756e2cae41fe9721e1511b4c5b3f5033dee18 | [
"Java"
] | 1 | Java | Endem1k/text-game | 8427d14a51c14980144437baf4d136fb6fee677e | 57ab329c3bc46eb99a5e1dcc09c171a55a28e2d1 |
refs/heads/master | <repo_name>andrew1989liu/blog<file_sep>/blog/routes/index.js
var express = require('express');
var router = express.Router();
var crypto = require('crypto');
var mongoose = require('mongoose');
var User = mongoose.model('User');
/* GET home page. */
// router.get('/', function(req, res, next) {
// res.render('index', { title: 'Express' });
// });
router.get('/',function(req,res){
res.render('index',{title: 'home'});
});
router.get('/reg',function(req,res){
res.render('reg',{title: 'register'});
});
router.post('/reg',function(req,res){
var password = req.body.password;
var passwordtwo = req.body.passwordtwo;
if ( password != passwordtwo){
req.flash('error', 'password and confirmed password not match!');
console.log(req.session.flash);
res.redirect('/reg');
}
var md5 = crypto.createHash('md5');
var password = md5.update(req.body.password).digest('hex');
User.findOne({name: req.body.name},function(err,user){
if (err){
req.flash('reg_check_error',err);
return res.redirect('/');
}
if (user) {
req.flash('reg_check_duplicate','User Exists! Please choose another ');
return res.redirect('/reg');
}
});
new User({
name: req.body.name,
password: <PASSWORD>,
email: req.body.email
}).save(function(err, user){
if (err){
req.flash('reg_error',err);
res.redirect('/');
}
req.session.user = user;
req.flash('reg_success','Register success');
res.redirect('/');
});
});
router.get('/login',function(req,res){
res.render('login',{title: 'login'});
});
router.post('/login',function(req,res){
});
router.get('/post',function(req,res){
res.render('post',{title: 'login'});
});
router.post('/post',function(req,res){
});
router.get('/logout',function(req,res){
});
module.exports = router;
| 1c476e5838722a12026495d7c1a4f524193a1a91 | [
"JavaScript"
] | 1 | JavaScript | andrew1989liu/blog | d4efeeead1d53e5405da5b14d412969e64eed2bb | 2ec15ae5bcd18df9464bf98a08b79fb6b1d507db |
refs/heads/master | <repo_name>sook19/PommodoroParrot<file_sep>/app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
def index
@timer = Timer.new
@survey = Survey.new
end
end
<file_sep>/app/models/timer.rb
class Timer < ActiveRecord::Base
belongs_to :survey
before_validation :set_loops_completed
def set_loops_completed
return if status == "Done"
if new_record?
self.loops_completed = 0
else
self.loops_completed +=1
end
if loops_completed < (survey.loops*2)
set_status
else
self.status = "Done"
end
end
def set_status
if status.blank?
self.status = "Working"
elsif status == "Working"
self.status = "Rest"
elsif status == "Rest"
self.status = "Working"
end
end
end
<file_sep>/db/migrate/20150718125828_add_name_to_surveys.rb
class AddNameToSurveys < ActiveRecord::Migration
def change
add_column :surveys, :name, :string
add_column :surveys, :gender, :string
add_column :surveys, :loops, :integer
end
end
<file_sep>/app/views/timers/index.json.jbuilder
json.array!(@timers) do |timer|
json.extract! timer, :id, :survey_id, :loops_completed
json.url timer_url(timer, format: :json)
end
<file_sep>/app/views/timers/show.json.jbuilder
json.extract! @timer, :id, :survey_id, :loops_completed, :created_at, :updated_at
<file_sep>/app/models/survey.rb
class Survey < ActiveRecord::Base
has_one :timer
after_create :create_timer
def create_timer
Timer.create(survey: self)
end
end
| 4603451b4877a858536045689061956723a497d9 | [
"Ruby"
] | 6 | Ruby | sook19/PommodoroParrot | 419c40ffca256cc69397388aa1e27fbd3d065d4b | 73aecd5f897ff463ccb4cfd13cc15fe2587e8e7e |
refs/heads/master | <repo_name>LJ-GH/ljdatepicker<file_sep>/readme.md
# 日期选择控件
- 可以选择本月,上个月,上三个月,上半年,上一年以及其他日期
## 使用方法
复制aar文件到app/libs文件夹中
在App的build.gradle
```
android{
...
repositories{
flatDir{
dirs 'libs'
}
}
...
}
...
dependencies{
...
compile (name:'ljdatepicker',ext:'aar')
...
}
```
添加监听
```java
SelectorOfRangeTime mSelectOfTime = (SelectorOfRangeTime) findViewById(R.id.select_of_time);
mSelectOfTime.setOnSelectConfirmListener(new SelectorOfRangeTime.OnSelectConfirmListener() {
@Override
public void call(String startTime, String endTime) {
final String ss = startTime + "~-----~" + endTime;
Toast.makeText(context, ss, Toast.LENGTH_SHORT).show();
}
});
```
<file_sep>/src/main/java/com/lj/ljdatepicker/SelectorOfRangeTime.java
package com.lj.ljdatepicker;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.lj.ljdatepicker.widget.DatePickDialog;
import com.lj.ljdatepicker.widget.OnSureLisener;
import com.lj.ljdatepicker.widget.bean.DateType;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by linjie on 2017/11/28.
*/
public class SelectorOfRangeTime extends LinearLayout implements View.OnClickListener {
private Context context;
private View conentView;
private View popupView;
private PopupWindow popupWindow;
private LinearLayout mTimeContainView;
private TextView mTvShowSelectTime;
private ImageView mButtonOpenTimeSelector;
private TextView mTvBtnCurrentMonth;
private TextView mTvBtnLastMonth;
private TextView mTvBtnLast3Month;
private TextView mTvBtnLast6Month;
private TextView mTvBtnLastYear;
private TextView mTvShowStartTime;
private LinearLayout mLlBtnStartTime;
private TextView mTvShowEndTime;
private LinearLayout mLlBtnEndTime;
private LinearLayout mLlBtnCancel;
private LinearLayout mLlBtnConfirm;
//日期变量
private Calendar calendar;
private String startTime; //yyyy-MM-dd
private String endTime; //yyyy-MM-dd
private String returnStartTime; //yyyy-MM-dd
private String returnEndTime; //yyyy-MM-dd
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//滚动 日期选择器
private DatePickDialog startTimeDatePickDialog;
private DatePickDialog endTimeDatePickDialog;
private OnSelectConfirmListener onSelectConfirmListener;
public interface OnSelectConfirmListener {
void call(String startTime, String endTime);
}
public void setOnSelectConfirmListener(OnSelectConfirmListener onSelectConfirmListener) {
this.onSelectConfirmListener = onSelectConfirmListener;
}
public SelectorOfRangeTime(Context context) {
this(context, null);
}
public SelectorOfRangeTime(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SelectorOfRangeTime(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
this.context = context;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
conentView = inflater.inflate(R.layout.selector_of_time, this);
mTimeContainView = (LinearLayout)conentView.findViewById(R.id.time_contain_view);
this.mTvShowSelectTime = (TextView) conentView.findViewById(R.id.tv_show_select_time);
this.mButtonOpenTimeSelector = (ImageView) conentView.findViewById(R.id.button_open_time_selector);
mButtonOpenTimeSelector.setOnClickListener(this);
popupView = inflater.inflate(R.layout.selector_of_time_popup, null);
this.mTvBtnCurrentMonth = (TextView) popupView.findViewById(R.id.tv_btn_current_month);
this.mTvBtnLastMonth = (TextView) popupView.findViewById(R.id.tv_btn_last_month);
this.mTvBtnLast3Month = (TextView) popupView.findViewById(R.id.tv_btn_last3_month);
this.mTvBtnLast6Month = (TextView) popupView.findViewById(R.id.tv_btn_last6_month);
this.mTvBtnLastYear = (TextView) popupView.findViewById(R.id.tv_btn_last_year);
this.mTvShowStartTime = (TextView) popupView.findViewById(R.id.tv_show_start_time);
this.mLlBtnStartTime = (LinearLayout) popupView.findViewById(R.id.ll_btn_start_time);
this.mTvShowEndTime = (TextView) popupView.findViewById(R.id.tv_show_end_time);
this.mLlBtnEndTime = (LinearLayout) popupView.findViewById(R.id.ll_btn_end_time);
this.mLlBtnCancel = (LinearLayout) popupView.findViewById(R.id.ll_btn_cancel);
this.mLlBtnConfirm = (LinearLayout) popupView.findViewById(R.id.ll_btn_confirm);
mTvBtnCurrentMonth.setOnClickListener(this);
mTvBtnLastMonth.setOnClickListener(this);
mTvBtnLast3Month.setOnClickListener(this);
mTvBtnLast6Month.setOnClickListener(this);
mTvBtnLastYear.setOnClickListener(this);
mLlBtnStartTime.setOnClickListener(this);
mLlBtnEndTime.setOnClickListener(this);
mLlBtnCancel.setOnClickListener(this);
mLlBtnConfirm.setOnClickListener(this);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SelectorOfRangeTime);
int backgroundColor = typedArray.getColor(R.styleable.SelectorOfRangeTime_background_color, Color.WHITE);
mTimeContainView.setBackgroundColor(backgroundColor);
int dateTextColor = typedArray.getColor(R.styleable.SelectorOfRangeTime_date_range_text_color, getResources().getColor(R.color.font_color_default));
int dateTextSize = typedArray.getDimensionPixelSize(R.styleable.SelectorOfRangeTime_date_range_text_size, 16);
mTvShowSelectTime.setTextColor(dateTextColor);
mTvShowSelectTime.setTextSize(dateTextSize);
int dateLogoColor = typedArray.getColor(R.styleable.SelectorOfRangeTime_date_logo_color, getResources().getColor(R.color.font_color_default));
final int defaultDateLogoWidth = (int)(getResources().getDisplayMetrics().density*30+0.5f);
final int defaultDateLogoHeight = (int)(getResources().getDisplayMetrics().density*25+0.5f);
int dateLogoWidth = typedArray.getDimensionPixelSize(R.styleable.SelectorOfRangeTime_date_logo_width, defaultDateLogoWidth);
int dateLogoHeight = typedArray.getDimensionPixelSize(R.styleable.SelectorOfRangeTime_date_logo_height, defaultDateLogoHeight);
mButtonOpenTimeSelector.setColorFilter(dateLogoColor);
ViewGroup.LayoutParams layoutParams = mButtonOpenTimeSelector.getLayoutParams();
layoutParams.width = dateLogoWidth;
layoutParams.height = dateLogoHeight;
mButtonOpenTimeSelector.setLayoutParams(layoutParams);
popupWindow = new PopupWindow(popupView, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
popupWindow.setTouchable(true);
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
//设置返回时间的初始值 本月初到现在
calendar = Calendar.getInstance();
returnEndTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
calendar.add(Calendar.MONTH, -1);
returnStartTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
}
public void showPopupWindow(View parent) {
if (!popupWindow.isShowing()) {
popupWindow.showAsDropDown(parent, 0, 0);
} else {
popupWindow.dismiss();
}
}
private void changeTabColor(TextView textView){
mTvBtnCurrentMonth.setTextColor(getResources().getColor(R.color.font_color_default));
mTvBtnLastMonth.setTextColor(getResources().getColor(R.color.font_color_default));
mTvBtnLast3Month.setTextColor(getResources().getColor(R.color.font_color_default));
mTvBtnLast6Month.setTextColor(getResources().getColor(R.color.font_color_default));
mTvBtnLastYear.setTextColor(getResources().getColor(R.color.font_color_default));
textView.setTextColor(getResources().getColor(R.color.default_color));
}
@Override
public void onClick(View view) {
int i = view.getId();
if (i == R.id.button_open_time_selector) {
this.showPopupWindow(view);
} else if (i == R.id.tv_btn_current_month) {
calendar = Calendar.getInstance();
endTime = sdf.format(calendar.getTime());
calendar.set(Calendar.DATE, 1);
startTime = sdf.format(calendar.getTime());
mTvShowStartTime.setText(startTime);
mTvShowEndTime.setText(endTime);
changeTabColor(mTvBtnCurrentMonth);
} else if (i == R.id.tv_btn_last_month) {
calendar = Calendar.getInstance();
endTime = sdf.format(calendar.getTime());
calendar.add(Calendar.MONTH, -1);
startTime = sdf.format(calendar.getTime());
mTvShowStartTime.setText(startTime);
mTvShowEndTime.setText(endTime);
changeTabColor(mTvBtnLastMonth);
} else if (i == R.id.tv_btn_last3_month) {
calendar = Calendar.getInstance();
endTime = sdf.format(calendar.getTime());
calendar.add(Calendar.MONTH, -3);
startTime = sdf.format(calendar.getTime());
mTvShowStartTime.setText(startTime);
mTvShowEndTime.setText(endTime);
changeTabColor(mTvBtnLast3Month);
} else if (i == R.id.tv_btn_last6_month) {
calendar = Calendar.getInstance();
endTime = sdf.format(calendar.getTime());
calendar.add(Calendar.MONTH, -6);
startTime = sdf.format(calendar.getTime());
mTvShowStartTime.setText(startTime);
mTvShowEndTime.setText(endTime);
changeTabColor(mTvBtnLast6Month);
} else if (i == R.id.tv_btn_last_year) {
calendar = Calendar.getInstance();
endTime = sdf.format(calendar.getTime());
calendar.add(Calendar.MONTH, -12);
startTime = sdf.format(calendar.getTime());
mTvShowStartTime.setText(startTime);
mTvShowEndTime.setText(endTime);
changeTabColor(mTvBtnLastYear);
} else if (i == R.id.ll_btn_start_time) {
startTimeDatePickDialog = new DatePickDialog(context);
//设置上下年分限制
// dialog.setYearLimt(1);
//设置标题
startTimeDatePickDialog.setTitle("选择开始时间");
//设置类型
startTimeDatePickDialog.setType(DateType.TYPE_YMD);
//设置消息体的显示格式,日期格式
startTimeDatePickDialog.setMessageFormat("yyyy-MM-dd");
//设置选择回调
startTimeDatePickDialog.setOnChangeLisener(null);
//设置点击确定按钮回调
startTimeDatePickDialog.setOnSureLisener(new OnSureLisener() {
@Override
public void onSure(Date date) {
String result = new SimpleDateFormat("yyyy-MM-dd").format(date);
startTime = result;
mTvShowStartTime.setText(result);
}
});
//设置弹出的选择时间是当前选择的时间
if(startTime!=null){
try {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(startTime);
startTimeDatePickDialog.setStartDate(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
startTimeDatePickDialog.show();
} else if (i == R.id.ll_btn_end_time) {
endTimeDatePickDialog = new DatePickDialog(context);
//设置上下年分限制
endTimeDatePickDialog.setYearLimt(5);
//设置标题
endTimeDatePickDialog.setTitle("选择结束时间");
//设置类型
endTimeDatePickDialog.setType(DateType.TYPE_YMD);
//设置消息体的显示格式,日期格式
endTimeDatePickDialog.setMessageFormat("yyyy-MM-dd");
//设置选择回调
endTimeDatePickDialog.setOnChangeLisener(null);
//设置点击确定按钮回调
endTimeDatePickDialog.setOnSureLisener(null);
endTimeDatePickDialog.setOnSureLisener(new OnSureLisener() {
@Override
public void onSure(Date date) {
String result = new SimpleDateFormat("yyyy-MM-dd").format(date);
endTime = result;
mTvShowEndTime.setText(result);
}
});
if(endTime!=null){
try {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
endTimeDatePickDialog.setStartDate(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
endTimeDatePickDialog.show();
} else if (i == R.id.ll_btn_cancel) {
popupWindow.dismiss();
} else if (i == R.id.ll_btn_confirm) {
if (startTime == null || endTime == null) {//没有任何选择操作
Toast.makeText(context.getApplicationContext(), "请选择时间", Toast.LENGTH_SHORT).show();
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
long now = new Date().getTime();
long startDate = sdf.parse(startTime).getTime();
long endDate = sdf.parse(endTime).getTime();
if (startDate > now) {
Toast.makeText(context.getApplicationContext(), "开始时间大于现在时刻", Toast.LENGTH_SHORT).show();
} else if (endDate > now) {
Toast.makeText(context.getApplicationContext(), "结束时间大于现在时刻", Toast.LENGTH_SHORT).show();
} else if (startDate >= endDate) {
Toast.makeText(context.getApplicationContext(), "开始时间大于等于结束时间", Toast.LENGTH_SHORT).show();
} else {
returnStartTime = startTime;
returnEndTime = endTime;
mTvShowSelectTime.setText(startTime + " 至 " + endTime);
popupWindow.dismiss();
if(onSelectConfirmListener !=null){
onSelectConfirmListener.call(returnStartTime, returnEndTime);
}
}
} catch (ParseException e) {
e.printStackTrace();
popupWindow.dismiss();
}
}
}
}
}
<file_sep>/src/main/java/com/lj/ljdatepicker/SelectorOfSingleTime.java
package com.lj.ljdatepicker;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.lj.ljdatepicker.widget.DatePickDialog;
import com.lj.ljdatepicker.widget.OnSureLisener;
import com.lj.ljdatepicker.widget.bean.DateType;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by linjie on 2017/12/5.
*/
public class SelectorOfSingleTime extends LinearLayout implements View.OnClickListener, OnSureLisener {
private Context mContext;
private View view;
private RadioButton mDay;
private RadioButton mMonth;
private RadioButton mYear;
private LinearLayout mBtnSelectTime;
private RadioGroup mRadioGroup;
private DatePickDialog dayPickDialog;
private SimpleDateFormat daySdf;
private DatePickDialog monthPickDialog;
private SimpleDateFormat monthSdf;
private DatePickDialog yearPickDialog;
private SimpleDateFormat yearSdf;
private SimpleDateFormat ymdhmsSdf;
private OnConfirmListener onConfirmListener;
private SimpleDateFormat currentFormat;
private TextView showTime;
private SelectorOfSingleTimeMode currentMode;
private DatePickDialog fullTimePickDialog;
public interface OnConfirmListener {
void onConfirm(Date date, String formatDateStr);
}
public void SetOnConfirmListener(OnConfirmListener onConfirmListener) {
this.onConfirmListener = onConfirmListener;
}
public SelectorOfSingleTime(Context context) {
this(context, null);
}
public SelectorOfSingleTime(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SelectorOfSingleTime(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
initView();
}
private void initView() {
this.view = LayoutInflater.from(mContext).inflate(R.layout.selector_of_daymonthyear, this);
this.mDay = (RadioButton) view.findViewById(R.id.day);
this.mMonth = (RadioButton) view.findViewById(R.id.month);
this.mYear = (RadioButton) view.findViewById(R.id.year);
this.mBtnSelectTime = (LinearLayout) view.findViewById(R.id.btn_select_time);
this.mRadioGroup = (RadioGroup) view.findViewById(R.id.radio_group);
this.showTime = (TextView) view.findViewById(R.id.tv_show_time);
mBtnSelectTime.setOnClickListener(this);
daySdf = new SimpleDateFormat("yyyy-MM-dd");
monthSdf = new SimpleDateFormat("yyyy-MM");
yearSdf = new SimpleDateFormat("yyyy");
ymdhmsSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
showTime.setText(daySdf.format(new Date()));
}
public void setMode(SelectorOfSingleTimeMode mode){
currentMode = mode;
if (mode == SelectorOfSingleTimeMode.MODE_YMD){
mDay.setVisibility(VISIBLE);
mMonth.setVisibility(VISIBLE);
mYear.setVisibility(VISIBLE);
mDay.setChecked(true);
showTime.setText(daySdf.format(new Date()));
}else if(mode == SelectorOfSingleTimeMode.MODE_YM){
mDay.setVisibility(GONE);
mMonth.setVisibility(VISIBLE);
mYear.setVisibility(VISIBLE);
mMonth.setChecked(true);
showTime.setText(monthSdf.format(new Date()));
}else if(mode == SelectorOfSingleTimeMode.MODE_Y){
mDay.setVisibility(GONE);
mMonth.setVisibility(GONE);
mYear.setVisibility(VISIBLE);
mYear.setChecked(true);
showTime.setText(yearSdf.format(new Date()));
}else if(mode == SelectorOfSingleTimeMode.MODE_M){
mDay.setVisibility(GONE);
mMonth.setVisibility(VISIBLE);
mYear.setVisibility(GONE);
mMonth.setChecked(true);
showTime.setText(monthSdf.format(new Date()));
}else if(mode == SelectorOfSingleTimeMode.MODE_D){
mDay.setVisibility(VISIBLE);
mMonth.setVisibility(GONE);
mYear.setVisibility(GONE);
mDay.setChecked(true);
showTime.setText(daySdf.format(new Date()));
}else if(mode == SelectorOfSingleTimeMode.MODE_YMD_HMS){
mDay.setVisibility(INVISIBLE);
mMonth.setVisibility(GONE);
mYear.setVisibility(GONE);
mDay.setChecked(true);
showTime.setText(ymdhmsSdf.format(new Date()));
}
}
@Override
public void onClick(View view) {
int i = view.getId();
if(i == R.id.btn_select_time){
if(currentMode == SelectorOfSingleTimeMode.MODE_YMD_HMS){
if(null == fullTimePickDialog){
fullTimePickDialog = new DatePickDialog(mContext);
fullTimePickDialog.setTitle("请选择日期");
fullTimePickDialog.setType(DateType.TYPE_ALL);
fullTimePickDialog.setCanceledOnTouchOutside(true);
fullTimePickDialog.setOnSureLisener(this);
fullTimePickDialog.show();
}else{
fullTimePickDialog.show();
}
currentFormat = ymdhmsSdf;
return;
}
int id = mRadioGroup.getCheckedRadioButtonId();
if(id == R.id.day){
if(null == dayPickDialog){
dayPickDialog = new DatePickDialog(mContext);
dayPickDialog.setTitle("请选择日期");
dayPickDialog.setType(DateType.TYPE_YMD);
dayPickDialog.setCanceledOnTouchOutside(true);
dayPickDialog.setOnSureLisener(this);
dayPickDialog.show();
}else{
dayPickDialog.show();
}
currentFormat = daySdf;
}else if(id == R.id.month){
if(null == monthPickDialog){
monthPickDialog = new DatePickDialog(mContext);
monthPickDialog.setTitle("请选择月份");
monthPickDialog.setType(DateType.TYPE_YM);
monthPickDialog.setCanceledOnTouchOutside(true);
monthPickDialog.setOnSureLisener(this);
monthPickDialog.show();
}else{
monthPickDialog.show();
}
currentFormat = monthSdf;
}else if(id == R.id.year){
if(null == yearPickDialog){
yearPickDialog = new DatePickDialog(mContext);
yearPickDialog.setTitle("请选择年份");
yearPickDialog.setType(DateType.TYPE_Y);
yearPickDialog.setCanceledOnTouchOutside(true);
yearPickDialog.setOnSureLisener(this);
yearPickDialog.show();
}else{
yearPickDialog.show();
}
currentFormat = yearSdf;
}
}
}
@Override
public void onSure(Date date) {
String s = currentFormat.format(date);
this.showTime.setText(s);
if(onConfirmListener!=null){
this.onConfirmListener.onConfirm(date,s);
}
}
}
| 89aaad3a7e2f54c8ed5278842c9241afb42f4121 | [
"Markdown",
"Java"
] | 3 | Markdown | LJ-GH/ljdatepicker | 8af2cc5d26e973b6d0ac61e16d2421f826df3d3c | a2d3ae2ac4903a5965c2cacc78d5b19be063a966 |
refs/heads/master | <repo_name>benhayesthomas/Tinypico-Radio<file_sep>/src/SimpleEncoder.py
from machine import Pin
class Encoder(object):
def __init__(self, pin_clk, pin_dt ):
self.aflag = 0
self.bflag = 0
self._value = 0
self.encoderA = Pin(pin_clk, mode=Pin.IN, pull=Pin.PULL_UP )
self.encoderB = Pin(pin_dt, mode=Pin.IN, pull=Pin.PULL_UP )
trig = Pin.IRQ_RISING | Pin.IRQ_FALLING
self.encoderA.irq(handler=self.pin_handlerA, trigger=trig )
self.encoderB.irq(handler=self.pin_handlerB, trigger=trig )
def pin_handlerA(self, pin):
if ( self.encoderA.value() is 1 and self.encoderB.value() is 1 and self.aflag is 1 ):
self._value += 1
self.bflag = 0
self.aflag = 0
elif ( self.encoderA.value() is 1 ):
self.bflag = 1
def pin_handlerB(self, pin):
if ( self.encoderA.value() is 1 and self.encoderB.value() is 1 and self.bflag is 1 ):
self._value -= 1
self.bflag = 0
self.aflag = 0
elif ( self.encoderA.value() is 1 ):
self.aflag = 1
@property
def value(self):
return self._value
<file_sep>/src/radiorun.py
import radio
import SimpleEncoder
import machine
from machine import Pin
import lcd_api
import i2c_lcd
import bounce
import time
import si5351
synth = si5351.SI5351( data=Pin(21), clock=Pin(22) )
lcd = i2c_lcd.I2cLcd( data=Pin(21), clock=Pin(22), num_lines=2, num_columns=16 )
button = bounce.Bounce( Pin(15, mode=Pin.IN, pull=Pin.PULL_UP))
enc = SimpleEncoder.Encoder( 26, 27 )
r = radio.Radio( button, enc, lcd, synth, 7010000 )
r.run()
<file_sep>/src/ads1115.py
from machine import Pin
from machine import I2C
import utime
_ADS1115_ADDRESS = const(0x48)
_ADS1015_CONVERSIONDELAY = const(1)
_ADS1115_CONVERSIONDELAY = const(9)
_DEFAULT_GAIN = 'Gain 2'
_ADS1015_GAIN = {
'Gain 2/3': 0x0000,
'Gain 1': 0x0200,
_DEFAULT_GAIN: 0x0400,
'Gain 4': 0x0600,
'Gain 8': 0x0800,
'Gain 16': 0x0A00
}
_ADS1015_REG_CONFIG_OS_MASK = const(0x8000) # OS Mask
_ADS1015_REG_CONFIG_OS_SINGLE = const(0x8000) # Write: Set to start a single-conversion
_ADS1015_REG_CONFIG_OS_BUSY = const(0x0000) # Read: Bit = 0 when conversion is in progress
_ADS1015_REG_CONFIG_OS_NOTBUSY = const(0x8000) # Read: Bit = 1 when device is not performing a conversion
_ADS1015_REG_CONFIG_MUX_MASK = const(0x7000) # Mux Mask
_ADS1015_REG_CONFIG_MUX_DIFF_0_1 = const(0x0000) # Differential P = AIN0, N = AIN1 (default)
_ADS1015_REG_CONFIG_MUX_DIFF_0_3 = const(0x1000) # Differential P = AIN0, N = AIN3
_ADS1015_REG_CONFIG_MUX_DIFF_1_3 = const(0x2000) # Differential P = AIN1, N = AIN3
_ADS1015_REG_CONFIG_MUX_DIFF_2_3 = const(0x3000) # Differential P = AIN2, N = AIN3
_ADS1015_REG_CONFIG_MUX_SINGLE_0 = const(0x4000) # Single-ended AIN0
_ADS1015_REG_CONFIG_MUX_SINGLE_1 = const(0x5000) # Single-ended AIN1
_ADS1015_REG_CONFIG_MUX_SINGLE_2 = const(0x6000) # Single-ended AIN2
_ADS1015_REG_CONFIG_MUX_SINGLE_3 = const(0x7000) # Single-ended AIN3
_ADS1015_REG_CONFIG_CMODE_MASK = const(0x0010) # CMode Mask
_ADS1015_REG_CONFIG_CMODE_TRAD = const(0x0000) # Traditional comparator with hysteresis (default)
_ADS1015_REG_CONFIG_CMODE_WINDOW = const(0x0010) # Window comparator
_ADS1015_REG_CONFIG_CPOL_MASK = const(0x0008) # CPol Mask
_ADS1015_REG_CONFIG_CPOL_ACTVLOW = const(0x0000) # ALERT/RDY pin is low when active (default)
_ADS1015_REG_CONFIG_CPOL_ACTVHI = const(0x0008) # ALERT/RDY pin is high when active
_ADS1015_REG_CONFIG_CLAT_MASK= const(0x0004) # Determines if ALERT/RDY pin latches once asserted
_ADS1015_REG_CONFIG_CLAT_NONLAT = const(0x0000) # Non-latching comparator (default)
_ADS1015_REG_CONFIG_CLAT_LATCH = const(0x0004) # Latching comparator
_ADS1015_REG_CONFIG_CQUE_MASK = const(0x0003)
_ADS1015_REG_CONFIG_CQUE_1CONV = const(0x0000) # Assert ALERT/RDY after one conversions
_ADS1015_REG_CONFIG_CQUE_2CONV = const(0x0001) # Assert ALERT/RDY after two conversions
_ADS1015_REG_CONFIG_CQUE_4CONV = const(0x0002) # Assert ALERT/RDY after four conversions
_ADS1015_REG_CONFIG_CQUE_NONE = const(0x0003) # Disable the comparator and put ALERT/RDY in high state (default)
_ADS1015_REG_CONFIG_DR_MASK = const(0x00E0) # Data Rate Mask
_ADS1015_REG_CONFIG_DR_128SPS = const(0x0000) # 128 samples per second
_ADS1015_REG_CONFIG_DR_250SPS = const(0x0020) # 250 samples per second
_ADS1015_REG_CONFIG_DR_490SPS = const(0x0040) # 490 samples per second
_ADS1015_REG_CONFIG_DR_920SPS = const(0x0060) # 920 samples per second
_ADS1015_REG_CONFIG_DR_1600SPS = const(0x0080) # 1600 samples per second (default)
_ADS1015_REG_CONFIG_DR_2400SPS = const(0x00A0) # 2400 samples per second
_ADS1015_REG_CONFIG_DR_3300SPS = const(0x00C0) # 3300 samples per second
_ADS1015_REG_CONFIG_MODE_MASK = const(0x0100) # Mode Mask
_ADS1015_REG_CONFIG_MODE_CONTIN = const(0x0000) # Continuous conversion mode
_ADS1015_REG_CONFIG_MODE_SINGLE= const(0x0100) # Power-down single-shot mode (default)
_ADS1015_REG_POINTER_MASK = const(0x03) # Point mask
_ADS1015_REG_POINTER_CONVERT = const(0x00) # Conversion
_ADS1015_REG_POINTER_CONFIG = const(0x01) # Configuration
_ADS1015_REG_POINTER_LOWTHRESH = const(0x02) # Low threshold
_ADS1015_REG_POINTER_HITHRESH = const(0x03) # High threshold
class ADS1115(object):
def __init__(self, data, clock, gain=_DEFAULT_GAIN, addr=_ADS1115_ADDRESS, conversion_delay=_ADS1115_CONVERSIONDELAY, bit_shift=0 ):
self._i2c_addr = addr
self._i2c=I2C(freq=400000,scl=clock,sda=data)
self._WRITE_BUFFER = bytearray(3)
self._READ_BUFFER = bytearray(2)
self._BUFFER = bytearray(1)
self._conversion_delay = conversion_delay
self._bit_shift = bit_shift
g = _ADS1015_GAIN.get(gain)
if g is None:
g = _ADS1015_GAIN.get(_DEFAULT_GAIN)
self._gain = g
def writeRegister( self, register, val ):
# Write an 16-bit unsigned value to the specified 8-bit address.
self._WRITE_BUFFER[0] = register & 0xFF
self._WRITE_BUFFER[1] = val >> 8
self._WRITE_BUFFER[2] = val & 0xff
#print("Write Reg:{0} = {1}:{2}".format(register, self._WRITE_BUFFER[1], self._WRITE_BUFFER[2]))
self._i2c.writeto(self._i2c_addr, self._WRITE_BUFFER )
def readRegister(self, register):
# Read an 8-bit unsigned value from the specified 8-bit address.
self._BUFFER[0] = register & 0xFF
self._i2c.writeto(self._i2c_addr, self._BUFFER)
self._i2c.readfrom_into(self._i2c_addr, self._READ_BUFFER)
return_value = ( self._READ_BUFFER[0] << 8 ) | self._READ_BUFFER[1]
#print("Read Reg:{0} {1}:{2}".format(register, self._READ_BUFFER[0], self._READ_BUFFER[1]))
return return_value
def readSingleEnded( self, channel=0 ):
config = ( _ADS1015_REG_CONFIG_CQUE_NONE | # Disable the comparator (default val)
_ADS1015_REG_CONFIG_CLAT_NONLAT | # Non-latching (default val)
_ADS1015_REG_CONFIG_CPOL_ACTVLOW | # Alert/Rdy active low (default val)
_ADS1015_REG_CONFIG_CMODE_TRAD | # Traditional comparator (default val)
_ADS1015_REG_CONFIG_DR_1600SPS | # 1600 samples per second (default)
_ADS1015_REG_CONFIG_MODE_SINGLE ) # Single-shot mode (default)
config |= self._gain;
if channel == 0:
config |= _ADS1015_REG_CONFIG_MUX_SINGLE_0
elif channel == 1:
config |= _ADS1015_REG_CONFIG_MUX_SINGLE_1
elif channel == 2:
config |= _ADS1015_REG_CONFIG_MUX_SINGLE_2
elif channel == 3:
config |= _ADS1015_REG_CONFIG_MUX_SINGLE_3
# Set 'start single-conversion' bit
config |= _ADS1015_REG_CONFIG_OS_SINGLE;
# Write config register to the ADC
self.writeRegister(_ADS1015_REG_POINTER_CONFIG, config);
#Wait for the conversion to complete
utime.sleep_ms(self._conversion_delay);
# Read the conversion results
# Shift 12-bit results right 4 bits for the ADS1015
return self.readRegister(_ADS1015_REG_POINTER_CONVERT) >> self._bit_shift
"""
/**************************************************************************/
/*!
@brief In order to clear the comparator, we need to read the
conversion results. This function reads the last conversion
results without changing the config value.
@return the last ADC reading
*/
/**************************************************************************/
int16_t Adafruit_ADS1015::getLastConversionResults() {
// Wait for the conversion to complete
delay(m_conversionDelay);
// Read the conversion results
uint16_t res =
readRegister(m_i2cAddress, ADS1015_REG_POINTER_CONVERT) >> m_bitShift;
if (m_bitShift == 0) {
return (int16_t)res;
} else {
// Shift 12-bit results right 4 bits for the ADS1015,
// making sure we keep the sign bit intact
if (res > 0x07FF) {
// negative number - extend the sign to 16th bit
res |= 0xF000;
}
return (int16_t)res;
}
}
"""
<file_sep>/src/bounce.py
import machine
from machine import Pin
import utime
class Bounce:
DEBOUNCED_STATE = const(1);
UNSTABLE_STATE = const(2);
CHANGED_STATE = const(4);
def __init__(self, pin, interval_millis=10):
self._pin = pin
self._previous_millis = utime.ticks_ms()
self._interval_millis = interval_millis
self._state = 0
self._duration_of_previous_state = 0
self._state_change_last_time = 0
if ( self.value is 1 ):
self._state = DEBOUNCED_STATE | UNSTABLE_STATE
@property
def value(self):
return self._pin.value()
def toggleState( self, flag ):
self._state ^= flag
def isState( self, flag ):
return (self._state & flag) != 0
def setStateFlag( self, flag ):
self._state |= flag
def getStateFlag( self, flag ):
return (self._state & flag) != 0
def unsetStateFlag( self, flag ):
self._state &= ~flag
def changeState( self ):
self.toggleState(DEBOUNCED_STATE)
self.setStateFlag( CHANGED_STATE )
self._duration_of_previous_state = utime.ticks_ms() - self._state_change_last_time;
self.state_change_last_time = utime.ticks_ms()
def changed( self ):
return self.isState(CHANGED_STATE)
def update( self ):
self.unsetStateFlag(CHANGED_STATE)
currentState = self.value
# print( "current: {0} State: {1}".format( currentState, self._state ) )
# If the reading is different from last reading, reset the debounce counter
if currentState != self.getStateFlag(UNSTABLE_STATE):
self._previous_millis = utime.ticks_ms()
self.toggleState(UNSTABLE_STATE)
# print( "millis: {0} State: {1}".format( self._previous_millis, self._state ) )
else:
# print( "diff millis: {0} DBState: {1}".format( utime.ticks_ms() - self._previous_millis, self.getStateFlag(DEBOUNCED_STATE ) ) )
if utime.ticks_ms() - self._previous_millis >= self._interval_millis:
# We have passed the threshold time, so the input is now stable
# If it is different from last state, set the STATE_CHANGED flag
if currentState != self.getStateFlag(DEBOUNCED_STATE):
self._previous_millis = utime.ticks_ms()
self.changeState()
return self.changed()
<file_sep>/src/radio.py
import machine
from machine import Pin
import time
import math
import si5351
class Radio:
MIN_FREQUENCY = const( 7000000 )
MAX_FREQUENCY = const( 30000000 )
MIN_RADIX = const( 0 )
MAX_RADIX = const( 6 )
MODE_FREQUENCY = const( 1 )
MODE_RADIX = const( 2 )
STARTING_RADIX = const(2)
def __init__(self, rbutton, encoder, lcd, s, frequency):
self._encoder = encoder
self._si5351 = s
self._frequency = frequency
self._radix = STARTING_RADIX
self._lcd = lcd
self._mode = MODE_FREQUENCY
self._rbutton = rbutton
self._mult = 100
self._old_encoder_value = 0
self._old_rbutton_value = 1
self._old_mult = 0
self._si5351.clock_0.drive_strength( si5351.STRENGTH_2MA )
self._si5351.clock_2.drive_strength( si5351.STRENGTH_2MA )
def encoderChanged( self, e ):
if self._mode == MODE_FREQUENCY:
self.frequencyChanged( e )
else:
self.radixChanged( e )
self._old_encoder_value = e
def frequencyChanged( self, e ):
if e > self._old_encoder_value:
self._frequency += math.floor(math.pow(10, self._radix ))
else:
self._frequency -= math.floor(math.pow( 10, self._radix ))
if self._frequency > MAX_FREQUENCY:
self._frequency = MAX_FREQUENCY
elif self._frequency < MIN_FREQUENCY:
self._frequency = MIN_FREQUENCY
self.setFrequency()
self.printlcd()
def setFrequency( self ):
f = self._frequency
if f < 8000000:
self._mult = 100
elif f < 11000000:
self._mult = 80
elif f < 15000000:
self._mult = 50
else:
self._mult = 30
self._si5351.set_frequency( self._frequency, self._si5351.clock_0, self._si5351.pll_a, self._mult )
self._si5351.set_frequency( self._frequency, self._si5351.clock_2, self._si5351.pll_a, self._mult )
if ( self._mult != self._old_mult ):
self._si5351.set_phase( self._si5351.clock_2, self._si5351.pll_a, self._mult )
self._old_mult = self._mult
def radixChanged( self, e ):
if e < self._old_encoder_value:
self._radix += 1
else:
self._radix -= 1
if self._radix > MAX_RADIX:
self._radix = MAX_RADIX
elif self._radix < MIN_RADIX:
self._radix = MIN_RADIX
self.showRadix()
def showRadix( self ):
cursorpos = 10 - self._radix
if ( self._radix > 2 ):
cursorpos -= 1
if ( self._radix > 5 ):
cursorpos -= 1
self._lcd.move_to( cursorpos, 0 )
def printlcd( self ):
f = self._frequency
mhz = math.floor( f / 1000000 )
khz = math.floor( ( f - mhz * 1000000 ) / 1000 )
hz = f % 1000;
self._lcd.move_to( 0, 0 );
self._lcd.putstr( "{0:3.0d},{1:03.0d}.{2:03.0d}".format( mhz, khz, hz ) );
def radixButtonPressed( self, b ):
if b == 1:
if self._mode == MODE_FREQUENCY:
self._mode = MODE_RADIX
self._lcd.show_cursor();
self._lcd.blink_cursor_on();
self.showRadix()
else:
self._mode = MODE_FREQUENCY
self._lcd.blink_cursor_off();
self._lcd.hide_cursor()
self._old_rbutton_value = b
def run(self):
self.printlcd()
self.setFrequency()
while True:
e = self._encoder.value
if e != self._old_encoder_value:
self.encoderChanged( e )
self._rbutton.update()
b = self._rbutton.value
if b != self._old_rbutton_value:
self.radixButtonPressed(b)
time.sleep(0.05)
| 7b9191c75e972b058762183ebe4c86f45b64d098 | [
"Python"
] | 5 | Python | benhayesthomas/Tinypico-Radio | 8b3afa9e06864fa3e76b8d7224212c653885dbe6 | 056f52629b6ce6eab351a38c452d9f62ae03fbfa |
refs/heads/master | <repo_name>thalesorm/TESTE-ESTAGIO-FRONT<file_sep>/src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AddEnqueteComponent } from './components/add-enquete/add-enquete.component';
import { EnqueteDetailsComponent } from './components/enquete-details/enquete-details.component';
import { EnqueteListComponent } from './components/enquete-list/enquete-list.component';
@NgModule({
declarations: [
AppComponent,
AddEnqueteComponent,
EnqueteDetailsComponent,
EnqueteListComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/models/enquete.model.spec.ts
import { Enquete } from './enquete.model';
describe('Enquete', () => {
it('should create an instance', () => {
expect(new Enquete()).toBeTruthy();
});
});
<file_sep>/src/app/components/enquete-list/enquete-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Enquete, Option } from 'src/app/models/enquete.model';
import { EnqueteService } from 'src/app/services/enquete.service';
@Component({
selector: 'app-enquete-list',
templateUrl: './enquete-list.component.html',
styleUrls: ['./enquete-list.component.css']
})
export class EnqueteListComponent implements OnInit {
enquetes?: Enquete[];
currentEnquete: Enquete = {};
options: any;
votes: any;
setVote:boolean = true;
currentDate = new Date();
currentIndex = -1;
title = '';
countVount: number = 0;
constructor(private enqueteService: EnqueteService) { }
ngOnInit(): void {
this.retrieveenquetes();
}
retrieveenquetes(): void {
this.enqueteService.getAll()
.subscribe(
data => {
this.enquetes = data;
console.log(data);
},
error => {
console.log(error);
});
}
refreshList(): void {
this.retrieveenquetes();
this.currentEnquete = {};
this.currentIndex = -1;
}
setActiveTutorial(enquete: Enquete, index: number): void {
this.currentEnquete = enquete;
try{
let start = new Date(enquete.dateStart);
let end = new Date(enquete.dateEnd);
if((start.getDate() <= this.currentDate.getDate()) && (end.getDate >= this.currentDate.getDate)){
this.setVote = true;
}else{
this.setVote = false;
}
}catch(e){
console.log(e)
}
this.currentIndex = index;
}
removeAllenquetes(): void {
this.enqueteService.deleteAll()
.subscribe(
response => {
console.log(response);
this.refreshList();
},
error => {
console.log(error);
});
}
vote(id: any){
this.enqueteService.vote(id).subscribe(res => {
this.refreshList();});
}
searchTitle(): void {
this.currentEnquete= {};
this.currentIndex = -1;
this.enqueteService.findByTitle(this.title)
.subscribe(
data => {
this.enquetes = data;
console.log(data);
},
error => {
console.log(error);
});
}
}<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EnqueteListComponent } from './components/enquete-list/enquete-list.component';
import { EnqueteDetailsComponent } from './components/enquete-details/enquete-details.component';
import { AddEnqueteComponent } from './components/add-enquete/add-enquete.component';
const routes: Routes = [
{ path: '', redirectTo: 'enquetes', pathMatch: 'full' },
{ path: 'enquetes', component: EnqueteListComponent },
{ path: 'enquete/:id', component: EnqueteListComponent },
{ path: 'add', component: AddEnqueteComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/src/app/models/enquete.model.ts
export class Enquete {
id?: number;
title?: string;
dateStart?: Date;
dateEnd?: Date;
status?: string;
options?: Option[];
}
export class Option{
id?: number;
title?: string;
enqueteId?: number;
votes?: Vote[];
countVote?: number;
}
export class Vote{
id?: number;
optionId?: number;
}
| 94e1edf00ceb93a8854415547fbcdf8e0b492e73 | [
"TypeScript"
] | 5 | TypeScript | thalesorm/TESTE-ESTAGIO-FRONT | 73aa11db1adf72d31700d45b4b1e8ca7479daab2 | 5f4c599bf808069490d8e4beeb831ac924856b43 |
refs/heads/master | <file_sep>import json
import os
import spio
class Playlist:
def __init__(self, user, name, uri, tracks, reference):
"""
Creates a new Playlist object
:param user: Associated user for this Playlist
:param name: The Name of the playlist (a URI currently)
:param tracks: The tracks of this Playlist
:param reference: The reference playlist Object (None if this is a reference)
"""
self.user = user
self.name = name
self.uri = uri
self.tracks = tracks
self.reference = reference
@classmethod
def from_file(cls, user, source_file, reference):
"""
Generates a playlist object from a dumped file
:param user: Associated user
:param source_file: File to load the Playlist from
:param reference: The reference playlist Object (None if this is a reference)
:return: The newly constructed Playlist object
"""
playlist = json.load(source_file)
uri = playlist["Playlist_URI"]
name = playlist["Name"]
tracks = playlist["Track_URIs"]
return cls(user, name, uri, tracks, reference)
@classmethod
def from_web_api(cls, user, access_token, uri, reference):
"""
Generates a playlist object from the spotify API
:param user: Associated user
:param access_token:
:param uri: the URI corresponding to the playlist
:param reference: The reference playlist Object (None if this is a reference)
:return: The newly constructed Playlist object
"""
tracks = spio.get_tracks(access_token, uri)
name = spio.get_name(access_token, uri)
return cls(user, name, uri, tracks, reference)
def __eq__(self, other):
if self is None and other is None:
return True
elif self is None or other is None:
return False
else:
return self.uri == other.uri and self.tracks == other.tracks
def sync(self):
"""
syncs a Playlist with its reference, adding any new track URI's to the reference
:return: the URI's of all tracks in the Playlist that were not in the reference
"""
diff = [i for i in self.tracks if i not in self.reference.tracks]
self.reference.tracks += diff
return diff
def write_out(self):
"""
Dumps a playlist object to a file, along with the reference
:return: None
"""
# todo messy code, but the only occurrance
if self.reference:
self.reference.write_out()
with open_playlist(self.user, self.uri, "w") as outfile:
json.dump({"Name": self.name, "Playlist_URI":self.uri, "Track_URIs":self.tracks}, outfile)
else:
with open_playlist(self.user, self.uri + "_ref", "w") as outfile:
json.dump({"Name": self.name, "Playlist_URI":self.uri, "Track_URIs":self.tracks}, outfile)
class Drainlist:
def __init__(self, user, source_file):
"""
Generates a new Drainlist object for the given user
:param user: Associated user
:param source_file: File Drainlist is loaded from
todo update to another level of nesting to prevent cross inheritance issues
currently if two playlists share a source one will update, update the ref
and the other will not get the changes, nesting is much simpler than weird
concurrency logic
"""
drainlist = json.load(source_file)
self.user = user
self.name = drainlist["Name"]
self.uri = drainlist["Playlist_URI"]
# todo can this be a set?
self.source_names = list(set([s["Name"] for s in drainlist["Sources"]]))
self.source_uris = list(set([s["URI"] for s in drainlist["Sources"]]))
self.sources = []
# if there are named sources add the proper playlist objects
for name in self.source_uris:
try:
self.add_source_file(name)
except FileNotFoundError as e:
uri = e.filename.split("/")[-1]
self.add_source_api(uri)
def add_source_file(self, source_name):
"""
Adds a new Playlist source to a drainlist by filename (Playlist URI)
fails if source and reference files do not exist
:param source_name: Playlist filename (Playlist URI)
:return: None
"""
with open_playlist(self.user, source_name, "r") as source_file:
with open_playlist(self.user, source_name + "_ref", "r") as ref_file:
ref = Playlist.from_file(self.user, ref_file, None)
templist = Playlist.from_file(self.user, source_file, ref)
self.sources += [templist]
def remove_source(self, source_name):
"""
Removes all Source from the Drainlist that match the given name
:param source_name: Name of Source PLaylists to remove (one name, but can remove multiple)
:return: None
"""
toRem = None
for source in self.sources:
if source.uri == source_name:
toRem = source
if toRem:
self.sources.remove(toRem)
def add_source_api(self, uri):
"""
Adds a new Playlist source to a drainlist via the API using the Playlist URI
:param uri: URI of the playlist to be added
:return: None
"""
# here if source file does not exist, but still
try:
refFile = open_playlist(self.user, uri + "_ref")
ref = Playlist.from_file(self.user, refFile, None)
except Exception as e:
ref = Playlist.from_web_api(self.user, spio.get_access_token(self.user), uri, None)
templist = Playlist.from_web_api(self.user, spio.get_access_token(self.user), uri, ref)
templist.write_out()
ref.write_out()
self.sources += [templist]
def populate(self, access_token):
"""
Adds one of each track (uniquely) in every source to the drainlist sink on Spotify
it will not add tracks already on the playlist
This should only be done on startup in order to skip the ref stage, can remove later
:param access_token: Securely ID's the user
:return: None
"""
tracks = []
for source in self.sources:
tracks += source.tracks
tracks = list(set(tracks) - set(spio.get_tracks(access_token, self.uri)))
spio.add_tracks_to_drain(access_token, self, list(set(tracks)))
def depopulate(self, access_token):
"""
Deletes all tracks from the drainlist sink on spotify
:param access_token: Securely ID's the user
:return: None
"""
tracks = []
for source in self.sources:
tracks += set(source.tracks)
spio.remove_tracks_from_drain(access_token, self, tracks)
def write_out(self):
"""
Dumps drainlist all sources and all references to disk
:return: None
"""
with open_drainlist(self.user, self.uri, "w+") as outfile:
json.dump({"Name": self.name, "Playlist_URI":self.uri, "Sources": spio.print_sources(self.sources)}, outfile)
for s in self.sources:
s.reference.write_out()
def sync(self):
"""
Syncs all sources, leaving references updated to include new Tracks
returns new tracks (to be uploaded immediately after)
:return: list of Track uri's returned by each sources syncing
"""
diff = set()
for source in self.sources:
[diff.add(i) for i in source.sync()]
return diff
def cleanup(self, user):
"""
Deletes written out source files, references are all that is stored long term
this should be changed to allow for direct comparison from in memory plists against
file references
:param user:
:return:
"""
for source in self.sources:
filename = user + "/" "Playlists" + "/" + source.uri
os.remove(filename)
def open_playlist(user, playlist_name, flag = "r"):
return open(user + "/Playlists/" + playlist_name, flag)
def open_drainlist(user, playlist_name, flag = "r"):
return open_playlist(user, playlist_name + "_drain", flag)
def open_reflist(user, playlist_name, flag = "r"):
return open_playlist(user, playlist_name + "_ref", flag)
<file_sep>from flask import Flask, redirect, request, sessions, render_template
import urllib
import requests
import json
import base64
import time
import playlist, spio
import io
import os
from flask_cors import CORS
####################################
######## Set up Constants ##########
####################################
app = Flask(__name__)
CORS(app)
cwd = "/Users/Danny/Documents/CS/SpotifyAppend"
# hacky test global thing, will remove later once the templates is properly attached
# user = "Danny" if __name__ == "__main__" else "Test_User"
user = "Danny"
# todo: change the API so that functions take in args for local testing,
# then create wrapper funcs that simply call the local
# func after extracting the args from a request
# todo change this to return to the templates homepage
auth_completed_url = spio.myUrl + "authentication_completed"
sec = []
with open(cwd + "/Secrets", "r") as infile:
for line in infile:
sec.append(line.strip())
client_id = sec[0]
client_secret= sec[1]
# Todo, you can probably remove these now, double check though
global access_token
global refresh_token
####################################
########### Auth Code ############
####################################
# This code is called when the app is first accessed from the Client, if the
# Tokens are present it presents the landing page, if not it requests tokens
@app.route("/")
def initialize():
try:
spio.get_access_token(user)
return redirect(auth_completed_url)
except Exception as e:
return redirect(spio.get_new_tokens().url)
# Landing page to return from a Spotify Token Request
# not gonna get a refresh token all the time except when you explicitly ask for one
# https://stackoverflow.com/questions/10827920/not-receiving-google-oauth-refresh-token
@app.route("/authentication_return")
def get_tokens():
code = ""
try:
code = request.args["code"]
except:
print("the code was not present, auth failed")
redirect(spio.myUrl)
# if auth succeeds we build the url to get our tokens from the "code"
response = spio.get_tokens_from_code(code)
# Save Tokens
jsonResp = response.json()
spio.write_new_tokens(user, jsonResp)
return redirect(auth_completed_url)
# This is the "Main Page" that we will do our main work from
# (managing drainlists).
# todo a one time refresh button to override the playlist refresh timer
@app.route("/authentication_completed")
def signed_in():
return render_template("index.html")
@app.route("/Create")
def create():
return render_template("create.html")
@app.route("/Edit")
def edit():
return render_template("edit.html")
####################################
######### End Auth Code ###########
####################################
####################################
######## Interactive Code ##########
####################################
# Takes playlists owned by the user and formats them to be sent to the templates
@app.route("/list_playlists")
def list_playlists_request():
user = request.args["user"]
lists = spio.get_playlists(spio.get_access_token(user))
resp = app.make_response(json.dumps([{"name": l["name"], "uri": l["uri"]} for l in lists]))
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
@app.route("/list_drains")
def list_drains_request():
user = request.args["user"]
drain_names = [f for f in os.listdir(user + "/Playlists/") if f.endswith("_drain")]
drains = []
for drain in [d.replace("_drain","") for d in drain_names]:
with playlist.open_drainlist(user, drain) as infile:
dlist = playlist.Drainlist(user, infile)
drains.append(dlist)
dlist.cleanup(user)
resp = app.make_response(json.dumps([{"Name": d.name, "URI": d.uri, "Sources": spio.print_sources(d.sources)} for d in drains]))
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
# Collects all drains associated with a user
def list_drains(user):
return [filename for filename in os.listdir(os.getcwd()+ "/" + user + "/Playlists") if filename.endswith("_drain")]
@app.route("/refresh")
def refresh_request():
user = request.args["user"]
token = spio.get_access_token(user)
refresh(user, token)
resp = app.make_response("success")
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
# Takes new drainlist data, generates the proper drainlist (creating a playlist to serve as the sink)
@app.route("/new_drain", methods = ["GET", "POST", "OPTIONS"])
def create_new_drain_request():
if request.method == "OPTIONS":
resp = app.make_response(json.dumps([{"name":"nope"}]))
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers["Access-Control-Allow-Headers"] = "*"
return resp
if request.method == "POST":
data = request.data.decode("utf-8")
data = json.loads(data)
ret = create_new_drain_from_name(data["user"] ,data["drainlist"], data["sources"])
return app.make_response(ret)
# return proper JSON here
def create_new_drain_from_name(user, dlistName, sources):
"""
Given a name (non-URI) this creates a new sink playlist and sets up the URI work as expected
:param user: User owning the Drainlist
:param dlistName: name for the sink playlist (Spotify Name)
:param sources: sources to be associated with the new Drainlist
:return:
todo prevent name collisions
"""
# create new playlist with given name, get the URI and proceed
uri = spio.create_playlists(spio.get_access_token(user), dlistName)
return create_new_drain(user, dlistName, uri, sources)
def create_new_drain(user, dListNameame, drainlist, sources):
"""
Creates a new drainlist
:param user: User owning the Drainlist
:param drainlist: Name for new Drainlist (should be a URI)
:param sources: list of sources to associate with the new drain
:return: the contents of the file as a string
"""
if "spotify:playlist:" not in sources[0]:
sources = ["spotify:playlist:" + source for source in sources]
sources = [{"URI": source, "Name":spio.get_name(spio.get_access_token(user), source)} for source in sources]
with playlist.open_drainlist(user, drainlist, "w+") as dfile:
json.dump({"Name": dListNameame,"Playlist_URI": drainlist, "Sources": sources}, dfile)
with playlist.open_drainlist(user, drainlist) as dfile:
dlist = playlist.Drainlist(user, dfile)
dlist.populate(spio.get_access_token(user))
dlist.cleanup(user)
return json.dumps({"Name": dListNameame,"Playlist_URI": drainlist, "Sources": sources})
@app.route("/remove_source")
def remove_source_request():
user = request.args["user"]
uri = request.args["listURI"]
sinkName = request.args["sinkURI"]
with playlist.open_drainlist(user, sinkName) as infile:
dlist = playlist.Drainlist(user, infile)
dlist.cleanup(user)
dlist.remove_source(uri)
dlist.write_out()
os.remove(user + "/Playlists/" + uri + "_ref")
resp = app.make_response("success")
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
@app.route("/add_source")
def add_source_request():
user = request.args["user"]
uri = request.args["listURI"]
sinkName = request.args["sinkURI"]
with playlist.open_drainlist(user, sinkName) as infile:
dlist = playlist.Drainlist(user, infile)
dlist.add_source_api(uri)
dlist.write_out()
dlist.cleanup(user)
resp = app.make_response("success")
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
####################################
###### End Interactive Code ########
####################################
def refresh(user, token):
"""
Refreshes / updates all of a users drainlists
The grandaddy of them all
:param user: The user who we are updating
:param token: The users token
:return: None
"""
uris = [f.replace("_drain", "") for f in os.listdir(user + "/Playlists/") if "_drain" in f]
for uri in uris:
with playlist.open_drainlist(user, uri) as infile:
d = playlist.Drainlist(user, infile)
diff = d.sync()
d.write_out()
spio.add_tracks_to_drain(token, d, diff)
d.cleanup(user)
# user = "Danny"
# token = spio.get_access_token(user)
# u = ["spotify:playlist:16wE0quJ4wHXGaY78MZikr", "spotify:playlist:0FMPIrKYN6hIEH54FyZ1oa"]
# refresh(user, token)
<file_sep>import sys, os
sys.path.append('..')
import unittest
import spotify
import spio
import playlist
test_user = "Test_User"
class IntegrationTests(unittest.TestCase):
drainSinkName = "drainSink"
drain_name = "spotify:playlist:069rrIb9s1MRw2BBwXmeJE"
sources = ["4L3PeQ9LzinSq0Q3KnzLvb", "6E2XjEeEOEhUKVoftRHusb"]
tracks = ['spotify:track:6koWevx9MqN6efQ6qreIbm', 'spotify:track:7EE7jbv7Dv8ZkyWBlKhPXX',
'spotify:track:1zTmKEtaxIqi2ByGBLmI3s', 'spotify:track:1RjP07A2H4WMmozQidd9x7',
'spotify:track:0dE9ro91KUtV5Xi7bDPy6b', 'spotify:track:1UYXdZZMnCrlUqDRuIs9OE',
'spotify:track:18rXOovmohAMcFwUPAUAN2', 'spotify:track:3DERgYjztCL6oME2fvRl6z',
'spotify:track:0TRbihonM8LyyQ7OClspEy', 'spotify:track:5MbUyUE6erY9mVgXaecQwR',
'spotify:track:0Mx2W2i58sIPmEvfKdh1Q2', 'spotify:track:52FCSkVx41xDQ3oCjHIeNJ',
'spotify:track:7hjJKZwcW0vze3A48dqcCr', 'spotify:track:08Z3vnfucOMerexVE2RR8w',
'spotify:track:4FqfG6WnkXEMc6ZZ58lJWb', 'spotify:track:7Jzr0HLMMvTOo9Xvc8EjZL',
'spotify:track:3nV9CwvpCHGd9fvJ1pn185', 'spotify:track:1eueYfJA1ADnfghW90xxxf',
'spotify:track:4cx6srR6OQzmd6mzpeaQsY', 'spotify:track:5WwaKGBmg0TpG8mRQpksl2',
'spotify:track:1wJCpDiJeQccXuNguS8umH', 'spotify:track:78qM62MHvNxFJLpShqmq28',
'spotify:track:5EeNRe6Fi29tTrssVzl4dw', 'spotify:track:3Lr9aRWF57Dd8NsjeWTKNp',
'spotify:track:1Z5GCYgzsBxb9VUUVQRG2E', 'spotify:track:74fNA9uOtYFbkpG7gE8AKV',
'spotify:track:5DQEWQoJ3deYCPkRIFm3Ci', 'spotify:track:7dYXMe7VAmmkKDyGByUOfM',
'spotify:track:3ozCQsJ9IA0v3ZlpE21UzK', 'spotify:track:71CRvX5TW0CsiCxGZ00IfA',
'spotify:track:2qOm7ukLyHUXWyR4ZWLwxA', 'spotify:track:4MbV8zrWudQflnbiIzp29t',
'spotify:track:3MQmQowCMVhepBDEsuBXIm', 'spotify:track:63BokRfXSQhEU6Qi2dSJpZ',
'spotify:track:0WKYRFtH6KKbaNWjsxqm70', 'spotify:track:503OTo2dSqe7qk76rgsbep',
'spotify:track:2C3QwVE5adFCVsCqayhPW7', 'spotify:track:2g8HN35AnVGIk7B8yMucww',
'spotify:track:0HOqINudNgQFpg1le5Hnqe', 'spotify:track:2Ih217RCGAmyQR68Nn7Cqo']
def setUp(self):
spotify.create_new_drain(test_user, self.drainSinkName ,self.drain_name, self.sources)
self.access_token = spio.get_access_token(test_user)
with playlist.open_drainlist(test_user, self.drain_name) as infile:
self.Dlist = playlist.Drainlist(test_user, infile)
if spio.get_tracks(self.access_token, self.Dlist.uri):
self.Dlist.depopulate(spio.get_access_token(test_user))
def tearDown(self):
for f in os.listdir(test_user + "/Playlists/"):
os.remove(test_user + "/Playlists/" + f)
if spio.get_tracks(self.access_token, self.Dlist.uri):
self.Dlist.depopulate(spio.get_access_token(test_user))
def test_integ_populate_and_sync(self):
# drop a track
dropped_track = self.Dlist.sources[0].reference.tracks.pop()
self.Dlist.sources[0].tracks.remove(dropped_track)
# populate
self.Dlist.populate(self.access_token)
tracks = self.tracks[:]
tracks.remove(dropped_track)
self.assertEqual(set(tracks), set(spio.get_tracks(self.access_token, self.Dlist.uri)))
# re-add the track and sync
self.Dlist.sources[0].tracks += [dropped_track]
diff = self.Dlist.sync()
spio.add_tracks_to_drain(self.access_token, self.Dlist, diff)
# check if the track was added
tracks += [dropped_track]
self.assertEqual(set(tracks), set(spio.get_tracks(self.access_token, self.Dlist.uri)))
# depopulate
self.Dlist.depopulate(spio.get_access_token(test_user))
self.assertEqual(set(), set(spio.get_tracks(self.access_token, self.Dlist.uri)))
self.Dlist.cleanup(test_user)
self.assertEqual(set(os.listdir(test_user + "/Playlists/")), {'spotify:playlist:4L3PeQ9LzinSq0Q3KnzLvb_ref', 'spotify:playlist:069rrIb9s1MRw2BBwXmeJE_drain', 'spotify:playlist:6E2XjEeEOEhUKVoftRHusb_ref'})
<file_sep>#Spotify Append
##What it does
Spotify Append allows for playlists to have ***sources***™.
A source is just a regular spotify playlist that your shiny new playlist tracks including any changes.
Songs that you delete from your destination playlist do not automatically re-add. At a high level it's a bunch of playlists coming in and a filter removing certain known tracks.
##Example
Schema: 1,2 are sources, 3 is the destination (a - e are tracks)
- 1 : {a,b} , 2 : {d, e} , 3 : {}
- 3 will initially contain: {a,b,d,e}
- user then deletes song a from 3 (song a)
- 3:{b,d,e}
- user adds c to 1:
- 1: {a,b,c} 3 : {b,c,d,e}
- user deletes d from 2
- 2: {e} (no change to 3)
The playlists are append only from the view of the sources. Removes are controlled entirely by the owner of the destination playlist
##How it does it
Frontend to backend is plain HTTP requests with JSON data
Backend endpoints: auth, get and show all playlists, show and create drainlists
Daily (or more often)run the sync.
Currently the whole thing works but its rather messy.
##Design Details
###Frontend endpoints are:
1. add / remove source (local file changes only)
2. create / list drains (create is immediately followed by a populate, list is locals only )
3. list playlists (API call to get all playlists)
###Backend:
1. everything is files (lots of manangemet with "open(a + b + c + d)" tons of places to go wrong)
2. temp playlists are written out to disk (needless)
##Moving Forward
- Currently we have a race condition if two sourced playlists use the same source there is only 1 copy meaning updates will only be applied to one destination.
- In order to fix this, we can just have every destination list be in a self contained directory, do deduplication later.
- Remove writing a reference out to disk so now we can do comparisons in memory, that's just lazy.
##Todo
1. Port to AWS (Lambda, S3, Dynamo)
2. Account system
##Notes
<file_sep>
var nameToUri;
var currentDlists;
function updatePlaylists(){
// get a better user delineation method
// user = window.prompt("what is your username")
user = "Danny";
// testing
if (!user.includes("Danny")){
user = "Danny";
}
var rule = "onclick=\"this.style.color = this.style.color == \'red\' ? \'black\' : \'red\'\" style=\"cursor: pointer\"";
var url= "http://127.0.0.1:5000/list_playlists";
url = url + "?user=" + user;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
plists = JSON.parse(xmlhttp.responseText);
document.getElementById('theList').innerHTML = "";
for (let i = 0; i < plists.length; i++) {
document.getElementById('theList').innerHTML += ('<li ' + rule + '>' + plists[i]["name"] + '</li>');
}
nameToUri = listToMap(plists);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function getDrainlists(){
user = "Danny";
var url= "http://127.0.0.1:5000/list_drains";
url = url + "?user=" + user;
var rule = "onclick=\"showStructure(this.innerHTML)\" style=\"cursor: pointer\"";
// todo update to actually send the request, you fool!
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
plists = JSON.parse(xmlhttp.responseText);
currentDlists = plists;
document.getElementById('drainList').innerHTML = "";
for (let i = 0; i < plists.length; i++) {
document.getElementById('drainList').innerHTML += ('<li ' + rule + '>' + plists[i]["Name"] + '</li>');
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
var url= "http://127.0.0.1:5000/list_playlists";
url = url + "?user=" + user;
var req2 = new XMLHttpRequest();
req2.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
plists = JSON.parse(req2.responseText);
nameToUri = listToMap(plists);
}
};
req2.open("GET", url, true);
req2.send();
}
function listToMap(lst){
m = new Map();
for (var i = 0; i < lst.length; i++) {
m[lst[i]["name"]] = lst[i]["uri"];
}
return m
}
function showStructure(item){
for (var i = 0; i < currentDlists.length; i++) {
if (item === currentDlists[i].Name){
displayStructure(currentDlists[i]);
}
}
}
function displayStructure(item){
card = document.getElementById("structure")
card.innerHTML = "<p></p>"
p = card.children[0]
p.innerHTML = "<div id=\"sinkName\"> Name: "+ item.Name + "</div>"
card.innerHTML += "Sources:"
card.innerHTML += "<ul id=\"strucList\" class= \"w3-ul\"></ul>"
ul = document.getElementById("strucList")
for (var i = 0; i < item.Sources.length; i++) {
ul.innerHTML += "<li> <div> " + item.Sources[i].Name + "<i class=\"fa fa-close\" style=\"margin-left: 5px\" onclick=\"deleteSource(this)\"></i> </div> </li>"
}
card.innerHTML += "<br><i class=\"fa fa-plus\" style = \"font-size : xx-large;\" onclick=\"addSource(this)\"</i>"
}
function addSource(item){
var name = prompt("enter Playlist Name: ")
uri = nameToUri[name]
sinkUri = nameToUri[document.getElementById("sinkName").innerHTML.split("Name: ")[1].trim()]
var url= "http://127.0.0.1:5000/add_source";
url = url + "?user=" + user;
url = url + "&listURI=" + uri;
url = url + "&sinkURI=" + sinkUri;
var req2 = new XMLHttpRequest();
req2.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
confirm("source: " + name + "has been added")
}
};
req2.open("GET", url, true);
req2.send();
// todo here do add source logic
}
function deleteSource(item){
name = item.parentElement.innerHTML.split("<")[0].trim();
uri = nameToUri[name]
sinkUri = nameToUri[document.getElementById("sinkName").innerHTML.split("Name: ")[1].trim()]
var url= "http://127.0.0.1:5000/remove_source";
url = url + "?user=" + user;
url = url + "&listURI=" + uri;
url = url + "&sinkURI=" + sinkUri;
var req2 = new XMLHttpRequest();
req2.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
confirm("source: " + name + "has been removed")
}
};
req2.open("GET", url, true);
req2.send();
// using the name / URI delete the source,
}
function search(searchString){
// todo this is garbage, but makes it look decent
window.scrollTo(0,146);
searchString = searchString.toUpperCase();
var ul = document.getElementById("theList");
var li = ul.getElementsByTagName("li");
for (var i = 0; i < li.length; i++) {
if (li[i].textContent.toUpperCase().includes(searchString)){
li[i].style.display = "";
}
else {
li[i].style.display = "none";
}
}
}
function collectHighlighted(){
var arr = [];
var ul = document.getElementById("theList");
var li = ul.getElementsByTagName("li");
for (var i = 0; i < li.length; i++) {
if (li[i].style.color === "red"){
arr.push(nameToUri[li[i].textContent]);
}
}
var name = document.getElementById("sourcedName").value;
console.log(arr);
console.log(name);
for (var i = 0; i < li.length; i++) {
li[i].style.color = "black";
}
document.getElementById("sourcedName").value = "";
createNewDrain(name, arr);
}
function createNewDrain(name, sources){
user = "Danny";
var url= "http://127.0.0.1:5000/new_drain";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
confirm("created new Drain with name " + name + " and Sources: " + sources);
}
};
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/json');
xmlhttp.send(JSON.stringify({"user": user, "drainlist":name, "sources":sources}));
// xmlhttp.send();
}
function refresh(){
user = "Danny";
var url= "http://127.0.0.1:5000/refresh";
url = url + "?user=" + user;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
<file_sep>import requests, base64, time, os
import json
# put this in the DB as well NO GLOBALS!
myUrl = "http://127.0.0.1:5000/"
cwd = "/Users/Danny/Documents/CS/SpotifyAppend"
uri_header = "spotify:playlist:"
sec = [] # Secrets can be put in the db secrets table
with open(cwd + "/Secrets", "r") as infile:
for line in infile:
sec.append(line.strip())
client_id = sec[0]
client_secret= sec[1]
####################################
######## Spotify IO Code ##########
####################################
def get_playlists(access_token):
"""
Returns the playlists followed by a user
:param access_token: determines the user to edit securely
:return: all playlists followed by the user (list of dictionaries)
"""
url = "https://api.spotify.com/v1/me/playlists"
headers = {"Authorization": "Bearer " + access_token}
requests.get(url=url, headers=headers)
try:
all_playlists = requests.get(url=url, headers=headers).json()
return all_playlists["items"]
except:
print("unable to acquire playlist list")
def create_playlists(access_token, name):
"""
Creates a new playlist for the user to follow
:param access_token: securely determines the user
:param name: name for the new playlist
:return: URI of the newly generated playlist
"""
url = "https://api.spotify.com/v1/me/playlists"
headers = {"Authorization": "Bearer " + access_token}
resp = requests.post(url=url, data=json.dumps({"name":name}), headers=headers)
r = json.loads(resp.text)
return r["uri"]
def get_name(access_token, uri):
id = uri.split(":")[2]
url = "https://api.spotify.com/v1/playlists" + "/" + id
headers = {"Authorization": "Bearer " + access_token}
requests.get(url=url, headers=headers)
plist = requests.get(url=url, headers=headers).json()
return plist["name"]
def remove_playlist(access_token, uri):
"""
unfollows one the user's playlist with the given URI
:param access_token: securely determines the user
:param uri: Idenifies the playlist to be deleted
:return: Boolean of success
"""
id = uri.split(":")[2]
url = "https://api.spotify.com/v1/playlists/" + id + "/followers"
headers = {"Authorization": "Bearer " + access_token}
resp = requests.delete(url=url, headers=headers)
return resp.status_code == 200
def get_tracks(access_token, uri):
"""
gets the tracks from a user's playlist (public or private)
:param access_token: securely ID's the user
:return: returns a list of all track URI's
"""
playlist_id = uri.split(":")[2]
ret = []
url = "https://api.spotify.com/v1/playlists/" + playlist_id + "/tracks"
headers = {"Authorization": "Bearer " + access_token}
hasNext = 1
while hasNext:
tracks = requests.get(url=url, headers=headers)
jsonTrack = tracks.json()
ret += [jsonTrack["items"][i]["track"]["uri"] for i in range(len(jsonTrack["items"]))]
hasNext = jsonTrack["next"]
url = jsonTrack["next"]
return ret
def add_tracks_to_drain(access_token, drainlist, tracks):
"""
Takes a list of tracks and a drainlist URI and appends the tracks to the drainlist
:param access_token: Securely ID's User
:param drainlist: drainlist sink URI
:param tracks: list of track URI's to be added to the list
:return:
"""
track_list = split_list(tracks, 100)
# if there are no tracks this is still an empty list, iterate through split list and upload
id = drainlist.uri.split(":")[2]
for tracks in track_list:
trackstring = generate_uri_string(tracks)
url = "https://api.spotify.com/v1/playlists/%s/tracks?uris=%s" % (id, trackstring)
headers = {"Authorization": "Bearer " + access_token}
requests.post(url=url, headers=headers)
def remove_tracks_from_drain(access_token, drainlist, tracks):
"""
Takes a list of tracks and a drainlist URI and removes the tracks from the drainlist
:param access_token: Securely ID's User
:param drainlist: drainlist sink URI
:param tracks: list of track URI's to be removed from the list
:return:
"""
id = drainlist.uri.split(":")[2]
track_list = split_list(tracks, 100)
for tracks in track_list:
url = "https://api.spotify.com/v1/playlists/" + id + "/tracks"
headers = {"Authorization": "Bearer " + access_token}
data = {"tracks":[{"uri":track} for track in tracks]}
requests.delete(url=url, headers=headers, json=data)
else:
return "no tracks"
####################################
###### End Spotify IO Code ########
####################################
####################################
########### Utilities #############
####################################
def split_list(tracks, splitsize):
"""
Splits a list of tracks into sublists smaller than splitsize
splitting is greedy, tracks are split into splitsize chunks
until fewer than splitsize remain resulting in a smaller final sublist
:param tracks: list of tracks URI's
:param splitsize: max size of the returned sublists
:return: list of lists of tracks
"""
tracks = list(tracks)
end = splitsize
ret = []
front = 0
while (front < len(tracks)):
ret += [tracks[front:end]]
front = end
end = min(len(tracks), end + splitsize)
return ret
def generate_uri_string(tracks):
"""
changes a list of tracks into a properly formatted uri string for bulk loads
:param tracks: list of tracks URI's
:return: a formatted string to be used in HTTP requests
"""
return "%2C".join(tracks)
####################################
###### Token Handling Code #########
####################################
##### User Interaction Token Code #####
# todo UI token code will be moved back to spotify.py or into another file
# backend Token code =/= templates token code, for the backend if the tokens are hosed
# just give up and cry
def get_tokens_from_code(code):
"""
Interim function, takes a "code" returned from the spotify auth API and acquires the users tokens
:param code: auth string from Spotify API
:return: POSTs the code and returns the response, containing the tokens
"""
url = "https://accounts.spotify.com/api/token/"
params = {"grant_type": "authorization_code", "code": code, "redirect_uri": myUrl + "authentication_return"}
headers = make_authorization_headers(client_id, client_secret)
return requests.post(url=url, data=params, headers=headers)
# Builds the Authentication URL and redirects the user there, so more tokens can be gathered
def get_new_tokens():
url = "https://accounts.spotify.com/authorize/"
scopes = "playlist-read-private playlist-modify-public playlist-modify-private playlist-read-collaborative user-follow-read"
params = { "client_id": client_id, "response_type": "code", "redirect_uri": myUrl + "authentication_return", "scope": scopes}
a = requests.get(url=url, params=params)
return a
##### End User Interaction Token Code #####
def write_new_tokens(user, tokenJson):
with tokenfile_open(user, "w+") as tokenfile:
new_token = {}
new_token["access_token"] = tokenJson["access_token"]
ttl = tokenJson["expires_in"]
new_token["expires_at_epoch"] = ttl + int(time.time())
if "refresh_token" in tokenJson:
new_token["refresh_token"] = tokenJson["refresh_token"]
json.dump(new_token, tokenfile)
def get_access_token(user):
# access the users token file
with tokenfile_open(user) as tokenfile:
tokens = json.load(tokenfile)
# if DNE then allow FNF exception to propogate
# if FNF then we need intervention to get new tokens which is out of scope for this file
# if the file is aged out then refresh and update the file
if tokens["expires_at_epoch"] < int(time.time()) + 60 * 5:
access_token , ttl = refresh_tokens(user)
tokens["access_token"] = access_token
tokens["expires_at_epoch"] = ttl + int(time.time())
with tokenfile_open(user, "w+") as tokenfile:
json.dump(tokens, tokenfile)
# finally return the token
return tokens["access_token"]
def get_refresh_token(user):
with tokenfile_open(user) as tokenfile:
tokens = json.load(tokenfile)
return tokens["refresh_token"]
# PURE SPOTIFY API CALL
def refresh_tokens(user):
url = "https://accounts.spotify.com/api/token/"
data = {"grant_type" : "refresh_token", "refresh_token" : get_refresh_token(user)}
headers = make_authorization_headers(client_id, client_secret)
resp = requests.post(url=url, data = data, headers = headers).json()
return resp["access_token"], resp["expires_in"]
def tokenfile_open(user, flag="r"):
return open(user + "/" + user + "_tokens", flag)
def make_authorization_headers(client_id, client_secret):
auth_header = base64.b64encode(str(client_id + ':' + client_secret).encode('ascii'))
return {'Authorization': 'Basic %s' % auth_header.decode('ascii')}
####################################
#### End Token Handling Code #######
####################################
def print_sources(sources):
return [{"Name":s.name, "URI":s.uri} for s in sources]
####################################
######### End Utilities ###########
#################################### | 28d8a659f246ecef90324aa2f1887370a6013cbc | [
"Markdown",
"Python",
"JavaScript"
] | 6 | Python | danny-white/SpotifyAppend | f85c31f063b4f95dab7a4e3952a75184e70a8c1e | 9624de0c790af96bde051dce96a40f741a52b268 |
refs/heads/master | <file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Text;
using System.Diagnostics;
namespace DownloadFile.UnitTest {
[TestClass]
public class DownloadFileTests {
// N.B: You need at least a 6Mbit/s speed connection to be able to pass the 'speed throttling' tests
// Link where you can find the files used for the tests: https://www.thinkbroadband.com/download
string OutputPath = String.Format(@"{0}\{1}\", Directory.GetCurrentDirectory(), "Unit Tests");
// 5MB File Test
const string URL_5MBFile = "http://ipv4.download.thinkbroadband.com/5MB.zip";
const string Name_5MBFile = "5MBFile_UnitTest.bin";
// 10MB File Test
const string URL_10MBFile = "http://ipv4.download.thinkbroadband.com/10MB.zip";
const string Name_10MBFile = "10MBFile_UnitTest.bin";
// 20MB File Test
const string URL_20MBFile = "http://ipv4.download.thinkbroadband.com/20MB.zip";
const string Name_20MBFile = "20MBFile_UnitTest.bin";
/// <summary>
/// Creates the directory where the test files will be downloaded and delete the old test files
/// </summary>
/// <param name="fullFilePath">The full local path of the current file being tested</param>
private void VerifyResources(string fullFilePath) {
if (File.Exists(fullFilePath))
File.Delete(fullFilePath);
if (!Directory.Exists(OutputPath))
Directory.CreateDirectory(OutputPath);
}
/// <summary>
/// Returns the digest hash derived from the test file using the MD5 algorithm
/// </summary>
/// <param name="fullFilePath">The full local path of the current file being tested</param>
private string GetMD5DigestHash(string fullFilePath) {
byte[] hash = (new System.Security.Cryptography.MD5CryptoServiceProvider()).ComputeHash(File.ReadAllBytes(fullFilePath));
var sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
sb.Append(hash[i].ToString("x2"));
return sb.ToString();
}
/*********************************************************************************************************************************************************/
[TestMethod]
public void VerifyIntegrity_5MBFile() {
// Arrange
string fullPath = String.Format("{0}{1}", OutputPath, Name_5MBFile);
const string expected_md5Digest = "b3215c06647bc550406a9c8ccc378756";
VerifyResources(fullPath);
// Act
HTTPDownloader.DownloadFile(URL_5MBFile, OutputPath, Name_5MBFile);
// Assert
Assert.AreEqual(expected_md5Digest, GetMD5DigestHash(fullPath));
}
[TestMethod]
public void VerifyIntegrity_10MBFile() {
// Arrange
string fullPath = String.Format("{0}{1}", OutputPath, Name_10MBFile);
const string expected_md5Digest = "3aa55f03c298b83cd7708e90d289afbd";
VerifyResources(fullPath);
// Act
HTTPDownloader.DownloadFile(URL_10MBFile, OutputPath, Name_10MBFile);
// Assert
Assert.AreEqual(expected_md5Digest, GetMD5DigestHash(fullPath));
}
[TestMethod]
public void VerifyIntegrity_20MBFile() {
// Arrange
string fullPath = String.Format("{0}{1}", OutputPath, Name_20MBFile);
const string expected_md5Digest = "9017804333c820e3b4249130fc989e00";
VerifyResources(fullPath);
// Act
HTTPDownloader.DownloadFile(URL_20MBFile, OutputPath, Name_20MBFile);
// Assert
Assert.AreEqual(expected_md5Digest, GetMD5DigestHash(fullPath));
}
/*********************************************************************************************************************************************************/
[TestMethod]
public void VerifyThrottleFeature_5MBFile_1Mbit() {
// Arrange
string fullPath = String.Format("{0}{1}", OutputPath, Name_5MBFile);
long[] expected_timingResult = { 36 * 1000, 46 * 1000}; // If the program has access to the full speed of your internet connection (in this case 1Mbit/s)
// the download should take ~41 seconds.
// But in a real world scenario, the connection speed can change second by second,
// so in order to claim the test a success, the download should finish between 36 and 46 seconds.
var stopWatch = new Stopwatch();
VerifyResources(fullPath);
// Act
stopWatch.Start();
HTTPDownloader.DownloadFile(URL_5MBFile, OutputPath, Name_5MBFile, 125000); // The download speed will be limited to 1Mbit/s
stopWatch.Stop();
// Assert
Assert.IsTrue(stopWatch.ElapsedMilliseconds >= expected_timingResult[0] && stopWatch.ElapsedMilliseconds <= expected_timingResult[1]);
}
[TestMethod]
public void VerifyThrottleFeature_10MBFile_2Mbit() {
// Arrange
string fullPath = String.Format("{0}{1}", OutputPath, Name_10MBFile);
long[] expected_timingResult = { 36 * 1000, 46 * 1000 }; // If the program has access to the full speed of your internet connection (in this case 2Mbit/s)
// the download should take ~41 seconds.
// But in a real world scenario, the connection speed can change second by second,
// so in order to claim the test a success, the download should finish between 36 and 46 seconds.
var stopWatch = new Stopwatch();
VerifyResources(fullPath);
// Act
stopWatch.Start();
HTTPDownloader.DownloadFile(URL_10MBFile, OutputPath, Name_10MBFile, 250000); // The download speed will be limited to 2Mbit/s
stopWatch.Stop();
// Assert
Assert.IsTrue(stopWatch.ElapsedMilliseconds >= expected_timingResult[0] && stopWatch.ElapsedMilliseconds <= expected_timingResult[1]);
}
[TestMethod]
public void VerifyThrottleFeature_20MBFile_4Mbit() {
// Arrange
string fullPath = String.Format("{0}{1}", OutputPath, Name_20MBFile);
long[] expected_timingResult = { 36 * 1000, 46 * 1000 }; // If the program has access to the full speed of your internet connection (in this case 4Mbit/s)
// the download should take ~41 seconds.
// But in a real world scenario, the connection speed can change second by second,
// so in order to claim the test a success, the download should finish between 36 and 46 seconds.
var stopWatch = new Stopwatch();
VerifyResources(fullPath);
// Act
stopWatch.Start();
HTTPDownloader.DownloadFile(URL_20MBFile, OutputPath, Name_20MBFile, 500000); // The download speed will be limited to 4Mbit/s
stopWatch.Stop();
// Assert
Assert.IsTrue(stopWatch.ElapsedMilliseconds >= expected_timingResult[0] && stopWatch.ElapsedMilliseconds <= expected_timingResult[1]);
}
}
}<file_sep>using System;
using System.IO;
using System.Threading;
using System.Diagnostics;
namespace HTTP_Downloader {
public class Program {
public static class _Debug {
// Used to track the time elapsed for the whole work
public static Stopwatch _Stopwatch = new Stopwatch();
/// <summary>
/// Writes to the console the given message
/// </summary>
/// <param name="message">The string to be written to the console</param>
public static void WriteFatalError(string message) {
Console.WriteLine("{0}\nPress any key to exit...", message);
Console.ReadKey();
Environment.Exit(1);
}
/// <summary>
/// Parse an argument and returns his value
/// </summary>
/// <param name="parameter">The character which identifies the start of the argument (Like '-f')</param>
/// <param name="args">The array which contains the arguments</param>
public static string GetArgument(char parameter, string[] args) {
string argValue = null;
for (int i = 0; i < args.Length; i++) {
if (args[i] == $"-{parameter}") {
try {
if (!String.IsNullOrEmpty(args[i + 1])) {
if (args[i + 1].StartsWith("\"")) {
for (int j = i + 1; j < args.Length; j++) {
argValue += args[j];
if (args[j].EndsWith("\""))
break;
}
} else
argValue = args[i + 1];
}
} catch {
WriteFatalError($"The '{parameter}' parameter is empty!");
break;
}
break;
}
}
return argValue;
}
}
static void Main(string[] args) {
/*args = new string[8];
args[0] = "-f";
args[1] = @"C:\Users\Mutu.A\Desktop\urls.txt"; // URLs list file
args[2] = "-o";
args[3] = @"C:\Users\Mutu.A\Desktop\test"; // Output directory
args[4] = "-n";
args[5] = "2"; // Number of concurrent threads
args[6] = "-l";
args[7] = "0"; // Speed limit*/
// Parsing the given arguments
string URLsFileList = _Debug.GetArgument('f', args);
string DownloadedFiles_OutputDirectory = _Debug.GetArgument('o', args);
uint Maximum_DownloadSpeedBytes = uint.MaxValue;
if (!UInt32.TryParse(_Debug.GetArgument('l', args), out Maximum_DownloadSpeedBytes))
_Debug.WriteFatalError("The '-l' parameter must be an (unsigned) integer (32-bit)");
else
if (Maximum_DownloadSpeedBytes < 62500 && Maximum_DownloadSpeedBytes != 0) // Minimum speed throttling : 0.5Mbit/s
Maximum_DownloadSpeedBytes = 62500;
else if (Maximum_DownloadSpeedBytes == 0) // 0 = no speed limit
Maximum_DownloadSpeedBytes = uint.MaxValue;
if (!Byte.TryParse(_Debug.GetArgument('n', args), out HTTPDownloader.Maximum_NumberOfConcurrentThreads))
_Debug.WriteFatalError("The '-n' parameter must be an (unsigned) integer (8-bit)!");
else
if (HTTPDownloader.Maximum_NumberOfConcurrentThreads == 0)
HTTPDownloader.Maximum_NumberOfConcurrentThreads = 1;
if (String.IsNullOrEmpty(URLsFileList))
_Debug.WriteFatalError("You must add the full path where the URLs list file is!");
if (String.IsNullOrEmpty(DownloadedFiles_OutputDirectory))
_Debug.WriteFatalError("You must add the full path where the downloaded files would be saved!");
Console.WriteLine("\nMaximum download speed: {0:0.0} Mbit/s => {1} bytes/s\n", Maximum_DownloadSpeedBytes / 125000F, Maximum_DownloadSpeedBytes);
_Debug._Stopwatch.Start();
// Parsing the file which contains the URLs list
// Before starting: We verify the existence of the 'Output Directory'/'URLs List File'
if (!Directory.Exists(DownloadedFiles_OutputDirectory))
_Debug.WriteFatalError("The output directory where the downloaded files would be saved doesn't exists!");
if (File.Exists(URLsFileList)) {
// Enumerating the lines in the file
foreach (string _s in File.ReadAllLines(URLsFileList)) {
if (!String.IsNullOrEmpty(_s)) {
string url = _s.Substring(0, _s.IndexOf(' ')); // Gets the URL from the current line
string fileName = _s.Substring(_s.IndexOf(' ') + 1); // Gets the local file name from the current line
// If the working threads are less than the maximum working threads allowed...
if (HTTPDownloader.Current_NumberOfConcurrentThreads < HTTPDownloader.Maximum_NumberOfConcurrentThreads) {
// We start a new working thread where the file should be downloaded
// Passing as parameters the URL, Output Directory, Local File Name and optionally the maximum speed limit
Thread downloadFileThread = new Thread(() => HTTPDownloader.DownloadFile(url, DownloadedFiles_OutputDirectory, fileName, Maximum_DownloadSpeedBytes));
downloadFileThread.Start();
// We need to keep track of the active working threads to simulate a queue list
HTTPDownloader.Current_NumberOfConcurrentThreads++;
}
// Until all threads are busy, we block the foreach loop
while (HTTPDownloader.Current_NumberOfConcurrentThreads >= HTTPDownloader.Maximum_NumberOfConcurrentThreads)
// Used to avoid overload of the CPU
Thread.Sleep(1);
}
}
} else
_Debug.WriteFatalError("Unable to find the file which contains the URLs list!");
// Blocking the main thread
while (true) {
if (HTTPDownloader.Current_NumberOfConcurrentThreads == 0) {
_Debug._Stopwatch.Stop();
Console.WriteLine("\n\nTime elapsed for the whole work: {0}\n", _Debug._Stopwatch.Elapsed);
break;
}
Thread.Sleep(1);
}
Console.WriteLine("Done! Press any key to exit...");
Console.ReadKey();
}
}
}<file_sep>using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Diagnostics;
public static class HTTPDownloader {
/// <summary>
/// Keeps track of the current amount of threads which are busy downloading a file
/// </summary>
public static byte Current_NumberOfConcurrentThreads;
/// <summary>
/// Maximum amount of possible simultaneous downloads
/// </summary>
public static byte Maximum_NumberOfConcurrentThreads = 1;
/// <summary>
/// Returns the response stream from the request
/// </summary>
private static Stream GetResponseStream(ref HttpWebRequest request) {
return request.GetResponse().GetResponseStream();
}
/// <summary>
/// Downloads a file using the HTTP Protocol. Returns true if the operation succeed
/// </summary>
/// <param name="url">URL of the file to be downloaded</param>
/// <param name="outputDirectory">Directory where to save the downloaded file</param>
/// <param name="fileName">The local name of the downloaded file</param>
/// <param name="maximum_DownloadSpeedBytes">The maximum speed in bytes per second</param>
public static void DownloadFile(string url, string outputDirectory, string fileName, uint maximum_DownloadSpeedBytes = uint.MaxValue) {
// Used to measure the elapsed time of the downloaded file
Stopwatch _stopWatch = new Stopwatch();
_stopWatch.Start();
try {
string filePath = String.Format("{0}\\{1}", outputDirectory.TrimEnd('\\'), fileName);
if (!File.Exists(filePath)) {
Console.WriteLine("[INFO]: Downloading the '{0}' file...", fileName);
// We create the request by using the 'get' method
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = WebRequestMethods.Http.Get;
// We need to set also an User Agent to avoid a 403 error response from the server
httpWebRequest.UserAgent = ".NET Framework HTTP Protocol Download File Test";
// By default the maximum connection allowed at once is limited to 2, we need to extend it using the value of the 'Maximum_NumberOfConcurrentThreads'
ServicePointManager.DefaultConnectionLimit = Maximum_NumberOfConcurrentThreads;
// Gets the 'Stream' from the response
using (Stream stream = GetResponseStream(ref httpWebRequest)) {
// Initializes the 'FileStream' which will write the data into the file
using (FileStream fileStream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read)) {
// Initializes the buffer which will contain the received data
const int buffSize = 4096;
byte[] buff = new byte[buffSize];
// The amount of data read from the chunk
int bytesRead = 0;
// The total amount of data which was read until the reaching of the speed limit (if the case)
uint totBytesRead = 0;
// This variable will contain the ticks passed from receiving the chunks of data until the speed limit will be reached within a second
long ticksPassedReachedSpeedLimit = DateTime.Now.Ticks;
while ((bytesRead = stream.Read(buff, 0, buffSize)) != 0) {
fileStream.Write(buff, 0, bytesRead);
totBytesRead += (uint)bytesRead;
// When the 'totBytesRead' value reaches the maximum download speed limit within a second,
// we use 'Thread.Sleep()' to throttle the speed which the file are being written.
// The value passed to 'Thread.Sleep()' is the amount of ms left within the current second
// The formula used for the throttling speed feature is the below:
// c - ((x - y) / c1) = ms
// Where:
// c => 1000 milliseconds (constant)
// x => 'DateTime.Now' in ticks
// y => 'ticksPassedReachedSpeedLimit'
// c1 => 10000 milliseconds (constant)
// ms => The value passed to 'Thread.Sleep()'
if (totBytesRead > maximum_DownloadSpeedBytes && (DateTime.Now.Ticks - ticksPassedReachedSpeedLimit) <= TimeSpan.TicksPerSecond) {
Thread.Sleep((int)(1000 - ((DateTime.Now.Ticks - ticksPassedReachedSpeedLimit) / 10000)));
totBytesRead = 0;
ticksPassedReachedSpeedLimit = DateTime.Now.Ticks;
}
}
}
}
} else
Console.WriteLine("[WARNING]: A file with the same name as the '{0}' already exists!", fileName);
} catch (Exception e) {
Console.WriteLine("[EXCEPTION : {0}]: Unable to download the '{1}' file!", e.Message, fileName);
}
_stopWatch.Stop();
// Now the main thread knows that a thread is free to download a new file
Current_NumberOfConcurrentThreads--;
Console.WriteLine("[INFO]: Download of the '{0}' file completed |> ELAPSED: {1}", fileName, _stopWatch.Elapsed);
}
} | a5dcf1b7e83cfefa4d07ee2d3fe7b4b4fee8a75a | [
"C#"
] | 3 | C# | polytronicgr/HTTP-Downloader | ceefd261b4b5295d1daa73db1ce43b8a1867d97b | 79ab3627a057259dfcb14b2ef38b2f9322d58226 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import './App.css';
import TopNav from './TopNav';
import PersonalCard from './PersonalCard';
import SkillSet from './SkillSet';
class App extends Component {
render() {
return (
<div className="App">
<TopNav/>
<PersonalCard/>
<SkillSet categories={this.getSkillSet()} skills={this.getUserSkills()}/>
</div>
);
}
getSkillSet() {
return [
{key: 'resilience', label: 'Resilience'},
{key: 'strength', label: 'Strength'},
{key: 'adaptability', label: 'Adaptability'},
{key: 'creativity', label: 'Creativity'},
{key: 'openness', label: 'Open to Change'},
{key: 'confidence', label: 'Confidence'}
];
}
getUserSkills() {
return {
resilience: 6,
strength: 10,
adaptability: 6,
creativity: 7,
openness: 0,
confidence: 10,
};
}
}
export default App;
<file_sep>import React, { Component } from 'react';
import './SkillSet.css';
import Skill from './Skill';
import { gql, graphql } from 'react-apollo';
class SkillSet extends Component {
constructor(props) {
super(props);
this.props = props;
}
render() {
return (
<ul className="skill-set">
{this.getCategories()}
</ul>
);
}
getCategories() {
const { data } = this.props;
console.log(data);
return data.allCategories ? data.allCategories.map((s, i) => {
return <li key={s.id}>
<Skill title={s.name} skills={s.skills} />
</li>
}) : null;
}
}
const query = gql`query Categories { allCategories { id name skills { id name description level1 level2 level3 level4 level5 } } }`
export default graphql(query)(SkillSet);<file_sep>import React, { Component } from 'react';
import './PersonalInfo.css';
class PersonalInfo extends Component {
constructor(props) {
super(props);
this.props = props;
}
render() {
return (
<div className="personal-info">
<img src="https://pbs.twimg.com/profile_images/766330229174390784/cdcY3bdn_400x400.jpg" alt="profile"/>
<div className="info-list">
<p className="info-item primary"><NAME></p>
<p className="info-item secondary"><span>Title</span>Web developer</p>
<p className="info-item secondary"><span>Manager</span><NAME></p>
<p className="info-item secondary"><span>Team</span>Discover</p>
</div>
</div>
);
}
}
export default PersonalInfo;<file_sep>import React, { Component } from 'react';
import Radar from 'react-d3-radar';
import './Chart.css';
class Chart extends Component {
constructor(props) {
super(props);
this.props = props;
}
render() {
return (
<div className="Chart">
<Radar
width={this.props.width}
height={this.props.height}
padding={this.props.padding}
domainMax={this.props.maxSkillLevel}
highlighted={null}
onHover={(point) => {
if (point) {
console.log(`${point.variableKey}: ${point.value}`);
}
}}
data={{
variables: this.props.skillSet,
sets: [{
key: 'me',
label: 'My Skills',
values: this.props.userSkills
}],
}}
/>
</div>
);
}
}
export default Chart;<file_sep>import React, { Component } from 'react';
import { RadioGroup, Radio } from 'react-radio-group';
class Skill extends Component {
constructor(props) {
super(props);
this.props = props;
console.log(props);
}
render() {
const { title } = this.props;
return (
<div>
<h2>{title}</h2>
{this.renderSkills()}
</div>
);
}
handleChange(_) {
console.log(_);
}
renderSkills() {
return this.props.skills.map(s => {
return (<div key={s.id}>
<h3>{s.name}</h3>
<RadioGroup name={s.name} onChange={this.handleChange}>
<Radio value="1" />{s.level1}
<Radio value="2" />{s.level2}
<Radio value="3" />{s.level3}
<Radio value="4" />{s.level4}
<Radio value="5" />{s.level5}
</RadioGroup>
</div>);
});
}
}
export default Skill; | 875a3f08825b032f4c26bb36f2f355db49d5e31f | [
"JavaScript"
] | 5 | JavaScript | MartinSandholt/holi | b4f5e53b7d4aa8d6a8dc88058296d55a1c856093 | e4d3405361dca7e88e097403b5be91001017bb3d |
refs/heads/master | <file_sep>import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// Read stories
System.out.println("Reading stories...");
ArrayList<Story> stories = readStories(args[0]);
System.out.println("Reading stories DONE.");
// Calculate tf-idf scores
System.out.println("Calculating tf-idf scores...");
ArrayList<ArrayList<HashMap<String, Double>>> tfIdfScores = calculateTfIdf(stories);
System.out.println("Calculating tf-idf scores DONE.");
// Build the cosine similarity matrix.
System.out.println("Calculating similarities...");
ArrayList<ArrayList<ArrayList<Double>>> similarities = buildSimilarityMatrices(stories, tfIdfScores);
System.out.println("Calculating similarities DONE.");
// Build the adjacency matrix
System.out.println("Building adjacency matrix...");
ArrayList<ArrayList<ArrayList<Integer>>> adjacencyMatrix = buildAdjacencyMatrix(similarities);
System.out.println("Building adjacency matrix DONE.");
// Probabilities with teleportation
System.out.println("Building transition matrix with teleportation...");
ArrayList<ArrayList<ArrayList<Double>>> transitionMatrix = buildTransitionMatrix(adjacencyMatrix, 0.15);
System.out.println("Building transition matrix with teleportation DONE.");
// Power method
System.out.println("Applying the power method...");
ArrayList<ArrayList<Double>> distributions = applyPowerMethod(transitionMatrix);
System.out.println("Applying the power method DONE.");
System.out.println(distributions.get(Integer.parseInt(args[1].split("\\.")[0])-1).toString());
// Create reference files for Rouge.
/*
for (int i = 1; i <= stories.size(); i++) {
String taskName = "news" + i;
try {
PrintWriter writer = new PrintWriter(taskName + "_reference1.txt", "UTF-8");
for (int j = 1; j <= stories.get(i-1).summary.size(); j++) {
writer.println(stories.get(i-1).summary.get(j-1));
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
*/
// Create system files for Rouge.
/*
for (int i = 1; i <= stories.size(); i++) {
String taskName = "news" + i;
ArrayList<Double> dist = distributions.get(i-1);
// Find the highest 3.
int highest1 = 0, highest2 = 1, highest3 = 2;
for (int k = 3; k < dist.size(); k++) {
if (dist.get(k) > dist.get(highest3)) {
highest3 = k;
}
if (dist.get(highest3) > dist.get(highest2)) {
int temp = highest3;
highest3 = highest2;
highest2 = temp;
}
if (dist.get(highest2) > dist.get(highest1)) {
int temp = highest2;
highest2 = highest1;
highest1 = temp;
}
}
try {
PrintWriter writer = new PrintWriter(taskName + "_system1" + ".txt", "UTF-8");
writer.println(stories.get(i-1).sentences.get(highest1));
writer.println(stories.get(i-1).sentences.get(highest2));
writer.println(stories.get(i-1).sentences.get(highest3));
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
*/
// Calculate average precision, recall and f score values.
/*
Scanner in = new Scanner(new File("Dataset/results.txt"));
System.out.println(in.nextLine());
double Avg_Recall1 = 0, Avg_Precision1=0, Avg_FScore1=0;
double Avg_Recall2 = 0, Avg_Precision2=0, Avg_FScore2=0;
double Avg_RecallL = 0, Avg_PrecisionL=0, Avg_FScoreL=0;
while (in.hasNextLine()) {
String line = in.nextLine();
in.nextLine();
String[] parts = line.split(",");
if (parts[0].equals("ROUGE-L+StopWordRemoval")) {
Avg_RecallL += Double.parseDouble(parts[3]);
Avg_PrecisionL += Double.parseDouble(parts[4]);
Avg_FScoreL += Double.parseDouble(parts[5]);
}
if (parts[0].equals("ROUGE-1+StopWordRemoval")) {
Avg_Recall1 += Double.parseDouble(parts[3]);
Avg_Precision1 += Double.parseDouble(parts[4]);
Avg_FScore1 += Double.parseDouble(parts[5]);
}
if (parts[0].equals("ROUGE-2+StopWordRemoval")) {
Avg_Recall2 += Double.parseDouble(parts[3]);
Avg_Precision2 += Double.parseDouble(parts[4]);
Avg_FScore2 += Double.parseDouble(parts[5]);
}
}
System.out.println(Avg_Recall1/1000 + ", " + Avg_Precision1/1000 + ", " + Avg_FScore1/1000);
System.out.println(Avg_Recall2/1000 + ", " + Avg_Precision2/1000 + ", " + Avg_FScore2/1000);
System.out.println(Avg_RecallL/1000 + ", " + Avg_PrecisionL/1000 + ", " + Avg_FScoreL/1000);
*/
}
/**
* Applies the power method to all documents.
*/
private static ArrayList<ArrayList<Double>> applyPowerMethod(ArrayList<ArrayList<ArrayList<Double>>> transitionMatrix) {
ArrayList<ArrayList<Double>> distributions = new ArrayList<>();
for (int docId = 0; docId < transitionMatrix.size(); docId++) {
ArrayList<Double> initialDistribution = new ArrayList<>();
initialDistribution.add(1.0);
for (int i = 1; i < transitionMatrix.get(docId).size(); i++) {
initialDistribution.add(0.0);
}
distributions.add(powerMethod(initialDistribution, transitionMatrix.get(docId)));
}
return distributions;
}
/**
* Recursively calls itself until the distribution is stabilized.
*/
private static ArrayList<Double> powerMethod(ArrayList<Double> distribution,
ArrayList<ArrayList<Double>> transition) {
// Iterate
ArrayList<Double> newDistribution = multiply(distribution, transition);
// Check if it is stabilized.
double distance = 0;
for (int i = 0; i < distribution.size(); i++) {
distance += (distribution.get(i) - newDistribution.get(i))*(distribution.get(i) - newDistribution.get(i));
}
distance = Math.sqrt(distance);
// Iterate if not stabilized.
if (distance > 0.00001) {
return powerMethod(newDistribution, transition);
} else {
return newDistribution;
}
}
/**
* Standard matrix multiplication.
*/
private static ArrayList<Double> multiply(ArrayList<Double> distribution,
ArrayList<ArrayList<Double>> transition) {
ArrayList<Double> newDistribution = new ArrayList<>();
for (int i = 0; i < transition.size(); i++) {
double value = 0;
for (int j = 0; j < distribution.size(); j++) {
value += distribution.get(j) * transition.get(j).get(i);
}
newDistribution.add(value);
}
return newDistribution;
}
/**
* Takes in the adjacency matrix and teleportation rate.
* Builds the transition matrix.
*/
private static ArrayList<ArrayList<ArrayList<Double>>> buildTransitionMatrix(
ArrayList<ArrayList<ArrayList<Integer>>> adjacencyMatrix, double teleportationRate) {
ArrayList<ArrayList<ArrayList<Double>>> transitionMatrix = new ArrayList<>();
for (int docId = 0; docId < adjacencyMatrix.size(); docId++) {
ArrayList<ArrayList<Double>> transitionMatrixForDocument = new ArrayList<>();
for (int lineId = 0; lineId < adjacencyMatrix.get(docId).size(); lineId++) {
// Start with distributing the teleportation rate.
ArrayList<Double> transitionLine = new ArrayList<>(
Collections.nCopies(adjacencyMatrix.get(docId).get(lineId).size(),
teleportationRate/adjacencyMatrix.get(docId).get(lineId).size()));
// Count the edges.
int edgeCount = 0;
for (int edge : adjacencyMatrix.get(docId).get(lineId)) {
if (edge == 1) {
edgeCount++;
}
}
// Distribute remaining possibilities to the edges.
for (int i = 0; i < transitionLine.size(); i++) {
if (adjacencyMatrix.get(docId).get(lineId).get(i) == 1) {
transitionLine.set(i, transitionLine.get(i) + (1-teleportationRate)/edgeCount);
}
}
// Add the line to the document.
transitionMatrixForDocument.add(transitionLine);
}
// Add the document to the matrix.
transitionMatrix.add(transitionMatrixForDocument);
}
return transitionMatrix;
}
/**
* Adds an edge between sentences if they have a similarity more than 0.10.
*/
private static ArrayList<ArrayList<ArrayList<Integer>>> buildAdjacencyMatrix(ArrayList<ArrayList<ArrayList<Double>>> similarities) {
ArrayList<ArrayList<ArrayList<Integer>>> adjacencyMatrix = new ArrayList<>();
for (int docId = 0; docId < similarities.size(); docId++) {
ArrayList<ArrayList<Integer>> adjacencyForDocument = new ArrayList<>();
for (int sentence1 = 0; sentence1 < similarities.get(docId).size(); sentence1++) {
ArrayList<Integer> adjacencyForSentence = new ArrayList<>();
for (int sentence2 = 0; sentence2 < similarities.get(docId).get(sentence1).size(); sentence2++) {
if (similarities.get(docId).get(sentence1).get(sentence2) > 0.10) {
adjacencyForSentence.add(1);
} else {
adjacencyForSentence.add(0);
}
}
adjacencyForDocument.add(adjacencyForSentence);
}
adjacencyMatrix.add(adjacencyForDocument);
}
return adjacencyMatrix;
}
/**
* Builds a similarity matrix for all documents.
*/
private static ArrayList<ArrayList<ArrayList<Double>>> buildSimilarityMatrices(ArrayList<Story> stories,
ArrayList<ArrayList<HashMap<String, Double>>> tfIdfScores) {
// <i, j, k> => in document i, similarity of sentence j to sentence k.
ArrayList<ArrayList<ArrayList<Double>>> similarities = new ArrayList<>();
for (int i = 0; i < stories.size(); i++) {
similarities.add(buildSimilarityMatrix(stories.get(i), tfIdfScores.get(i)));
}
return similarities;
}
/**
* Builds a similarity matrix for one document.
*/
private static ArrayList<ArrayList<Double>> buildSimilarityMatrix(Story story, ArrayList<HashMap<String,Double>> tfIdfForSentences) {
ArrayList<ArrayList<Double>> similarities = new ArrayList<>();
for (int i = 0; i < story.sentences.size(); i++) {
ArrayList<Double> similarityVector = new ArrayList<>();
for (int j = 0; j < story.sentences.size(); j++) {
similarityVector.add(cosineSimilarity(tfIdfForSentences.get(i), tfIdfForSentences.get(j)));
}
similarities.add(similarityVector);
}
return similarities;
}
/**
* Calculates cosine similarity between two tf-idf vectors.
*/
private static double cosineSimilarity(HashMap<String, Double> tfIdf1, HashMap<String, Double> tfIdf2) {
tfIdf1 = normalizeVector(tfIdf1);
tfIdf2 = normalizeVector(tfIdf2);
double similarity = 0;
for (String word : tfIdf1.keySet()) {
if (tfIdf2.containsKey(word)) {
similarity += tfIdf1.get(word) * tfIdf2.get(word);
}
}
return similarity;
}
/**
* Normalizes given vector
*/
private static HashMap<String, Double> normalizeVector(HashMap<String, Double> tfIdf) {
// Calculate length
double length = 0;
for (double value : tfIdf.values()) {
length += value*value;
}
length = Math.sqrt(length);
// Normalize
HashMap<String, Double> normalized = new HashMap<>();
for (String key : tfIdf.keySet()) {
normalized.put(key, tfIdf.get(key)/length);
}
return normalized;
}
/**
* Calculates tf-idf scores for each word in story set.
*/
private static ArrayList<ArrayList<HashMap<String, Double>>> calculateTfIdf(ArrayList<Story> stories) {
// < Word : # of d containing the word >.
HashMap<String, Integer> df = new HashMap<>();
// Array of < Word : # of times term occurs in sentence > for each doc
ArrayList<ArrayList<HashMap<String, Integer>>> tf = new ArrayList<>();
for (Story story : stories) {
// Array of < Word : # of times term occurs in sentence > for this doc
ArrayList<HashMap<String, Integer>> docTf = new ArrayList<>();
// Dictionary for the document.
HashSet<String> docDict = new HashSet<>();
for (String line : story.sentences) {
// < Word : # of times term occurs in sentence >
HashMap<String, Integer> sentenceTf = new HashMap<>();
for (String word : normalizeText(line).split(" ")) {
// Remove single char words
if (word.length() < 2) {
continue;
}
if (sentenceTf.containsKey(word)) {
sentenceTf.put(word, sentenceTf.get(word) + 1);
} else {
sentenceTf.put(word, 1);
}
docDict.add(word);
}
// Add this sentence's term frequencies.
docTf.add(sentenceTf);
}
// Add this document's term frequencies.
tf.add(docTf);
// Update this story's words' df.
for (String word : docDict) {
if (df.containsKey(word)) {
df.put(word, df.get(word) + 1);
} else {
df.put(word, 1);
}
}
}
// Calculate idf from df scores.
HashMap<String, Double> idf = new HashMap<>();
for (String word : df.keySet()) {
idf.put(word, Math.log10(1000.0/df.get(word)));
}
// Calculate tf-idf for all sentences.
ArrayList<ArrayList<HashMap<String, Double>>> tfIdf = new ArrayList<>();
for (int docId = 0; docId < tf.size(); docId++) {
ArrayList<HashMap<String, Double>> tfIdfForDoc = new ArrayList<>();
for (int sentenceId = 0; sentenceId < tf.get(docId).size(); sentenceId++) {
HashMap<String, Double> tfIdfForSentence = new HashMap<>();
for (String word : tf.get(docId).get(sentenceId).keySet()) {
double tfScore = tf.get(docId).get(sentenceId).get(word) == 0 ? 0 : 1 + Math.log10(tf.get(docId).get(sentenceId).get(word));
tfIdfForSentence.put(word, tfScore * idf.get(word));
}
tfIdfForDoc.add(tfIdfForSentence);
}
tfIdf.add(tfIdfForDoc);
}
return tfIdf;
}
/**
* Gets rid of punctuation.
*/
private static String normalizeText(String text) {
// Make text lowercase.
text = text.toLowerCase();
// Remove all punctuation marks and new lines.
text = text.replaceAll("\\.", " ");
text = text.replaceAll("\\,", " ");
text = text.replaceAll("\\'", " ");
text = text.replaceAll("\"", " ");
text = text.replaceAll("\\/", " ");
text = text.replaceAll("\\-", " ");
text = text.replaceAll("\\_", " ");
text = text.replaceAll("\\*", " ");
text = text.replaceAll("<", " ");
text = text.replaceAll(">", " ");
text = text.replaceAll(Pattern.quote("!"), " ");
text = text.replaceAll(Pattern.quote("?"), " ");
text = text.replaceAll(Pattern.quote(";"), " ");
text = text.replaceAll(Pattern.quote(":"), " ");
text = text.replaceAll(Pattern.quote("("), " ");
text = text.replaceAll(Pattern.quote(")"), " ");
text = text.replaceAll(Pattern.quote("="), " ");
text = text.replaceAll(Pattern.quote("$"), " ");
text = text.replaceAll(Pattern.quote("%"), " ");
text = text.replaceAll(Pattern.quote("#"), " ");
text = text.replaceAll(Pattern.quote("+"), " ");
text = text.replaceAll("\n", " ");
return text;
}
/**
* Returns array of stories.
*/
private static ArrayList<Story> readStories(String directoryLocation) {
ArrayList<Story> stories = new ArrayList<>();
for (int i = 1; i <= 1000; i++) {
stories.add(readStory(directoryLocation + "/" + i + ".txt"));
}
return stories;
}
/**
* Returns a single story.
*/
private static Story readStory(String fileLocation) {
Scanner in = null;
try {
in = new Scanner(new File(fileLocation));
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
}
Story story = new Story();
// Read story
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.equals("")) {
break;
}
story.sentences.add(line);
}
// Read summary
while (in.hasNextLine()) {
story.summary.add(in.nextLine());
}
in.close();
return story;
}
}
<file_sep>import java.util.ArrayList;
public class Story {
ArrayList<String> sentences = new ArrayList<>();
ArrayList<String> summary = new ArrayList<>();
}
<file_sep>/**
* <NAME>
* 2013400090
*/
For detailed explanation about the project, please refer to the project report.
To run the executable;
Make sure that there is a folder containing files 1.txt, 2.txt, ..., 1000.txt.
Run the executable by using this command:
java -jar /path/to/directory/runnable.jar /path/to/dataset/directory 1.txt
replace 1.txt with any other document name to get its probability result list.
| aa34462b113a7ac3462c8c38335e96f56c351f11 | [
"Java",
"Text"
] | 3 | Java | theTytoAlba/CmpE493Hw3 | 82e82d6994fa1be774cb68c2191e60250025d5f9 | 57800b39eff9397a280e73e2bc8f4a0e3b6f8ceb |
refs/heads/master | <repo_name>metaltapimenye/interview-node<file_sep>/index.js
// const app = require("express")();
var express = require('express');
var app = express();
var x2j = require("xml2js");
var bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs'),imposible=false;
var sendthemthis = "<head><script src='https://code.jquery.com/jquery-3.2.1.min.js'></script><script src='main.js'></script></head><body><div id='cont'></div></body>",ref={};
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(express.static(__dirname+'/public'));
var datafile = 'data.json',content='';
function readit(){content = fs.readFileSync(datafile).toString(); return content;}
function reference(){
var str = '',ret={};
const req = http.get( {host: 'www.ecb.europa.eu',path:'/stats/eurofxref/eurofxref-daily.xml'},function (hores){ // inviting callback hell:start
hores.on('data', function (chunk) {
str += chunk;
});
hores.on('end', function () {
var p = new x2j.Parser();
p.parseString( str, function( err, re ) {
re = re['gesmes:Envelope'].Cube[0].Cube[0].Cube;
var stemp = {},ltemp = []
re.forEach(function(v,i,o){
// console.info(v.$)
stemp[v.$.currency] = {};
stemp[v.$.currency].rate = v.$.rate;
try{
stemp[v.$.currency].treshold = doc[v.$.currency].treshold;
}catch(e){}
})
ref = stemp;
});
});
});
req.end();
}
reference();
function sync(){
writeit(ref);
return readit();
}
function writeit(data){
s = JSON.stringify( data, undefined, 3 );
var fd = fs.openSync(datafile, 'w');
fs.writeFileSync(datafile, s, 'utf8', function (err) {});
fs.closeSync(fd)
return s;
}
app.get("/", (req, res) => {
res.send(sendthemthis);
});
app.post("/fetch", (req, res) => {
var s= reference(),conto = [];
if(content){
conto = JSON.parse(content)
}
var s = sync();
res.send(s.replace(/fix/ig,''));
});
app.get("/data", (req, res) => {
content = readit();
var clean = content.replace(/fix/ig,'')
if(!clean){clean = '[]'}
res.send(clean);
});
app.post("/update", (req, res) => {
try{
var re = JSON.parse(content),ga='';
var post =req.body;
Object.keys(re).forEach(function(val){
if(post.cur[val] && post.rate){
try{
re[val].rate= 'fix'+post.cur[val];
}catch(e){
console.log(e)
}
}
if(post.tres[val] && post.tres){
try{
re[val].treshold= 'fix'+post.tres[val];
}catch(e){
console.log(e)
}
}
})
s = writeit(re);
res.send(readit().replace(/fix/ig,''));
}catch(e){
res.send(e);
}
});
app.get("/cron", (req, res) => {
try{
var re = JSON.parse(content);
Object.keys(re).forEach(function(k){
try{
if(parseFloat(re[k].treshold) < parseFloat(re[k].treshold)){
// make alert here
}
}catch(e){}
})
}catch(e){
res.send('[status:2]');
}
});
app.post("/unset", (req, res) => {
var re = JSON.parse(content = readit()),te={};
try{
var post = req.body;
console.info(post);
Object.keys(re).forEach(function(k){
if(post.cur[k]){
try{
re[k].rate= ref[k].rate;
delete re[k].treshold;
} catch (e){
}
}else{
// console.info(re[k].rate);
try{
re[k].rate= (re[k].rate.indexOf('fix') !== -1)?re[k].rate:ref[k].rate;
} catch(e){}
}
})
console.info(re);
writeit(re);
res.send(readit().replace(/fix/ig,''));
}catch(e){
console.info(e)
res.send('[status:2]');
}
});
var port = process.env.PORT || 5000;
app.listen(port, () => {
console.log("Listening on " + port);
});<file_sep>/public/main.js
$(document).ready(function(){
$(document).on('click','.warn',function(){
var d = $(this).parents('tr.r').find(':input').serialize();
tres(d)
})
$(document).on('click','.rate',function(){
var d = $(this).parents('tr.r').find(':input').serialize();
rate(d)
})
$(document).on('click','.init',function(){
pop()
})
$(document).on('click','.x',function(){
unset(this)
})
function tres(d){
$.ajax({
url:'update',
datatype:'json',
method:'POST',
data:d+'&tres=1',
success:function(data){
get()
alert('repupulated!');
}
})
}
function rate(d){
$.ajax({
url:'update',
datatype:'json',
method:'POST',
data:d+'&rate=1',
success:function(data){
get()
alert('repupulated!');
}
})
}
function build(data){
$('#cont').html('');
var s = [],al=[];
walker = $.parseJSON(data);
if(!$.trim(walker)){virgin();return;}
$.each(walker,function(k,v){
var tres =(typeof v.treshold !== 'undefined')?v.treshold:'';
s.push('<tr class=r rel=><td>'+k+'</td><td><input name="cur['+k+']" value="'+v.rate+'"><button class=rate>Set</button></td><td><input name="tres['+k+']" value="'+tres+'"><button class=warn>Set</button></td><td><button class=x>x</button></td></tr>');
if(parseFloat(tres) < parseFloat(v.rate) ){ al.push(k)}
})
if(al.length){ alert('rate of '+al.join(',')+ ' too high') }
$('#cont').html('<table class=t><thead><tr class=rh><td>Currency</td><td>Rate</td><td>Treshold</td><td>Option</td></tr></thead><tbody>'+s.join('')+'<tr><td colspan=100%><button class="init">reset</button></td></tr></tbody></table>');
}
function pop(){
$.ajax({
url:'fetch',
datatype:'json',
method:'POST',
data:'a=a',
success:function(data){
build(data)
}
})
}
function virgin(){
if(!$('#cont').text()){
$('#cont').append('<button class=init>Init</button>')
}
}
function get(){
$.ajax({
url:'data',
datatype:'json',
method:'get',
data:'a=a',
success:function(data){
build(data)
}
})
}
function unset(o){
var d = $(o).parents('tr.r').find(':input').serialize();
$.ajax({
url:'unset',
datatype:'json',
method:'post',
data:d,
success:function(data){
get()
}
})
}
get();
}) | 931bdf61eb6a6a6ffcac5775d2f3ba4fdafe5d5e | [
"JavaScript"
] | 2 | JavaScript | metaltapimenye/interview-node | 81ababc8a81fbb383053009efca04b00b5147f44 | 1bfb85246d3fdeadea42cad094bc09ddc4364c55 |
refs/heads/master | <repo_name>benkim0414/bundle<file_sep>/README.md
[](https://heroku.com/deploy)
# bundle
A microservice for Flower Shop code challenge. It provides only a HTTP GET method.
## Installation
```
go get github.com/benkim0414/bundle
```
## Run Server
```
export PORT=8080
go run main.go
```
## GET
```
GET /bundle
{
"code": "R12|L09|T58"
}
```
## Examples
### Request
```
curl -X GET -d '{"code": "R12"}' http://localhost:8080/bundle
```
### Response
```
{
"bundles": [
{ "name": "Roses", "code": "R12", "size": 5, "cost": 6.99 },
{ "name": "Roses", "code": "R12", "size": 10, "cost": 12.99 }
],
"error": null
}
```
<file_sep>/bundle/middlewares_test.go
package bundle
import (
"bytes"
"context"
"testing"
"github.com/go-kit/kit/log"
)
func TestLoggingMiddleware(t *testing.T) {
tests := []struct {
code FlowerCode
want []byte
}{
{Roses, []byte("method=Get code=R12 error=null")},
{Lilies, []byte("method=Get code=L09 error=null")},
{Tulips, []byte("method=Get code=T58 error=null")},
}
var buf bytes.Buffer
logger := log.NewLogfmtLogger(&buf)
s := NewService()
mw := LoggingMiddleware(logger)(s)
ctx := context.Background()
for _, c := range tests {
mw.Get(ctx, c.code)
got := buf.Bytes()
// check if log is correct, except for "took=..."
// since we don't know the exact time server serve the request.
if !bytes.HasPrefix(got, c.want) {
t.Errorf("got %s, want prefix %s", got, c.want)
}
buf.Reset()
}
}
<file_sep>/bundle/endpoints_test.go
package bundle
import (
"context"
"reflect"
"testing"
)
func TestServerEndpoints(t *testing.T) {
tests := []struct {
c FlowerCode
want getResponse
}{
{
c: Roses,
want: getResponse{
[]Bundle{
{"Roses", Roses, 5, 6.99},
{"Roses", Roses, 10, 12.99},
},
nil,
},
},
{
c: Lilies,
want: getResponse{
[]Bundle{
{"Lilies", Lilies, 3, 9.95},
{"Lilies", Lilies, 6, 16.95},
{"Lilies", Lilies, 9, 24.95},
},
nil,
},
},
{
c: Tulips,
want: getResponse{
[]Bundle{
{"Tulips", Tulips, 3, 5.95},
{"Tulips", Tulips, 5, 9.95},
{"Tulips", Tulips, 9, 16.99},
},
nil,
},
},
}
s := NewService()
e := MakeServerEndpoints(s)
ctx := context.Background()
for _, c := range tests {
req := getRequest{c.c}
resp, _ := e.GetEndpoint(ctx, req)
if !reflect.DeepEqual(resp, c.want) {
t.Errorf("got %+v, want %+v", resp, c.want)
}
}
}
<file_sep>/bundle/service_test.go
package bundle
import (
"context"
"reflect"
"testing"
)
var testBundles = []Bundle{
{"Roses", Roses, 5, 6.99},
{"Roses", Roses, 10, 12.99},
{"Lilies", Lilies, 3, 9.95},
{"Lilies", Lilies, 6, 16.95},
{"Lilies", Lilies, 9, 24.95},
{"Tulips", Tulips, 3, 5.95},
{"Tulips", Tulips, 5, 9.95},
{"Tulips", Tulips, 9, 16.99},
}
func TestNewService(t *testing.T) {
want := &bundleService{testBundles}
got := NewService()
if !reflect.DeepEqual(got, want) {
t.Errorf("NewService() = %+v, want %+v", got, want)
}
}
func TestBundleServiceGet(t *testing.T) {
type want struct {
bs []Bundle
err error
}
tests := []struct {
c FlowerCode
want want
}{
{
c: All,
want: want{
bs: testBundles,
err: nil,
},
},
{
c: Roses,
want: want{
bs: []Bundle{
{"Roses", Roses, 5, 6.99},
{"Roses", Roses, 10, 12.99},
},
err: nil,
},
},
{
c: Lilies,
want: want{
bs: []Bundle{
{"Lilies", Lilies, 3, 9.95},
{"Lilies", Lilies, 6, 16.95},
{"Lilies", Lilies, 9, 24.95},
},
err: nil,
},
},
{
c: Tulips,
want: want{
bs: []Bundle{
{"Tulips", Tulips, 3, 5.95},
{"Tulips", Tulips, 5, 9.95},
{"Tulips", Tulips, 9, 16.99},
},
err: nil,
},
},
{
c: FlowerCode("A14"),
want: want{
bs: nil,
err: ErrNotFound,
},
},
}
s := NewService()
ctx := context.Background()
for _, c := range tests {
bs, err := s.Get(ctx, c.c)
if !reflect.DeepEqual(bs, c.want.bs) {
t.Errorf("got %+v, want %+v", bs, c.want.bs)
}
if !reflect.DeepEqual(err, c.want.err) {
t.Errorf("got %+v, want %+v", err, c.want.err)
}
}
}
<file_sep>/bundle/transport_test.go
package bundle
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"reflect"
"testing"
"github.com/go-kit/kit/log"
)
func TestHTTPHandler(t *testing.T) {
tests := []struct {
path string
want getResponse
}{
{
path: "/bundle",
want: getResponse{
[]Bundle{
{"Roses", Roses, 5, 6.99},
{"Roses", Roses, 10, 12.99},
{"Lilies", Lilies, 3, 9.95},
{"Lilies", Lilies, 6, 16.95},
{"Lilies", Lilies, 9, 24.95},
{"Tulips", Tulips, 3, 5.95},
{"Tulips", Tulips, 5, 9.95},
{"Tulips", Tulips, 9, 16.99},
},
nil,
},
},
}
logger := log.NewLogfmtLogger(os.Stderr)
s := NewService()
h := MakeHTTPHandler(s, logger)
ts := httptest.NewServer(h)
defer ts.Close()
for _, c := range tests {
resp, err := http.Get(ts.URL + c.path)
if err != nil {
t.Error(err)
}
var got getResponse
err = json.NewDecoder(resp.Body).Decode(&got)
if err != nil {
t.Error(err)
}
defer resp.Body.Close()
if !reflect.DeepEqual(got, c.want) {
t.Errorf("got %+v, want %+v", got, c.want)
}
}
}
| 1f60b58b7999a70786831b6fda92e7e325b4a2e7 | [
"Markdown",
"Go"
] | 5 | Markdown | benkim0414/bundle | e3dc7e57752168a6603c93c955f7dcf534626618 | ba5c77796678779450c29b39a972f3ca65ef2ec9 |
refs/heads/master | <file_sep>using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc;
namespace Engine.Layout
{
public interface ILayoutComponentHelper
{
Task<IHtmlContent> ContainerAsync(IViewComponentHelper helper, string name);
Task<IHtmlContent> ContentAsync(IViewComponentHelper helper);
}
}<file_sep>namespace Engine.ViewModel
{
public class ViewComponentViewModel
{
public string ViewComponent { get; set; }
public object Arguments { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Engine.Configuration;
using Microsoft.Extensions.Configuration.Yaml;
namespace Engine
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) {
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddYamlFile("appsettings.yml")
.Build();
var engineConfiguration = Startup.Configuration = new EngineConfiguration();
ConfigurationBinder.Bind(configuration, engineConfiguration);
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureServices(services => services.AddSingleton(engineConfiguration))
.UseUrls(engineConfiguration.Website.Urls())
.Build();
}
}
}
<file_sep>using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
namespace Engine.Extensions
{
public static class RazorPageExtensions
{
public static Task<IHtmlContent> ContainerAsync(this RazorPage<object> page, string name)
{
if (page == null)
{
throw new ArgumentNullException(nameof(page));
}
var typeInfo = page.GetType().GetTypeInfo();
var helper = (IViewComponentHelper) typeInfo.DeclaredFields.Where(f => f.FieldType == typeof(IViewComponentHelper)).First().GetValue(page);
return helper.InvokeAsync("Container", name);
}
public static Task<IHtmlContent> ContentAsync(this RazorPage<object> helper)
{
return null;
}
}
}<file_sep>using System.Collections.Generic;
namespace Engine.Configuration
{
public class DatabaseConfiguration
{
public string Host { get; set; }
public int Port { get; set; } = 5432;
public string Username { get; set; }
public string Password { get; set; }
public string Database { get; set; }
private string _connectionString;
public string ConnectionString() {
if (_connectionString is default) {
_connectionString = $"Server={Host};Port={Port};Database={Database};User Id={Username};Password={Password};";
}
return _connectionString;
}
}
}<file_sep>using System.Threading.Tasks;
using Engine.Core;
using Microsoft.AspNetCore.Routing;
namespace Engine.Plugin
{
public interface IMvcPlugin : IPlugin
{
void Initialize(IEngine engine);
}
}<file_sep>using System.ComponentModel.DataAnnotations;
namespace BlogPlugin.Models
{
public class Post
{
[Required]
public long Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Heading { get; set; }
[Required]
public string Body { get; set; }
}
}<file_sep>using System.Data.SqlClient;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using Dapper;
using BlogPlugin.Models;
using BlogPlugin.ViewModels;
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
namespace BlogPlugin.Controllers
{
public class PostIndexViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync([FromServices] IDbConnection connection, string postName)
{
connection.Open();
var post = await connection.QueryFirstOrDefaultAsync<Post>(
"select * from plugins_blogplugin_posts where is_published = true and title = @postName",
new { postName });
if (post is default)
{
return Content("Not found");
}
return View(
"/Plugin/BlogPlugin/Views/Post.cshtml",
new PostViewModel
{
Post = post
});
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Threading.Tasks;
using Engine.Layout;
using Engine.ViewModel;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using Microsoft.Extensions.DependencyInjection;
namespace Engine.Controllers
{
public class PluginController : Controller
{
private readonly ILayoutManager _layoutManager;
private readonly IViewComponentSelector _viewComponentSelector;
public PluginController(
ILayoutManager layoutManager,
IViewComponentSelector viewComponentSelector
)
{
this._layoutManager = layoutManager;
this._viewComponentSelector = viewComponentSelector;
}
[AllowAnonymous]
public IActionResult Index([FromServices] IServiceProvider serviceProvider, [FromServices] IActionContextAccessor actionContextAccessor)
{
if (User?.Identity?.IsAuthenticated != true
&& (bool)RouteData.DataTokens["RequireAuthenticated"])
{
return RedirectToAction("Login", "Account");
}
var layout = _layoutManager.LayoutForRoute(RouteData.DataTokens["RouteName"] as string);
var pluginViewComponentName = RouteData.DataTokens["ViewComponent"] as string;
return View(new ViewComponentViewModel
{
ViewComponent = "PluginLayout",
Arguments = new object[] {
_layoutManager.PathForLayoutView(layout),
new ViewComponentViewModel
{
ViewComponent = pluginViewComponentName,
Arguments = null
}
}
});
}
}
public class PluginLayoutViewComponent : ViewComponent
{
public Task<IViewComponentResult> InvokeAsync(object[] arguments)
{
var layout = arguments[0] as string;
var viewModel = arguments[1] as ViewComponentViewModel;
return Task.FromResult((IViewComponentResult) View(layout, viewModel));
}
}
}<file_sep>using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
namespace Engine.Layout
{
public interface ILayoutManager
{
IList<ILayout> Layouts { get; }
// IList<ILayoutComponent> LayoutComponents { get; }
ILayout LayoutForRoute(string name);
string PathForLayoutView(ILayout layout);
IEnumerable<string> ComponentsForName(string name);
}
}<file_sep>using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
namespace Engine.Plugin
{
public class MockPluginManager : IPluginManager
{
private readonly IServiceProvider _provider;
private IList<IPlugin> _plugins;
public IList<IPlugin> Plugins
{
get
{
if (_plugins is default) {
_plugins = new List<IPlugin>();
_plugins.Add(ActivatorUtilities.CreateInstance<ApiPlugin.ApiPlugin>(_provider));
_plugins.Add(ActivatorUtilities.CreateInstance<BlogPlugin.BlogPlugin>(_provider));
}
return _plugins;
}
}
public MockPluginManager(IServiceProvider provider)
{
_provider = provider;
}
}
}<file_sep># RedInk
C# Website Engine
<file_sep>using System;
using System.Data;
using System.Security.Claims;
using System.Threading.Tasks;
using Dapper;
using Engine.Extensions;
using Engine.Model;
using Engine.Request;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Engine.Controllers
{
public class AccountController : Controller
{
[AllowAnonymous]
public IActionResult Login()
{
return View();
}
public async Task<IActionResult> Logout() {
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login", "Account");
}
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> Login(
[FromServices] IDbConnection connection,
[FromForm] LoginRequest loginRequest)
{
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
connection.Open();
var user = await connection.QueryFirstOrDefaultAsync<User>(
"select * from users where email = @Email", new { loginRequest.Email }
);
if (user is default) {
return BadRequest();
}
var passwordTokens = user.Password.Split("|");
if (loginRequest.Password.Hash(ref passwordTokens[1]).Equals(passwordTokens[0])) {
user.IsAuthenticated = true;
user.AuthenticationType = "cookie";
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(user)
);
HttpContext.Response.Cookies.Append("UserId", user.Id.ToString());
return Redirect("/");
}
return BadRequest();
}
}
}<file_sep>using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace Engine.Core
{
public class Engine : IEngine, IInternalEngine
{
private IRouteBuilder _mvcRouteBuilder;
private IApplicationBuilder _app;
private IRouteBuilder _internalRouteBuilder;
public IAdmin Admin { get; private set; }
public Engine() { }
public void Initialize(IApplicationBuilder app, IRouteBuilder builder)
{
_app = app;
_mvcRouteBuilder = builder;
_internalRouteBuilder = new RouteBuilder(app);
Admin = new Admin(this);
}
public IEngine MapMvcRoute(string name, string template)
{
_mvcRouteBuilder.MapRoute(name, template);
return this;
}
public IEngine MapRoute(string route, Func<RequestDelegate, RequestDelegate> handler)
{
_app.Use(handler);
return this;
}
public IEngine MapRoute(string name, string template, string viewComponent, bool requireAuthenticated)
{
_mvcRouteBuilder.MapRoute(
name: name,
template: template,
defaults: new { controller = "Plugin", action = "Index" },
constraints: null,
dataTokens: new
{
RouteName = name,
ViewComponent = viewComponent,
RequireAuthenticated = requireAuthenticated
}
);
return this;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;
namespace Engine.Components
{
public class HtmlContentsViewComponentResult : IViewComponentResult
{
/// <summary>
/// Gets the encoded content.
/// </summary>
public IEnumerable<IHtmlContent> EncodedContent { get; }
public HtmlContentsViewComponentResult(params IHtmlContent[] encodedContent)
{
if (encodedContent == null)
{
throw new ArgumentNullException(nameof(encodedContent));
}
EncodedContent = encodedContent;
}
/// <summary>
/// Writes the <see cref="EncodedContent"/>.
/// </summary>
/// <param name="context">The <see cref="ViewComponentContext"/>.</param>
public void Execute(ViewComponentContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
foreach (var content in EncodedContent)
{
context.Writer.Write(content);
}
}
/// <summary>
/// Writes the <see cref="EncodedContent"/>.
/// </summary>
/// <param name="context">The <see cref="ViewComponentContext"/>.</param>
/// <returns>A completed <see cref="Task"/>.</returns>
public Task ExecuteAsync(ViewComponentContext context)
{
Execute(context);
return Task.CompletedTask;
}
}
}<file_sep>using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Engine.Core
{
public interface IEngine
{
IAdmin Admin { get; }
void Initialize(IApplicationBuilder builder, IRouteBuilder routeBuilder);
IEngine MapRoute(string name, string template, string viewComponent, bool requireAuthenticated = false);
IEngine MapRoute(string route, Func<RequestDelegate, RequestDelegate> handler);
}
internal interface IInternalEngine {
IEngine MapMvcRoute(string name, string template);
}
}<file_sep>using System.Threading.Tasks;
using Engine.Core;
using Microsoft.AspNetCore.Builder;
namespace Engine.Plugin
{
public interface IRequestPlugin : IPlugin
{
void Initialize(IApplicationBuilder engine);
}
}<file_sep>using System;
using System.Collections.Generic;
using Engine.Layout;
namespace BlogPlugin.Layouts.Default
{
public class DefaultLayout : ILayout
{
public string View => "Views/Index.cshtml";
public HashSet<Type> Plugins => new HashSet<Type>(new [] {
typeof(BlogPlugin)
});
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
namespace Engine.Layout
{
public class MockLayoutManager : ILayoutManager
{
private readonly IServiceProvider _provider;
private IList<ILayout> _layouts;
public IList<ILayout> Layouts
{
get
{
if (_layouts is default)
{
_layouts = new List<ILayout>(new[] {
ActivatorUtilities.CreateInstance<BlogPlugin.Layouts.Default.DefaultLayout>(_provider)
});
}
return _layouts;
}
}
public MockLayoutManager(IServiceProvider provider)
{
this._provider = provider;
}
public ILayout LayoutForRoute(string name)
{
return Layouts.First();
}
public string PathForLayoutView(ILayout layout)
{
return "/Plugin/BlogPlugin/Layouts/Default/" + layout.View;
}
public IEnumerable<string> ComponentsForName(string name)
{
if (name.Equals("header")) {
return new [] { "Header", "Header" };
}
if (name.Equals("footer")) {
return new [] { "Footer", "Footer" };
}
throw new Exception();
}
}
}<file_sep>using System.Collections.Generic;
using Engine.Core.Models;
namespace Engine.Core
{
public class Admin : IAdmin
{
public IList<MenuCategory> Menu { get; set; } = new List<MenuCategory>();
internal Admin(IInternalEngine internalEngine) {
internalEngine.MapMvcRoute(
name: "admin",
template: "admin/{controller=Admin}/{action=Index}"
);
}
public void RegisterMenuCategory(MenuCategory menuCategory)
{
Menu.Add(menuCategory);
}
}
}<file_sep>using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Builder;
using Engine.Plugin;
using System.Collections.Generic;
using Engine.Core.Models;
using Engine.Core;
using BlogPlugin.ViewComponents;
namespace BlogPlugin
{
public class BlogPlugin : IMvcPlugin
{
public void Initialize(IEngine engine)
{
engine.Admin.RegisterMenuCategory(new MenuCategory {
DisplayName = "Posts",
Items = new List<MenuCategoryItem>(new [] {
new MenuCategoryItem {
DisplayName = "View Posts",
ViewComponent = typeof(AdminViewPostsViewComponent)
}
})
});
engine.MapRoute("editPost", "blog/{postName}/edit", "PostIndex", true);
engine.MapRoute("post", "blog/{postName}", "PostIndex");
}
}
}<file_sep>using System.Collections.Generic;
namespace Engine.Plugin
{
public interface IPluginManager
{
IList<IPlugin> Plugins { get; }
}
}<file_sep>using System.Collections.Generic;
namespace Engine.Configuration
{
public class WebsiteConfiguration
{
public bool UseHttps { get; set; }
public bool RequireHttps { get; set; }
public string Host { get; set; }
public int Port { get; set; }
private string[] _urls;
public string[] Urls() {
if (_urls == null) {
var urls = new List<string>();
if (UseHttps) urls.Add($"https://{Host}:{Port}");
if (!UseHttps && !RequireHttps) urls.Add($"http://{Host}:{Port}");
_urls = urls.ToArray();
}
return _urls;
}
}
}<file_sep>using Engine.Core;
namespace Engine.Plugin.LayoutPlugin
{
public class LayoutPlugin : IMvcPlugin
{
public void Initialize(IEngine engine)
{
}
}
}<file_sep>using System.Collections.Generic;
using Engine.Core.Models;
namespace Engine.Core
{
public interface IAdmin
{
IList<MenuCategory> Menu { get; }
void RegisterMenuCategory(MenuCategory menuCategory);
}
}<file_sep>using System.Collections.Generic;
using System.Linq;
namespace Engine.Plugin
{
public static class PluginExtensions
{
public static IEnumerable<TPlugin> Plugins<TPlugin>(this IPluginManager manager)
where TPlugin : IPlugin
{
return manager.Plugins.Where(p => p is TPlugin).Select(p => (TPlugin) p);
}
public static TPlugin Plugin<TPlugin>(this IPluginManager manager) {
return (TPlugin) manager.Plugins.FirstOrDefault(p => p is TPlugin);
}
}
}<file_sep>using Engine.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.ViewComponents;
namespace Engine.Controllers.Admin
{
public class AdminController : Controller
{
public IActionResult Index([FromQuery] string url) {
return View();
}
}
}<file_sep>using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace Engine.Components
{
public class HeaderViewComponent : ViewComponent
{
public Task<IViewComponentResult> InvokeAsync()
{
return Task.FromResult((IViewComponentResult)Content("<p>Header</p>"));
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Engine.Configuration;
using Engine.Core;
using Engine.Layout;
using Engine.Middleware;
using Engine.Plugin;
using Engine.Service;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Engine
{
public class Startup
{
public static EngineConfiguration Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options => {
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<ILayoutComponentHelper, LayoutComponentHelper>();
services.AddAuthentication()
.AddCookieAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);
services.AddSingleton<IEngine, Core.Engine>();
services.AddScoped<IDbConnection>(provider =>
new Npgsql.NpgsqlConnection(Configuration.Database.ConnectionString()));
services.AddSingleton<IPluginManager, MockPluginManager>();
services.AddSingleton<ILayoutManager, MockLayoutManager>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<UserMiddleware>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IEngine engine, IPluginManager pluginManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMiddleware<UserMiddleware>();
app.UseMvc(routeBuilder => {
engine.Initialize(app, routeBuilder);
foreach (var plugin in pluginManager.Plugins<IRequestPlugin>()) {
plugin.Initialize(app);
}
foreach (var plugin in pluginManager.Plugins<IMvcPlugin>()) {
plugin.Initialize(engine);
}
routeBuilder.MapRoute(
name: "default",
template: "{controller=Index}/{action=Index}"
);
});
app.Run((context) =>
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
return Task.CompletedTask;
});
}
}
}
<file_sep>using System;
using System.Data;
using System.Threading.Tasks;
using Engine.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Engine.Middleware
{
public class UserMiddleware : IMiddleware
{
private IUserService _userService;
public UserMiddleware(IUserService userService) {
_userService = userService;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
if (!context.User.Identity.IsAuthenticated) {
await next(context);
return;
}
var user = await _userService.GetUserById(long.Parse(context.Request.Cookies["UserId"]));
context.Items.Add("User", user);
await next(context);
}
}
}<file_sep>using System.Collections.Generic;
namespace Engine.Configuration
{
public class EngineConfiguration
{
public WebsiteConfiguration Website { get; set; }
public DatabaseConfiguration Database { get; set; }
}
}<file_sep>using System.Threading.Tasks;
using Engine.Model;
namespace Engine.Service
{
public interface IUserService
{
Task<User> GetUserById(long id);
}
}<file_sep>using System;
using System.Collections.Generic;
namespace Engine.Layout
{
public interface ILayout
{
string View { get; }
HashSet<Type> Plugins { get; }
}
}<file_sep>namespace Engine.ViewModel
{
public class PluginViewModel
{
public ViewComponentViewModel Layout { get; set; }
public ViewComponentViewModel Plugin { get; set; }
}
}<file_sep>using System.Collections.Generic;
namespace Engine.Core.Models
{
public class MenuCategory
{
public string DisplayName { get; set; }
public IList<MenuCategoryItem> Items { get; set; }
}
}<file_sep>using System;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
namespace Engine.Extensions
{
public static class StringExtensions
{
public static string Hash(this string self, ref string base64Salt)
{
byte[] salt;
if (base64Salt == null)
{
salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
base64Salt = Convert.ToBase64String(salt);
}
else
{
salt = Convert.FromBase64String(base64Salt);
}
// derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
return Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: <PASSWORD>,
salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256 / 8));
}
}
}<file_sep>using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace BlogPlugin.ViewComponents
{
public class AdminViewPostsViewComponent : ViewComponent
{
public Task<IViewComponentResult> InvokeAsync() {
return Task.FromResult<IViewComponentResult>(null);
}
}
}<file_sep>using System.Threading.Tasks;
using Engine.Layout;
using Microsoft.AspNetCore.Mvc;
namespace Engine.Components
{
public class FooterViewComponent : ViewComponent
{
public Task<IViewComponentResult> InvokeAsync() {
return Task.FromResult((IViewComponentResult) Content("Footer"));
}
}
}<file_sep>using Engine.Model;
namespace Engine.Service
{
public class ModelService<TModel>
where TModel : IModel
{
public virtual TModel Query(long id) {
return default(TModel);
}
// public virtual TModel Query(QueryBuilder builder) {
// return default(TModel);
// }
}
}<file_sep>using BlogPlugin.Models;
namespace BlogPlugin.ViewModels
{
public class PostViewModel
{
public Post Post { get; set; }
}
}<file_sep>using System;
using System.Data;
using System.Threading.Tasks;
using Dapper;
using Engine.Model;
using Microsoft.Extensions.DependencyInjection;
namespace Engine.Service
{
public class UserService : IUserService
{
private IServiceProvider _serviceProvider;
public UserService(IServiceProvider serviceProvider)
{
this._serviceProvider = serviceProvider;
}
public async Task<User> GetUserById(long id)
{
using (var scope = _serviceProvider.CreateScope()) {
var connection = scope.ServiceProvider.GetRequiredService<IDbConnection>();
return await connection.QueryFirstOrDefaultAsync<User>("select * from users where id = @id", new { id });
}
}
}
}<file_sep>using System.Linq;
using System.Threading.Tasks;
using Engine.Layout;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;
namespace Engine.Components
{
public class ContainerViewComponent : ViewComponent
{
private readonly ILayoutManager _layoutManager;
private readonly DefaultViewComponentHelper _componentHelper;
public ContainerViewComponent(ILayoutManager layoutManager, IViewComponentHelper componentHelper)
{
this._layoutManager = layoutManager;
this._componentHelper = componentHelper as DefaultViewComponentHelper;
}
public async Task<IViewComponentResult> InvokeAsync(string name) {
_componentHelper.Contextualize(ViewContext);
var components = _layoutManager.ComponentsForName(name);
var content = await Task.WhenAll(components.Select(async c => await _componentHelper.InvokeAsync(c, null)));
return new HtmlContentsViewComponentResult(content);
}
}
}<file_sep>using System;
namespace Engine.Core.Models
{
public class MenuCategoryItem
{
public string DisplayName { get; set; }
public Type ViewComponent { get; set; }
}
}<file_sep>using Microsoft.AspNetCore.Mvc;
namespace BlogPlugin.Controllers
{
public class IndexController : Controller
{
public string Index() {
return "Index";
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Engine.Layout
{
public class LayoutComponentHelper : ILayoutComponentHelper
{
private readonly IViewComponentSelector _viewComponentSelector;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IActionContextAccessor _actionContextAccessor;
private readonly IServiceProvider _serviceProvider;
private readonly IOptions<MvcOptions> _optionsAccessor;
public LayoutComponentHelper(
IViewComponentSelector viewComponentSelector,
IHttpContextAccessor httpContextAccessor,
IActionContextAccessor actionContextAccessor,
IServiceProvider serviceProvider,
IOptions<MvcOptions> optionsAccessor)
{
_viewComponentSelector = viewComponentSelector;
_httpContextAccessor = httpContextAccessor;
_actionContextAccessor = actionContextAccessor;
_serviceProvider = serviceProvider;
_optionsAccessor = optionsAccessor;
}
public Task<IHtmlContent> ContainerAsync(IViewComponentHelper helper, string name)
{
return helper.InvokeAsync("Container", name);
}
public async Task<IHtmlContent> ContentAsync(IViewComponentHelper helper)
{
var actionContext = _actionContextAccessor.ActionContext;
var viewComponentName = actionContext.RouteData.DataTokens["ViewComponent"] as string;
var compositeValueProvider = await CompositeValueProvider.CreateAsync(actionContext, _optionsAccessor.Value.ValueProviderFactories);
var pluginViewComponent = _viewComponentSelector.SelectComponent(viewComponentName);
var parameterBinder = ActivatorUtilities.CreateInstance<ParameterBinder>(_serviceProvider);
var parameterBag = new Dictionary<string, object>();
foreach (var parameter in pluginViewComponent.Parameters)
{
var parameterDescriptor = new ParameterDescriptor {
BindingInfo = BindingInfo.GetBindingInfo(parameter.GetCustomAttributes()),
Name = parameter.Name,
ParameterType = parameter.ParameterType,
};
var result = await parameterBinder.BindModelAsync(
actionContext,
compositeValueProvider,
parameterDescriptor);
parameterBag[parameter.Name] = result.IsModelSet ? result.Model : null;
}
return await helper.InvokeAsync(viewComponentName, parameterBag);
}
}
}<file_sep>using System;
using System.Security.Cryptography;
using Engine.Core;
using Engine.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Engine.Plugin.ApiPlugin
{
public class ApiPlugin : IRequestPlugin
{
// private Type[] _apiModels;
public void Initialize(IApplicationBuilder app)
{
var apiRouter = new RouteHandler(context => {
var routeValues = context.GetRouteData().Values;
return context.Response.WriteAsync(
$"Hello! Route values: {string.Join(", ", routeValues)}");
});
var routeBuilder = new RouteBuilder(app, apiRouter);
routeBuilder.MapRoute(
"Track Package Route",
"package/{operation:regex(^(track|create|detonate)$)}/{id:int}");
routeBuilder.MapGet("hash/{password}", context =>
{
var password = context.GetRouteValue("password") as string;
string salt = null;
var hash = password.Hash(ref salt);
return context.Response.WriteAsync($"{hash}|{salt}");
});
var routes = routeBuilder.Build();
app.UseRouter(routes);
}
}
}<file_sep>using System.ComponentModel.DataAnnotations;
using System.Security.Principal;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Engine.Model
{
public class User : IIdentity, IModel
{
public long Id { get; set; }
public string Name { get; set; }
[Required]
public string Email { get; set; }
[BindNever]
public string Password { get; set; }
public string AuthenticationType { get; set; }
public bool IsAuthenticated { get; set; }
}
}<file_sep>using Engine.Model;
using Microsoft.AspNetCore.Http;
namespace Engine.Extensions
{
public static class HttpContextExtensions
{
public static User User(this HttpContext context) {
return context.Items["User"] as User;
}
}
} | d570605cc32d9df58c152cd5a921f9863f7e28f8 | [
"Markdown",
"C#"
] | 48 | C# | berdon/RedInk | 52a35c129e5d050a8fd459bdb7d75a2b6dc0a26e | d1368237402ed6ffa357cf8791b18fa0270a110b |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorld
{
//Adventure Game
public static class Game
{
//character name and introduction
static string CharacterName = "<NAME>";
//Game Title
public static void StartGame()
{
Console.WriteLine("Adventure!\n\n");
Console.WriteLine("This is strictly for educational purposes");
Console.WriteLine("It is the end of summer, you hear the cicadas chirping as you get out of your taxi.\n");
Console.WriteLine("Before you stands an old decrepit old house. The roof seems to be poorly maintained.\n");
Console.WriteLine("\"I'm really not sure why you are here errrr...\" says the cab driver who seems to be at a loss with what to call you");
}
public static void NameChar()
{
Console.WriteLine("You're probably never going to meet him again, but it's rude to not introduce yourself\n\n");
//input character name and print introduction - insert validation of names later. Ignore for now.
CharacterName = Console.ReadLine();
Console.WriteLine("");
}
public static void StartAdventure() //Actual choices start here
{
Console.WriteLine($"The cab driver gives you a look like this is completely pointless \"Goodluck {CharacterName}! we're never meeting again.\"\n\n ");
Console.WriteLine("You stare as the taxi drives off, leaving you alone with the house. \nYou don't know what his problem is but you're never meeting them again");
Console.WriteLine("There doesn't seem to be anything else nearby except for a mailbox\n\n");
Console.WriteLine(" \"Hmmm...\" you think to yourself.\n");
Console.WriteLine("What next?\n");
}
}
class Item
{
}
class Program
{
static void Main()
{
Game.StartGame();
Game.NameChar();
Game.StartAdventure();
Console.ReadKey();
}
}
}
<file_sep># Text-Based-Test
Learning to Code by Text Based Adventure
I'm seriously just learning how to code with this.
| 559a8b680c8240e7344421b74619df84c1ac1c38 | [
"Markdown",
"C#"
] | 2 | C# | bsl168/Text-Based-Test | f19b25e10f338797490c59a3665baec09ad4b05c | aa315b295c3f10598654ced193bf6141763e3db0 |
refs/heads/master | <file_sep>from flask import Flask
from flask_bcrypt import Bcrypt
app = Flask(__name__)
app.config['SECRET_KEY'] = '<KEY>'
bcrypt = Bcrypt(app)
from app import views<file_sep># DemocracyDonations
A platform for transparent donations
To run application:
export FLASK_APP=node_server.py
flask run --port 8000
python3 run_app.py
<file_sep>import datetime
import json
import webbrowser
import os
import secrets
from app import bcrypt
import requests
from flask import render_template, redirect, request, url_for, flash
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo
from app import app
# The node with which our application interacts, there can be multiple
# such nodes as well.
CONNECTED_NODE_ADDRESS = "http://127.0.0.1:8000"
posts = []
def fetch_posts():
"""
Function to fetch the chain from a blockchain node, parse the
data and store it locally.
"""
get_chain_address = "{}/chain".format(CONNECTED_NODE_ADDRESS)
response = requests.get(get_chain_address)
if response.status_code == 200:
content = []
chain = json.loads(response.content)
for block in chain["chain"]:
for tx in block["transactions"]:
tx["index"] = block["index"]
tx["hash"] = block["previous_hash"]
content.append(tx)
global posts
posts = sorted(content, key=lambda k: k['timestamp'],
reverse=True)
@app.route('/')
def index():
fetch_posts()
return render_template('index.html',
title='Democracy Donations: Transparent politics',
posts=posts,
node_address=CONNECTED_NODE_ADDRESS,
readable_time=timestamp_to_string)
@app.route('/democracyDollars')
def democracyDollars():
return render_template('democracyDollars.html',
title='Democracy Dollars Fund: Helping everyone be heard! ',
node_address=CONNECTED_NODE_ADDRESS,
readable_time=timestamp_to_string)
@app.route('/donations')
def donations():
fetch_posts()
return render_template('donations.html',
title='All donations made to Democracy Dollars',
posts=posts,
node_address=CONNECTED_NODE_ADDRESS,
readable_time=timestamp_to_string )
@app.route('/BlockchainData')
def BlockchainData():
#webbrowser.open_new_tab("{}/chain".format(CONNECTED_NODE_ADDRESS))
return redirect("{}/chain".format(CONNECTED_NODE_ADDRESS))
class RegistrationForm(FlaskForm):
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email',
validators=[DataRequired(), Email()])
password = PasswordField('<PASSWORD>', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password',
validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Sign Up')
def validate_username(self, username):
fetch_posts()
for i in posts:
if username.data == i["username"]:
raise ValueError('That username is taken. Please choose a different one.', 'danger')
def validate_email(self, email):
fetch_posts()
for i in posts:
if email.data == i["email"]:
raise ValueError('That email is taken. Please choose a different one.', 'danger')
@app.route("/register", methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
post_object = {
'id' : 'user',
'email': form.email.data,
'username': form.username.data,
'password': <PASSWORD>_<PASSWORD>(form.password.data).decode('utf-8')
}
# Submit a transaction
new_tx_address = "{}/new_transaction".format(CONNECTED_NODE_ADDRESS)
requests.post(new_tx_address,
json=post_object,
headers={'Content-type': 'application/json'})
webbrowser.open_new_tab("{}/mine".format(CONNECTED_NODE_ADDRESS))
flash(f'Account created for {form.username.data}!', 'success')
return redirect(url_for('index'))
return render_template('register.html', title='Register', form=form)
class LoginForm(FlaskForm):
email = StringField('Email',
validators=[DataRequired(), Email()])
password = PasswordField('<PASSWORD>', validators=[DataRequired()])
remember = BooleanField('Remember Me')
submit = SubmitField('Login')
@app.route("/login", methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
fetch_posts()
try:
for i in posts:
user = (i["email"] == form.email.data)
if user and bcrypt.check_password_hash(i["password"], form.password.data):
#login_user(user, remember=form.remember.data)
flash('You have been logged in!', 'success')
return redirect(url_for('index'))
except KeyError:
flash('Login Unsuccessful. Please check email and password.', 'danger')
else:
flash('Login Unsuccessful. Please check email and password', 'danger')
return render_template('login.html', title='Login', form=form)
@app.route('/submit', methods=['POST'])
def submit_textarea():
"""
Endpoint to create a new transaction via our application.
"""
post_content = request.form["content"]
firstName = request.form["firstName"]
lastName = request.form["lastName"]
donorEmail = request.form["donorEmail"]
donorAddress = request.form["donorAddress"]
donorZip = request.form["donorZip"]
donorPhone = request.form["donorPhone"]
donation = request.form["donation"]
fund = request.form["fund"]
campaign = request.form["campaign"]
post_object = {
'id' : 'donation',
'content': post_content,
'firstName': firstName,
'lastName': lastName,
'donorEmail': donorEmail,
'donorAddress': donorAddress,
'donorZip': donorZip,
'donorPhone': donorPhone,
'donation': donation,
'fund': fund,
'campaign': campaign
}
# Submit a transaction
new_tx_address = "{}/new_transaction".format(CONNECTED_NODE_ADDRESS)
requests.post(new_tx_address,
json=post_object,
headers={'Content-type': 'application/json'})
#webbrowser.open_new_tab("{}/mine".format(CONNECTED_NODE_ADDRESS))
return redirect("{}/mine".format(CONNECTED_NODE_ADDRESS))
def timestamp_to_string(epoch_time):
return datetime.datetime.fromtimestamp(epoch_time).strftime('%H:%M')
| dadf3dc492f9c6f98c4d84d71bffc34b4e7cc23f | [
"Markdown",
"Python"
] | 3 | Python | goatatwork/DemocracyDonations | 9da2d83a60414447f34af6ec082754c6503f9c8d | 39bc9c3b74d7be73012027af55b3c3d395e0e040 |
refs/heads/master | <file_sep>package com.example.breda.muhammadbredataftayani_1202154209_modul6;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class RegisterUser extends AppCompatActivity {
EditText rgEmail,rgPassword;
Button rgRegister;
TextView rgLogin;
String emails,passwords;
FirebaseAuth auth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_user);
auth=FirebaseAuth.getInstance();
if (auth.getCurrentUser()!=null){
Intent intent=new Intent(this,LoginUser.class);
startActivity(intent);
}
rgEmail=(EditText)findViewById(R.id.rgEmail);
rgPassword=(EditText)findViewById(R.id.rgPass);
rgRegister=(Button)findViewById(R.id.rgLogin);
rgLogin=(TextView)findViewById(R.id.rgMove);
rgLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(RegisterUser.this, LoginUser.class);
startActivity(intent);
}
});
rgRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
register();
}
});
}
public void register(){
emails=rgEmail.getText().toString();
passwords=rgPassword.getText().toString();
if(TextUtils.isEmpty(emails)){
Toast.makeText(getApplicationContext(),"input email",Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(passwords)){
Toast.makeText(getApplicationContext(),"input password",Toast.LENGTH_SHORT).show();
}
auth.createUserWithEmailAndPassword(emails,passwords)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Intent intent=new Intent(RegisterUser.this,MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(),"gagal daftar",Toast.LENGTH_SHORT).show();
}
}
});
}
}
| 1b23b9fc66eb33ec3b39b4c4df53b676f0815d24 | [
"Java"
] | 1 | Java | taftayani/Muhammad-Breda-Taftayani_1202154209_Modul6 | fdd09834bdd8f5affd2ca4f1b118b7cfdef81ce4 | 0a165e3082f1cd63f4fb7468240e3e7835488210 |
refs/heads/main | <file_sep>"use strict";
// 服务端地址
var fetch = require('node-fetch');
var serviceUrl = 'https://www.cde.org.cn';
const fetchPost = async (url, params) => {
const response = await fetch(serviceUrl + url, {
method: 'post',
body: typeof data === 'string' ? params : objectToStrParams(resolveParams(params)),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});
if (response.status >= 200 && response.status < 300) {
const o = await response['json']();
return o;
}
console.log('error response', response);
const error = new Error(response.statusText);
error.response = response;
console.log('fetch error', error, url);
return error;
}
function resolveParams(params) {
if (!params) {
return;
}
const data = {};
Object.keys(params).forEach((key) => {
if ([undefined, null].indexOf(params[key]) === -1) {
data[key] = typeof params[key] === 'string' ? encodeURIComponent(params[key]) : params[key];
}
});
return data;
}
function objectToStrParams(data) {
if (!data) return '';
const params = [];
Object.keys(data).forEach((key) => {
params.push(`${key}=${data[key]}`);
});
return params.join('&');
}
module.exports.getIssueNotice = async (params) => {
return fetchPost('https://www.cde.org.cn/zdyz/getDomesticGuideList?MmEwMD=3xGxwmXEsWtn4RQ4ybYY8zBiPY1Vjq5BAiicidoBdblEQRPMlQunQztyKTAiLdGlDkIR1K2YqIwhY22LqEvfzBcIHU8uIt14CmKSDbmpjnLCUpEEgBwtsJiRxIn9C2_JbhC62qC9g9bKPwKje8k106P2<KEY>', {
pageNum: 1,
pageSize: 20,
isFbtg: 1,
classid: '2853510d929253719601db17b8a9fd81',
})
}
<file_sep>const { ipcRenderer, app, session } = require('electron')
const path = require('path');
const fse = require('fs-extra');
const fs = require('fs');
const { findIndex } = require('lodash');
// const { getIssueNotice } = require('./service')
let filedir = '';
//监听主进程,设置环境变量、记住密码
ipcRenderer.on('page-loaded', (event, json) => {
filedir = path.join(json.homePath, '/cdeFiles/news.json'); // 存放文件的位置
if (location.href.indexOf('9cd8db3b7530c6fa0c86485e563f93c7') > -1) { // 指导原则
setTimeout(getGuidPrinciple, 2000)
setTimeout(() => {
window.location.href = 'https://www.cde.org.cn/zdyz/listpage/2853510d929253719601db17b8a9fd81';
}, 20000)
} else if (location.href.indexOf('2853510d929253719601db17b8a9fd81') > -1) { // 发布通告
setTimeout(getIssueNotice, 2000)
setTimeout(() => {
window.location.href = 'https://www.cde.org.cn/zdyz/listpage/3c49fad55caad7a034c263cfc2b6eb9c';
}, 20000)
} else if (location.href.indexOf('3c49fad55caad7a034c263cfc2b6eb9c') > -1) { // 征求意见
setTimeout(getIssueNotice, 2000)
}
setInterval(() => { // 1小时定时器
window.location.href = 'https://www.cde.org.cn/zdyz/listpage/9cd8db3b7530c6fa0c86485e563f93c7';
}, 1000 * 60 * 60 * 1)
});
const saveData = async (newsList) => { // 数组新老对比
try {
// const dataStr = await fse.readFile(filedir, 'utf8')
const dataStr = fs.readFileSync(filedir, 'utf8');
const oldNewsListJSON = JSON.parse(dataStr)
const oldNewsListArr = jsonManager(oldNewsListJSON)
let hasNew = false;
for (let i = 0; i < newsList.length; i++) {
console.log(findIndex(oldNewsListArr, ['link', newsList[i].link]))
if (findIndex(oldNewsListArr, ['link', newsList[i].link]) === -1) {
oldNewsListArr.unshift(newsList[i])
hasNew = true
} else {
break
}
}
if (hasNew) {
const newsListJSON = arrayManager(oldNewsListArr)
fse.outputFileSync(filedir, JSON.stringify(newsListJSON))
}
} catch (err) {
const newsListJSON = arrayManager(newsList)
fse.outputFileSync(filedir, JSON.stringify(newsListJSON))
}
}
function getIssueNotice() { // 获取发布通告和征求意见的内容
const newslistNode = document.getElementsByClassName('news_content_title');
const newsDate = document.getElementsByClassName('news_date');
const links = document.getElementsByClassName('right_default');
const list = Array.from(newslistNode).map((i, index) => {
return { text:newslistNode[index].innerText, link: links[index].href, time: newsDate[index].innerText }
})
saveData(list);
}
function getGuidPrinciple() { // 获取指导原则
const newslistNode = document.getElementsByClassName('layui-table')[1].children[0].children;
const links = document.getElementsByClassName('a-link');
const list = Array.from(newslistNode).map((i, index) => {
const textArr = i.innerText?.split('\n') || [];
return { text:textArr[2], link: links[index].href, time: textArr[textArr.length - 1] }
})
saveData(list);
}
function arrayManager (data, pKey) { // 数组转json
const obj = {};
const keys = [];
data.forEach((item, i) => {
const key = (pKey && item[pKey]) || i;
obj[key] = item;
keys.push(key);
});
return obj
};
function jsonManager (json) { // json转数组
const arr = [];
for (var i in json) {
arr.push(json[i])
}
return arr
};<file_sep># 启动和打包详见package.json即可
# 如何解决mac下安装ffi-napi时报“No Xcode or CLT version detected!”的错误
1. `sudo rm -rf $(xcode-select -p)`
2. `sudo xcode-select --install`
3. 若第二步安装不成功,报网络错误,则手动安装xcode-select,参考这篇文章 https://www.macwk.com/article/macos-command-line-tools-cannot-be-installed
# ffi-napi github地址
https://github.com/node-ffi-napi/node-ffi-napi
windows 安装如有报错,可参考文档安装相关配置项
# 签名和公证参考文章
https://mp.apipost.cn/a/4b137555c8bdbc05 | 9bf08fc5b2de2566aff35514c88a4dd2adf1ec9f | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | hywww/package-dms-desktop | e256c02e2437217218024bcd5b3f051e43aeb792 | 1b4600e7d3be9b598476d45ff8addeab5b9435d8 |
refs/heads/master | <file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : writeResult.py
# Author: TongJC
# Date : 2020-03-28
import xlrd,os
from openpyxl import *
from xlutils.copy import *
from common.setting import bases
class WriteResult():
def writeresult(self,row,value):
print('===========测试结果写入result 表格========')
self.file_path = os.path.join(bases.REPORT_PATH, bases.RESULT_NAME)
self.workbook = xlrd.open_workbook(self.file_path)
self.new_workbook = copy(self.workbook) # 复制新的工作表
self.new_worksheet = self.new_workbook.get_sheet(0)
self.new_worksheet = self.new_worksheet.write(row,11,value) #重新写入
self.new_workbook.save(self.file_path)
if __name__ == '__main__':
import time
write = WriteResult()
for i in range(1,5):
time.sleep(2)
write.writeresult(i,"helloworld"+str(i))
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : test_newlogin_case.py
# Author: TongJC
# Date : 2020-03-30
from common.requestMethod import RunMethod
from common.getparam import OpExcel
from case.mybase import MyBase
from common.writeResult import WriteResult
import requests,json
#停止维护
class newLoginCase(MyBase):
def test_case(cls):
cls.request = RunMethod()
cls.myExcel = OpExcel()
cls.writeResult = WriteResult()
cls.s = requests.session()
list_dict = cls.myExcel.get_param("LoginCase")
cell = 1
for i in list_dict:
url = i['url']
method = i['method'].lower()
print(method)
headers = json.loads(i['headers'])
data = json.loads(i['data'])
expect = i['expect']
result = cls.request.run_main(method,url,data)
print(result)
cls.assertIn(expect,result)
if expect in result:
cls.writeResult.writeresult(cell,"通过")
else:
cls.writeResult.writeresult(cell, "失败")
cell +=1
if __name__ == '__main__':
# MyBase.main()
run = newLoginCase()
run.test_case()<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : LWJ_case.py
# Author: TongJC
# Date : 2020/1/8
import requests
from case.mybase import MyBase
import json,re
from common.getparam import opexcel
from common.log import atp_log
class LWJ_Case(MyBase):
u"""LWJ登录成功"""
def test_login_success(cls):
atp_log.info("测试LWJ登录成功场景")
url= 'http://siteadmin-staging.liweijia.com/security/lv_check?type=normal&returnUrl=http%3A%2F%2Fsiteadmin-staging.liweijia.com%2F'
atp_log.info("加载初始URL【%s】"%url)
header = {
"laravel_session":"hgsjpU63z4cDebMX6XvqWQ9jtaHEirCyP2qn8fpB",
"sid" : "node_aojia_25513rw1j4iqkiml18o130eh8n0y4.node_aojia_255",
"LX-WXSRF-JTOKEN":"<PASSWORD>"
}
data = {
"lv_username": "<EMAIL>",
"lv_password": <PASSWORD>"
}
res = requests.post(url= url, headers = header, data= data, verify = False, allow_redirects = False)
print(res.headers)
#字符串操作
#cookie_sid = res.headers['Set-Cookie'].split(';')[0]
#cookie_LWJ = res.headers['Set-Cookie'].split(' ')[1].split(';')[0]
#正则表达式
cookie_sid = re.findall(r'(sid=.+api)', str(res.headers))[0]
#print(cookie_sid)
cookie_LWJ = re.findall(r'(LX-WXSRF-JTOKEN=.+;P)', str(res.headers))[0].split(';')[0]
print(cookie_LWJ)
#print(res.headers['Set-Cookie'])
#print(cookie_LWJ)
atp_log.info("禁止重定向,获取response headers【%s,%s】"%(cookie_sid,cookie_LWJ))
new_cookie = cookie_sid + ';' + cookie_LWJ
atp_log.info("组装新的headers【%s】"%new_cookie)
url2 = 'http://cloud.sales-staging.liweijia.com/services/ums/isLogin'
atp_log.info("加载登录验证URL【%s】"%url2)
header2 = {
"Cookie": new_cookie
}
res2 = cls.s.get(url = url2, headers = header2, verify = False)
#print(json.loads(res2.text))
#print(type(json.loads(res2.text)))
hope_data = json.loads(res2.text)['result']['name']
atp_log.info("获取验证关键信息【%s】"%hope_data)
#print(hope_data)
cls.assertIn("管理员",hope_data)
atp_log.info("断言结果【%s】? =【管理员】"%hope_data)
if __name__ == '__main__':
lwj = LWJ_Case()
lwj.test_login_success()
<file_sep>import requests
from case.mybase import MyBase
import json
from common.getparam import opexcel
from common.log import atp_log
class LoginCase(MyBase):
u"""通过case_name驱动"""
#def setUp(self):
#warnings.simplefilter("ignore",ResourceWarning) #忽略ResourceWarning
#self.s = requests.session()
def test_login_success(cls):
u"""登录成功场景"""
atp_log.info('==========测试账号密码正确登录成功场景==========')
test_login_success_data = opexcel.get_test_data(opexcel.get_param("LoginCase"),
"test_login_success") # 类名与sheet页名一致,用例方法名与excel中case_name一致
if not test_login_success_data:
atp_log.warning("未获取到用例数据")
url = test_login_success_data.get('url')
atp_log.info("读取URL--【%s】"%url)
headers = test_login_success_data.get('headers')
data = test_login_success_data.get('data')
atp_log.info("接口参数--【%s】"%data)
expect_res = test_login_success_data.get('expect_res')
res = cls.s.post(url = url,
headers = json.loads(headers),
json=json.loads(data),
verify = False)
result = json.loads(res.text)["code"] #从请求返回中获取关键字
#se1 = "SUCCESS" #登录成功则返回SUCCESS
atp_log.info('断言:【%s】?=【%s】'%(expect_res,result))
cls.assertEqual(expect_res,result) #断言
def test_login_fail(cls):
u"""登录失败场景"""
atp_log.info('==========测试账号密码错误登录失败场景==========')
test_login_fail_data = opexcel.get_test_data(opexcel.get_param("LoginCase"),
"test_login_fail") #
if not test_login_fail_data:
atp_log.warning("未获取到用例数据")
url = test_login_fail_data.get('url')
atp_log.info("读取URL--【%s】" % url)
headers = test_login_fail_data.get('headers')
data = test_login_fail_data.get('data')
atp_log.info("接口参数--【%s】" % data)
expect_res = test_login_fail_data.get('expect_res')
res = cls.s.post(url =url,
headers = json.loads(headers),
json=json.loads(data),
verify = False)
result = json.loads(res.text)["msg"]
#se2 = "用户名或密码错误121" #账户或密码错误则返回错误data
atp_log.info('断言:【%s】?=【%s】' % (expect_res, result))
cls.assertEqual(expect_res,result)
if __name__ == '__main__':
MyBase.main()<file_sep>import xlrd,os,json
import jsonpath
from xlutils import copy
from common.log import atp_log
from common.setting import bases
class OpExcel():
"""从excel中读取参数,并转换 成字典"""
def __init__(self):
# 用一个字典来接收每个请求返回的数据,作为后面有参数关联的全局参数
self.result_dict = {}
#从excel提取list[dict{}]
def get_param(self,sheet_name):
param_path = os.path.join(bases.PARAM_PATH, bases.PARAM_NAME)
params_list = []
if param_path.endswith('.xls') or param_path.endswith('.xlsx'): #判断参数文件是否合法
try:
book = xlrd.open_workbook(param_path) #打开excel
sheet = book.sheet_by_name(sheet_name) #获取sheet页
title = sheet.row_values(0)
for i in range(1,sheet.nrows): #循环每一行
row_data = sheet.row_values(i) #获取每行数据
data = dict(zip(title,row_data)) #将第标题和对应数据组装成dict
params_list.append(data)
except Exception as e:
atp_log.error('【%s】excel参数获取失败,错误信息为%s'%(param_path,e))
else:
atp_log.error('参数文件不合法>>%s'%param_path)
return params_list
"""
def get_test_data(self,params):
param_list = []
param_dic = {}
dic_id = 1
for list in params:
case_num =len(params)
for i in list:
param_list.append(i) #循环取出params中的参数append到param_list
if i.endswith("}"): #从param_list中取出参数,组装成字典,key从1开始计数
param_dic[dic_id] = eval(i) #如果取出的参数是{}这种形式的str,使用eval处理为有效表达式dict
else:
param_dic[dic_id] = i
dic_id += 1
atp_log.info("共获取到%s条用例参数"%case_num)
return param_dic
"""
def _get_test_data(self,params_list,case_name):
#本方法暂时没用
for case_data in params_list:
if case_name == case_data['case_name']: #当从列表中找到对应用例名的数据时,返回该字典
return case_data
#获取json中参数
def get_json_data(self,keyname):
"""
从json文件取对应参数
:param keyname:
:return:
"""
json_path = os.path.join(bases.PARAM_PATH,"data.json")
with open(json_path,encoding='utf-8') as f:
data = json.loads(f.read())[keyname] #读取对应的json参数
return data
#多个依赖参数分割
def relation_data(self,str):
"""
:param str:
:return:
"""
list_data = []
if str !='':
if ',' in str:
list_data = str.split(',')
else:
list_data.append(str)
return list_data
#将读取到的参数进行处理
def convert_data(self,sheet):
"""
根据参数文档中data字段,判断是否需要从json文件提取对应数据。
如果本身为json直接转为dict即可
有些json参数特别大,仅用excel难以管理故使用json文件,需从json文件取数据。
:param sheet: 读取的sheet名
:return: [data1{},data2{}...]
"""
data = self.get_param(sheet)
for i in data:
if i['data'] != '':
if i['data'].endswith('}'): #如果以}结尾,表示本身是json参数
i['data'] = json.loads(i['data']) #本身是json,直接转换为字典即可
else:
i['data'] =self.get_json_data(i['data']) #否则就取json文件中对应的json
#atp_log.info("不需从json文件取数据")
return data
#关联参数提取
def get_response_data(self, str, regex):
"""
从接口返回结果,根据regex表达式取出对应数据
:param str: 接口返回结果
:param regex: jsonpath表达式
:return:
"""
if str !=''and str.endswith('}') and regex !='':
pyjson = json.loads(str) #返回参数的json字串转换为dict
#pyjson = eval(str)
data =jsonpath.jsonpath(pyjson,regex) #根据jsonpath表达式查找对应数据
if isinstance(data, list):
return data[0] #jsonpath提取返回结果为list
else:
atp_log.error('关联参数获取为None')
return ''
elif str !=''and str.endswith('>') and regex !='':
atp_log.error('暂时没有支持xml解析,待下个版本优化')
else:
atp_log.info('接口返回数据为空或Excel中depend_data为空')
opexcel = OpExcel() #实例化
if __name__ == '__main__':
import requests
# params=opexcel.convert_data("LoginCase")
# req = requests.session()
# req.post(url =params[0]['url'],json = params[0]['data'])
# res = req.post(url =params[2]['url'] ,headers = {'RSESSIONID_NAME':'82f8192546aa5d5b4a3099e8361ec525'},json = params[2]['data'])
# print(res.text)
print(opexcel.get_param("LoginCase"))
#print(opexcel.relation_data('smaaa,hshha'))
print(opexcel.get_response_data('{"a":"123","c":{"b":"456"}}','$.a'))
<file_sep>from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
import smtplib
from .log import atp_log
from .setting import bases #引入Setting的实例化对象
class MailSend():
def send_mail(self,smtp_dict, report):
"""
用于将测试报告发送到邮箱
:param
smtp_dict = {
"smtp_server": "发送邮件的smtp ex:smtp.126.com",
"send_user": "发送邮件的邮箱 ex:<EMAIL>",
"send_pwd": "发送邮件的邮箱密码 ex:<PASSWORD>",
"sender": "发件人邮箱用于显示收到邮件中的发件人 ex:<EMAIL>",
"receiver": "收件人邮箱 ",多个收件人可以写成list
"subject": "邮件主题 ex:自动化测试报告"
"from":"邮件发送方 ex:smartpig自动化平台"
}
"""
# 邮件正文内容
content = bases.CONTENT # 获取Setting对象属性(正文内容)
textApart = MIMEText(content)
# 组装邮件
msg = MIMEMultipart()
# 添加多个附件
for i in range(len(report)):
htmlApart = MIMEApplication(open(report[i], 'rb').read()) # 读取附件
htmlApart.add_header('Content-Disposition', 'attachment', filename=report[i].split('\\')[-1]) # 邮件中展示的附件名称可以自定义
msg.attach(htmlApart) # 附件
msg.attach(textApart) # 邮件正文
msg['Subject'] = smtp_dict["subject"] # 设置邮件主题
msg['From'] = formataddr([smtp_dict["from"], smtp_dict["send_user"]]) # 设置发件人昵称
# 发送邮件
try:
smtp = smtplib.SMTP_SSL() # QQ邮箱必须用SSL 其他可以不用
smtp.connect(smtp_dict["smtp_server"], port=465) # 其他邮箱端口为25
smtp.login(smtp_dict["send_user"], smtp_dict["send_pwd"])
smtp.sendmail(smtp_dict["sender"], smtp_dict["receiver"], msg.as_string())
atp_log.info("报告邮件已发送")
smtp.quit() # 断开链接
except smtplib.SMTPException as se:
atp_log.error("邮件发送失败!!%s" % se)
print("邮件发送失败报错信息为:%s" % se)
mail_send = MailSend()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : requestMethod.py
# Author: TongJC
# Date : 2020-03-30
import requests
class RunMethod():
def __init__(self):
self.requests = requests.session()
def post_main(self,url,header = None,data = None):
if header !=None:
res = self.requests.post(url =url,headers =header, data =data)
else:
res = self.requests.post(url=url, data =data)
return res
def get_main(self, url, header=None, data = None):
if header ==None:
res = self.requests.get(url=url, data=data)
else:
res = self.requests.get(url=url, headers=header, data=data)
return res
def postjson_main(self,url,data=None):
res = self.requests.post(url=url, json=data)
return res
def delete_main(self,url,data = None):
res = self.requests.delete(url = url,json = data)
return res
def run_main(self, method, url, data=None):
if method =='postjson':
res = self.postjson_main(url,data)
elif method == 'post':
res = self.post_main(url,data)
elif method =='delete':
res = self.delete_main(url,data)
else:
res = self.get_main(url,data)
return res
myRequest = RunMethod()<file_sep>import unittest,time
class Login_case(unittest.TestCase):
u"""测试用例集合:描述XX"""
@classmethod
def setUpClass(cls):
time.sleep(1)
print("在每次setUp之前执行")
@classmethod
def tearDownClass(cls):
pass
def setUp(self):
pass
def tearDown(self):
pass
def test_login(self):
print("正在运行用例")
if __name__ == '__main__':
unittest.main()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : ddt_newlogin_case.py
# Author: TongJC
# Date : 2020-03-31
import ddt,json,os,xlrd
from xlutils.copy import *
from common.setting import bases
from case.mybase import MyBase
from common.getparam import opexcel
from common.requestMethod import myRequest
from common.log import atp_log
@ddt.ddt
class NewLoginCase(MyBase):
u"""慧养猪接口测试"""
params = opexcel.convert_data("LoginCase")
@ddt.data(*params)
def test_run_case(cls,i):
result_dict = opexcel.result_dict #全局字典
if i['run'].lower() == 'yes':
atp_log.info("==========参数获取==========")
print("==========参数获取==========")
#准备请求参数
url = i['url']
method = i['method'].lower()
data = i['data']
expect = i['expect']
row = int(i['id'].split('-')[1] ) #当前用例在excel中的行数
#获取参数依赖
if i['depend_id'].startswith("smartpig"):
depend_id_list = opexcel.relation_data(i['depend_id'])
depend_data_list = opexcel.relation_data(i['depend_data'])
atp_log.info("=========等待数据依赖处理==========")
print("=========等待数据依赖处理==========")
try:
for j in range(len(depend_id_list)):
depend_data = opexcel.get_response_data(result_dict[depend_id_list[j]],
depend_data_list[j]) #获取到依赖接口返回的指定数据
if method == 'delete':
if depend_data !='':
url = os.path.join(url, depend_data) #将url拼接
else:
data = json.loads(json.dumps(data).replace('$'+str(j+1),depend_data)) #以此替换json中的$1,$2.......
# depend_data = opexcel.get_response_data(result_dict[i['depend_id']],i['depend_data']) #获取依赖的返回数据
# if method == 'delete':
# url = os.path.join(url, depend_data) #将url拼接
# else:
# data = data.replace('$',depend_data) #如果是json中的依赖参数,就替换
except Exception as e:
atp_log.error("获取返回依赖数据失败--%s"%e)
atp_log.info("【%s】--url:%s" % (method, url))
print("【%s】--url:%s" % (method, url))
atp_log.info("data == %s"%data)
print("data == %s"%data)
result = None
try:
result = myRequest.run_main(method, url, data)
except Exception as e:
atp_log.error("请求发送失败:%s"%e)
atp_log.info("statusCode = 【%s】"%result.status_code)
print("statusCode = 【%s】"%result.status_code)
atp_log.info("result == %s"%result.text)
print("result == %s"%result.text)
result_dict[i['id']] = result.text #将返回结果添加到全局字典
#print(result_dict)
cls.assertIn(expect, result.text)
try:
if expect in result.text:
cls.writeResult.writeresult(row, "测试通过")
else:
cls.writeResult.writeresult(row, "测试失败")
cls.writeResult.saveresult()
except Exception as e:
atp_log("测试结果写入失败-----【%s】"%e)
else:
#cls.assertEqual(1,1,"skip")
row = int(i['id'].split('-')[1])
cls.writeResult.writeresult(row, "未执行")
if __name__ == '__main__':
MyBase.main()
<file_sep>import logging,os
from logging import handlers
from .setting import bases #引入Setting的实例化对象
class MyLogger():
def get_level(self,str):
level={
'debug':logging.DEBUG,
'info':logging.INFO,
'warn':logging.WARNING,
'error':logging.ERROR
}
str=str.lower()
return level.get(str)
def __init__(self,file_name,level='info',backCount=5,when='D'):
logger=logging.getLogger() # 先实例化一个logger对象
logger.setLevel(self.get_level(level)) # 设置日志的级别的人
cl=logging.StreamHandler() # 负责往控制台输出的人
bl = handlers.TimedRotatingFileHandler(filename=file_name, when=when, interval=1, backupCount=backCount,encoding='utf-8')
fmt = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')
cl.setFormatter(fmt) # 设置控制台输出的日志格式
bl.setFormatter(fmt) # 设置文件里面写入的日志格式
logger.addHandler(cl)
logger.addHandler(bl)
self.logger = logger
path=os.path.join(bases.LOG_PATH,bases.LOG_NAME) #拼好日志的绝对路径
atp_log = MyLogger(path,bases.LEVEL).logger #直接在这里实例化,用的时候就不用再实例化了
<file_sep>import os
import unittest
from common import HTMLTestRunner_cn
from common.setting import bases #引入Setting的实例化对象
from common.myemail import mail_send #引入MailSend的实例化对象
import sys
import os
from common.log import atp_log
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(curPath)
def add_case(rule = "ddt_newlogin_case.py"):
"""第一步,获取setting的CASE_PATH,组装case,返回case列表"""
discover = unittest.defaultTestLoader.discover(bases.CASE_PATH,pattern=rule)
#print(discover)
return discover
def run_case():
"""第二步,运行所有case,生成测试报告,返回报告的绝对路径"""
reportFilePath = os.path.join(bases.REPORT_PATH,bases.REPORT_NAME) #组装完整的报告绝对路径
with open(reportFilePath,"wb") as file:
runner = HTMLTestRunner_cn.HTMLTestRunner(stream=file,
verbosity=2,
title="API自动化测试报告",
description="本次测试是针对慧养猪API接口串联测试,结果如下:",
retry=0,
save_last_try=False
)
runner.run(add_case())
return reportFilePath
if __name__ == '__main__':
smtp_dict = bases.SMTP_DICT #获取参数
result = os.path.join(bases.REPORT_PATH,bases.RESULT_NAME) #测试结果
# atp_log.info("获取邮件参数,准备将测试结果写入邮件...")
#mail_send.send_mail(smtp_dict, [run_case(),result]) #直接调用邮件发送即可运行所有用例
run_case()
<file_sep>import unittest
import warnings
import requests
from common.log import atp_log
from common.getparam import OpExcel
from common.requestMethod import RunMethod
from common.writeResult import WriteResult
import os,xlrd
from xlutils.copy import *
from common.setting import bases
class MyBase(unittest.TestCase):
"""继承Unittest,处理warning."""
@classmethod
def setUpClass(cls):
atp_log.info('=====测试开始=====')
warnings.simplefilter("ignore", ResourceWarning) # 忽略ResourceWarning
#cls.s = requests.session() #session关联,会话保持
#cls.data_dic = opexcel.get_test_data(opexcel.get_param()) #从excel获取的参数,用例继承该父类,可直接使用参数
cls.writeResult = WriteResult()
cls.cell = 1
# 初始化结果excel
cls.file_path = os.path.join(bases.PARAM_PATH,bases.PARAM_NAME)
cls.workbook = xlrd.open_workbook(cls.file_path)
cls.new_workbook = copy(cls.workbook) # 复制新的工作表
#cls.new_worksheet = cls.new_workbook.get_sheet(0)
cls.new_workbook.save(os.path.join(bases.REPORT_PATH,bases.RESULT_NAME)) #结果xls文件创建
@classmethod
def tearDownClass(cls):
atp_log.info('=====测试结束=====')
<file_sep>import ddt,json
from case.mybase import MyBase
import unittest,requests
from common.getparam import opexcel
import warnings
from common.log import atp_log
#print(opexcel.get_param("LoginCase_DDT"))
#ddt_data = opexcel.get_param("LoginCase_DDT")
@ddt.ddt
class LoginDdtCase(MyBase):
u"""ddt数据驱动模式"""
ddt_data = opexcel.get_param("LoginCase_DDT") #获取LoginCase_DDT这个sheet页的数据
def setUp(cls):
cls.s = requests.session()
warnings.simplefilter("ignore", ResourceWarning)
atp_log.info("======ddt驱动模式======")
atp_log.info("======setUp======")
def login_msg(cls,url,headers,data):
response = cls.s.post(url=url, headers=headers, json=data)
return response
@ddt.data(*ddt_data)
def test_login_case(cls,data):
u"""登录成功/失败场景"""
res = cls.login_msg(data['url'], json.loads(data['headers']), json.loads(data['data'])) #转换为dict
atp_log.info("接口调用......")
result = json.loads(res.text)[data['msg']] #获取response的关键信息
atp_log.info('断言:【%s】?=【%s】'%(result,data['expect_res']))
cls.assertIn(data['expect_res'], result) #断言
def tearDown(cls):
atp_log.info("======tearDown======")
if __name__ == '__main__':
MyBase.main()<file_sep>import os.path
import time
class Setting():
"""存放全局基础信息,方便管理"""
def __init__(self):
self.BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
self.SMTP_DICT = {
"smtp_server": "smtp.exmail.qq.com", # 发送邮件服务器
"send_user": "<EMAIL>", # 发送邮件的邮箱账号
#"send_pwd": "<PASSWORD>", # 发送邮件的账号密码
"send_pwd" : "<PASSWORD>",
"sender": "<EMAIL>", # 显示在邮件中的发件人,必须与send_user一致
"receiver": ["<EMAIL>","<EMAIL>","<EMAIL>"], # 收件邮箱地址
"subject": "smartpig自动化测试报告", # 邮件主题
"from": "smartpig自动化平台" #邮件发送方
}
# 项目名称(自定义)
self.PROJECT_NAME = 'Smartpig'
# 存放用例的路径
self.CASE_PATH = os.path.join(self.BASE_PATH,'case')
# 存放报告的路径
self.REPORT_PATH = os.path.join(self.BASE_PATH,'report')
# 报告的文件名
times = time.strftime("%Y%m%d%H%M%S")
self.REPORT_NAME = self.PROJECT_NAME+times+'report.html'
#邮件中正文内容
self.CONTENT = 'Hi all,\n 本次测试结果已生成,请查阅附件(本邮件是自动化测试邮件,请勿回复!)。为了更好的报告展示,请您使用chrome打开报告。谢谢!'
#邮件中展示自定义附件名
self.File_NAME = 'smartpig_report.html'
# 日志的文件名
self.LOG_NAME='atp.log'
# 存放日志的路径
self.LOG_PATH = os.path.join(self.BASE_PATH, 'logs')
# 默认日志级别
self.LEVEL = 'info'
# 用例参数文件路径
self.PARAM_PATH = os.path.join(self.BASE_PATH,'params')
# 用例参数文件名
self.PARAM_NAME = 'interface.xlsx'
# 测试结果文件名
self.RESULT_NAME = 'result'+times+'.xls'
bases = Setting() #实例化Setting
<file_sep># ApiTest框架
基本结构:
本框架基于unittest,综合了很多大神的思想和实现方式。也有一点点自己不成熟的思考。python水平有限,槽点肯定很多,还有很多可优化封装的地方,暂时先用着吧,下个版本继续优化。
## 第一版本
### 1.Excel读取
将Excel数据转换为以表头为key,对应的每一个单元格为value的dict,并将多个dict组装到list。
得到list[dict{}],即List<Map<K,V>>
### 2.根据用例名称对应,手写case
```python
def test_login_fail(cls):
u"""登录失败场景"""
atp_log.info('==========测试账号密码错误登录失败场景==========')
test_login_fail_data = opexcel.get_test_data(opexcel.get_param("LoginCase"),
"test_login_fail") #
if not test_login_fail_data:
atp_log.warning("未获取到用例数据")
url = test_login_fail_data.get('url')
atp_log.info("读取URL--【%s】" % url)
headers = test_login_fail_data.get('headers')
data = test_login_fail_data.get('data')
atp_log.info("接口参数--【%s】" % data)
expect_res = test_login_fail_data.get('expect_res')
res = cls.s.post(url =url,
headers = json.loads(headers),
json=json.loads(data),
verify = False)
result = json.loads(res.text)["msg"]
#se2 = "用户名或密码错误121" #账户或密码错误则返回错误data
atp_log.info('断言:【%s】?=【%s】' % (expect_res, result))
cls.assertEqual(expect_res,result)
```
### 3.测试报告
## 第二版本
### 1.日志模块
### 2.邮件模块
### 3.setting模块
将全局的path,邮箱配置,参数配置封装
## 第三版本
### 1.DDT驱动
```python
@ddt.ddt
class NewLoginCase(MyBase):
params = opexcel.convert_data("LoginCase")
@ddt.data(*params)
def test_run_case(cls,i):
result_dict = opexcel.result_dict #全局字典
if i['run'].lower() == 'yes': #准备请求参数
url = i['url']
method = i['method'].lower()
data = i['data']
expect = i['expect']
row = int(i['id'].split('-')[1]) #当前用例在excel中的行数
#获取参数依赖
if i['depend_id'].startswith("smartpig"):
try:
depend_data =
opexcel.get_response_data(result_dict[i['depend_id']],i['depend_data']) #获取依赖的返回数据
if method == 'delete':
url = os.path.join(url, depend_data) #将url拼接 else:
data = data.replace('$',depend_data) #如果是json中的依赖参数,就替换 except Exception as e:
atp_log.error("获取返回依赖数据失败--%s"%e)
result = myRequest.run_main(method, url, data) result_dict[i['id']] = result #将返回结果添加到全局字典
print(result_dict)
cls.assertIn(expect, result)
try:
if expect in result: cls.writeResult.writeresult(row, "测试通过")
else:
cls.writeResult.writeresult(row, "测试失败")
except Exception as e:
atp_log("测试结果写入失败!!")
```
### 2.api参数关联问题处理
引入jsonpath
根据depend_id找到对应的用例编号,根据用例编号找到对应的全局的result_dict,从中取出该api返回结果。根据depend_data,通过jsonpath,找到对应数据。
然后将对应数据赋值给relation_data里对应的字段。思考,如果是一个接口请求参数需要前面多个返回值的支持,那就将depend_id和depand_data做成List,如果list长度==1,则直接都去list[0],与之前操作一样。如果是list长度>=2,就循环list,分别取值,替换即可。
### 3.json文件
如果将我们接口所需参数直接贴至excel,会占用很大篇幅且很难看
使用json文件,与对应data字段对应,则清晰明了
### 4.requests封装
根据不同的请求,get、post、delete、put等统一封装,调用一个方法即可
## 第四版本
### 1.测试结果回写
可以直观的通过excel,知道每一个api测试结果
### 2.多参数关联问题处理
将depend_id设置为id1,id2 这样以逗号分割,depend_data,也是以逗号分割得jsonpath表达式。通过将他们分别组装成depend_id_list与depend_data_list。再迭代depend_id_list,分别取到response对应的数据,根据原本在请求json参数中设置的$1,$2做替换,即可解决多参数依赖问题。
```python
if i['depend_id'].startswith("smartpig"):
depend_id_list = opexcel.relation_data(i['depend_id'])
depend_data_list = opexcel.relation_data(i['depend_data'])
atp_log.info("=========等待数据依赖处理==========")
print("=========等待数据依赖处理==========")
try:
for j in range(len(depend_id_list)):
depend_data = opexcel.get_response_data(result_dict[depend_id_list[j]],depend_data_list[j]) #获取到依赖接口返回的指定数据
if method == 'delete':
url = os.path.join(url, depend_data) #将url拼接
else:
data = json.loads(json.dumps(data).replace('$'+str(j+1),depend_data)) #以此替换json中的$1,$2.......
# depend_data = opexcel.get_response_data(result_dict[i['depend_id']],i['depend_data']) #获取依赖的返回数据
# if method == 'delete':
# url = os.path.join(url, depend_data) #将url拼接
# else:
# data = data.replace('$',depend_data) #如果是json中的依赖参数,就替换
except Exception as e:
atp_log.error("获取返回依赖数据失败--%s"%e)
```
### 3.在测试报告中展示日志
这个只需在代码关键位置print即可
| 2168762e25c2964dc65bec6f89046e186f79c3de | [
"Markdown",
"Python"
] | 15 | Python | tongjc123/ApiTest | edc6644c4c7a0086f862a2913e1ff04768de3ba9 | 8390eb548632b93d0906065f7d6278840ba24d1d |
refs/heads/main | <repo_name>Nakul-bot/floema<file_sep>/app/pages/Detail/index.js
import Page from 'classes/Page';
export default class Detail extends Page {
constructor() {
super({ id: 'detail', element: '.detail' });
}
}
| e3b5e7d90d21c2a8354c7ddb217a2e2ffb903619 | [
"JavaScript"
] | 1 | JavaScript | Nakul-bot/floema | 3a243b56fe7a2a9439a57bf61401ccf8e1656f3c | e9d2adac2c21c834ff6c31046a7eccfd050f3134 |
refs/heads/master | <repo_name>thp/tactile<file_sep>/debian/postinst
#!/bin/sh
if [ -x /usr/sbin/update-sudoers ]; then
/usr/sbin/update-sudoers
fi
<file_sep>/demo.py
#!/usr/bin/python
# (c) 2011-02-17 <NAME> <thp.io>; public domain
import gtk
import hildon
import time
import subprocess
def tactile(pattern):
subprocess.Popen(('sudo', 'tactile', pattern))
def cb(*args):
tactile(args[-1])
def on_visible(widget, visible, kind):
if widget.props.visible:
tactile(kind)
else:
tactile(kind+'-out')
w = hildon.StackableWindow()
a = hildon.AppMenu()
b = gtk.Button('blubb')
b.connect('button-press-event', cb, 'button')
def on_show_dialog(*args):
global dlg
dlg.show_all()
a.append(b)
a.connect('notify::visible', on_visible, 'appmenu')
w.set_app_menu(a)
a.show_all()
dlg = gtk.Dialog()
dlg.connect('notify::visible', on_visible, 'dialog')
dlg.set_title('heya')
for i in range(7):
dlg.vbox.add(gtk.Label('xxx'+str(i)))
def on_delete(dlg, *args):
dlg.hide()
return True
dlg.connect('delete-event', on_delete)
sw = hildon.PannableArea()
adj = sw.get_vadjustment()
def xxx(*args):
if adj.props.value == adj.props.lower:
cb('scroll-stop')
adj.connect('changed', xxx, 'changed')
v = gtk.VBox()
v.set_border_width(20)
sw.add_with_viewport(v)
b = gtk.Button('show the dialog')
b.connect('clicked', on_show_dialog)
b.set_name('HildonButton-finger')
b.set_size_request(-1, 70)
b.connect('button-press-event', cb, 'button')
v.add(b)
v.add(gtk.Label(' '))
def on_value_changed(*args):
tactile('slider-change')
hsc = gtk.HScale()
hsc.set_range(0, 1000)
hsc.connect('value-changed', on_value_changed)
v.add(hsc)
v.add(gtk.Label(' '))
for i in range(200):
v.add(gtk.Label('xxx'+str(i)))
w.add(sw)
w.connect('destroy', gtk.main_quit)
w.show_all()
gtk.main()
<file_sep>/makefile
CFLAGS += -O2 -Wall
LDFLAGS += -s
tactile: tactile.o
install: tactile
install tactile $(DESTDIR)/usr/bin
install -m755 demo.py $(DESTDIR)/usr/bin/tactile-demo.py
install -m644 tactile.sudoers $(DESTDIR)/etc/sudoers.d
clean:
rm -f tactile tactile.o
<file_sep>/tactile.c
/* (c) 2011-02-17 <NAME> <thp.io>; public domain */
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define VIBRA "/sys/class/leds/twl4030:vibrator/brightness"
typedef struct {
const char *name;
useconds_t delay;
unsigned char pattern[128];
int count;
} Pattern;
static Pattern patterns[] = {
{"button", 15, {200}, 1},
{"appmenu", 40, {40, 70, 20, 50, 40, 20}, 6},
{"appmenu-out", 40, {30, 45, 30, 35, 30, 20}, 6},
{"dialog", 30, {0, 60, 0, 70, 0, 80}, 6},
{"dialog-out", 30, {0, 60, 0, 50, 0, 30}, 6},
{"scroll-stop", 10, {120}, 1},
{"slider-change", 20, {50, 40, 30, 20, 30, 40}, 6},
{NULL},
};
int set(unsigned char value, useconds_t delay)
{
FILE *fp;
if ((fp = fopen(VIBRA, "w")) != NULL)
{
fprintf(fp, "%d\n", (int)value);
fclose(fp);
usleep(1000*delay);
return 0;
}
return 1;
}
int play(Pattern *p)
{
int i = 0;
while (i < p->count)
set(p->pattern[i++], p->delay);
return set(0, 0);
}
int main(int argc, char **argv)
{
Pattern *p;
if (argc == 2)
for (p = patterns; p->name; p++)
if (!strcmp(p->name, argv[1]))
return play(p);
return 1;
}
<file_sep>/debian/rules
#!/usr/bin/make -f
# -*- makefile -*-
# Sample debian/rules that uses debhelper.
# This file was originally written by <NAME> and <NAME>.
# As a special exception, when this file is copied by dh-make into a
# dh-make output file, you may use that output file without restriction.
# This special exception was added by <NAME> in version 0.37 of dh-make.
build: build-stamp
build-stamp:
dh_testdir
$(MAKE)
touch $@
clean:
dh_testdir
dh_testroot
rm -f build-stamp
-$(MAKE) clean
dh_clean
install: build
dh_testdir
dh_testroot
dh_clean -k
dh_installdirs
$(MAKE) DESTDIR=$(CURDIR)/debian/tactile install
binary: build install
dh_testdir
dh_testroot
dh_installchangelogs
dh_link
dh_strip
dh_compress
dh_fixperms
dh_installdeb
dh_shlibdeps
dh_gencontrol
dh_md5sums
dh_builddeb
.PHONY: build clean binary install
| 5817eb2e9c0d6f22c25fb8239f800e01e1d3ac0a | [
"C",
"Python",
"Makefile",
"Shell"
] | 5 | Shell | thp/tactile | 6109a1ab1a915c62f8712cc6fe0eccd5bacc2f46 | 73db09145f0f7dd5a525f45299fdd813997f961c |
refs/heads/master | <file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 1192.168.127.12
-- Generation Time: Aug 20, 2020 at 05:44 PM
-- Server version: 10.4.11-MariaDB
-- PHP Version: 7.4.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `restful_db`
--
-- --------------------------------------------------------
--
-- Table structure for table `kontak`
--
CREATE TABLE `kontak` (
`kontak_id` int(5) NOT NULL,
`no_ktp` int(16) NOT NULL,
`nama` varchar(64) NOT NULL,
`no_hp` int(16) NOT NULL,
`alamat` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `kontak`
--
INSERT INTO `kontak` (`kontak_id`, `no_ktp`, `nama`, `no_hp`, `alamat`) VALUES
(2, 123123123, 'testing', 321321321, 'jl. abcd');
-- --------------------------------------------------------
--
-- Table structure for table `product`
--
CREATE TABLE `product` (
`product_id` int(11) NOT NULL,
`product_name` varchar(200) DEFAULT NULL,
`product_price` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `product`
--
INSERT INTO `product` (`product_id`, `product_name`, `product_price`) VALUES
(1, 'Akua', 3000),
(2, 'Indomi', 3000),
(15, 'Teh Pucuk', 4000);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `kontak`
--
ALTER TABLE `kontak`
ADD PRIMARY KEY (`kontak_id`);
--
-- Indexes for table `product`
--
ALTER TABLE `product`
ADD PRIMARY KEY (`product_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `kontak`
--
ALTER TABLE `kontak`
MODIFY `kontak_id` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const prodRouter = require('./routes/products')
const kontakRouter = require('./routes/kontak')
// parse application/json
app.use(bodyParser.json());
//load route
app.use('/api/products', prodRouter)
app.use('/api/kontak', kontakRouter)
//Server listening
app.listen(3000,() =>{
console.log('Server started on port 3000...');
});<file_sep>//-----------import express-----------
const express = require('express')
const router = express.Router()
const db = require('../db');
const { route } = require('./kontak');
//tampilkan semua data product
router.get('/',(req, res) => {
let sql = "SELECT * FROM product";
let query = db.query(sql, (err, results) => {
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
//tampilkan data product berdasarkan id
router.get('/:id',(req, res) => {
let sql = "SELECT * FROM product WHERE product_id="+req.params.id;
let query = db.query(sql, (err, results) => {
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
//Tambahkan data product baru
router.post('/',(req, res) => {
let data = {product_name: req.body.product_name, product_price: req.body.product_price};
let sql = "INSERT INTO product SET ?";
let query = db.query(sql, data,(err, results) => {
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
//Edit data product berdasarkan id
router.put('/:id',(req, res) => {
let sql = "UPDATE product SET product_name='"+req.body.product_name+"', product_price='"+req.body.product_price+"' WHERE product_id="+req.params.id;
let query = db.query(sql, (err, results) => {
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
//Delete data product berdasarkan id
router.delete('/:id',(req, res) => {
let sql = "DELETE FROM product WHERE product_id="+req.params.id+"";
let query = db.query(sql, (err, results) => {
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
//-----------export-----------
module.exports = router | 6bb511fa18d9a645180d82cfb5e5160df066ba8d | [
"JavaScript",
"SQL"
] | 3 | SQL | dnsiwa/restful-api | bdd0d893c9819f9c55d312b2dd001151e27e813b | 2bc8ddb281bc089f71499828a77dc4c4fde99413 |
refs/heads/master | <repo_name>aoesoft/myplugin<file_sep>/aoesoft/src/aoesoft/ui/MyAction.java
package aoesoft.ui;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
public class MyAction implements IWorkbenchWindowActionDelegate {
private IWorkbenchWindow window;
public void run(IAction action) {
if(window == null)
return;
IWorkbenchPage page = window.getActivePage();
if(page == null)
return;
try {
PlatformUI.getPreferenceStore().setValue("actionName", action.getId());
page.showView("aoesoft.ui.MyView");
} catch (PartInitException e) {
e.printStackTrace();
}
}
public void selectionChanged(IAction action, ISelection selection) {
}
public void dispose() {
}
public void init(IWorkbenchWindow window) {
this.window = window;
}
}
<file_sep>/aoesoft/src/aoesoft/ui/MyViewPopupAction.java
package aoesoft.ui;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
public class MyViewPopupAction implements IViewActionDelegate {
private IViewPart part;
public MyViewPopupAction() {
}
public void run(IAction action) {
MessageDialog.openWarning(part.getSite().getShell(), part.getTitle(), "ÕâÊÂÊÓͼ");
}
public void selectionChanged(IAction action, ISelection selection) {
}
public void init(IViewPart view) {
this.part = view;
}
}
| 925a60f82f277fee89ef672139a487039fa07b53 | [
"Java"
] | 2 | Java | aoesoft/myplugin | f5772f6fac3200d5528083e757f2a3a86cee5bef | 96d90c2d2d2de0e2e8edf20b4a406858fcd24a6f |
refs/heads/main | <file_sep>package proektna.demo.service.impl;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import proektna.demo.model.Author;
import proektna.demo.model.Book;
import proektna.demo.model.exceptions.AuthorNotFoundException;
import proektna.demo.model.exceptions.BookNotFoundException;
import proektna.demo.repository.AuthorRepository;
import proektna.demo.repository.BookRepository;
import proektna.demo.service.BookService;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class BookServiceImpl implements BookService {
private final BookRepository bookRepository;
private final AuthorRepository authorRepository;
public BookServiceImpl(BookRepository bookRepository,
AuthorRepository authorRepository) {
this.bookRepository = bookRepository;
this.authorRepository = authorRepository;
}
@Override
public List<Book> findAll() {
return this.bookRepository.findAll();
}
@Override
public Optional<Book> findById(Long id) {
return this.bookRepository.findById(id);
}
@Override
public Optional<Book> findByName(String name) {
return this.bookRepository.findByName(name);
}
@Override
@Transactional
public Optional<Book> save(String name, Long authorId, String izdavac,
String description,String zanr,
Double price,Integer coupons, String picturePath) {
Author author = this.authorRepository.findById(authorId)
.orElseThrow(() -> new AuthorNotFoundException(authorId));
return Optional.of(this.bookRepository.save(new Book(name, author,izdavac,
description,zanr,price,coupons,picturePath)));
}
@Override
@Transactional
public Optional<Book> edit(Long id, String name, Long authorId,String izdavac, String description,String zanr,
Double price,Integer coupons, String picturePath) {
Book book = this.bookRepository.findById(id).orElseThrow(() -> new BookNotFoundException(id));
book.setName(name);
book.setIzdavackaKukja(izdavac);
book.setPrice(price);
book.setDescription(description);
book.setZanr(zanr);
book.setCouponsForBook(coupons);
book.setPicturePath(picturePath);
Author author = this.authorRepository.findById(authorId)
.orElseThrow(() -> new AuthorNotFoundException(authorId));
book.setAuthor(author);
return Optional.of(this.bookRepository.save(book));
}
@Override
public void deleteById(Long id) {
this.bookRepository.deleteById(id);
}
@Override
public List<Book> findBookByZanr(String zanr) {
return this.bookRepository.findAll().stream()
.filter(r->r.getZanr().equals(zanr)).collect(Collectors.toList());
}
@Override
public List<Book> firstFiveBooks() {
return this.bookRepository.findTop5ByOrderByVotesDesc();
}
@Override
public void votes(Long [] array) {
Book book=null;
for(Long item : array){
book=this.bookRepository.findById(item).get();
Integer n=book.getVotes();
n=n+1;
book.setVotes(n);
this.bookRepository.save(book);
}
}
}
<file_sep>package proektna.demo.service.impl;
import org.springframework.stereotype.Service;
import proektna.demo.model.Author;
import proektna.demo.model.Book;
import proektna.demo.model.exceptions.AuthorNotFoundException;
import proektna.demo.model.exceptions.BookNotFoundException;
import proektna.demo.repository.AuthorRepository;
import proektna.demo.service.AuthorService;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
public class AuthorServiceImpl implements AuthorService {
private final AuthorRepository authorRepository;
public AuthorServiceImpl(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Override
public Optional<Author> findById(Long id) {
return this.authorRepository.findById(id);
}
@Override
public List<Author> findAll() {
return this.authorRepository.findAll();
}
@Override
public Optional<Author> save(String name, String surname, Date birthDate,String country) {
return Optional.of(this.authorRepository.save(new Author(name, surname,birthDate,country)));
}
@Override
public Optional<Author> edit(Long id, String name, String surname, Date date, String country) {
Author author=this.authorRepository.findById(id).orElseThrow(() -> new AuthorNotFoundException(id));
author.setName(name);
author.setSurname(surname);
author.setBirthDate(date);
author.setCountry(country);
return Optional.of(this.authorRepository.save(author));
}
@Override
public void deleteById(Long id) {
this.authorRepository.deleteById(id);
}
}
<file_sep>package proektna.demo.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import proektna.demo.model.Book;
import proektna.demo.service.BookService;
@Controller
@RequestMapping
public class ViewBook {
private final BookService bookService;
public ViewBook(BookService bookService) {
this.bookService = bookService;
}
@GetMapping("/view/{id}")
public String getViewPage(@PathVariable Long id, Model model) {
if (this.bookService.findById(id).isPresent()) {
Book book = this.bookService.findById(id).get();
model.addAttribute("book", book);
return "view-book";
}
return "redirect:/books?error=BookNotFound";
}
}
<file_sep>package proektna.demo.service;
import proektna.demo.model.Book;
import proektna.demo.model.ShoppingCart;
import java.util.List;
public interface ShoppingCartService {
List<Book> listAllBooksInShoppingCart(Long cartId);
ShoppingCart getActiveShoppingCart(String username);
ShoppingCart addBookToShoppingCart(String username, Long productId);
void deleteBookFromShoppingCart (String username,Long bookId);
}
<file_sep>package proektna.demo.model.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UsernameNotFoundException extends RuntimeException{
public UsernameNotFoundException(String username) {
super(String.format("Username with username: %s was not found", username));
}
}
<file_sep>package proektna.demo.model;
import lombok.Data;
import javax.persistence.*;
@Data
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String izdavackaKukja;
@Column(length = 1000)
private String description;
//tuka da se vidi vrskava, ne sum sigurna deka e vaka
@ManyToOne
private Author author;
private Double price;
private String zanr;
private Integer votes;
@Basic(fetch = FetchType.LAZY)
private String picturePath;
private Integer couponsForBook;
@Transient
public String getPicturePath() {
if (picturePath== null || id == null) return null;
return "/book-photos/" + id + "/" + picturePath;
}
public Book() {
}
public Book(String name, Author author ,String izdavac,String description,
String zanr,Double price,Integer coupons,String picturePath) {
this.name = name;
this.author=author;
this.izdavackaKukja=izdavac;
this.price=price;
this.zanr=zanr;
this.picturePath=picturePath;
this.description=description;
this.couponsForBook=coupons;
votes=0;
}
}
<file_sep>package proektna.demo.model.exceptions;
public class InvalidUsernameOrPasswordException extends RuntimeException{
}
<file_sep>package proektna.demo.model.exceptions;
public class UserEnterMoreCoupondThanHave extends RuntimeException {
public UserEnterMoreCoupondThanHave() {
super("user enter more coupons than he have");
}
}
<file_sep>server.port=8080
spring.profiles.active=prod
spring.mvc.hiddenmethod.filter.enabled=true
spring.mail.host=smtp.gmail.com
spring.mail.port=25
spring.mail.username=<EMAIL>
spring.mail.password=<PASSWORD>
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
<file_sep>package proektna.demo.service;
import proektna.demo.model.Book;
import java.util.List;
import java.util.Optional;
public interface BookService {
List<Book> findAll();
Optional<Book> findById(Long id);
Optional<Book> findByName(String name);
Optional<Book> save(String name, Long author,String izdavac,String description,
String zanr,Double price,Integer coupons,String picturePath);
Optional<Book> edit(Long id, String name, Long authorId,String izdavac, String description,String zanr,
Double price,Integer coupons, String picturePath);
void deleteById(Long id);
List<Book> findBookByZanr(String zanr);
List <Book> firstFiveBooks();
void votes(Long [] array);
}
<file_sep>package proektna.demo.service.impl;
import org.springframework.stereotype.Service;
import proektna.demo.model.Book;
import proektna.demo.model.Bundle;
import proektna.demo.model.exceptions.BundleNotFoundException;
import proektna.demo.repository.BundleRepository;
import proektna.demo.service.BookService;
import proektna.demo.service.BundleService;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class BundleServiceImpl implements BundleService {
private final BundleRepository bundleRepository;
private final BookService bookService;
public BundleServiceImpl(BundleRepository bundleRepository, BookService bookService) {
this.bundleRepository = bundleRepository;
this.bookService = bookService;
}
@Override
public List<Bundle> findAll() {
return this.bundleRepository.findAll();
}
public Optional<Bundle> findById(Long id){
return this.bundleRepository.findById(id);
}
@Override
public void deleteById(Long id) {
this.bundleRepository.deleteById(id);
}
@Override
@Transactional
public Optional<Bundle> save(String name,
String description,
Double price, Integer coupons, String picturePath) {
return Optional.of(this.bundleRepository.save(new Bundle(name,
description,price,coupons,picturePath)));
}
@Override
@Transactional
public Optional<Bundle> edit(Long id, String name,
String description,
Double price, Integer coupons, String picturePath) {
Bundle bundle= this.bundleRepository.findById(id).orElseThrow(() -> new BundleNotFoundException(id));
bundle.setName(name);
bundle.setDescription(description);
bundle.setPriceBundle(price);
bundle.setCoupons(coupons);
bundle.setBundlePicturePath(picturePath);
return Optional.of(this.bundleRepository.save(bundle));
}
}
<file_sep>package proektna.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import proektna.demo.model.Bundle;
@Repository
public interface BundleRepository extends JpaRepository<Bundle,Long> {
}
<file_sep>package proektna.demo.web.controller;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import proektna.demo.model.ShoppingCart;
import proektna.demo.model.User;
import proektna.demo.service.ShoppingCartService;
import proektna.demo.service.UserService;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/shopping-cart")
public class ShoppingCartController {
private final ShoppingCartService shoppingCartService;
private final UserService userService;
public ShoppingCartController(ShoppingCartService shoppingCartService, UserService userService) {
this.shoppingCartService = shoppingCartService;
this.userService = userService;
}
@GetMapping
public String getShoppingCartPage(HttpServletRequest req,
Model model) {
String username = req.getRemoteUser();
ShoppingCart shoppingCart = this.shoppingCartService.getActiveShoppingCart(username);
model.addAttribute("books", this.shoppingCartService.listAllBooksInShoppingCart(shoppingCart.getId()));
// model.addAttribute("bodyContent", "shopping-cart");
return "shopping-cart";
}
@DeleteMapping("/delete/{id}")
public String deleteBookFromShoppingCart(@PathVariable Long id,
Authentication authentication) {
User user = (User) authentication.getPrincipal();
this.shoppingCartService.deleteBookFromShoppingCart(user.getUsername(),id);
return "redirect:/shopping-cart";
}
@PostMapping("/add-book/{id}")
public String addProductToShoppingCart(@PathVariable Long id, HttpServletRequest req, Authentication authentication) {
try {
User user = (User) authentication.getPrincipal();
this.shoppingCartService.addBookToShoppingCart(user.getUsername(), id);
return "redirect:/shopping-cart";
} catch (RuntimeException exception) {
return "redirect:/shopping-cart?error=" + exception.getMessage();
}
}
@PostMapping("/order")
public String orderBooks(@RequestParam Integer useCoupons,
HttpServletRequest req,
Authentication authentication) {
try {
User user = (User) authentication.getPrincipal();
this.userService.calculateCoupons(useCoupons, user);
return "order-confirm";
}
catch (RuntimeException exception){
return "redirect:/order-confirm?error=" + exception.getMessage();
}
}
}<file_sep>package proektna.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import proektna.demo.model.Author;
@Repository
public interface AuthorRepository extends JpaRepository<Author,Long> {
//sega zasega e prazno zosto Jpa gi ima metodite osnovni
//kaj repo nemame implementacii zosto imame bazi
}
<file_sep>package proektna.demo.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import proektna.demo.model.Author;
import proektna.demo.model.Book;
import proektna.demo.service.AuthorService;
import proektna.demo.service.BookService;
import java.sql.Array;
import java.util.List;
@Controller
@RequestMapping(value = {"/vote"})
public class Vote {
private final BookService bookService;
public Vote(BookService bookService, AuthorService authorService) {
this.bookService = bookService;
}
@GetMapping
public String getVotePage(Model model) {
List<Book> books = this.bookService.findAll();
model.addAttribute("books", books);
return "vote";
}
@PostMapping("/upload")
public String userVote(@RequestParam Long firstChoice,
@RequestParam Long secondChoice,
@RequestParam Long thirdChoice,
@RequestParam Long fourthChoice,
@RequestParam Long fifthChoice) {
Long [] array= {firstChoice,secondChoice,thirdChoice,fourthChoice,fifthChoice};
this.bookService.votes(array);
return "redirect:/home";
}
}<file_sep>package proektna.demo.model;
import lombok.Data;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Data
@Entity
public class Bundle {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private Double priceBundle;
@Basic(fetch = FetchType.LAZY)
private String bundlePicturePath;
private Integer coupons;
@Transient
public String getBundlePicturePath() {
if (bundlePicturePath== null || id == null) return null;
return "/bundle-photos/" + id + "/" + bundlePicturePath;
}
public Bundle() {
}
public Bundle(String name, String description, Double priceBundle,
Integer coupons,String bundlePicturePath) {
this.name = name;
this.description = description;
this.priceBundle = priceBundle;
this.bundlePicturePath = bundlePicturePath;
this.coupons=coupons;
}
}
<file_sep>package proektna.demo.model.dto;
import lombok.Data;
import org.springframework.stereotype.Component;
import proektna.demo.model.Book;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Data
@Component
public class BundleDto {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private Double priceBundle;
private Integer coupons;
public BundleDto() {
}
public BundleDto(String name, String description, Double priceBundle,
Integer coupons) {
this.name = name;
this.description = description;
this.priceBundle = priceBundle;
this.coupons=coupons;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPriceBundle() {
return priceBundle;
}
public void setPriceBundle(Double priceBundle) {
this.priceBundle = priceBundle;
}
public Integer getCoupons() {
return coupons;
}
public void setCoupons(Integer coupons) {
this.coupons = coupons;
}
}
<file_sep>package proektna.demo.model.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.NOT_FOUND)
public class AuthorNotFoundException extends RuntimeException{
public AuthorNotFoundException(Long id) {
super(String.format("Author with id: %d was not found", id));
}
}
<file_sep>package proektna.demo.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import proektna.demo.service.EmailService;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private final JavaMailSender javaMailSender;
public EmailServiceImpl(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
public void sendMail(String subject, String message1) throws MessagingException {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setTo("<EMAIL>");
mail.setSubject(subject);
mail.setText(message1);
javaMailSender.send(mail);
}
}
| 6b9d6f45c312e935e37ebbbd18fea0fc8c816f71 | [
"Java",
"INI"
] | 19 | Java | andreatrifunova/bookStore | d1c4def184b64959c5a55d7cc88087824c664afc | fa7e94bbf7aad430ac1c3c602b717a1dcd69f4c7 |
refs/heads/master | <file_sep>package screens;
import static io.appium.java_client.pagefactory.LocatorGroupStrategy.ALL_POSSIBLE;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.pagefactory.AndroidFindBy;
import io.appium.java_client.pagefactory.HowToUseLocators;
import util.screens.BaseScreen;
// TODO: Auto-generated Javadoc
/**
* DashBoard screen.
*
* @author Hans.Marquez
*
*/
public class CategoryList extends BaseScreen {
/**
* Constructor method.
*
* @param driver the driver
* @author Rosangela.pedrozo
*/
public CategoryList(AndroidDriver<AndroidElement> driver) {
super(driver);
}
/**
* The Attractions button.
*/
@HowToUseLocators(androidAutomation = ALL_POSSIBLE)
@AndroidFindBy(id = "com.disney.wdpro.dlr:id/categoryTitle")
private AndroidElement AttractionsButton;
/**
* The Hotel category button.
*/
@HowToUseLocators(androidAutomation = ALL_POSSIBLE)
@AndroidFindBy(xpath = "//android.widget.LinearLayout[@content-desc=\"Hotels, Category, 11of12, button\"]")
private AndroidElement HotelsButton;
public boolean ishoteloptionavailable(){
return isElementAvailable(HotelsButton);
}
/**
* Clicking CategoryList Buttons.
*/
public void clickingcategorylistbuttons(){
click(AttractionsButton);
}
/**
* Alert control.
*/
@Override
public void alertControl() {
// TODO Auto-generated method stub
}
}<file_sep>package screens;
import static io.appium.java_client.pagefactory.LocatorGroupStrategy.ALL_POSSIBLE;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.pagefactory.AndroidFindBy;
import io.appium.java_client.pagefactory.HowToUseLocators;
import util.screens.BaseScreen;
// TODO: Auto-generated Javadoc
/**
* DashBoard screen.
*
* @author Hans.Marquez
*
*/
public class AddsPlansOption extends BaseScreen {
/**
* Constructor method.
*
* @param driver the driver
* @author Rosangela.pedrozo
*/
public AddsPlansOption(AndroidDriver<AndroidElement> driver) {
super(driver);
}
/**
* The Reserve Dining button.
*/
@HowToUseLocators(androidAutomation = ALL_POSSIBLE)
@AndroidFindBy(xpath = "//android.widget.FrameLayout[@content-desc=\"Reserve Dining, 2 of 5, button\"]/android.widget.LinearLayout")
private AndroidElement ReserveDiningButton;
public boolean isreservediningoptionavailable(){
return isElementAvailable(ReserveDiningButton);
}
/**
* Alert control.
*/
@Override
public void alertControl() {
// TODO Auto-generated method stub
}
}<file_sep>package screens;
import static io.appium.java_client.pagefactory.LocatorGroupStrategy.ALL_POSSIBLE;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.pagefactory.AndroidFindBy;
import io.appium.java_client.pagefactory.HowToUseLocators;
import util.screens.BaseScreen;
// TODO: Auto-generated Javadoc
/**
* DashBoard screen.
*
* @author Hans.Marquez
*
*/
public class PrivacyandLegal extends BaseScreen {
/**
* Constructor method.
*
* @param driver the driver
* @author Rosangela.pedrozo
*/
public PrivacyandLegal(AndroidDriver<AndroidElement> driver) {
super(driver);
}
/**
* The privacy and legal button.
*/
@HowToUseLocators(androidAutomation = ALL_POSSIBLE)
@AndroidFindBy(xpath = "//android.widget.RelativeLayout[@content-desc=\"Privacy & Legal button\"]/android.widget.TextView[2]")
private AndroidElement PrivacyandLegalButton;
/**
* The privacy Policy button.
*/
@HowToUseLocators(androidAutomation = ALL_POSSIBLE)
@AndroidFindBy(uiAutomator = "new UiSelector().resourceIdMatches(\".*:id/txt_element\")")
@AndroidFindBy(uiAutomator = "new UiSelector().className(\"android.widget.TextView\").textContains(\"Privacy Policy\")")
private AndroidElement PrivacyPolicyButton;
/**
* The terms of use button.
*/
@HowToUseLocators(androidAutomation = ALL_POSSIBLE)
@AndroidFindBy(uiAutomator = "new UiSelector().className(\"android.widget.TextView\").textContains(\"Terms of Use\")")
private AndroidElement TermsofUseButton;
/**
* The supplemental terms and conditions button.
*/
@HowToUseLocators(androidAutomation = ALL_POSSIBLE)
@AndroidFindBy(uiAutomator = "new UiSelector().className(\"android.widget.TextView\").textContains(\"Supplemental Terms and Conditions\")")
private AndroidElement SupplementalTermsandConditionsButton;
/**
* The legal notices button.
*/
@HowToUseLocators(androidAutomation = ALL_POSSIBLE)
@AndroidFindBy(uiAutomator = "new UiSelector().className(\"android.widget.TextView\").textContains(\"Legal Notices\")")
private AndroidElement LegalNoticesButton;
/**
* The property rules button.
*/
@HowToUseLocators(androidAutomation = ALL_POSSIBLE)
@AndroidFindBy(uiAutomator = "new UiSelector().className(\"android.widget.TextView\").textContains(\"Property Rules\")")
private AndroidElement PropertyRulesButton;
/**
* The electronic communication disclosure button.
*/
@HowToUseLocators(androidAutomation = ALL_POSSIBLE)
@AndroidFindBy(uiAutomator = "new UiSelector().className(\"android.widget.TextView\").textContains(\"Electronic Communications Disclosure\")")
private AndroidElement ElectronicCommunicationDisclosureButton;
public boolean isprivacypolicyoptionavailable() {
return isElementAvailable(PrivacyPolicyButton);
}
public boolean istermsofuseoptionavailable() {
return isElementAvailable(TermsofUseButton);
}
public boolean issupplementaltermsandconditionsoptionavailable() {
return isElementAvailable(SupplementalTermsandConditionsButton);
}
public boolean legalnoticesoptionavailable() {
return isElementAvailable(LegalNoticesButton);
}
public boolean ispropertyrulesoptionavailable() {
return isElementAvailable(PropertyRulesButton);
}
public boolean iselectroniccommunicationdisclosureoptionavailable() {
return isElementAvailable(ElectronicCommunicationDisclosureButton);
}
/**
* Clicking privacy and legal Button.
*/
public void clickingprivacyandlegalbutton(){
click(PrivacyandLegalButton);
}
public void scrollToPrivacyandLegal(){
scrollDown(5);
}
/**
* Alert control.
*/
@Override
public void alertControl() {
// TODO Auto-generated method stub
}
}
| 284f525000ec5d990659322c7a43c55fa88ecaaf | [
"Java"
] | 3 | Java | rosapedrozo/AutomationMobileRosangelaPedrozo | 85280c85e580bc9a9dffb155b67db408509c8b39 | ea5b67bf9fc1679846296373cdfea1a7e64aa82d |
refs/heads/master | <file_sep>hi ra ela unav
ljkbn
| 8d5c43a2ca6a9a2d73741dd519d45828a9867b81 | [
"Java"
] | 1 | Java | Maheshkumarvadde/Maheshkumarvadde | 445d7172c82d6b824f2d8882a3b7346ab5478b24 | aa6831ac7774a11fde923ec6df60aeb933e9b449 |
refs/heads/master | <file_sep>export class Camera {
constructor(id, size) {
this.elem = document.getElementById(id);
this.x = size/2;
this.y = size/2;
this.xOriginal = size/2;
this.yOriginal = size/2;
this.size = size;
}
rotateCube(x, y) {
this.x += x;
this.y += y;
let deg = this.calculateDeg();
this.elem.style.transform="translateZ(-250px) rotateX("+ deg[0] +"deg) rotateY(" + deg[1] + "deg)";
}
calculateDeg() {
const xRatio = (this.x - (this.size/2)) / (this.size/2);
const yRatio = (this.y - (this.size/2)) / (this.size/2);
const xDeg = -45 * xRatio;
const yDeg = 45 * yRatio;
return [yDeg, xDeg];
}
resetCube() {
this.x = this.xOriginal;
this.y = this.yOriginal;
}
}<file_sep>export class Game {
constructor(snake, food, canvas, options = {}) {
this.snake = snake;
this.food = food;
this.canvas = canvas;
this.gameOver = true;
this.score = 0;
this.context = canvas.getContext("2d");
this.settings = {
bgColor: 'transparent',
borderColor: 'black',
speed: 40,
scoreElem: options.scoreElem
}
}
previewGame() {
this.clearCanvas();
this.drawSnake();
this.drawFood();
}
startGame() {
this.gameOver = false;
this.score = 0;
this.updateDOMScore();
this.snake.resetCoords();
this.food.randomlySetFood(this.canvas.width, this.snake);
this.gameLoop();
}
handleKeyPress(keyCode) {
if (this.gameOver) {
this.startGame();
} else {
this.snake.changeDirection(keyCode);
}
}
gameLoop() {
const self = this;
setTimeout(function() {
self.clearCanvas();
try {
self.snake.advance(self);
} catch(e) {
self.drawSnake();
self.gameOver = true;
return;
}
self.drawSnake();
self.drawFood();
self.gameLoop();
}, self.settings.speed);
}
clearCanvas() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.fillStyle = this.settings.bgColor;
this.context.strokestyle = this.settings.borderColor;
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.context.strokeRect(0, 0, this.canvas.width, this.canvas.height);
}
drawSnake() {
const self = this;
this.snake.coords.forEach(function(snakePart) {
self.context.fillStyle = self.snake.fillColor;
self.context.strokestyle = self.snake.borderColor;
self.context.fillRect(snakePart.x, snakePart.y, 10, 10);
self.context.strokeRect(snakePart.x, snakePart.y, 10, 10);
});
}
drawFood() {
this.context.fillStyle = this.food.color;
this.context.fillRect(this.food.coords.x, this.food.coords.y, 10, 10);
}
isCollision() {
const snakeHead = this.snake.coords[0];
if (snakeHead.x < 0 || snakeHead.x >= this.canvas.width) return true;
else if (snakeHead.y < 0 || snakeHead.y >= this.canvas.height) return true;
let headlessSnake = [...this.snake.coords];
headlessSnake.shift();
if (headlessSnake.filter(coords => coords.x === snakeHead.x && coords.y === snakeHead.y).length) return true;
return false;
}
handleEatFood() {
this.score++;
this.updateDOMScore();
this.food.randomlySetFood(this.canvas.width, this.snake);
}
updateDOMScore() {
if (this.settings.scoreElem !== undefined) {
const scoreElem = document.getElementById(this.settings.scoreElem);
scoreElem.textContent = this.score;
}
}
}<file_sep>import {Snake} from './lib/Snake.js';
import {Food} from './lib/Food.js';
import {Camera} from './lib/Camera.js';
import {Game} from './lib/Game.js';
window.addEventListener('load', function () {
const food = new Food();
const canvas = document.getElementById("game-canvas");
const camera = new Camera('game-cube', canvas.width);
const snake = new Snake(camera);
const options = {
scoreElem: 'score'
};
const game = new Game(snake, food, canvas, options);
game.clearCanvas();
document.addEventListener("keydown", function(e) {
game.handleKeyPress(e.keyCode);
});
}); | cc0c52fb4e5a624c5152733eab053677dd9be862 | [
"JavaScript"
] | 3 | JavaScript | newMichael/snake | 641c23fa6016f12d45761535c7b9e2dfb45e38c6 | 7029e27421fe287f05e36b1b0156af31535e8e28 |
refs/heads/master | <file_sep>SCRIPTS/sbgnpd2an/sbgnpd2an \
--story a=glyph0,glyph4,glyph1 \
--story atp=glyph7,glyph8 \
--initial-state glyph1,glyph3,glyph7,glyph2 \
--names-are-ids\
MODELS/Example/maps/example.sbgn > MODELS/Example/analysis/an/stories/stories.an
<file_sep>SCRIPTS/sbgnpd2an/sbgnpd2an \
--story atm=a676,a613,a277 \
--story gsk3b=a663,a661 \
--story cdk3=a212,a215 \
--story p14arf=a678,a681,a881 \
--story p21cip=a760,sa544,sa906,sa543 \
--story apc=a864,a863,a855 \
--story mga=a157,a162 \
--story cdc2=sa380,a812,a809,a818,csa94,sa381,a837,a35,a803,a791,a832,a825,a836 \
--story cdk6=a32,a741,csa90,a757,a689,a719,a725,a697,a40,a758 \
--story e2f8=sa548,sa854 \
--story p53=a593,a671,sa558,csa96,a590,a592 \
--story cdk7=a634,a845,a642 \
--story wee1=a651,sa551 \
--story p27kip1=a700,a886,a887,a701 \
--story chek2=a588,a278 \
--story cdc20=a858,a856 \
--story dp1=a884,a885,a5 \
--story chek1=a614,a615 \
--story cdk4=a696,a752,a770,a11,a776,a740,a773,csa91,a753,a735,a45,a688,a737 \
--story cdk2=a34,csa97,csa98,csa89,csa99,a33,csa100,a39,a632,a713,a711,csa93,csa92,a796,a851,a849 \
--story hsp90=a763,a766 \
--story nbs1=a673,a591 \
--story pkmyt1=a785,a811 \
--story cdc25c=a815,a816,a879,sa550,sa409 \
--story e2f6=a916,a13,a943,sa851,a129,a51,a61,a52,a67,a929,a954,a966,a60 \
--story pcna=a878,a875 \
--story e2f1=a14,a371,a532,a602,a462,a598,a612,a890,a524,a22,a610,a231,a450,a891,a235,a30,a475,a227,a347,sa376 \
--story e2f4=a828,a6,a1002,a28,a365,a348,a3,a359,sa850,a979 \
--initial-state a3,a14,a13,sa854,a45,a40,a212,a39,a634,a35,a41,a36,a37,a38,a211,a633,a1,a4,a18,a5,a2,a815,a765,a678,a590,a651,a700,a760,a682,a691,a278,a613,a673,a665,a185,sa382,a23,sa378,a280,a874,a856,a857,a855,a635,a661,a662,a159,a875,a158,a157,a25,a309,a414,a53,a54,a944,a164,a165,a307,a308,a341,a785,a27 \
--names-are-ids\
MODELS/RB_E2F/maps/e2f_rb_no_genes.sbgn > MODELS/RB_E2F/analysis/an/stories/stories.an
#%s/ STORY \([a-z0-9_]*\)\n\([a-z0-9,]*\)/ --story \1=\2 \\/
<file_sep>#!/bin/python
import subprocess
import sys
import os
import argparse
import copy
import libsbgnpy.libsbgn as libsbgn
from libsbgnpy.libsbgnTypes import *
def getModels(s):
models = []
new_model = False
for line in s.split("\n"):
if line[0:11] == "SATISFIABLE":
break
if line[0:6] == "Answer":
new_model = True
continue
if new_model is True and line != "":
model = sorted(line.split(" "))
models.append(model)
new_model = False
return models
def getSetsOfStories(models):
sets = set()
for model in models:
preSet = []
for literal in model:
if "gather" in literal:
pair = literal[:-1].split("gather(")[1].split(",")
added = False
for s in preSet:
if pair[0] in s:
s.add(pair[1])
added = True
break
elif pair[1] in s:
s.add(pair[0])
added = True
break
if added is False:
preSet.append(set([pair[0],pair[1]]))
postSet = []
for s in preSet:
added = False
for q in postSet:
if len(s & q) != 0:
q = s | q
added = True
break
if added is False:
postSet.append(s)
postSet = [frozenset(s) for s in postSet]
sets.add(frozenset(postSet))
return sets
def getMaximalSets(sets):
maxSets = copy.copy(sets)
for s in sets:
for q in sets:
if q != s and q.issuperset(s):
maxSets.remove(s)
break
return maxSets
def getFinalSets(sets):
finalSets = copy.copy(sets)
for q in sets:
for s in sets:
if s != q:
for qq in q:
finalSet = False
for ss in s:
if ss.issuperset(qq):
finalSet = True
break
if finalSet is False:
break
if finalSet is True:
finalSets.remove(q)
break
return finalSets
def printSetsOfStories(sets, dlabels = None):
for i, s in enumerate(sets):
print("SET {0}".format(i+1))
for j, q in enumerate(s):
print("STORY {0}".format(j+1))
if dlabels is not None:
print(",".join([dlabels[e] for e in q]))
else:
print(",".join(q))
print("")
toAdd = False
usage = "usage: %stories [options] FILE"
parser = argparse.ArgumentParser()
parser.add_argument("input")
parser.add_argument("--story", action="append")
parser.add_argument("--initial-state")
parser.add_argument("--clabel",action = "store_true")
parser.add_argument("--max", help = "1:maximal sets, 2: final sets, 3:maximal set w.r.t the number of EPNs")
parser.add_argument("--plabel", help = "print stories with EPNs labels")
args = parser.parse_args()
infile = args.input
if args.initial_state is not None or args.story is not None:
f = open(infile.split(".sbgn")[0]+"_add.tmp.asp","w")
if args.initial_state is not None:
for epn in args.initial_state.split(","):
f.write("ini("+epn+").\n")
if args.story is not None:
stories = [s.split(",") for s in args.story]
for story in stories:
for i in range(len(story)-1):
f.write("gather("+story[i]+","+story[i+1]+").\n")
f.close()
toAdd = True
basedir = os.path.dirname(os.path.realpath(__file__))
l=["/home/rougny/CircadianClock/clingo","-n","0",os.path.join(basedir,"stories.asp"),infile]
if toAdd is True:
l.append(infile.split(".sbgn")[0]+"_add.tmp.asp")
if args.clabel is True:
l.append(os.path.join(basedir,"clabel.asp"))
if args.max == "3":
l.append(os.path.join(basedir,"max.asp"))
l.append("--quiet=1")
try:
res = subprocess.check_output(l,universal_newlines=True)
except subprocess.CalledProcessError as clingo_exp:
models = getModels(clingo_exp.output)
sets = getSetsOfStories(models)
if args.max == "1":
sets = getMaximalSets(sets)
elif args.max == "2":
sets = getFinalSets(sets)
if args.plabel:
dlabels = {}
sbgn = libsbgn.parse(args.plabel, silence=True)
sbgnMap = sbgn.get_map()
for glyph in sbgnMap.get_glyph():
if glyph.get_label() is not None:
dlabels[glyph.get_id()] = glyph.get_label().get_text()
printSetsOfStories(sets, dlabels)
else:
printSetsOfStories(sets)
if toAdd is True:
pass
os.remove(infile.split(".sbgn")[0]+"_add.tmp.asp")
<file_sep>echo "---------------"
echo "G0"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_G0_a6=1.reduced.an a6=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_G0_a6=1.reach
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_G0_a359=1.reduced.an a359=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_G0_a359=1.reach
echo "---------------"
echo "earlyG0"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_earlyG1_a725=1.reduced.an a725=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_earlyG1_a725=1.reach
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_earlyG1_a450=1.reduced.an a450=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_earlyG1_a450=1.reach
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_earlyG1_a462=1.reduced.an a462=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_earlyG1_a462=1.reach
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_earlyG1_a735=1.reduced.an a735=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_earlyG1_a735=1.reach
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_earlyG1_a475=1.reduced.an a475=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_earlyG1_a475=1.reach
echo "---------------"
echo "lateG1"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_lateG1_a524=1.reduced.an a524=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_lateG1_a524=1.reach
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_lateG1_a532=1.reduced.an a532=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_lateG1_a532=1.reach
echo "---------------"
echo "earlyS"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_earlyS_a632=1.reduced.an a632=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_earlyS_a632=1.reach
echo "---------------"
echo "lateS"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_lateS_csa89=1.reduced.an csa89=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_lateS_csa89=1.reach
echo "---------------"
echo "G2"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_G2_a837=1.reduced.an a837=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_G2_a837=1.reach
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_G2_a803=1.reduced.an a803=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_G2_a803=1.reach
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_G2_a809=1.reduced.an a809=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_G2_a809=1.reach
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_G2_a832=1.reduced.an a832=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_G2_a832=1.reach
echo "---------------"
echo "M"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_M_a816=1.reduced.an a816=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_M_a816=1.reach
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_M_sa551=1.reduced.an sa551=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_M_sa551=1.reach
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_M_a791=1.reduced.an a791=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_M_a791=1.reach
pint-mole -i MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_M_a858=1.reduced.an a858=1 > MODELS/RB_E2F/analysis/reach/nostories/normal/nostories_M_a858=1.reach
<file_sep>#!/bin/python
import sys
import argparse
import colorsys
import itertools
from fractions import Fraction
def zenos_dichotomy():
for k in itertools.count():
yield Fraction(1,2**k)
def getfracs():
"""
[Fraction(0, 1), Fraction(1, 2), Fraction(1, 4), Fraction(3, 4), Fraction(1, 8), Fraction(3, 8), Fraction(5, 8), Fraction(7, 8), Fraction(1, 16), Fraction(3, 16), ...]
[0.0, 0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875, 0.0625, 0.1875, ...]
"""
yield 0
for k in zenos_dichotomy():
i = k.denominator # [1,2,4,8,16,...]
for j in range(1,i,2):
yield Fraction(j,i)
bias = lambda x: (math.sqrt(x/3)/Fraction(2,3)+Fraction(1,3))/Fraction(6,5) # can be used for the v in hsv to map linear values 0..1 to something that looks equidistant
def genhsv(h):
for s in [Fraction(6,10)]: # optionally use range
for v in [Fraction(8,10),Fraction(5,10)]: # could use range too
yield (h, s, v) # use bias for v here if you use range
genrgb = lambda x: colorsys.hsv_to_rgb(*x)
flatten = itertools.chain.from_iterable
gethsvs = lambda: flatten(map(genhsv,getfracs()))
getrgbs = lambda: map(genrgb, gethsvs())
def genhtml(x):
uint8tuple = map(lambda y: int(y*255), x)
return uint8tuple
# return "rgb({},{},{})".format(*uint8tuple)
gethtmlcolors = lambda: map(genhtml, getrgbs())
def isInStory(epn, stories):
i = -1
for j, story in enumerate(stories):
if epn in story:
i = j
break
return i
parser = argparse.ArgumentParser()
parser.add_argument("infile")
parser.add_argument("--output", "-o")
parser.add_argument("--story", action="append")
args = parser.parse_args()
infile = args.infile
if args.output:
output = args.output
else:
if ".cd.xml" in infile:
output = infile.split(".cd.xml")[0]+".colored.cd.xml"
else:
output = infile+".colored.cd.xml"
if args.story:
colors = [tuple(c) for c in list(itertools.islice(gethtmlcolors(), len(args.story)))]
stories = [s.split(",") for s in args.story]
ifile = open(infile)
ofile = open(output,"w")
string = ""
inNode = False
for line in ifile:
if "<celldesigner:complexSpeciesAlias id=" in line or "<celldesigner:speciesAlias id=" in line:
inNode = True
id = line.split('"')[1]
if "</celldesigner:complexSpeciesAlias>" in line or "</celldesigner:speciesAlias>" in line:
inNode = False
if inNode is True and "color" in line:
i = isInStory(id, stories)
if i != -1:
color = colors[i]
colorhex = "ff"+hex(color[0])[2:]+hex(color[1])[2:]+hex(color[2])[2:]
line = line.split('"')[0]+'"'+colorhex+'"'+' scheme="Color"/>\n'
ofile.write(line)
ifile.close()
ofile.close()
<file_sep>#!/bin/python
import sys
import argparse
import colorsys
import itertools
from fractions import Fraction
parser = argparse.ArgumentParser()
parser.add_argument("infile")
parser.add_argument("--output", "-o")
parser.add_argument("--initial-state")
args = parser.parse_args()
infile = args.infile
if args.output:
output = args.output
else:
if ".cd.xml" in infile:
output = infile.split(".cd.xml")[0]+".ini.cd.xml"
else:
output = infile+".ini.cd.xml"
if args.initial_state:
ini = args.initial_state.split(",")
ifile = open(infile)
ofile = open(output,"w")
string = ""
inNode = False
for line in ifile:
if "<celldesigner:complexSpeciesAlias id=" in line or "<celldesigner:speciesAlias id=" in line:
inNode = True
id = line.split('"')[1]
if "</celldesigner:complexSpeciesAlias>" in line or "</celldesigner:speciesAlias>" in line:
inNode = False
if inNode is True and id in ini and "singleLine" in line:
line = line.split('"')[0] + '"5.0"' + line.split('"')[2]
ofile.write(line)
ifile.close()
ofile.close()
<file_sep>./reducePhases.py --log logs/stories/normal/reducePhases.log --dir MODELS/RB_E2F/analysis/an/stories/reduced/normal/ -i MODELS/RB_E2F/analysis/an/stories/stories.an phases
echo "---------------"
echo "G0"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal e2f4=a6 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_G0_e2f4=a6.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal e2f4=a359 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_G0_e2f4=a359.reduced.an
echo "---------------"
echo "earlyG0"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal cdk4=a735 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_earlyG1_cdk4=a735.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal e2f1=a462 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_earlyG1_e2f1=a462.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal e2f1=a475 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_earlyG1_e2f1=a475.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal cdk6=a725 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_earlyG1_cdk6=a725.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal e2f1=a450 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_earlyG1_e2f1=a450.reduced.an
echo "---------------"
echo "lateG1"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal e2f1=a524 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_lateG1_e2f1=a524.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal e2f1=a532 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_lateG1_e2f1=a532.reduced.an
echo "---------------"
echo "earlyS"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal cdk2=a632 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_earlyS_cdk2=a632.reduced.an
echo "---------------"
echo "lateS"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal cdk2=csa89 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_lateS_cdk2=csa89.reduced.an
echo "---------------"
echo "G2"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal cdc2=a803 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_G2_cdc2=a803.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal cdc2=a837 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_G2_cdc2=a837.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal cdc2=a809 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_G2_cdc2=a809.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal cdc2=a832 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_G2_cdc2=a832.reduced.an
echo "---------------"
echo "M"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal wee1=sa551 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_M_wee1=sa551.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal cdc2=a791 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_M_cdc2=a791.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal cdc20=a858 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_M_cdc20=a858.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/stories/stories.an --reduce-for-goal cdc25c=a816 -o MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_M_cdc25c=a816.reduced.an
<file_sep>#!/usr/bin/env python3
# vi:et
import itertools
from sbgnlib import *
from dnf import *
class AN(dict):
def __init__(self):
dict.__init__(self)
self.comments = {}
self.initial_state = []
self.states = {}
def register_automaton(self, name, states, comment=None):
self[name] = dict([(s, []) for s in states])
self.states[name] = states
if comment:
self.comments[name] = comment
def register_transition(self, a, i, j, *conds):
self[a][i].append((j,conds))
def set_initial_state(self, state):
self.initial_state = state[:]
def __str__(self):
def str_state(state):
if type(state) == int:
return str(state)
else:
return "\"%s\"" % state
s = "(* automata *)\n"
for a in sorted(self.keys()):
comment = ""
if a in self.comments:
comment = "\t(* %s *)" % self.comments[a]
s += "\"%s\"\t[%s]%s\n" % \
(a, ", ".join(map(str_state, self.states[a])),comment)
s += "\n"
s += "(* transitions *)\n\n"
for a in sorted(self.keys()):
has_one = False
for i in sorted(self[a]):
for (j, conds) in sorted(self[a][i]):
sv = " and ".join(["\"%s\"=%s" % (b,str_state(k))
for (b,k) in sorted(conds)])
if sv:
sv = " when %s" % sv
s += "\"%s\" %s -> %s%s\n" % (a, str_state(i), str_state(j), sv)
has_one = True
if has_one:
s += "\n"
if self.initial_state:
s += "initial_state %s" % ", ".join(["\"%s\"=%s" % (a,str_state(i))\
for (a,i) in self.initial_state])
return s
def logic_from_entity(n):
if n.type in ENTITY_CLASSES:
dnf = DNF(AndClause(Lit(n)))
elif n.type == "and":
dnf = logic_from_entity(n.inputs[0])
for m in n.inputs[1:]:
dnf = dnf & logic_from_entity(m)
elif n.type == "or":
dnf = logic_from_entity(n.inputs[0])
for m in n.inputs[1:]:
dnf |= logic_from_entity(m)
elif n.type == "not":
pass
return dnf
class ModulationLogic:
def __init__(self, modulations):
self.m_dnf = [] # independent modulations
self.necessary = DNF(AndClause()) # necessary
if not modulations:
self.pos = DNF(AndClause())
self.neg = self.pos.neg()
else:
for (cls, var) in modulations:
dnf = logic_from_entity(var)
if cls == "necessary stimulation":
self.necessary = self.necessary & dnf
else:
self.m_dnf.append((cls, dnf))
if not self.m_dnf: # only necessary stimulation
self.pos = self.necessary
self.neg = self.necessary.neg()
else:
self.pos = DNF()
self.neg = self.necessary.neg()
for (cls, dnf) in self.m_dnf:
if cls in ["stimulation", "catalysis","modulation"]:
self.pos |= dnf & self.necessary
self.neg |= dnf.neg()
if cls in ["inhibition", "modulation"]:
self.pos |= dnf.neg() & self.necessary
self.neg |= dnf
class Story:
def __init__(self, sid):
self.sid = sid
STORY_BOT = "null"
def an_from_sbgnpd(model, do_conflicts=False, stories=None, initial_state=None,
names_are_ids=False):
an = AN()
conflicts = {}
# 1. determine automata for entities
entities = set([e for e in model.entities.values() if not e.is_void()])
if names_are_ids:
def an_name(e):
return e.id
else:
def an_name(e):
return e.name
if stories:
story_name = [s[0] if s[0] is not None else "story%d" % (i+1) \
for (i, s) in enumerate(stories)]
stories = [s[1] for s in stories]
e2story = {}
if stories:
for (i, story) in enumerate(stories):
for e in story:
e2story[e.id] = i
an.register_automaton(story_name[i], [STORY_BOT]+[an_name(e) for e in story])
done = set()
for e in model.entities.values():
if e.is_void():
continue
e = model.resolve_clone(e)
if e.id in done:
continue
if e.id not in e2story:
an.register_automaton(an_name(e), [0, 1], comment=repr(e))
if do_conflicts:
if len(e.consumers) > 1:
for p in e.consumers:
if p.id not in conflicts:
conflicts[p.id] = set()
conflicts[p.id].update(e.consumers)
done.add(e.id)
# declare conflict between all the processes in a same story
if stories:
for story in stories:
procs = set()
for e in story:
procs.update(e.consumers)
for p in procs:
if p.id not in conflicts:
conflicts[p.id] = set()
conflicts[p.id].update(procs)
# filter self-conflicts
for pid, ps in conflicts.items():
conflicts[pid] = set([p for p in ps if p.id != pid])
#print(conflicts, file=sys.stderr)
def local_states_of_entity(e, present=True):
if isinstance(e, Story) and not present:
return [(story_name[e.sid], STORY_BOT)]
elif e.id in e2story:
sid = e2story[e.id]
a = story_name[sid]
if present:
return [(a, an_name(e))]
else:
return [(a, an_name(f)) for f in stories[sid] if f.id != e.id] \
+ [(a, STORY_BOT)]
else:
return [(an_name(e), 1 if present else 0)]
def local_states_of_lit(l):
return local_states_of_entity(an_name(l), l.ispos)
def lconds_of_andclause(c):
maps = list(map(local_states_of_lit, c))
return itertools.product(*maps)
def register_transition(a, i, j, *andclause):
for conds in lconds_of_andclause(andclause):
an.register_transition(a, i, j, *conds)
# 2. determine transitions
for p in model.processes.values():
ml = ModulationLogic(p.modulations)
pconflicts = conflicts.get(p.id, set())
if not pconflicts and len(p.consumptions) == 0:
for e in p.productions:
a, j = local_states_of_entity(e)[0]
if e.id in e2story:
i = STORY_BOT
else:
i = 0
for conds in ml.pos:
register_transition(a, i, j, conds)
elif not pconflicts and len(p.productions) == 0 and len(p.consumptions) == 1:
e = p.consumptions[0]
a, i = local_states_of_entity(e)[0]
if e.id in e2story:
j = STORY_BOT
else:
j = 0
for conds in ml.pos:
register_transition(a, i, j, *conds)
else:
def group_per_stories(d, es):
for e in es:
sid = e2story.get(e.id, None)
if sid not in d:
d[sid] = []
d[sid].append(e)
consumptions = {}
productions = {}
group_per_stories(consumptions, p.consumptions)
group_per_stories(productions, p.productions)
pstories = set(productions.keys())
pstories.update(consumptions.keys())
if None in pstories:
pstories.remove(None)
for (sid, es) in consumptions.items():
if sid is None:
continue
assert len(es) <= 1, \
"invalid story %d: %s consumes %s" % (sid, p, es)
for (sid, es) in productions.items():
if sid is None:
continue
assert len(es) <= len(consumptions.get(sid, [])), \
"invalid story %s: %s produces more stories (%s -> %s)" \
% (sid, p, consumptions.get(sid, []), es)
implicit_process = not pconflicts and len(consumptions) <= 1 and \
len(productions) <= 1 and \
None not in consumptions and None not in productions
if implicit_process:
p_pos = ml.pos
else:
an.register_automaton(an_name(p), [0, 1], comment=repr(p))
necessary_clause = AndClause()
for e in p.consumptions:
necessary_clause.add(Lit(e))
for c in pconflicts:
if c.id == p.id:
continue
necessary_clause.add(Lit(c, False))
# process activation
for conds in ml.pos:
conds = conds.copy()
conds &= necessary_clause
register_transition(an_name(p), 0, 1, *conds)
p_pos = DNF(AndClause(Lit(p)))
# productions
cond_production_done = AndClause()
for e in productions.get(None, []):
for conds in p_pos:
register_transition(an_name(e), 0, 1, *conds)
cond_production_done.add(Lit(e))
if not consumptions:
for (sid, es) in productions.items():
if sid is None:
continue
e = es[0]
a, j = local_states_of_entity(e)[0]
for conds in p_pos:
register_transition(a, STORY_BOT, j, *conds)
def story_next_lit(sid):
if sid in productions:
e = productions[sid][0]
state = True
else:
e = Story(sid)
state = False
return Lit(e, state)
# process de-activation
if not implicit_process:
# process inhibition
done = cond_production_done
for sid in pstories:
done.add(story_next_lit(sid))
register_transition(an_name(p), 1, 0, *done)
done = DNF(done)
else:
done = DNF(AndClause())
# consumptions
for (sid, es) in consumptions.items():
if sid is None:
for e in es:
for conds in p_pos & done:
#for conds in stories_around & p_pos:
register_transition(an_name(e), 1, 0, *conds)
else:
e = es[0]
a, i = local_states_of_entity(es[0])[0]
if sid in productions:
b, j = local_states_of_entity(productions[sid][0])[0]
else:
j = STORY_BOT
for conds in p_pos:
register_transition(a, i, j, *conds)
# 3. set initial state
if initial_state:
initial_state = [local_states_of_entity(e)[0] for e in initial_state]
an.set_initial_state(initial_state)
return an
def parse_gid_list(model, s):
gs = []
for gid in s.split(","):
gid = gid.strip()
g = model.entities[gid]
g = model.resolve_clone(g)
gs.append(g)
return gs
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input")
parser.add_argument("--output", "-o")
parser.add_argument("--conflicts", action="store_true",
help="declare processes with shared reactants in conflict")
parser.add_argument("--story", action="append",
help="comma-separated list of glyph ids, possibly prefixed with name=")
parser.add_argument("--initial-state",
help="comma-seperated list of glyph ids present in the initial state")
parser.add_argument("--names-are-ids", action="store_true",
help="use glyph id as automata name")
args = parser.parse_args()
model = parse_sbgn_pd(args.input)
def parse_story_spec(model, data):
if "=" in data:
name, data = data.split("=")
name = name.strip()
data = data.strip()
else:
name = None
return (name, parse_gid_list(model, data))
stories = None
if args.story:
stories = [parse_story_spec(model, s) for s in args.story]
initial_state = None
if args.initial_state:
initial_state = parse_gid_list(model, args.initial_state)
an = an_from_sbgnpd(model, do_conflicts=args.conflicts, stories=stories,
initial_state=initial_state, names_are_ids=args.names_are_ids)
if args.output:
open(args.output, "w").write(str(an))
else:
print(str(an))
<file_sep>#!/bin/bash
SCRIPTS/stories/stories\
--story a22,a371,a30,a347,a602,a227,a231,a14,a598,sa376,a235,a610,a612,a450,a524,a532,a462,a475,a890,a891\
--story a45,a696,a770,a776,a688,a11,a740,a752,a753,csa91,a737,a773,a735\
--story csa90,a719,a725,a741,a32,a689,a40,a758,a757,a697\
--story csa92,csa93,a711,a34,a849,a796,a39,a851,a33,a632,csa98,csa97,csa89,csa100,csa99,a713\
--story a845,a642,a634\
--story a836,a837,a803,a832,a809,a35,a812,a825,a818,a791,sa380,sa381,csa94\
--story a828,a6,a28,a348,a1002,a979,a359,a365,sa850,a3\
--story a51,a60,a61,a67,a954,a966,a929,a943,a52,a129,sa851,a13,a916\
--story a212,a215\
--story a590,a671,a592,a593,csa96,sa558\
--max 3 \
MODELS/RB_E2F/asp/rb_e2f.asp > MODELS/RB_E2F/stories/rb_e2f.stories
<file_sep>#!/bin/python
import argparse
from Entity import *
from EntityClazz import EntityClazz
from Utils import *
from PDNetwork import *
usage = "usage: %sbgnpd2asp FILE"
parser = argparse.ArgumentParser()
parser.add_argument("input")
parser.add_argument("-o")
args = parser.parse_args()
infile = args.input
net = SBGN.readSBGNML(infile)
if args.o:
SBGN.writeCG2ASP(net, args.o)
else:
print(SBGN.getCG2ASP(net))
<file_sep>
class Compartment:
def __init__(self, id = None, label = None):
self.id = id
self.label = label
def getLabel(self):
return self.label
def getId(semf):
return self.id
def setLabel(self, label):
self.label = label
def setId(self, id):
self.id = id
def __eq__(self, other):
return isinstance(other, Compartment) and self.label == other.label
def __hash__(self):
return hash(self.label)
<file_sep>from enum import Enum
class ProcessClazz(Enum):
PROCESS = {"name": "process", "h" : 24, "w" : 24}
OMITTED_PROCESS = {"name": "omitted process", "h" : 24, "w" : 24}
UNCERTAIN_PROCESS = {"name": "uncertain process", "h" : 24, "w" : 24}
ASSOCIATION = {"name": "association", "h" : 24, "w" : 24}
DISSOCIATION = {"name": "dissociation", "h" : 24, "w" : 24}
PHENOTYPE = {"name": "phenotype", "h" : 24, "w" : 24}
<file_sep>#!/bin/python
import sys
import argparse
import colorsys
import itertools
from fractions import Fraction
def zenos_dichotomy():
for k in itertools.count():
yield Fraction(1,2**k)
parser = argparse.ArgumentParser()
parser.add_argument("infile")
parser.add_argument("--output", "-o")
args = parser.parse_args()
infile = args.infile
if args.output:
output = args.output
else:
if ".cd.xml" in infile:
output = infile.split(".cd.xml")[0]+".uncolored.cd.xml"
else:
output = infile+".uncolored.cd.xml"
ifile = open(infile)
ofile = open(output,"w")
inNode = False
for line in ifile:
if "<celldesigner:complexSpeciesAlias id=" in line or "<celldesigner:speciesAlias id=" in line:
inNode = True
if "</celldesigner:complexSpeciesAlias>" in line or "</celldesigner:speciesAlias>" in line:
inNode = False
if inNode is True and "color" in line:
colorhex = "ffffffff"
line = line.split('"')[0]+'"'+colorhex+'"'+' scheme="Color"/>\n'
ofile.write(line)
ifile.close()
ofile.close()
<file_sep># sbgnpd2an-suppl
Supplementary material of the BMC Systems Biology paper on SBGN-PD to Automata Networks
## Requirements
- python >= 3 (http://python.org)
- clingo >= 4 (http://sourceforge.net/projects/potassco/files/clingo/)
- libsbgnpy 0.1.2 (https://pypi.python.org/pypi/libsbgnpy)
- Mole (http://www.lsv.ens-cachan.fr/~schwoon/tools/mole/)
- pint (http://loicpauleve.name/pint/)
## Main programs in SCRIPTS/:
* `maps/cd2sbgnml`: converts a CellDesigner file to a SBGN-ML file using the CellDesignger file and the SBGN-ML file exported from CellDesigner
* `maps/colorcd`: colors the stories of a SBGN-PD map
* `asp/sbgnpd2asp`: writes the compound graph of a SBGN-PD map to ASP
* `stories/stories`: finds all valid sets of stories of an SBGN-PD map
* `sbgnpd2an/sbgnpd2an`: builds an AN model from a SBGN-PD map under the general or the stories semantics
## Usage examples:
asp/sbgnpd2asp
----------------
Get compound graph in ASP:
SCRIPTS/asp/sbgnpd2asp -o MODELS/Example/asp/example.asp MODELS/Example/maps/example.sbgn
stories/stories
----------------
Get maximally valid sets of stories:
SCRIPTS/stories/stories --max 1 MODELS/Example/asp/example.asp > MODELS/Example/stories/example1.stories
Get final sets of stories:
SCRIPTS/stories/stories --max 2 MODELS/Example/asp/example.asp > MODELS/Example/stories/example2.stories
Get valid sets of stories maximazing the number of EPN in stories:
SCRIPTS/stories/stories --max 3 MODELS/Example/asp/example.asp > MODELS/Example/stories/example3.stories
Get final sets of stories inluding a story with EPNs b and c, and one with EPNs adp,atp:
SCRIPTS/stories/stories --story glyph3,glyph0 --story glyph8,glyph1 --max 2 MODELS/Example/asp/example.asp > MODELS/Example/stories/example4.stories
Get final sets of stories considering constraint (v):
SCRIPTS/stories/stories --clabel --max 2 MODELS/Example/asp/example.asp > MODELS/Example/stories/example5.stories
sbgnpd2an/sbgnpd2an
----------------
Get AN model under the general semantics:
SCRIPTS/sbgnpd2an/sbgnpd2an --initial-state glyph1,glyph3,glyph7,glyph2 MODELS/Example/maps/example.sbgn > MODELS/Example/analysis/an/nostories/nostories.an
Get AN model under the stories semantics:
SCRIPTS/sbgnpd2an/sbgnpd2an --story a=glyph0,glyph4,glyph1 --story atp=glyph7,glyph8 --initial-state glyph1,glyph3,glyph7,glyph2 --names-are-ids MODELS/Example/maps/example.sbgn > MODELS/Example/analysis/an/stories/stories.an
pint-export
----------------
Get reduced model (stories semantics) for goal a=glyph4 (story a, state aP):
pint-export -i MODELS/Example/analysis/an/stories/stories.an --reduce-for-goal a=glyph4 -o MODELS/Example/analysis/an/stories/reduced/stories_a=glyph4.reduced.an
Get PRISM model (stories semantics) from AN model:
pint-export -i MODELS/Example/analysis/an/nostories/nostories.an -l prism -o MODELS/Example/analysis/prism/nostories/nostories.nm
pint-mole
----------------
Check reachability of state aP of story a:
pint-mole -i MODELS/Example/analysis/an/stories/reduced/stories_a=glyph4.reduced.an a=glyph4 > MODELSExample/analysis/reach/stories/stories_a=glyph4.reach
pint-export
----------------
Get State Transition Graph of an AN model
pint-sg --state-graph MODELS/Example/analysis/stg/stories/stories.dot -i MODELS/Example/analysis/an/stories/stories.an
## Main files in MODELS/:
RB_E2F/: contains all files related to the RB/E2F map
maps/rb_e2f.sbgn: the RB/E2F map in SBGN-ML format | generated by MODELS/RB_E2F/scripts/maps/make_sbgn_from_cd.sh
asp/rb_e2f.asp: RB/E2F's compound graph in ASP | generated by MODELS/RB_E2F/scripts/asp/make_asp.sh
stories/rb_e2f.stories: maximal valid set of stories of the RB/E2F map | generated by MODELS/RB_E2F/scripts/stories/make_stories.sh
analysis/an/nostories/: AN models under the general sem.
nostories.an: AN model under the general sem. | generated by MODELS/RB_E2F/scripts/analysis/an/nostories/make_an.sh
simultaneity/: AN models built to check simultaneity | generated by MODELS/RB_E2F/scripts/analysis/an/nostories/simultaneity/make_an.sh
reduced/: reduced models
normal/: from nostories.an | generated by MODELS/RB_E2F/scripts/analysis/an/nostories/reduced/disable_e2f1/make_reduced.sh
disable_e2f1/: when E2F1 is disabled | generated by MODELS/RB_E2F/scripts/analysis/an/nostories/reduced/disable_e2f1/make_reduced.sh
disable_prev_phase/: when prev. phase is disabled | generated by MODELS/RB_E2F/scripts/analysis/an/nostories/reduced/disable_prev_phase/make_reduced.sh
simultaneity/: for simultaneity | generated by MODELS/RB_E2F/scripts/analysis/an/nostories/reduced/simultaneity/make_reduced.sh
analysis/an/stories/: AN models under the stories sem.
...
analysis/an/nostoriestriggers: AN models with transc. effects under the general sem.
...
analysis/an/storiestriggers*: AN models with transc. effects under the stories sem.
...
analysis/phases/rb_e2f.phases: phases of the cell cycle
ERK/: contains all files related to the ERK map
maps/erk.sbgn: the ERK map in SBGN-ML format
asp/erk.asp: ERK's compound graph in ASP | generated by MODELS/ERK/scripts/asp/make_asp.sh
stories/erk.stories: maximal valid set of stories of the ERK map | generated by MODELS/ERK/scripts/stories/make_stories.sh
PolyQ/: contains all files related to the PolyQ map
maps/polyq.sbgn: the PolyQ map in SBGN-ML format
asp/polyq.asp: PolyQ's compound graph in ASP | generated by MODELS/PolyQ/scripts/asp/make_asp.sh
stories/polyq.stories: maximal valid set of stories of the PolyQ map | generated by MODELS/PolyQ/scripts/stories/make_stories.sh
analysis/an/stories/stories.an: AN model under the stories sem. | generated by MODELS/PolyQ/scripts/analysis/an/stories/make_an.sh
analysis/prism/stories/noprobas/noprobas.prism: PRISM model under the stories sem. with no probas | generated by MODELS/PolyQ/scripts/analysis/prism/stories/noprobas/make_prism.sh
analysis/prism/stories/probas/probas.prism: PRISM model under the stories sem. with ptobas
analysis/prism/stories/probas/property.csl: the probavility to be computed on the prism model
analysis/results/probas.txt: probas computed from the two previous files | generated by MODELS/PolyQ/scripts/analysis/results/get_probas.sh
analysis/results/probas.png: results plotted | generated by MODELS/PolyQ/scripts/analysis/results/make_gnuplot_graph.sh
Example/: contains all files related to the example map
...
<file_sep>SCRIPTS/asp/sbgnpd2asp -o MODELS/RB_E2F/asp/rb_e2f.asp MODELS/RB_E2F/maps/rb_e2f.sbgn
<file_sep>#!/bin/bash
SCRIPTS/sbgnpd2an/sbgnpd2an \
--story glyph2,glyph41,glyph3,glyph38,glyph39 \
--story glyph4,glyph5,glyph35 \
--initial-state glyph14,glyph15,glyph17,glyph24,glyph4,glyph18,glyph41,glyph6 \
MODELS/PolyQ/maps/polyq.sbgn > MODELS/PolyQ/analysis/an/stories/stories.an
<file_sep>
import itertools
import sys
class Lit:
def __init__(self, name, pos=True):
self.__name = name
self.__pos = pos
@property
def name(self):
return self.__name
id = name
@property
def ispos(self):
return self.__pos
@property
def isneg(self):
return not self.__pos
def __repr__(self):
return "%s%s" % ("!" if not self.__pos else "", self.__name)
def neg(self):
return Lit(self.__name, not self.__pos)
def __eq__(self, l):
if not isinstance(l, Lit):
return False
return l.__name == self.__name and l.__pos == self.__pos
def __hash__(self):
return hash((self.__name, self.__pos))
class AndClause(set):
def __init__(self, *lits):
if False in lits:
self.add(False)
else:
for lit in lits:
if lit.neg() in self:
self.clear()
break
else:
self.add(lit)
def __hash__(self):
return hash(tuple(self))
def __repr__(self):
if False in self:
return "false"
elif len(self) == 0:
return "true"
else:
return " and ".join([repr(l) for l in self])
def copy(self):
return AndClause(*set.copy(self))
def __and__(c1, c2):
return AndClause(*c1.union(c2))
def __iand__(self, c2):
self.update(c2)
return self
def inv(self):
return AndClause(*[l.neg() for l in self])
class DNF(set):
def __init__(self, *ands):
self.update(ands)
self.simplify()
def __repr__(self):
if len(self) == 0:
return "false"
elif len(self) == 1:
return repr(list(self)[0])
else:
return " or ".join(["(%s)" % repr(andc) if len(andc) > 1 else repr(andc) \
for andc in self])
def __or__(dnf1, dnf2):
dnf = DNF(*dnf1.union(dnf2))
dnf.simplify()
return dnf
def __ior__(self, dnf2):
self.update(dnf2)
self.simplify()
return self
def __and__(dnf1, dnf2):
dnf = DNF()
for andc1 in dnf1:
for andc2 in dnf2:
dnf.add(AndClause(*andc1.union(andc2)))
dnf.simplify()
return dnf
def simplify(self):
try:
self.remove(AndClause(False))
except KeyError:
pass
andc = list(sorted(self, key=len))
while len(andc):
largest = andc.pop()
if largest.inv() in andc:
self.clear()
self.add(AndClause())
break
for c in andc:
if largest.issuperset(c):
self.remove(largest)
break
def neg(self):
dnf = DNF(*map(lambda x: AndClause(*map(lambda l: l.neg(), x)), itertools.product(*self)))
dnf.simplify()
return dnf
if __name__ == "__main__":
#expr1 = DNF(AndClause(Lit("B",False), Lit("C")), AndClause(Lit("D")))
#expr2 = DNF(AndClause(Lit("D"), Lit("E")), AndClause(Lit("E"), Lit("F")))
expr1 = DNF(AndClause(Lit("B"),Lit("C")), AndClause(Lit("B"),Lit("D")))
expr2 = DNF(AndClause(Lit("B"),Lit("C")), AndClause(Lit("C"),Lit("D")))
expr = expr1 | expr2
nexpr = expr1.neg() | expr2.neg()
print(expr1)
print(expr2)
print("---")
print(expr)
print(nexpr)
<file_sep>from enum import Enum
class EntityClazz(Enum):
UNSPECIFIED_ENTITY = {"name": "unspecified entity", "h" : 40, "w" : 40}
SIMPLE_CHEMICAL = {"name": "simple chemical", "h" : 40, "w" : 40}
MACROMOLECULE = {"name": "macromolecule", "h" : 60, "w" : 108}
NUCLEIC_ACID_FEATURE = {"name": "nucleic acid feature", "h" : 40, "w" : 40}
SIMPLE_CHEMICAL_MULTIMER = {"name": "simple chemical multimer", "h" : 40, "w" : 40}
MACROMOLECULE_MULTIMER = {"name": "macromolecule multimer", "h" : 40, "w" : 40}
NUCLEIC_ACID_FEATURE_MULTIMER = {"name": "nucleic acid feature multimer", "h" : 40, "w" : 40}
COMPLEX = {"name": "complex", "h" : 40, "w" : 40}
COMPLEX_MULTIMER = {"name": "complex multimer", "h" : 40, "w" : 40}
SOURCE_AND_SINK = {"name": "source and sink", "h" : 40, "w" : 40}
PERTURBATION = {"name": "perturbation", "h" : 40, "w" : 40}
<file_sep>SCRIPTS/sbgnpd2an/sbgnpd2an \
--initial-state glyph1,glyph3,glyph7,glyph2 \
MODELS/Example/maps/example.sbgn > MODELS/Example/analysis/an/nostories/nostories.an
<file_sep>class StateVariable:
def __init__(self, id = None, variable = None, value = None):
self.id = id
self.variable = variable
self.value = value
def getId(self):
return self.id
def getVariable(self):
return self.variable
def getValue(self):
return self.value
def setVariable(self, var):
self.variable = var
def setValue(self, val):
self.value = val
def setId(self, id):
self.id = id
def __eq__(self, other):
return isinstance(other, StateVariable) and \
self.variable == other.variable and \
self.value == other.value
def __hash__(self):
return hash((self.variable, self.value))
def __str__(self):
return "id: {0}, {1}@{2}".format(self.id, self.value, self.variable)
<file_sep>SCRIPTS/asp/sbgnpd2asp -o MODELS/PolyQ/asp/polyq.asp MODELS/PolyQ/maps/polyq.sbgn
<file_sep>./reducePhases.py --nostories --log logs/nostories/normal/reducePhases.log --dir MODELS/RB_E2F/analysis/an/nostories/reduced/normal/ -i MODELS/RB_E2F/analysis/an/nostories/nostories.an phases
echo "---------------"
echo "G0"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a359=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_G0_a359=1.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a6=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_G0_a6=1.reduced.an
echo "---------------"
echo "earlyG0"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a735=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_earlyG1_a735=1.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a450=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_earlyG1_a450=1.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a462=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_earlyG1_a462=1.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a725=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_earlyG1_a725=1.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a475=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_earlyG1_a475=1.reduced.an
echo "---------------"
echo "lateG1"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a532=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_lateG1_a532=1.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a524=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_lateG1_a524=1.reduced.an
echo "---------------"
echo "earlyS"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a632=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_earlyS_a632=1.reduced.an
echo "---------------"
echo "lateS"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal csa89=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_lateS_csa89=1.reduced.an
echo "---------------"
echo "G2"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a803=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_G2_a803=1.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a837=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_G2_a837=1.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a809=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_G2_a809=1.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a832=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_G2_a832=1.reduced.an
echo "---------------"
echo "M"
echo "---------------"
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal sa551=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_M_sa551=1.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a791=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_M_a791=1.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a816=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_M_a816=1.reduced.an
pint-export -i MODELS/RB_E2F/analysis/an/nostories/nostories.an --reduce-for-goal a858=1 -o MODELS/RB_E2F/analysis/an/nostories/reduced/normal/nostories_M_a858=1.reduced.an
<file_sep>from ProcessClazz import *
class Process:
def __init__(self, id = None, clazz = None, label = None, reactants = None, products = None):
self.id = id
self.clazz = clazz
self.label = label
if reactants is not None:
self.reactants = reactants
else:
self.reactants = set()
if products is not None:
self.products = products
else:
self.products = set()
def getId(self):
return self.id
def getClazz(self):
return self.clazz
def getLabel(self):
return self.label
def getReactants(self):
return self.reactants
def getProducts(self):
return self.products
def setId(self, id):
self.id = id
def setClazz(self, clazz):
self.clazz = clazz
def setLabel(self, label):
self.label = label
def setReactants(self, reactants):
self.reactants = reactants
def setProducts(self, products):
self.products = products
def addReactant(self, reactant):
self.reactants.add(reactant)
def addProduct(self, product):
self.products.add(product)
def __eq__(self, other):
return isinstance(other, Process) and \
self.clazz == other.clazz and \
self.label == other.label and \
self.reactants == other.reactants and \
self.products == other.products
def __hash__(self):
return hash((self.clazz, self.label, frozenset(self.reactants), frozenset(self.products)))
# return [0, hash(self.clazz)][self.clazz is not None] + \
# [0, hash(self.label)][self.label is not None] + \
# [0, hash(frozenset(self.reactants))][len(self.reactants) > 0] + \
# [0, hash(frozenset(self.products))][len(self.products) > 0]
def __str__(self):
s = "id: {0}, clazz: {1}, label: {2}\n".format(self.id, self.clazz, self.label)
for reac in self.reactants:
s += " Reactant: {0}\n".format(reac)
for prod in self.products:
s += " Product: {0}\n".format(prod)
return s
<file_sep>#!/bin/python
import sys
import argparse
import colorsys
import itertools
from fractions import Fraction
def zenos_dichotomy():
for k in itertools.count():
yield Fraction(1,2**k)
def getfracs():
"""
[Fraction(0, 1), Fraction(1, 2), Fraction(1, 4), Fraction(3, 4), Fraction(1, 8), Fraction(3, 8), Fraction(5, 8), Fraction(7, 8), Fraction(1, 16), Fraction(3, 16), ...]
[0.0, 0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875, 0.0625, 0.1875, ...]
"""
yield 0
for k in zenos_dichotomy():
i = k.denominator # [1,2,4,8,16,...]
for j in range(1,i,2):
yield Fraction(j,i)
bias = lambda x: (math.sqrt(x/3)/Fraction(2,3)+Fraction(1,3))/Fraction(6,5) # can be used for the v in hsv to map linear values 0..1 to something that looks equidistant
def genhsv(h):
for s in [Fraction(6,10)]: # optionally use range
for v in [Fraction(8,10),Fraction(5,10)]: # could use range too
yield (h, s, v) # use bias for v here if you use range
genrgb = lambda x: colorsys.hsv_to_rgb(*x)
flatten = itertools.chain.from_iterable
gethsvs = lambda: flatten(map(genhsv,getfracs()))
getrgbs = lambda: map(genrgb, gethsvs())
def genhtml(x):
uint8tuple = map(lambda y: int(y*255), x)
return uint8tuple
# return "rgb({},{},{})".format(*uint8tuple)
gethtmlcolors = lambda: map(genhtml, getrgbs())
def isInStory(epn, stories):
i = -1
for j, story in enumerate(stories):
if epn in story:
i = j
break
return i
parser = argparse.ArgumentParser()
parser.add_argument("input")
parser.add_argument("--output", "-o")
parser.add_argument("--story", action="append")
args = parser.parse_args()
input = args.input
if args.output:
output = args.output
else:
if ".graphml" in input:
output = input.split(".graphml")[0]+".colored.graphml"
else:
output = input+".colored.graphml"
if args.story:
colors = [tuple(c) for c in list(itertools.islice(gethtmlcolors(), len(args.story)))]
stories = [s.split(",") for s in args.story]
ifile = open(input)
ofile = open(output,"w")
string = ""
inNode = False
for line in ifile:
if "<node" in line:
inNode = True
if "</node" in line:
inNode = False
if inNode is True:
if "key=\"na6\"" in line:
green = line
elif "key=\"na7\"" in line:
red = line
elif "key=\"na5\"" in line:
blue = line
else:
ofile.write(line)
if "key=\"na0\"" in line:
epn = line.split(">")[1].split("<")[0]
print(epn)
i = isInStory(epn, stories)
if i != -1:
color = colors[i]
red = red.split(">")[0]+">"+str(color[0])+"<"+red.split("<")[2]
green = green.split(">")[0]+">"+str(color[1])+"<"+red.split("<")[2]
blue = blue.split(">")[0]+">"+str(color[2])+"<"+red.split("<")[2]
ofile.write(red)
ofile.write(blue)
ofile.write(green)
else:
ofile.write(line)
ifile.close()
ofile.close()
<file_sep>import libsbgnpy.libsbgn as libsbgn
from PDNetwork import *
from EntityClazz import *
from ProcessClazz import *
from ModulationClazz import *
from SubEntityClazz import *
from StateVariable import *
# from libsbgnpy.libsbgnTypes import *
class SBGN:
@staticmethod
def makeSvFromGlyph(sbgnMap, net, glyph):
if glyph.get_state() is not None:
return StateVariable(glyph.get_id(), glyph.get_state().get_variable(), glyph.get_state().get_value())
else:
return StateVariable()
@staticmethod
def makeEntityFromGlyph(sbgnMap, net, glyph):
entity = Entity()
entity.setId(glyph.get_id())
entity.setClazz(EntityClazz[glyph.get_class().name])
if glyph.get_label() is not None:
entity.setLabel(glyph.get_label().get_text())
else:
entity.setLabel(None)
entity.setCompartmentRef(glyph.get_compartmentRef())
for subglyph in glyph.get_glyph():
if subglyph.get_class().name in [attribute.name for attribute in list(EntityClazz)]:
subentity = SBGN.makeEntityFromGlyph(sbgnMap, net, subglyph)
entity.addComponent(subentity)
elif subglyph.get_class().name == 'STATE_VARIABLE':
sv = SBGN.makeSvFromGlyph(sbgnMap, net, subglyph)
entity.addStateVariable(sv)
already = net.getEntity(entity)
if already is not None:
return already
else:
return entity
@staticmethod
def getGlyphById(sbgnMap, id):
for glyph in sbgnMap.get_glyph():
if glyph.get_id() == id:
return glyph
return None
@staticmethod
def makeProcessFromGlyph(sbgnMap, net, glyph):
process = Process()
process.setId(glyph.get_id())
process.setClazz(ProcessClazz[glyph.get_class().name])
if glyph.get_label() is not None:
process.setLabel(glyph.get_label().get_text())
else:
process.setLabel(None)
for arc in sbgnMap.get_arc():
if arc.get_class().name == "CONSUMPTION" and arc.get_target() in [port.get_id() for port in glyph.get_port()]:
sourceId = arc.get_source()
sourceGlyph = SBGN.getGlyphById(sbgnMap, sourceId)
sourceEntity = SBGN.makeEntityFromGlyph(sbgnMap, net, sourceGlyph)
reactant = net.getEntity(sourceEntity)
process.addReactant(reactant)
elif arc.get_class().name == "PRODUCTION" and arc.get_source() in [port.get_id() for port in glyph.get_port()]:
targetId = arc.get_target()
targetGlyph = SBGN.getGlyphById(sbgnMap, targetId)
targetEntity = SBGN.makeEntityFromGlyph(sbgnMap, net, targetGlyph)
product = net.getEntity(targetEntity)
process.addProduct(product)
already = net.getProcess(process)
if already is not None:
return already
else:
return process
@staticmethod
def makeModulationFromArc(sbgnMap, net, arc):
sourceId = arc.get_source()
sourceGlyph = SBGN.getGlyphById(sbgnMap, sourceId)
sourceEntity = SBGN.makeEntityFromGlyph(sbgnMap, net, sourceGlyph)
sourceEntity = net.getEntity(sourceEntity)
targetId = arc.get_target()
targetGlyph = SBGN.getGlyphById(sbgnMap, targetId)
targetProcess = SBGN.makeProcessFromGlyph(sbgnMap, net, targetGlyph)
targetProcess = net.getProcess(targetProcess)
clazz = ModulationClazz[arc.get_class().name]
modulation = Modulation(clazz, sourceEntity, targetProcess)
return modulation
@staticmethod
def readSBGNML(filename):
sbgn = libsbgn.parse(filename, silence=True)
sbgnMap = sbgn.get_map()
net = PDNetwork()
for glyph in sbgnMap.get_glyph():
if glyph.get_class().name in [attribute.name for attribute in list(EntityClazz)]:
entity = SBGN.makeEntityFromGlyph(sbgnMap, net, glyph)
net.addEntity(entity)
for glyph in sbgnMap.get_glyph():
if glyph.get_class().name in [attribute.name for attribute in list(ProcessClazz)]:
process = SBGN.makeProcessFromGlyph(sbgnMap, net, glyph)
net.addProcess(process)
# Bug modulations with logical operators with ports that can be source
for arc in sbgnMap.get_arc():
if arc.get_class().name in [attribute.name for attribute in list(ModulationClazz)]:
modulation = SBGN.makeModulationFromArc(sbgnMap, net, arc)
net.addModulation(modulation)
return net
@staticmethod
def getCG2ASP(net):
s = ""
for entity in net.getEntities():
if not net.isSink(entity):
s += "epn({0}).\n".format(entity.getId())
if entity.hasLabel():
s += "belong({0}, {1}).\n".format(SBGN.normalizeLabel(entity.getLabel()), entity.getId())
for subentity in entity.getComponents():
if subentity.hasLabel():
s += "belong({0}, {1}).\n".format(SBGN.normalizeLabel(subentity.getLabel()), entity.getId())
for process in net.getProcesses():
reactants = process.getReactants()
products = process.getProducts()
if len(reactants) == 0:
for product in products:
for product2 in products:
if product != product2:
if not net.isSink(product):
s += "edge({0},{1},{2}).\n".format(product.getId(), product2.getId(), process.getId())
else:
for reactant in reactants:
for product in products:
if not net.isSink(product):
s += "edge({0},{1},{2}).\n".format(reactant.getId(), product.getId(), process.getId())
return s
@staticmethod
def writeCG2ASP(net, filename):
ofile = open(filename, "w")
s = SBGN.getCG2ASP(net)
ofile.write(s)
ofile.close()
@staticmethod
def normalizeLabel(label):
label = label.replace("*","_")
label = label.replace("/","_")
label = label.replace(" ","_")
label = label.replace("-","_")
label = label.lower()
return label
@staticmethod
def writeSBGNML(net, filename):
sbgn = SBGN.makeSBGNML(net)
sbgn.write_file(filename)
ifile = open(filename)
s = ifile.read()
ifile.close()
s = s.replace("sbgn:","")
s = s.replace(' xmlns:sbgn="http://sbgn.org/libsbgn/0.2"', "")
s = s.replace('."', '.0"')
ofile = open(filename, "w")
ofile.write(s)
ofile.close()
@staticmethod
def makeGlyphFromEntity(epn, iglyph):
g = libsbgn.glyph()
g.set_class(libsbgn.GlyphClass[epn.getClazz().name])
g.set_id("glyph{0}".format(iglyph))
iglyph += 1
bbox = libsbgn.bbox(0, 0, epn.getClazz().value["w"], epn.getClazz().value["h"])
g.set_bbox(bbox)
label = libsbgn.label()
label.set_text(epn.getLabel())
g.set_label(label)
for component in epn.getComponents():
iglyph, gc = SBGN.makeGlyphFromComponent(component, iglyph)
g.add_glyph(gc)
for i, sv in enumerate(epn.getStateVariables()):
gsv = libsbgn.glyph()
gsv.set_id("glyph{0}".format(iglyph))
iglyph += 1
gsv.set_class(libsbgn.GlyphClass["STATE_VARIABLE"])
gsv.set_state(libsbgn.stateType(sv.getVariable(), sv.getValue()))
bbox = libsbgn.bbox()
bbox.set_x(g.get_bbox().get_x()+40*i+6)
bbox.set_y(g.get_bbox().get_y()-10)
bbox.set_h(22)
bbox.set_w(40)
gsv.set_bbox(bbox)
g.add_glyph(gsv)
return iglyph, g
def makeGlyphFromComponent(comp, iglyph):
g = libsbgn.glyph()
g.set_class(libsbgn.GlyphClass[comp.getClazz().name])
g.set_id("glyph{0}".format(iglyph))
iglyph += 1
bbox = libsbgn.bbox(0, 0, comp.getClazz().value["w"], comp.getClazz().value["h"])
g.set_bbox(bbox)
label = libsbgn.label()
label.set_text(comp.getLabel())
g.set_label(label)
for component in comp.getComponents():
iglyph, gc = SBGN.makeGlyphFromComponent(component, iglyph)
g.add_glyph(gc)
for i, sv in enumerate(comp.getStateVariables()):
gsv = libsbgn.glyph()
gsv.set_id("glyph{0}".format(iglyph))
iglyph += 1
gsv.set_class(libsbgn.GlyphClass["STATE_VARIABLE"])
gsv.set_state(libsbgn.stateType(sv.getVariable(), sv.getValue()))
bbox = libsbgn.bbox()
bbox.set_x(g.get_bbox().get_x()+40*i+6)
bbox.set_y(g.get_bbox().get_y()-10)
bbox.set_h(22)
bbox.set_w(40)
gsv.set_bbox(bbox)
g.add_glyph(gsv)
return iglyph, g
@staticmethod
def makeGlyphFromProcess(process, iglyph):
p = libsbgn.glyph()
p.set_class(libsbgn.GlyphClass[process.getClazz().name])
p.set_id("glyph{0}".format(iglyph))
iglyph += 1
bbox = libsbgn.bbox(0, 0, process.getClazz().value["w"], process.getClazz().value["h"])
p.set_bbox(bbox)
port1 = libsbgn.port()
# port1.set_id("{0}.1".format(p.get_id()))
# port1.set_y(bbox.get_y() + bbox.get_h() / 2)
# port1.set_x(bbox.get_x())
# port2 = libsbgn.port()
# port2.set_id("{0}.2".format(p.get_id()))
# port2.set_y(bbox.get_y() + bbox.get_h() / 2)
# port2.set_x(bbox.get_x() + bbox.get_w())
# p.add_port(port1)
# p.add_port(port2)
return iglyph, p
@staticmethod
def makeArcsFromProcess(process, iarc, dids):
arcs = []
for reactant in process.getReactants():
arc = libsbgn.arc()
start = libsbgn.startType(0, 0)
end = libsbgn.endType(0, 0)
arc.set_source(dids[reactant.getId()])
# arc.set_target("{0}.1".format(process.getId()))
arc.set_target(dids[process.getId()])
arc.set_id("arc{0}".format(iarc))
iarc += 1
arc.set_start(start)
arc.set_end(end)
arc.set_class(libsbgn.ArcClass.CONSUMPTION)
arcs.append(arc)
for product in process.getProducts():
arc = libsbgn.arc()
start = libsbgn.startType(0, 0)
end = libsbgn.endType(0, 0)
# arc.set_source("{0}.2".format(process.getId()))
arc.set_source(dids[process.getId()])
arc.set_target(dids[product.getId()])
arc.set_id("arc{0}".format(iarc))
iarc += 1
arc.set_start(start)
arc.set_end(end)
arc.set_class(libsbgn.ArcClass.PRODUCTION)
arcs.append(arc)
return iarc, arcs
@staticmethod
def makeArcFromModulation(modulation, iarc, dids):
arc = libsbgn.arc()
start = libsbgn.startType(0, 0)
end = libsbgn.endType(0, 0)
arc.set_source(dids[modulation.getSource().getId()])
arc.set_target(dids[modulation.getTarget().getId()])
arc.set_id("arc{0}".format(iarc))
iarc += 1
arc.set_start(start)
arc.set_end(end)
arc.set_class(libsbgn.ArcClass[modulation.getClazz().name])
return iarc, arc
@staticmethod
def makeSBGNML(net):
iglyph = 0
iarc = 0
sbgn = libsbgn.sbgn()
sbgnmap = libsbgn.map()
language = libsbgn.Language.PD
sbgnmap.set_language(language)
sbgn.set_map(sbgnmap);
dids = {}
for epn in net.getEntities():
iglyph, g = SBGN.makeGlyphFromEntity(epn, iglyph)
sbgnmap.add_glyph(g)
dids[epn.getId()] = g.get_id()
for process in net.getProcesses():
iglyph, p = SBGN.makeGlyphFromProcess(process, iglyph)
sbgnmap.add_glyph(p)
dids[process.getId()] = p.get_id()
iarc, arcs = SBGN.makeArcsFromProcess(process, iarc, dids)
for arc in arcs:
sbgnmap.add_arc(arc)
for modulation in net.getModulations():
iarc, arc = SBGN.makeArcFromModulation(modulation, iarc, dids)
sbgnmap.add_arc(arc)
return sbgn
if __name__ == "__main__":
net = SBGN.readSBGNML("example.sbgn")
SBGN.writeSBGNML(net, "example2.sbgn")
<file_sep>#!/bin/bash
pint-export -l prism \
-i MODELS/PolyQ/analysis/an/stories/stories.an \
-o MODELS/PolyQ/analysis/prism/stories/noprobas/noprobas.prism
# --initial-state glyph14,glyph15,glyph17,glyph24,glyph4,glyph18,glyph41,glyph6 \
<file_sep>#!/bin/bash
SCRIPTS/stories/stories --max 1 MODELS/Example/asp/example.asp > MODELS/Example/stories/example1.stories
SCRIPTS/stories/stories --max 2 MODELS/Example/asp/example.asp > MODELS/Example/stories/example2.stories
SCRIPTS/stories/stories --max 3 MODELS/Example/asp/example.asp > MODELS/Example/stories/example3.stories
SCRIPTS/stories/stories --story glyph3,glyph0 --story glyph8,glyph1 --max 2 MODELS/Example/asp/example.asp > MODELS/Example/stories/example4.stories
SCRIPTS/stories/stories --clabel --max 2 MODELS/Example/asp/example.asp > MODELS/Example/stories/example5.stories
<file_sep>#!/bin/bash
SCRIPTS/maps/cd2sbgnml MODELS/RB_E2F/maps/rb_e2f.cd.xml MODELS/RB_E2F/maps/rb_e2f.cd.sbgn MODELS/RB_E2F/maps/rb_e2f.sbgn
<file_sep>#!/bin/bash
SCRIPTS/stories/stories \
--initial-state glyph4,glyph41,glyph18 \
--clabel \
--max 2 \
MODELS/PolyQ/asp/polyq.asp > MODELS/PolyQ/stories/polyq.stories
<file_sep>#!/bin/python
import sys
from collections import defaultdict
import xml.etree.ElementTree as ET
cdfile = sys.argv[1]
sbgnfile = sys.argv[2]
ofile = sys.argv[3]
tree = ET.parse(cdfile)
root = tree.getroot()
dspecies = {}
dstates = {}
dcompartments = {}
dcomplexes = defaultdict(list)
lmulti = []
ns = {'default_cd':'http://www.sbml.org/sbml/level2',
'celldesigner':'http://www.sbml.org/2001/ns/celldesigner',
'default_sbgnml':'http://sbgn.org/libsbgn/0.2'}
ET.register_namespace("",ns["default_sbgnml"])
#GET IDs, COMPARTMENTS, COMPLEXES
for alias in root.findall(".//celldesigner:speciesAlias",ns):
dspecies[alias.get("id")] = alias.get("species")
dcompartments[alias.get("id")] = alias.get("compartmentAlias")
complexAlias = alias.get("complexSpeciesAlias")
if complexAlias is not None:
dcomplexes[complexAlias].append(alias.get("id"))
for alias in root.findall(".//celldesigner:complexSpeciesAlias",ns):
dspecies[alias.get("id")] = alias.get("species")
dcompartments[alias.get("id")] = alias.get("compartmentAlias")
#GET STATES
for id in dspecies.keys():
specy = root.findall(".//celldesigner:species[@id='"+dspecies[id]+"']",ns)
if len(specy)!=0:
specy = specy[0]
lstates = specy.findall(".//celldesigner:modification",ns)
if len(lstates)!=0:
dstates[id] = [(state.get("residue"),state.get("state")) for state in lstates]
for id in dspecies.keys():
specy = root.findall(".//default_cd:species[@id='"+dspecies[id]+"']",ns)
if len(specy)!=0:
specy = specy[0]
lstates = specy.findall(".//celldesigner:modification",ns)
if len(lstates)!=0:
dstates[id] = [(state.get("residue"),state.get("state")) for state in lstates]
#GET MULTIMERS
for id in dspecies.keys():
specy = root.findall(".//default_cd:species[@id='"+dspecies[id]+"']",ns)
if len(specy)!=0:
specy = specy[0]
if len(specy.findall(".//celldesigner:homodimer",ns))!=0:
lmulti.append(id)
tree = ET.parse(sbgnfile)
root = tree.getroot()
#WRITE COMPARTMENTS
for id in dcompartments.keys():
glyph = root[0].findall("default_sbgnml:glyph[@id='"+id+"']",ns)[0]
if dcompartments[id] is not None:
glyph.attrib["compartmentRef"] = dcompartments[id]
#WRITE STATES
for id in dstates.keys():
i = 97
glyph = root[0].findall("default_sbgnml:glyph[@id='"+id+"']",ns)[0]
for res_state in dstates[id]:
res = res_state[0]
state = res_state[1]
sv = ET.Element("{http://sbgn.org/libsbgn/0.2}glyph",{"id":id+chr(i), "class":"state variable"})
bbox = ET.Element("{http://sbgn.org/libsbgn/0.2}bbox",{"y":"0","x":"0","h":"0","w":"0"})
if state == "phosphorylated":
state = "P"
elif state == "acetylated":
state = "Ac"
else:
state = "?"
s = ET.Element("{http://sbgn.org/libsbgn/0.2}state",{"variable":res,"value":state})
sv.append(s)
sv.append(bbox)
i = i+1
glyph.append(sv)
#WRITE MULTI
for id in lmulti:
glyph = root[0].findall("default_sbgnml:glyph[@id='"+id+"']",ns)[0]
if glyph.attrib["class"] == "macromolecule":
glyph.attrib["class"] = "macromolecule multimer"
#WRITE COMPLEXES
for id in dcomplexes.keys():
complex = root[0].findall("default_sbgnml:glyph[@id='"+id+"']",ns)[0]
for sid in dcomplexes[id]:
species = root[0].findall("default_sbgnml:glyph[@id='"+sid+"']",ns)[0]
root[0].remove(species)
complex.append(species)
#WRITE FILE
tree.write(ofile, encoding = "UTF-8", xml_declaration=True)
<file_sep>#!/bin/bash
SCRIPTS/stories/stories \
--max 2 \
MODELS/ERK/asp/erk.asp > MODELS/ERK/stories/erk.stories
<file_sep>#!/bin/bash
SCRIPTS/stories/stories\
--max 2 \
MODELS/RB_E2F/asp/rb_e2f.asp > MODELS/RB_E2F/stories/rb_e2f_all.stories
<file_sep>from ModulationClazz import *
class Modulation:
def __init__(self, clazz = None, source = None, target = None):
self.source = source
self.target = target
self.clazz = clazz
def getClazz(self):
return self.clazz
def getSource(self):
return self.source
def getTarget(self):
return self.target
def setClazz(self, clazz):
self.clazz = clazz
def setSource(self, source):
self.source = source
def setTarget(self, target):
self.target = target
def __eq__(self, other):
return self.source == other.source and \
self.target == other.target
def __hash__(self):
return hash((self.source, self.target))
<file_sep>from Entity import *
from Process import *
from Modulation import *
from StateVariable import *
from Compartment import *
class PDNetwork:
def __init__(self, entities = None, processes = None, modulations = None, compartments = None):
if entities is not None:
self.entities = entities
else:
self.entities = set()
if processes is not None:
self.processes = processes
else:
self.processes = set()
if modulations is not None:
self.modulations = modulations
else:
self.modulations = set()
if compartments is not None:
self.compartments = compartments
else:
self.compartments = set()
def getProcesses(self):
return self.processes
def getEntities(self):
return self.entities
def getModulations(self):
return self.modulations
def getCompartments(self):
return self.compartments
def setProcesses(self, processes):
self.processes = processes
def setEntities(self, entities):
self.entities = entities
def setModulations(self, modulations):
self.modulations = modulations
def setCompartments(self, compartments):
self.compartments = compartments
def addProcess(self, process):
self.processes.add(process)
def addEntity(self, entity):
self.entities.add(entity)
def addModulation(self, modulation):
self.modulations.add(modulation)
def addCompartments(self, compartment):
self.compartments.add(compartment)
def getEntity(self, entity):
if isinstance(entity, Entity):
for entity2 in self.entities:
if entity == entity2:
return entity2
return None
elif isinstance(entity, str):
for entity2 in self.entities:
if entity2.getId() == entity:
return entity2
return None
def getProcess(self, process):
if isinstance(process, Process):
for process2 in self.processes:
if process == process2:
return process2
return None
elif isinstance(process, str):
for process2 in self.processes:
if process2.getId() == process:
return process
return None
def getModulation(self, modulation):
for modulation2 in self.modulations:
if modulation2 == modulation:
return modulation2
return None
def getCompartment(self, compartment):
for compartment1 in self.compartments:
if compartment2 == compartment:
return compartment2
return None
def isProduced(self, entity):
for process in self.getProcesses():
if entity in process.getProducts():
return True
return False
def isConsumed(self, entity):
for process in self.getProcesses():
if entity in process.getReactants():
return True
return False
def isModulator(self, entity):
for modulation in self.getModulations():
if entity == modulation.getSource():
return True
return False
def isSource(self, entity):
if entity.getClazz() == EntityClazz.SOURCE_AND_SINK and not self.isProduced(entity):
return True
else:
return False
def isSink(self, entity):
if entity.getClazz() == EntityClazz.SOURCE_AND_SINK and not self.isConsumed(entity):
return True
else:
return False
# def updateIds(self):
# iepn = 0
# isubepn = 0
# isv = 0
# icomp = 0
# iproc = 0
# for epn in self.getEntities():
# epn.setId("epn{0}".format(iepn))
# iepn += 1
# for subepn in epn.getComponents():
# subepn.setId("subepn{0}".format(isubepn))
# isubepn += 1
# for sv in epn.getStateVariables():
# sv.setId("sv{0}".format(isv))
# isv += 1
# for comp in self.getCompartments():
# comp.setId("comp{0}".format(icomp))
# icomp += 1
# for proc in self.getProcesses():
# proc.setId("proc{0}".format(iproc))
# iproc += 1
def removeSingleEntities(self):
toRemove = set()
for epn in self.getEntities():
if not self.isProduced(epn) and not self.isConsumed(epn) and not self.isModulator(epn):
toRemove.add(epn)
for epn in toRemove:
self.entities.remove(epn)
def setNoneLabelsToEmptyStrings(self):
for epn in self.entities:
if epn.getLabel() is None:
epn.setLabel("")
def __str__(self):
s = ""
for epn in self.getEntities():
s += "Epn: {0}\n".format(epn)
for proc in self.getProcesses():
s += "Process: {0}\n".format(proc)
return s
<file_sep>#!/bin/python
from collections import defaultdict
def readPhases(infile):
dphases = defaultdict(set)
ifile = open(infile)
for i, line in enumerate(ifile):
if i == 0:
order = line[:-1].split("#")[0].replace(" ","").split(",")
continue
if line[0] != "#" and line != "\n":
l = line.replace(" ","").split("#")[0].split(":")
phase = l[0]
if l[1][-1] == '\n':
l[1] =l[1][:-1]
conjuncts = frozenset(l[1].split(","))
dphases[phase].add(conjuncts)
ifile.close()
return order, dphases
def stateNoStory(state):
l = state.split('=')
if l[1].isdigit():
return state
state = l[1] + "=1"
return state
def stateAN(state):
state = state.replace('"','')
l = state.split('=')
state = '"{0}"'.format(l[0])
state += "="
if not l[1].isdigit():
state += '"{0}"'.format(l[1])
else:
state += l[1]
return state
def statePhase(state):
return state.replace('"','')
if __name__ == '__main__':
model = "stories"
fphases = "MODELS/RB_E2F/analysis/phases/rb_e2f.phases"
fmodel = "MODELS/RB_E2F/analysis/an/"+model+".an"
tempbase = "MODELS/RB_E2F/analysis/an/simultaneity/"+model+"/"
order, dphases = readPhases(fphases)
for i, p in enumerate(order):
for j, q in enumerate(order[i+1:]):
for c in dphases[order[i]]:
for s in c:
for d in dphases[q]:
for r in d:
st = ""
ifile = open(fmodel)
for line in ifile:
if "initial_context" in line or "initial_state" in line:
s = stateAN(s)
r = stateAN(r)
st += '"{0}_{1}" [0,1]\n'.format(p, q)
st += '"{0}_{1}" 0 -> 1 when {2} and {3}\n'.format(p, q, s, r)
if line[-1] == '\n':
line = line[:-1]
line += ',"{0}_{1}" = 0\n'.format(p, q)
st += line
s = statePhase(s)
r = statePhase(r)
temp = tempbase + model
temp += "_"
temp += p
temp += "_"
temp += q
temp += "_"
temp += s
temp += "_"
temp += r
temp += ".an"
ofile = open(temp, "w")
ofile.write(st)
ofile.close()
<file_sep>#!/bin/bash
pint-sg --state-graph MODELS/Example/analysis/stg/nostories/nostories.dot -i MODELS/Example/analysis/an/nostories/nostories.an
<file_sep>echo "---------------"
echo "G0"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_G0_e2f4=a359.reduced.an e2f4=a359 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_G0_e2f4=a359.reach
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_G0_e2f4=a6.reduced.an e2f4=a6 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_G0_e2f4=a6.reach
echo "---------------"
echo "earlyG0"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_earlyG1_cdk4=a735.reduced.an cdk4=a735 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_earlyG1_cdk4=a735.reach
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_earlyG1_cdk6=a725.reduced.an cdk6=a725 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_earlyG1_cdk6=a725.reach
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_earlyG1_e2f1=a450.reduced.an e2f1=a450 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_earlyG1_e2f1=a450.reach
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_earlyG1_e2f1=a475.reduced.an e2f1=a475 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_earlyG1_e2f1=a475.reach
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_earlyG1_e2f1=a462.reduced.an e2f1=a462 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_earlyG1_e2f1=a462.reach
echo "---------------"
echo "lateG1"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_lateG1_e2f1=a524.reduced.an e2f1=a524 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_lateG1_e2f1=a524.reach
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_lateG1_e2f1=a532.reduced.an e2f1=a532 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_lateG1_e2f1=a532.reach
echo "---------------"
echo "earlyS"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_earlyS_cdk2=a632.reduced.an cdk2=a632 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_earlyS_cdk2=a632.reach
echo "---------------"
echo "lateS"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_lateS_cdk2=csa89.reduced.an cdk2=csa89 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_lateS_cdk2=csa89.reach
echo "---------------"
echo "G2"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_G2_cdc2=a809.reduced.an cdc2=a809 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_G2_cdc2=a809.reach
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_G2_cdc2=a837.reduced.an cdc2=a837 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_G2_cdc2=a837.reach
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_G2_cdc2=a832.reduced.an cdc2=a832 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_G2_cdc2=a832.reach
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_G2_cdc2=a803.reduced.an cdc2=a803 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_G2_cdc2=a803.reach
echo "---------------"
echo "M"
echo "---------------"
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_M_cdc20=a858.reduced.an cdc20=a858 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_M_cdc20=a858.reach
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_M_cdc25c=a816.reduced.an cdc25c=a816 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_M_cdc25c=a816.reach
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_M_wee1=sa551.reduced.an wee1=sa551 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_M_wee1=sa551.reach
pint-mole -i MODELS/RB_E2F/analysis/an/stories/reduced/normal/stories_M_cdc2=a791.reduced.an cdc2=a791 > MODELS/RB_E2F/analysis/reach/stories/normal/stories_M_cdc2=a791.reach
<file_sep>#!/bin/bash
pint-sg --state-graph MODELS/Example/analysis/stg/stories/stories.dot -i MODELS/Example/analysis/an/stories/stories.an
<file_sep>#!/bin/python
from collections import defaultdict
def readPhases(infile):
dphases = defaultdict(set)
ifile = open(infile)
for i, line in enumerate(ifile):
if i == 0:
order = line[:-1].split("#")[0].replace(" ","").split(",")
continue
if line[0] != "#" and line != "\n":
l = line.replace(" ","").split("#")[0].split(":")
phase = l[0]
if l[1][-1] == '\n':
l[1] =l[1][:-1]
conjuncts = frozenset(l[1].split(","))
dphases[phase].add(conjuncts)
ifile.close()
return order, dphases
def stateNoStory(state):
l = state.split('=')
if l[1].isdigit():
return state
state = l[1] + "=1"
return state
def stateAN(state):
state = state.replace('"','')
l = state.split('=')
state = '"{0}"'.format(l[0])
state += "="
if not l[1].isdigit():
state += '"{0}"'.format(l[1])
else:
state += l[1]
return state
def statePhase(state):
return state.replace('"','')
if __name__ == '__main__':
situations = ["normal","disable_e2f1","disable_prev_phase"]
models = ["nostories","stories","nostoriestriggers","storiestriggers","storiestriggers2"]
fphases = "MODELS/RB_E2F/analysis/phases/rb_e2f.phases"
ofile = open("MODELS/RB_E2F/analysis/results/results.csv", "w")
order, dphases = readPhases(fphases)
dresults = {}
for situation in situations:
dresults[situation] = {}
for model in models:
dresults[situation][model] = {}
for phase in order:
all = "False"
dresults[situation][model][phase] = {}
for conjunct in dphases[phase]:
for state in conjunct:
path = "MODELS/RB_E2F/analysis/reach/"
path += model
path += "/"
path += situation
path += "/"
path += model
path += "_"
path += phase
path += "_"
if model == "nostories" or model == "nostoriestriggers":
state = state.split("=")[1]+"=1"
path += state
path += ".reach"
res = open(path).read()[:-1]
dresults[situation][model][phase][state] = res
if res == "True":
all = "True"
dresults[situation][model][phase]["all"] = all
# ofile.write("phase,state,")
#
# for situation in situations:
# ofile.write(situation)
# for model in models:
# ofile.write(",")
#
# ofile.write("\n")
# ofile.write(",,")
# for situation in situations:
# for model in models:
# ofile.write(model)
# ofile.write(",")
#
# ofile.write("\n")
#
# for i, phase in enumerate(order):
# ofile.write(phase)
# for j, conjunct in enumerate(dphases[phase]):
# for k, state in enumerate(conjunct):
# ofile.write(",")
# ofile.write(state)
# ofile.write(",")
# for situation in situations:
# for model in models:
# if model == "nostories" or model == "nostoriestriggers":
# statebis = state.split("=")[1]+"=1"
# else:
# statebis = state
# ofile.write(dresults[situation][model][phase][statebis])
# ofile.write(",")
# ofile.write("\n")
#
ofile.write("phase,")
for situation in situations:
ofile.write(situation)
for model in models:
ofile.write(",")
ofile.write("\n")
ofile.write(",")
for situation in situations:
for model in models:
ofile.write(model)
ofile.write(",")
ofile.write("\n")
for phase in order:
ofile.write(phase)
ofile.write(",")
for situation in situations:
for model in models:
ofile.write(dresults[situation][model][phase]["all"])
ofile.write(",")
ofile.write("\n")
#SIMULTANEITY
ofile.write("\n\n\n")
ofile.write("model,")
for model in models:
ofile.write("{0}{1}".format(model, ","*len(order)))
ofile.write("\nphase,")
for model in models:
for p in order:
ofile.write("{0},".format(p))
ofile.write("\n")
for i, p in enumerate(order):
# print("Phase1 : {0}".format(p))
st = "{0}:".format(p)
ofile.write("{0},".format(p))
for model in models:
# print(" Model : {0}".format(model))
ofile.write(","*(i+1))
for j, q in enumerate(order[i+1:]):
# print(" Phase2 : {0}".format(q))
all = "False"
for c in dphases[p]:
for s in c:
if model == "nostories" or model == "nostoriestriggers":
s = stateNoStory(s)
for d in dphases[q]:
for r in d:
if model == "nostories" or model == "nostoriestriggers":
r = stateNoStory(r)
path = "MODELS/RB_E2F/analysis/reach/{0}/simultaneity/".format(model)
path += model
path += "_"
path += p
path += "_"
path += q
path += "_"
path += s
path += "_"
path += r
path += ".reach"
res = open(path).read()[:-1]
if "True" in res:
all = "True"
break
elif "False" in res:
pass
else:
all = "Error"
if all == "True":
break
if all == "True":
break
if all == "True":
break
ofile.write("{0},".format(all))
ofile.write("\n")
ofile.close()
<file_sep>from enum import Enum
class ModulationClazz(Enum):
CATALYSIS = "catalysis"
MODULATION = "modulation"
STIMULATION = "stimulation"
INHIBITION = "inhibition"
UNKNOWN_INFLUENCE = "unknown influence"
NECESSARY_STIMULATION = "necessary stimulation"
<file_sep>SCRIPTS/asp/sbgnpd2asp -o MODELS/ERK/asp/erk.asp MODELS/ERK/maps/erk.sbgn
<file_sep>SCRIPTS/asp/sbgnpd2asp -o MODELS/Example/asp/example.asp MODELS/Example/maps/example.sbgn
<file_sep>from EntityClazz import *
class Entity:
def __init__(self, id = None, clazz = None, label = None, compartmentRef = None, components = None, svs = None):
self.id = id
self.clazz = clazz
self.label = label
self.compartmentRef = compartmentRef
if components is not None:
self.components = components
else:
self.components = set()
if svs is not None:
self.svs = svs
else:
self.svs = set()
def setId(self, id):
self.id = id
def setClazz(self, clazz):
self.clazz = clazz
def setLabel(self, label):
self.label = label
def setCompartmentRef(self, compartmentRef):
self.compartmentRef = compartmentRef
def setComponents(self, components):
self.components = components
def addComponent(self, component):
self.components.add(component)
def removeComponent(self, component):
self.components.remove(component)
def setStateVariables(self, svs):
self.svs = svs
def addStateVariable(self, sv):
self.svs.add(sv)
def removeStateVariable(self, sv):
self.svs.remove(sv)
def getId(self):
return self.id
def getClazz(self):
return self.clazz
def getLabel(self):
return self.label
def getCompartmentRef(self):
return self.compartmentRef
def getComponents(self):
return self.components
def getStateVariables(self):
return self.svs
def hasLabel(self):
return self.label is not None
def __eq__(self, other):
if not isinstance(other, Entity):
return False
if not self.clazz == EntityClazz.SOURCE_AND_SINK:
return self.label == other.label and \
self.clazz == other.clazz and \
self.compartmentRef == other.compartmentRef and \
self.components == other.components and \
self.svs == other.svs
else:
return self.id == other.id and self.clazz == other.clazz
def __hash__(self):
if not self.clazz == EntityClazz.SOURCE_AND_SINK:
return hash((self.clazz, self.label, self.compartmentRef, frozenset(self.components), frozenset(self.svs)))
# return [0, hash(self.clazz)][self.clazz is not None] + \
# [0, hash(self.label)][self.label is not None] + \
# [0, hash(self.compartmentRef)][self.compartmentRef is not None] + \
# [0, hash(frozenset(self.components))][len(self.components) > 0] + \
# [0, hash(frozenset(self.svs))][len(self.svs) > 0]
else:
return hash(self.id)
def __str__(self):
s = "id: {0}, clazz: {1}, label: {2}\n".format(self.getId(), self.getClazz(), self.getLabel())
for sv in self.getStateVariables():
s += " Sv:{0}\n".format(sv)
return s
| 15818289e04f93e0b4b183361472f01519f9a2b3 | [
"Markdown",
"Python",
"Shell"
] | 43 | Shell | pauleve/sbgnpd2an-suppl | a56726780d2394b22b3a76410c3359a9756dddbb | 26945960103563171b17baa415a3c0635b57279f |
refs/heads/master | <repo_name>ZhaoRS/ZRSAdPicView<file_sep>/Example/Podfile
use_frameworks!
target 'ZRSAdPicView_Example' do
pod 'ZRSAdPicView', :path => '../'
target 'ZRSAdPicView_Tests' do
inherit! :search_paths
pod 'FBSnapshotTestCase'
end
end
| a8af3c05285d3ad947b06b2420360b470644b9cc | [
"Ruby"
] | 1 | Ruby | ZhaoRS/ZRSAdPicView | 5c1c75739872a72a0afd0e8630c8b5366516f1f3 | 3d871c1f17c1c2b661fae216308da6350b85cc01 |
refs/heads/source | <repo_name>oaxacarb/oaxacarb.github.io<file_sep>/source/posts/2016/2016-10-01-global-day-code-retreat-2016.html.markdown
---
title: Global Day Coderetreat Oaxaca 2016
date: 2016-10-01 20:44 UTC
tags: [code retreat, evento, comunidad]
---

La comunidad de Oaxaca.rb invita a todos los desarrolladores de software a participar en el Global Day Code Retreat 2016 a realizarse el sábado 22 de octubre del presente año, en las oficinas del COCYT, ubicadas en <NAME>il # 517, Centro, Oaxaca.
La dinámica del Global Day Code Retreat consiste en 8 horas de práctica de TDD (Desarrollo Dirigido por Pruebas, por sus siglas en Inglés). TDD es una técnica de diseño de software y la kata que se practica durante el code retreat es El juego de la vida.
Puedes programar en el lenguaje en el que te sientas más cómodo, PHP, Java, Python, etc. Nosotros, obviamente, recomendamos Ruby :)
Dado que la práctica se extiende durante todo el día, para que tú sólo te preocupes por aprender y practicar, nosotros nos encargamos de la comida.
Si estás interesado, debes incribirte [aquí](http://goo.gl/xU8n3A).
La máquina virtual la puedes descargar aquí:
* [link uno](http://www.mediafire.com/file/lo8y7noekhg319f/oaxacarb.z01) (950 mb)
* [link dos](http://www.mediafire.com/file/8jiov5hxihguot8/oaxacarb.z02) (950 mb)
* [link tres](http://www.mediafire.com/file/pvgzow4bodo5d0j/oaxacarb.zip) (901 mb)
* [link md5](http://www.mediafire.com/file/js8vh64xwma2tws/oaxacarb.md5) (Para corroborar la descarga de la máquina virtual)
Recuerda que el evento es gratuito.
Te esperamos.
<file_sep>/source/posts/2014/2014-03-11-configuracion-de-rvm-y-ruby.html.markdown
---
title: Configuración del entorno de trabajo Ruby con RVM
date: 2014-03-11 16:13 UTC
tags: rvm, ruby
---
Muchas veces, al trabajar con un lenguaje interpretado (como ruby o python) es necesario instalar varias librerías, pero siempre queda el miedo de romper algo con tanta instalación; es deseable poder tener múltiples configuraciones independientes, incluso por proyecto. Para eso tenemos [RVM](https://rvm.io/).
En palabras del autor, **Ruby Version Manager** (RVM) se puede describir de la siguiente manera:
> Una herramienta que permite fácilmente instalar, gestionar y trabajar con múltiples entornos ruby, desde versiones del intérprete hasta sets de gemas.
#### Instalación de RVM
Para instalar RVM en nuestro sistema **Linux**, hay que seguir los siguientes pasos:
Descargamos e instalamos RVM
``\curl -sSL https://get.rvm.io | bash``
Al final de la instalación, veremos un mensaje que nos pide copiar cierto contenido a nuestro archivo ``.bash_profile`` (archivo oculto ubicado en nuestro directorio home), seguimos la recomendación para obtener un archivo parecido a lo siguiente:
``. $HOME/.bashrc``
``[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"``
``source ~/.profile``
Luego, cargamos la nueva configuración de bash en nuestra sesión actual (o reiniciamos nuestra consola, lo que gusten)
``source ~/.bash_profile``
Listo, ya tenemos RVM instalado, lo podemos comprobar con el comando ``rvm -v``, lo que nos debe de mostrar la versión de RVM instalada en nuestro sistema.
#### Instalación de Ruby
Ya que tenemos instalado RVM, instalar Ruby es tan fácil como correr un comando, indicándole la versión deseada (recomendamos la *2.1.0*)
rvm install ruby-2.1.0
Nos sentamos unos momentos a esperar a que termine la instalación...
#### Configuración de RVM por proyecto
RVM es lo suficientemente "inteligente" como para identificar las versiones que requerimos dentro de un proyecto, agrupando las librerias requeridas en **gemsets**, para ésto, requerimos tener un par de archivos dentro de nuestro directorio de trabajo: ``.ruby-version`` y ``.ruby-gemset`` (ambos archivos ocultos).
Para crear y configurar un nuevo directorio de proyecto, creamos los dos archivos mencionados anteriormente denotando la versión de ruby y el nombre del gemset deseado:
``mkdir proyecto && cd proyecto``
``echo '2.1.0' > .ruby-version``
``echo 'proyecto' > .ruby-gemset``
Esto creará un gemset llamado *proyecto* que utiliza la versión *2.1.0* de ruby, denotado como **ruby-2.1.0@proyecto**, ahora, cada que entremos al directorio ``proyecto``, RVM cargará automáticamente la configuración deseada, y todas las librerías (gemas) que instalemos en dicho proyecto quedarán aisladas en el mismo.
Si aún estamos dentro de nuestra carpeta *proyecto*, ejecutamos el comando ``cd .`` (punto):
``=> ruby-2.1.0 - #gemset created ruby-2.1.0@proyecto``
``=> ruby-2.1.0 - #generating proyecto wrappers.......``
Por último, comprobamos que todo se encuentre en orden, verificamos la versión de ruby en uso con el comando:
``rvm list``
``=* ruby-2.1.0 [ x86_64 ]``
Y el gemset cargado actualmente:
``rvm gemset list``
``=> proyecto``
Listo, ruby 2.1.0 instalado y gemset creado, estamos listos para trabajar.
<file_sep>/source/README.md
# Oaxaca Ruby User Group Website
## General information
This website is powered by [Middleman](http://middlemanapp.com).
## How to build the website?
* Clone the repository
* Change to **source** branch
```
git checkout source
```
* Install all the dependencies
```
bundle install
```
* Run the server
```
middleman server
```
* The website is in http://localhost:4567
* To deploy the site:
```
middleman deploy
```
<file_sep>/Gemfile
# If you have OpenSSL installed, we recommend updating
# the following line to use "https"
source 'http://rubygems.org'
gem "builder"
gem 'middleman', '4.2.1'
gem 'middleman-deploy', '~> 2.0.0.pre.alpha'
gem 'middleman-disqus'
gem 'middleman-syntax', '~> 3.0'
gem 'middleman-blog', '~> 4.0', '>= 4.0.2'
gem 'nokogiri'
gem 'middleman-sprockets'
gem 'sprockets', '3.7.2'
gem 'haml', '~> 5.2', '>= 5.2.2'
# Live-reloading plugin
gem "middleman-livereload", "~> 3.1.0"
# For faster file watcher updates on Windows:
gem "wdm", "~> 0.1.0", :platforms => [:mswin, :mingw]
<file_sep>/source/posts/2016/2016-10-29-recuento-global-day-of-coderetreat-oaxaca-2016.html.markdown
---
title: "Recuento: Global Day of CodeRetreat Oaxaca 2016"
date: 2016-10-29 18:07 UTC
tags: evento, comunidad
---
El día Sábado 22 de Octubre, realizamos el evento [GDCR2016](http://globalday.coderetreat.org "Global Day of CodeRetreat 2016") como en años anteriores
el evento empezó a las 9:00 am.
Después de haber dado la introducción y ver que todos los asistentes contaran con la máquina virtual, nos centramos en resolver el problema del [Juego De La Vida](http://es.wikipedia.org/wiki/Juego_de_la_vida)
El proceso de trabajo se dividió en sesiones de 40 minutos, en los cuales se trabajo mediante el esquema de [Pair Programming](https://es.wikipedia.org/wiki/Programaci%C3%B3n_en_pareja) y haciendo uso de [TTD](https://es.wikipedia.org/wiki/Desarrollo_guiado_por_pruebas) (Test-Driven Development).


Al finalizar cada sesión, se realizó una pequeña retrospectiva para ir viendo el enfoque que cada pareja tomo y los problemas que surgieron al tratar de resolver el Juego de la vida.
Además al final de la sesión se cambiaba de pareja, para ir haciendo Pair Programming con los diferentes asistentes.
Está dinámica se prolongo hasta las dos de la tarde cuando llego el momento de ingerir los sagrados alimentos.

Posterior al receso que se tomo para la comida que fue de una hora, continuamos con una sesión más, de ahí se realizó un cambio para la siguiente sesión
la nueva regla consistió en no permitir que los asistentes hablaran en el momento de escribir código, está regla se agrego con el fin de que los asistentes escribieran código legible y entendible
es decir que su compañero de trabajo entendiera lo que el otro estaba codificando sin tener que explicarle verbalmente.
El agregar este cambio fue genial, los asistentes estuvieron muy emocionados y al final de la sesión mediante la retrospectiva nos lo hicieron saber.
Sin duda alguna el Global Day of CodeRetreat 2016 fue un éxito como en años anteriores, el hecho de contar con personas con gran experiencia en el mundo del desarrollo y sobretodo en el ambiente de TDD
hizo que el evento fuera genial.
También se agradece a los asistentes, por su gran participación y a los integrantes de esta comunidad que se tomaron su tiempo para que esté evento se llevará acabo
<file_sep>/source/posts/2015/2015-11-04-global-day-coderetreat-oaxaca-2015.html.markdown
---
title: Global Day Coderetreat Oaxaca 2015
date: 2015-11-04 06:30 UTC
tags: evento, comunidad
---
~~~ruby
puts '¡Es un evento mundial!'
~~~
***

Hola soy parte de la comunidad [oaxacarb](www.oaxacarb.com) me llamo <NAME> y en esta ocasión me tocó el privilegio de invitarlos al **Global Day Code Retreat Oaxaca 2015**, se realizará el día **sábado 14 de Noviembre 2015**, en las oficinas del COCYT Oaxaca ubicado en **<NAME> # 517**, centro.
Esta vez será mi segundo año acompañando a la comunidad en el GDCR y estoy emocionado por ver caras nuevas que estén interesados en la programación y aun mejor en la programación guiada por pruebas, somos una comunidad que solucionamos katas en ruby apoyados de minitest o rspec nos reunimos cada quince días por si alguien tiene interés de seguir participando pero bueno no quiero dar más detalle ni desviarme del tema, sería genial que cuentes con tiempo disponible porque dura de 9am - 6pm.
Si programas en **Php, Java, Python no te preocupes en la maquina virtual que proporcionamos viene instalado** el entorno para que puedas desarrollar a gusto.
No olvides cubrir los prerrequisitos:
* [NO ES NECESARIO QUE SEPAS RUBY](http://tryruby.org/levels/1/challenges/0)
* [Descargar la maquina virtual](https://mega.nz/#F!RFcHkQ4Q!61dqWQYNZydbukrhdNJ6yw)
* [Realizar el registro](https://goo.gl/ehLW7Q)
* [Ganas de convivir y compartir](http://oaxacarb.org/)
~~~ruby
puts 'no te lo pierdas, el GDCR es una vez al año.'
~~~
**predicamos el [lenguaje ruby](http://tryruby.org/levels/1/challenges/0)**
<file_sep>/source/posts/2017/2017-10-28-global-day-of-code-retreat-oaxaca-2017.html.markdown
---
title: "Global Day Of Code Retreat Oaxaca 2017"
date: 2017-10-28 11:16 UTC
tags: [code retreat, evento, comunidad]
---

[*Se dice que en las adversidades se conocen las personas fuertes queriendo indicar que la adversidad es como la fragua donde se templan los ánimos varoniles y heroicos*](https://es.wikipedia.org/wiki/Adversidad) **wiki adversidad**
La comunidad **oaxaca.rb** ante la **adversidad** y como lo dice el significado, vistiendose de **HÉROE** por **CUARTA VEZ CONSECUTIVA** traemos el [**GLOBAL DAY OF CODE RETREAT**](http://coderetreat.org/) a Oaxaca.
> **Nota:**
> Antes de que salgas corriendo cuando leás **TDD** o **Ruby** y decidas no asistir, quiero recordarte que no es necesario que sepas programar en ese lenguaje, es mas no es necesario que **programes**, recuerda aquí nadie te justa, no es una competencia, mucho menos un curso de hecho lo importante es **convivir** y que sepas que existe mas gente rara como tu en Oaxaca :v
La comunidad de Oaxaca.rb invita a todos los desarrolladores de software a participar en el Global Day Code Retreat 2017 a realizarse el **sábado 18 de noviembre del presente año**, en las instalaciones del [**COWORK INN**](https://www.facebook.com/coworkinn.mx/) [, ubicadas en Privada de Amapolas #220 Col. Reforma, 68050 Oaxaca de Juárez, Mexico.](https://wego.here.com/directions/mix//Cowork-Inn,-Privada-de-Amapolas-220-Col.-Reforma,-68050-Oaxaca-de-Juárez,-Mexico:<KEY>map=17.07148,-96.7148,15,normal&fb_locale=es_LA)
La dinámica del Global Day Code Retreat consiste en la práctica de TDD (Desarrollo Dirigido por Pruebas, por sus siglas en Inglés). TDD es una técnica de diseño de software y como cada año la kata que se practica durante el Code Retreat es [**El juego de la vida**](https://es.wikipedia.org/wiki/Juego_de_la_vida).
**Puedes programar en el lenguaje en el que te sientas más cómodo, PHP, Java, Python, etc. Nosotros, obviamente, recomendamos Ruby :)**
Dado que la práctica se extiende durante todo el día, para que tú sólo te preocupes por aprender y practicar, nosotros nos encargamos de la **comida**.
Si estás interesado, debes incribirte [aquí](https://goo.gl/5Zu6pV).
> NOTA:
> Si te inscribes y no iras por favor desocupa el lugar, puede haber algún otro interesado.
La máquina virtual la puedes descargar aquí:
*(Si no descargas la maquina virtual, no te preocupes en el evento la repartimos)*
* [link uno](http://www.mediafire.com/file/lo8y7noekhg319f/oaxacarb.z01) (950 mb)
* [link dos](http://www.mediafire.com/file/8jiov5hxihguot8/oaxacarb.z02) (950 mb)
* [link tres](http://www.mediafire.com/file/pvgzow4bodo5d0j/oaxacarb.zip) (901 mb)
* [link md5](http://www.mediafire.com/file/js8vh64xwma2tws/oaxacarb.md5) (Para corroborar la descarga de la máquina virtual)
Recuerda que el evento es gratuito.
**ESTO SE VA A DESCONTROLAR GDCR 2017!!!**
<file_sep>/source/posts/2015/2015-02-06-platica-nick-sutterer-en-oaxaca.html.markdown
---
title: "Plática: ¡<NAME> en Oaxaca!"
date: 2015-02-06 18:53 UTC
tags: platica, comunidad
---
El 21 de Febrero de 2015 estaremos de manteles largos, [<NAME>](https://twitter.com/apotonick) el creador de [TrailBlazer](http://www.trailblazerb.org/) nos dará una plática a toda la comunidad.
{: .center }
Para registrarse al evento, da clic en [este enlace](https://www.eventbrite.com/e/platica-nick-sutterer-creador-de-trailblazer-tickets-15642957507)
BREAK_ARTICLE
**English version**
We are really happy to announce that on February 21st, 2015 [<NAME>](https://twitter.com/apotonick) [TrailBlazer's](http://www.trailblazerb.org/) creator giving a talk to our community.
{: .center }
To register for the event use [this link](https://www.eventbrite.com/e/platica-nick-sutterer-creador-de-trailblazer-tickets-15642957507)
<file_sep>/source/posts/2017/2017-08-29-trivia-cual-es-la-forma-mas-rapida-de-borrar-el-ultimo-parametro.html.markdown
---
title: "Trivia vim 3: ¿Cuál es la forma más rapida de borrar el último parámetro?"
date: 2017-08-29 11:07 UTC
tags: trivia, comunidad, vim
---
~~~ruby
# Trivia vim 3:
# Si el cursor está ubicado sobre la segunda coma (después de slack).
# ¿Cuál es la forma más rapida de borrar el último parámetro?
# By @thotmx
def trivia_tres
explodify(comunidad, slack, oaxaca)
end
~~~
<file_sep>/source/posts/2017/2017-08-15-trivia-cual-es-la-forma-mas-rapida-de-sustituir-el-texto-entre-comillas.html.markdown
---
title: "Trivia vim 2: ¿Cuál es la forma mas rapida de sustituir el texto entre comillas?"
date: 2017-08-15 11:07 UTC
tags: trivia, comunidad, vim
---
~~~ruby
# Trivia vim 2:
# Si el cursor está ubicado sobre la letra "o" de la palabra "oaxacarb"
# ¿Cuál es la forma mas rapida de sustituir el texto entre comillas?
# By @lesm
"Eres bienvenido a oaxacarb, animate"
~~~
<file_sep>/source/posts/2014/2014-09-23-agradecimiento-cocyt.html.markdown
---
title: Agradecimiento al COCyT
date: 2014-09-23 21:47 UTC
tags: comunidad, gracias
---
A nombre de la comunidad oaxaca.rb queremos agradecer al Consejo Oaxaqueño de Ciencia y Tecnología ([COCyT](http://www.cocyt.oaxaca.gob.mx/)) por su apoyo para la realización de los eventos de la comunidad, y así contribuir a la difusión de técnicas y herramientas actuales para el desarrollo de software, que tanta falta hace en nuestro estado.
Después de tener dificultades para conseguir un lugar fijo para la realización de los eventos, el COCyT nos está apoyando a partir del 20 de Septiembre, para la realización del evento en sus instalaciones los días sábados de 4 a 6 pm, cada 15 días, como lo habíamos venido realizando.
<file_sep>/source/posts/2018/2018-03-20-editor-markdown-con-vue-js.html.markdown
---
title: Editor markdown con vue.js
date: 2018-03-20
tags: [vuejs, javascript]
---
Regresando con el tema de Vue.js que vimos en un [post anterior](http://oaxacarb.org/posts/vuejs-primeros-pasos-en-vuejs.html) y como lo mencione ahi haremos un editor markdown.
* Aquí tenemos el [editor markdown](http://oaxacarb.org/markdown.html) funcionando.
* Aquí tenemos el [código](https://github.com/oaxacarb/markdown-editor), lo subi conforme explicó en el post.
* Usamos la [librería](https://github.com/markedjs/marked) para pasar el texto plano a markdown.
### Comenzamos
El editor se divide en tres partes, **Root, Editor, Preview**.
**Root** es la instancia de vue donde se *“aloja”* el componente Editor y dentro de Editor se *“aloja”* el componente Preview.
**Editor** es el **componente** donde se escribe en markdown. (Izquierda)
**Preview** es el **componente** donde **visualiza** lo escrito en markdown pero **transformado**. (Derecha)
### Plugin Vuejs
Puedes apoyarte de la [extensión](https://github.com/vuejs/vue-devtools) para visualizar los componentes y sus propiedades.

###1. Estructura inicial
Creó la estructura inicial cargando la librería de vue.js
###2. Instancia de vue
La instancia es la llamada a Vue y hace referencia que es carga en el identificador *#app*
~~~ javascript
let app = new Vue({
el: '#app',
})
~~~
###3. Creación del componente Editor
El componente **Editor** se encuentra en la variable **let Editor** y tiene a su disposición la propiedad **text** dentro de **data()** y su *html* declarado en **template**,
Por lo tanto lo que escribamos en el **textarea** se verá reflejado en la propiedad **text** y viceversa.

###4. Creación del componente Preview
El componente **Preview** se encuentra dentro del componente **Editor** a esto se le conoce como *componente hijo*, al igual que el componente **Editor** cuenta con su *html* declarado en **template**
El *componente hijo* se declara dentro del *componente padre*. Como podemos ver en el plugin de chrome Preview está dentro de Editor

###5. Agregar estilos css
Se encuentra en el **header** del archivo.

###6. Props en componente Preview
Cada componente tiene su propio alcance **data**. Esto significa que no puede y no debería hacer referencia directa a los datos principales de un componente hijo, los datos se pueden pasar a los componentes hijos usando **props**
**v-bind** o **:** permite pasar **data** del componente padre al hijo y el componente hijo lo toma a través de **props**.

~~~javascript
// Los ":" es shortcut de v-bind:
<preview v-bind:text="text"></preview>
<preview :text="text"></preview>
~~~
###7. Computed property en componente Preview
*Computed property* reacciona al **cambio** de una propiedad, en nuestro caso es **text**, cuando a text se le asigna un **valor** nuevo, **markdownText** se lanza y ejecuta la función donde se encuentre dicha propiedad.

###8. Implementando marked
Implementamos marked y sucede algo inesperado
~~~javascript
computed: {
markdownText() {
return marked(this.text, { sanitize: true })
}
}
~~~
En el componente **Preview** *imprime las etiquetas html*, esto sucede porque vuejs automáticamente **escapa** las **etiquetas html** cuando usamos la sintaxis **doble corchete** ```{{}}```
~~~html
<div class="editor__preview">{{ markdownText }}</div>
~~~
~~~html
<p>Párrafo</p><p>#h1</p>
~~~

Para **solucionar** el escape de html vuejs cuenta con una etiqueta **v-html** la cual implementaremos.
~~~html
<div class="editor__preview" v-html="markdownText"></div>
~~~
*Vuejs por ser reactivo a través de la etiqueta **v-model** es two data binding (el valor “viaja” en dos sentidos)*
* [Vuejs](https://vuejs.org/)
* [v-model](https://vuejs.org/v2/guide/forms.html#v-model-with-Components)
* [Props](https://vuejs.org/v2/guide/components.html#Props)
* [Computed property](https://vuejs.org/v2/guide/computed.html)
<file_sep>/source/posts/2015/2015-05-01-kata-minitest-rompiendo-la-paralisis-inicial.html.markdown
---
title: "Kata Minitest: Rompiendo la parálisis inicial"
date: 2015-05-01 21:44 UTC
tags: ruby, comunidad, kata
---
Algo que suele detener al comenzar algún proyecto, práctica o actividad es la parálisis inicial, esto es, de pensar en todas las cosas que tenemos que hacer, recordar o investigar antes de comenzar la actividad, nos quita la motivación de hacerlo y decidimos posponerlo.
Para evitar esto, sobre todo cuando queremos practicar una Kata con Minitest, pongo los siguientes códigos de ejemplo:
BREAK_ARTICLE
**Ejemplo de Minitest para versión menor a la 5**
~~~ruby
require 'minitest/autorun'
class TestExample < MiniTest::Unit::TestCase
def test_example
assert_equal true, nil.nil?
end
end
~~~
**Ejemplo de Minitest para versión 5**
~~~ruby
require 'minitest/autorun'
class TestExample < Minitest::Test
def test_example
assert_equal true, nil.nil?
end
end
~~~
Lo único que tenemos que hacer es copiar ese código, pegarlo (aunque lo más recomendable es escribirlo de nuevo, pero ya no hay que recordar ni pensar demasiado). Después ejecutar:
```
ruby nombre_archivo.rb
```
Y podemos ver nuestras prueba corriendo. Ahora sólo se comienza a tirar código...
¡Happy Testing!
**Nota:** El código de ejemplo no es el más correcto para las convenciones de Minitest, pero su objetivo es mostrar que cuando se usa **assert_equal** primero se pone el valor, y después el método a ejecutar.
<file_sep>/source/posts/2023/2023-03-03-remoto.html.markdown
---
title: Plática "Recomendaciones para trabajo remoto"
date: 2023-03-03 00:00 UTC
tags: [evento, empleo, remoto]
---
Este **Sábado 4 de Marzo de 2023** tendremos la plática **Recomendaciones para trabajo remoto**. En el cuál buscaremos darle continuidad a algunas conversaciones surgidas en la [plática anterior](/posts/reactivando.html). Enfocado a recomendaciones y prácticas para hacer el trabajo remoto algo agradable y que no sea desgastante.
Si quieres acompañarnos en este evento, te esperamos en [Presa Chicoasén 102, Presa San Felipe, 68024 Oaxaca de Juárez, Oax](https://maps.app.goo.gl/xT5p7eyKHJYRGRdj9) . [¡Aparta tu lugar aquí!](http://bit.ly/3IQVPCb) Tenemos **cupo limitado**.
La plática también será transmitida por Facebook: [https://www.facebook.com/oaxacarb](https://www.facebook.com/oaxacarb)
Agradecemos a la diputada [<NAME>](https://twitter.com/SoyGabyPerezMx) por el apoyo con el espacio para la realización de este evento.<file_sep>/source/posts/2017/2017-09-11-trivia-como-borrar-el-texto-dentro-del-tag.html.markdown
---
title: "Trivia vim 4: ¿Cuál es la forma más rapida de borrar el texto dentro del tag <p>?"
date: 2017-09-11 11:16 UTC
tags: trivia, comunidad, vim
---
~~~html
<!-- Trivia vim 4:
Si el cursor está ubicado sobre la letra e de la palabra elm.
¿Cuál es la forma más rapida de borrar el texto dentro del tag <p>?
By @thotmx -->
<html>
<p>La plática de elm estuvo excelente!</p>
</html>
~~~
<file_sep>/source/posts/2014/2014-09-23-platica-taller-modelos-en-rails.html.markdown
---
title: "Plática: Modelos en Rails"
date: 2014-09-23 20:54 UTC
tags: platica, comunidad, rails
---
En esta plática se aborda de manera básica el manejo de modelos con el framework Ruby on Rails.
<iframe width="420" height="315" src="//www.youtube.com/embed/Fq9NMqqPvZE" frameborder="0" allowfullscreen></iframe>
<iframe width="420" height="315" src="//www.youtube.com/embed/KrPkLEOa3nc" frameborder="0" allowfullscreen></iframe>
La grabación de esta plática fue un poco improvisada, pero forma parte del aprendizaje :).
<file_sep>/source/posts/2014/2014-03-13-coding-dojo-15-marzo-2014.html.markdown
---
title: Coding Dojo - 15 de Marzo 2014
date: 2014-03-13 04:45 UTC
tags: dojo, comunidad
---
La comunidad **oaxaca.rb** invita a propios y extraños al **Coding Dojo** que se llevará a cabo el sábado 15 de marzo de 2014 en las instalaciones de la Secretaría de Desarrollo económico del municipio de Oaxaca de Juárez, ubicadas en la calle de Matamoros #102 Centro.
#### ¿Qué es un Coding Dojo?
Los Coding Dojos tienen como finalidad el fomentar las buenas prácticas de programación en el desarrollo de software, por medio de la práctica y ejercicios continuos (denominados katas) los asistentes aprenden nuevas técnicas y metodologías que pueden serles útiles en su día a día profesional; es un espacio para el aprendizaje, la compartición de conocimiento y la convivencia.
Si estás interesado en asistir puedes inscribirte en el [evento creado en Eventbrite](https://www.eventbrite.com/e/coding-dojo-tickets-10919244755). Asegura tu lugar, ya que tenemos cupo limitado.
<file_sep>/source/javascripts/app.js
//= require 'vendor/jquery'
//= require_tree './vendor'
//= require 'foundation'
//= require_tree './foundation'
//= require vendor/socialite
$(document).foundation();
$(document).ready(function(){
Socialite.load("blog-social");
});
<file_sep>/source/posts/2015/2015-09-12-platica-bloques-en-ruby.html.markdown
---
title: "Plática: Bloques en Ruby"
date: 2015-09-12 13:39 UTC
tags: platica, comunidad
---
Hace un par de meses ApuX dio una plática sobre ["Bloques en Ruby"](https://www.youtube.com/embed/IW9ZiP7f8Ck).
Aquí el video.
<center>
<iframe width="300" height="215" src="https://www.youtube.com/embed/IW9ZiP7f8Ck?rel=0" frameborder="0" allowfullscreen></iframe>
</center>
<file_sep>/source/posts/2014/2014-09-23-platica-artoo-un-framework-ruby-para-controlarlos-a-todos.html.markdown
---
title: "Plática: Artoo, un framework Ruby para controlarlos a todos..."
date: 2014-09-23 20:58 UTC
tags: platica, comunidad
---
En esta plática se brinda un introducción al framework Artoo, y se brindan algunos ejemplos básicos de su funcionamiento con Arduino y OpenCV.
<iframe width="560" height="315" src="//www.youtube.com/embed/ndJcWJgqGo0" frameborder="0" allowfullscreen></iframe>
Le agradecemos al personal de [<NAME>](http://oaxacanuestro.com/) por facilitarnos el equipo para realizar la grabación de la plática.
<file_sep>/source/posts/2014/2014-11-12-global-day-code-retreat-oaxaca-2014.html.markdown
---
title: Global Day Code Retreat Oaxaca 2014
date: 2014-11-12 18:37 UTC
tags: evento, comunidad
---
Te invitamos a asistir al __Global Day Code Retreat Oaxaca 2014__, será el sábado 15 de noviembre de 9:00 am a 6:00 pm en la calle de __<NAME>il #517, Centro__.
[](http://www.eventbrite.com/e/global-day-code-retreat-oaxaca-2014-tickets-14079697755 "Click para apartar lugares")
El Coderetreat es un evento de un día completo de práctica, enfocado a revisar los __fundamentos del diseño y desarrollo de software__. A través de proveer a los desarrolladores la oportunidad de formar parte de éste ejercicio práctico, eliminando la presión de terminar lo que se comenzó, el formato del Coderetreat ha probado ser una herramienta efectiva para el desarrollo y mejora de las habilidades de los asistentes.
El evento __no tienen ningún costo__. Si estás interesado en asistir, puedes apartar tus lugares en eventbrite siguiendo [este enlace](http://www.eventbrite.com/e/global-day-code-retreat-oaxaca-2014-tickets-14079697755).
<file_sep>/source/posts/2014/2014-05-07-clases-extendiendo-las-clases.html.markdown
---
title: Clases extendiendo las clases
date: 2014-05-07 20:42 UTC
tags: ruby
---
**Todas las cosas que utilizamos en Ruby son objetos.**
En Ruby podemos ver diferentes tipos o clases de objetos: textos, enteros, flotantes, matrices, y algunos objetos especiales (true, false y nil).
En Ruby, estas clases están siempre en mayúsculas: String, Integer, Float, Array, etc.
Bién, ahora mensionaré después de esta breve explicación de las Clases como es que podemos **EXTENDER** de las clases en Ruby.
En Ruby las clases nunca se consideran cerradas, y se pueden modificar añadiendo métodos, variables, por ejemplo,
vamos a añadir una nueva funcionalidad a la Clase Integer:
~~~ruby
class Integer
def to_romano
if self == 5
romano = 'V'
else
romano = 'X'
end
romano
end
end
~~~
Probaremos esto con un par de números:
~~~ruby
puts 5.to_romano
puts 10.to_romano
~~~
Resultado:
~~~ruby
V
~~~
~~~ruby
X
~~~
<file_sep>/source/posts/2018/2018-03-07-addison-ceo-de-lullabot-visita-oaxaca-rb.html.markdown
---
title: Addison, CEO de Lullabot, visita Oaxaca.rb
date: 2018-03-07 05:29 UTC
tags: [Evento, PHP, Drupal, Lullabot]
---
<a class="profile-image" href="#">
<img src="/images/2018/addison-200px.jpg" alt="<NAME>">
</a>
Este **Viernes 9 de Marzo**, nuestra comunidad se pone de manteles largos, ya que recibimos la visita de nuestra amiga [<NAME>](https://www.drupal.org/user/65088).
Involucrada en Drupal desde 2006 en diferentes roles como desarrolladora, consultora y trainer, Addison fue directora de educación en Lullabot y Product Manager en Drupalize.me, para después tomar control como CEO de Lullabot.
Addison ha trabajado en documentación técnica y entrenamiento desde el año 2000, liderando los esfuerzos documentales de Drupal desde el 2008 hasta el 2010; además, ella ha colaborado con parches para el Core de Drupal y con mantenimiento para diferentes módulos del mismo.
Addison (Addy, para los cuates) nos compartirá un poco de sus experiencias colaborando en Drupal y cómo el esfuerzo comunitario ha jugado una rol primordial para la creación, mantenimiento y modernización del proyecto.
Si quieres acompañarnos en esta plática, te esperamos en las oficinas de [Cowork Inn](https://www.facebook.com/coworkinn.mx/), ubicadas en Privada de Amapolas #220, en la colonia Reforma. [¡Aparta tu lugar aquí!](https://goo.gl/ju31ez) Tenemos **cupo limitado**.
<file_sep>/source/posts/2014/2014-05-20-coding-dojo-24-mayo-2014.html.markdown
---
title: Coding Dojo - 24 Mayo 2014
date: 2014-05-20 22:21 UTC
tags: dojo, comunidad
---
La comunidad **oaxaca.rb** extiende la invitación a los programadores de Oaxaca (y zonas aledañas) al **7o Coding Dojo**. Se realizará el **sábado 24 de mayo** en las instalaciones de la **Secretaría de Desarrollo Económico**; la dirección es **Matamoros #102, Centro. Oaxaca de Juárez Oaxaca**.
<div class="text-center" markdown="1">
[](https://www.eventbrite.com/e/coding-dojo-tickets-11696056219)
</div>
Puedes registrarte en el [evento de Eventbrite](https://www.eventbrite.com/e/coding-dojo-tickets-11696056219). Si ya has asistido anteriormente y conoces a alguien que pueda estar interesado en aprender metodologías de programación y de paso el lenguaje Ruby, ¡invítalo! (tenemos *kata* de bienvenida).
La maquina virtual que se utiliza en el Dojo está disponible en [este enlace](https://mega.co.nz/#!VU0GhRgB!Vhl0Vjc_xqZILoc1WKyMY4f4RbeAZQBCaZBOtSUhKl4). Si tienes alguna duda, puedes dejarla en la sección de comentarios (en la parte inferior). ¡Nos vemos el sábado!
<file_sep>/source/posts/2017/2017-09-12-platica-elm-by-thotmx.html.markdown
---
title: "Platica: Elm Un lenguaje delicioso para webapps"
date: 2017-09-12 11:16 UTC
tags: platica, comunidad, elm
---
Hola, hoy les contare sobre “La platica de elm” que por cierto estuvo excelente, gracias a [@thotmx](https://github.com/thotmx).
### ¿Que es elm?
Elm es un lenguaje funcional que compila JavaScript. Compite con proyectos como React como una herramienta para crear sitios web y aplicaciones web.
### ¿Por qué un lenguaje funcional?
Segun la documentación dice que te olvides de las cosas extrañas que haz escuchado de esto y pienses que elm es:
* No hay errores de ejecución en la práctica. No nulo. No indefinido no es una función.
* Mensajes de error amigables que le ayudan a agregar funciones más rápidamente. (creanme muy amigables)
* Código bien diseñado que se mantiene bien arquitectado a medida que crece tu aplicación.
* Versión automática semántica automática para todos los paquetes de Elm.
Ninguna combinación de bibliotecas de JS puede darle esto, sin embargo, todo es gratis y fácil en Elm
### Requisitos
* Necesitas tener instalado [node](https://nodejs.org/es/download/), lo cual instala npm (es el manejador de paquetes por defecto para Node.js).
* Instalas elm, yo la instale hoy y me intalo la version ```elm@0.18.0``` con la cual trabajaremos.
~~~bash
# El tag -g es para instalarlo de forma global.
npm install -g elm
~~~
### Juega con elm
Algunos ejemplos de lo que puedes hacer con elm, tambien puedes encapsular funciones :P
~~~bash
# En terminal abre una consola interactiva.
$ elm-repl
> 1 / 2
0.5 : Float
> List.length [1,2,3,4]
4 : Int
> String.reverse "stressed"
"desserts" : String
> :exit
~~~
### Servidor de apps elm
~~~bash
# En terminal levanta un servidor para visualizar aplicaciones de elm, donde las devuelve compiladas y listas para probar.
$ elm-reactor
elm-reactor 0.18.0
Listening on http://localhost:8000
~~~

### Ejemplos
Escribe en un archivo con extensión elm, en mi caso.
~~~bash
-- vim oaxacarb.elm
import Html exposing (text)
main =
text "Hello, World!"
~~~
### Más de elm
[Visita el gist de @thotmx](https://gist.github.com/thotmx/f0b0a1b5b97ccb4d8f301d482a366fb8/revisions), donde encontraras la plática paso a paso.
### Enlaces recomendados (escrito por @thotmx)
* [Sitio oficial de Elm](http://elm-lang.org/) - Esta es la entrada al mundo de Elm. Un sitio con buenos recursos y excelente documentación. Puedes probar Elm directamente en un editor en la web.
* [Tutorial de Elm](https://www.elm-tutorial.org/en/) - Un tutorial de Elm que aborda detalles de lenguaje y arquitectura. Muy fácil de seguir y muy explicativo.
* [Elm in Action](https://www.manning.com/books/elm-in-action) - Libro sobre Elm escrito por un miembro relevante de la comunidad Elm.
* [Elm, Building web apps](https://pragmaticstudio.com/courses/elm) - Curso de Pragmatic Studio, vale mucho la pena, es muy concreto, los videos son muy cortos pero abordan temas relevantes en cada video. El curso consta de 22 videos. También es recomendable revisar los recursos gratuitos de Pragmatic Studio relacionados con Elm.
* [Phoenix with Elm](http://www.cultivatehq.com/posts/phoenix-elm-1/) - Un tutorial sumamente interesante de integración de Elm con Phoenix (Elixir). Nos lleva a construir una aplicación de reservación de asientos en un autobús. Aunque la versión de Elm que utiliza el tutorial es antigua, en mi [cuenta de github](https://github.com/thotmx) se puede encontrar un repositorio con el tutorial con la versión 0.18 de Elm.
Coméntanos como te fue...
<file_sep>/source/posts/2014/2014-05-17-estructuras-de-datos-y-algoritmos-ruby-edition.html.markdown
---
title: Estructuras de datos y algoritmos (Ruby Edition)
date: 2014-05-17 00:04 UTC
tags: ruby, recursos, ebook
---
**Concise Notes on Data Structures and Algorithms Ruby Edition** (por *<NAME>*) es un ebook gratuito en formato **PDF** publicado por [bookboon.com](http://bookboon.com/es) el cual trata conceptos como: *arrays*, *contenedores*, *pilas*, *colas*, *recursividad*, *arboles* y *grafos* entre otros, así como también, aborda algunos algoritmos de ordenamiento básicos como podrían ser: *Bubble Sort* y *Insertion Sort* todo esto enfocado directamente al lenguaje Ruby.
El libro consta de 197 páginas y se encuentra dividido en 24 capítulos de fácil seguimiento. El indice temático es el siguiente:
* Introduction
* Built-In Types
* Arrays
* Assertions
* Containers
* Stacks
* Queues
* Stacks and Recursion
* Collections
* Lists
* Analyzing Algorithms
* Function Growth Rates
* Basic Sorting Algorithms
* Recurrences
* Merge sort and Quicksort
* Trees, Heaps, and Heapsort
* Binary Trees
* Binary Search and Binary Search Trees
* Sets
* Maps
* Hashing
* Hashed Collections
* Graphs
* Graph Algorithms
Para descargar el ebook basta con acceder al siguiente [enlace](http://bookboon.com/es/concise-notes-on-data-structures-and-algorithms-ebook) y llenar un pequeño cuestionario el cual una vez completado, permitirá el acceso a dicho archivo.
Que lo disfruten ;).
<file_sep>/source/posts/2023/2023-01-31-reactivando.html.markdown
---
title: Reactivando la comunidad con "Tu primer empleo en TI"
date: 2023-01-31 21:30 UTC
tags: [evento, empleo]
---
*Última actualización: 1 de Febrero de 2023*
Este **Sábado 4 de Febrero de 2023** tendremos la plática **Tu primer empleo en TI**. En el cuál buscaremos brindar a recién egresados o a gente que le gustaría cambiarse de trabajo un poco de información que pueda serles de utilidad a la hora de decidirse. Para que la decisión pueda basarse en sus gustos, intereses y planes a futuro.
Además se darán algunas pláticas rápidas, sobre diferentes temas:
**Pláticas relámpago:**
- **Burnout: Lo que pocos hablan** por [Neomatrix](https://github.com/neomatrixcode)
Si quieres acompañarnos en este evento, te esperamos en la 2a Privada de la Noria 209-A. [¡Aparta tu lugar aquí!](http://bit.ly/3wKCAV5) Tenemos **cupo limitado**.
La plática también será transmitida por Facebook: [https://www.facebook.com/oaxacarb](https://www.facebook.com/oaxacarb)
<file_sep>/source/posts/2014/2014-03-27-coding-dojo-29-marzo-2014.html.markdown
---
title: Coding Dojo - 29 Marzo 2014
date: 2014-03-27 04:45 UTC
tags: dojo, comunidad
---
La comunidad **oaxaca.rb** invita a propios y extraños al **3er Coding Dojo** que se llevará a cabo el sábado 29 de marzo de 2014 en las instalaciones de la empresa Pintura y Publicidad de Oaxaca, ubicadas en [Emiliano Zapata 412, Trinidad de las Huertas](https://www.google.com.mx/maps?q=Emiliano+Zapata+403A&ll=17.055623,-96.716077&spn=0.002321,0.004128&t=m&hnear=Emiliano+Zapata+403,+Plan+de+Ayala,+Puebla&z=19&layer=c&cbll=17.055526,-96.716096&panoid=XJ9QFI7BkMwWP046NzBHFw&cbp=12,285.94,,0,1.52), Oaxaca de Juárez, Oaxaca.
Si estás interesado en asistir puedes inscribirte en el [evento creado en Eventbrite](https://www.eventbrite.com/e/coding-dojo-tickets-11089630383). Asegura tu lugar, ya que tenemos cupo limitado.
#### ¿Qué es un Coding Dojo?
Los Coding Dojos tienen como finalidad el fomentar las buenas prácticas de programación en el desarrollo de software, por medio de la práctica y ejercicios continuos (denominados katas) los asistentes aprenden nuevas técnicas y metodologías que pueden serles útiles en su día a día profesional; es un espacio para el aprendizaje, la compartición de conocimiento y la convivencia.
<file_sep>/source/posts/2023/2023-04-23-gpt-como-herramienta.html.markdown
---
title: Recursos de la Plática "Utiliza ChatGPT como herramienta de programación"
date: 2023-04-23 00:00 UTC
tags: [plática, evento, chatgpt, programación]
---
El **Sábado 7 de Abril de 2023** tuvimos en la comunidad la plática **Utiliza ChatGPT como herramienta de Programación** por [Neomatrix](https://github.com/neomatrixcode).
Fue una plática amena e interesante, con retroalimentación de los asistentes.
Además, [Neomatrix](https://github.com/neomatrixcode) nos proporcionó los siguientes recursos:
- Un post en Medium que incluye todo lo revisado durante la plática: [Utiliza ChatGPT como herramienta de Programación](https://josueacevedo.medium.com/utiliza-chatgpt-4-como-herramienta-de-programaci%C3%B3n-83fc3e8786fe)
- Y un enlace bonus para aprender sobre prompting (Multilenguage): [Learn Prompting](https://learnprompting.org/docs/intro).
¡Gracias a [Neomatrix](https://github.com/neomatrixcode) por la excelente charla!<file_sep>/source/posts/2016/2016-01-09-react-js-una-guia-para-desarrolladores.html.markdown
---
title: "Plática: React.js - Una guía para desarrolladores Rails"
date: 2016-01-09 19:05 UTC
tags: rails, react, frontend, javascript
---
<div data-alert class="alert-box info radius">
<i class="fi-info size-14"></i>
<span>
Este artículo es una traducción; la versión original se puede leer en <a href="https://www.airpair.com/reactjs/posts/reactjs-a-guide-for-rails-developers" target="_blank">Airpair</a>.
</span>
</div>

### Introducción a React.js
React.js es el nuevo chico popular de la cuadra de los "Frameworks Javascript", y resalta por su simplicidad. Donde otros frameworks implementan un framework MVC completo, podríamos decir que React sólo implementa la V (de hecho, algunos reemplazan la V de su framework con React). Las aplicaciones React son construidas sobre dos principios importantes: Componentes y Estados. Los compomentes se pueden formar de otros componentes más pequeños, empotrados o personalizados; el Estado {dirige} lo que los chicos en Facebook llaman one-way reactive data flow, que significa que nuestro UI reaccionará a cada cambio de estado.
Una de las cosas buenas sobre React es que no requiere dependencias adicionales, por lo que puede trabajar prácticamente con cualquier otra biblioteca de JavaScript. Aprovechando esta característica, vamos a incluirlo en nuestro stack de Rails para construir una aplicación enfocada a frontend, o, como se podría decir, Rails con esteroides.
### Una aplicación de seguimiento de gastos
Para esta guía, vamos a construir una pequeña aplicación desde cero para hacer un seguimiento de nuestros gastos; cada registro consistirá en una fecha, un título y una cantidad. Un registro se tratará como crédito si su cantidad es mayor que cero, en caso contrario se tratará como débito. Aquí una maqueta del proyecto:

Resumiendo, la aplicación se comportará como sigue:
* Cuando el usuario cree un nuevo registro a través del formulario, éste se añadirá a la tabla de registros
* El usuario podrá editar {en línea} cualquier registro existente
* Al hacer clic en cualquier botón "Borrar" se eliminará el registro asociado de la tabla
* Al agregar, editar o eliminar un registro existente, se actualizarán las cantidades en la parte superior de la página
### Inicializando nuestro proyecto React.js en Rails
Primero lo primero: tenemos que crear nuestro nuevo proyecto Rails; le llamaremos `Accounts`:
~~~
rails new accounts
~~~
Para la interfaz de usuario de este proyecto, vamos a usar Twitter Bootstrap. El proceso de instalación está fuera del alcance de este post, pero se puede instalar la gema oficial de `bootstrap-sass` siguiendo las instrucciones desde el [repositorio oficial de GitHub](https://github.com/twbs/bootstrap-sass).
Una vez que hayamos creado nuestro proyecto, se procede a incluir React. Para este post decidí incluirlo mediante la gema oficial [react-rails](https://github.com/reactjs/react-rails) porque vamos a aprovechar algunas características interesantes de la gema, pero hay otras formas, como [Rails assests](https://rails-assets.org/) o incluso descargar el paquete desde la [página oficial](https://facebook.github.io/react/) y pegarlo en nuestra carpeta `javascripts`.
Si has desarrollado aplicaciones Rails antes, sabes lo fácil que es instalar una gema: Añade `rails-react` a tu Gemfile.
~~~
rails new accounts
~~~
Entonces, hay que decirle (amablemente) a Rails que instale las nuevas gemas:
~~~
bundle install
~~~
`react-rails` viene con un script de instalación, lo que creará un archivo `components.js` y un directorio `componentes` bajo `app/assests/javascripts` donde vivirán nuestros componentes React.
~~~
rails g react:install
~~~
Si ves el archivo `application.js` después de ejecutar el instalador, te darás cuenta de que hay tres nuevas líneas:
~~~js
//= require react
//= require react_ujs
//= require components
~~~
Básicamente, incluye la biblioteca de *React*, el archivo manifiesto `componentes` y un archivo que luce familiar terminado en _ujs_. Como ya habrás adivinado por el nombre del archivo, react-rails incluye un driver JavaScript no instrusivo que nos ayudará a montar nuestros componentes React y también se encargará de eventos Turbolinks.
### Creación del recurso
Vamos a construir un recurso `Record`, que incluirá una fecha, un título y una cantidad. En lugar de utilizar el generador de `scaffold`, vamos a utilizar el generador de `resource`, ya que no vamos a utilizar todos los archivos y métodos creados por el scaffold. Otra opción podría ser ejecutar el `scaffold` y luego eliminar los archivos/métodos no utilizados, pero nuestro proyecto podría quedar muy revuelto después de esto. Dentro de tu proyecto, ejecuta el siguiente comando:
~~~
rails g resource Record title date:date amount:float
~~~
Después de un poco de magia, terminamos con un nuevo modelo `Record`, con su controlador y rutas. Sólo tenemos que crear nuestra base de datos y ejecutar migraciones pendientes.
~~~
rake db:create db:migrate
~~~
Como agrergado, puedes crear un par de registros desde la consola de Rails:
~~~ruby
Record.create title: 'Record 1', date: Date.today, amount: 500
Record.create title: 'Record 2', date: Date.today, amount: -100
~~~
No se olvide de iniciar el servidor con `rails server`.
¡Listo! Estamos listos para escribir algo de código.
### Anidando componentes: Listado de registros {records}
Para nuestra primera tarea, tenemos que _renderear_ todos los registro existentes dentro de una tabla. Primero, tenemos que crear una acción `index` dentro de nuestro `RecordsController`:
~~~ruby
# app/controllers/records_controller.rb
class RecordsController < ApplicationController
def index
@records = Record.all
end
end
~~~
Después, tenemos que crear un nuevo archivo `index.html.erb` en `apps/views/records/`, este archivo servirá como un puente entre nuestra aplicación Rails y nuestros componentes React. Para lograr esto, vamos a utilizar el método _helper_, `react_component`, que recibe el nombre del componente React que queramos _renderear_, junto con los datos que queremos pasar.
~~~erb
<%# app/views/records/index.html.erb %>
<%= react_component 'Records', { data: @records } %>
~~~
Vale la pena mencionar que este _helper_ es proporcionado por la gema `rails-react`, si decides utilizar otro tipo de integración con React, este _helper_ no estará disponible.
Ahora puede navegar hasta `localhost:3000/records`. Obviamente, esto todavía no va a funcionar, debido a la falta de un componente React `Records`, pero si vemos el HTML generado dentro de la ventana del navegador, podemos ver algo como el siguiente código
~~~html
<div data-react-class="Records" data-react-props="{...}">
</div>
~~~
Con este markado HTML presente, `react_ujs` detectará que queremos _renderear_ un componente React y creará una instancia del mismo, incluyendo las propiedades que enviamos a través del método `react_component`, en nuestro caso, el contenido de `@records`.
El momento para crear nuestro primer componente React ha llegado, dentro del directorio `javascripts/components`, crea un nuevo archivo llamado `records.js.coffee`, este archivo contendrá nuestro componente `Records`.
~~~coffee
# app/assets/javascripts/components/records.js.coffee
@Records = React.createClass
render: ->
React.DOM.div
className: 'records'
React.DOM.h2
className: 'title'
'Records
~~~
Cada componente requiere un método `render`, que será el encargado de _renderear_ el propio componente. El método `render` debe devolver una instancia de `ReactComponent`, de esta manera, cuando React ejecuta un _re-render_, se comportará de forma óptima (ya que React detecta la existencia de nuevos nodos construyendo un DOM virtual en la memoria). En el fragmento anterior creamos una instancia de `h2`, un `ReactComponent` ya incluido en React.
NOTA: Otra forma de crear una instancia `ReactComponents` dentro del método `render` es a través de la sintaxis `JSX`. El siguiente fragmento es equivalente al anterior:
~~~coffee
render: ->
`<div className="records">
<h2 className="title"> Records </h2>
</div>`
~~~
Personalmente, cuando trabajo con CoffeeScript, prefiero usar la sintaxis `React.DOM` sobre `JSX` porque el código se estructura jerárquicamente por sí sólo, como en HAML. Por otro lado, si estás tratando de integrar React en una aplicación existente construida con erb, tienes la opción de reutilizar el código _erb_ existente y convertirlo en _JSX_.
Ahora puedes refrescar tu navegador.

¡Perfecto! Hemos _rendereado_ nuestro primer componente React. Ahora, es tiempo de mostrar nuestros registros.
Además del método `render`, los componentes React hacen uso de `properties` para comunicarse con otros componentes y `states` para detectar si se requiere o no _re-renderear_. Necesitamos inicializar el estado y las propiedades de nuestro componente con los valores deseados:
~~~coffee
# app/assets/javascripts/components/records.js.coffee
@Records = React.createClass
getInitialState: ->
records: @props.data
getDefaultProps: ->
records: []
render: ->
...
~~~
El método `getDefaultProps` inicializa las propiedades de nuestros componentes en caso de que olvidemos enviar los datos al instanciarlos, y el método `getInitialState` genera el estado inicial de nuestro componente. Ahora tenemos que mostrar los registros provistos realmente por nuestra vista Rails.
Parece que vamos a necesitar un método _helper_ para formatear cadenas de cantidad. Podemos implementar un sencillo formateador de cadenas y hacerlo accesible para todos nuestros archivos `coffeescript`. Crea un nuevo archivo `utils.js.coffee` en `javascripts/` con el siguiente contenido:
~~~coffee
# app/assets/javascripts/utils.js.coffee
@amountFormat = (amount) ->
'$ ' + Number(amount).toLocaleString()
~~~
Tenemos que crear un nuevo componente `Record` para mostrar cada registro individual. Crea un nuevo archivo `record.js.coffee` bajo el directorio `javascripts/components` e inserta el siguiente contenido:
~~~coffee
# app/assets/javascripts/components/record.js.coffee
@Record = React.createClass
render: ->
React.DOM.tr null,
React.DOM.td null, @props.record.date
React.DOM.td null, @props.record.title
React.DOM.td null, amountFormat(@props.record.amount)
~~~
El componente `Record` mostrará una fila que contiene la información de cada atributo del registro. No te preocupes por esos valores `null`s en las llamadas de `React.DOM.*`, significan que no estamos enviando atributos a los componentes. Ahora actualiza el método `render` dentro del componente `Records` con el siguiente código:
~~~coffee
# app/assets/javascripts/components/records.js.coffee
@Records = React.createClass
...
render: ->
React.DOM.div
className: 'records'
React.DOM.h2
className: 'title'
'Records'
React.DOM.table
className: 'table table-bordered'
React.DOM.thead null,
React.DOM.tr null,
React.DOM.th null, 'Date'
React.DOM.th null, 'Title'
React.DOM.th null, 'Amount'
React.DOM.tbody null,
for record in @state.records
React.createElement Record, key: record.id, record: record
~~~
¿Viste qué pasó? Hemos creado una tabla con una fila como encabezado, y en el cuerpo de la tabla creamos un elemento `Record` por cada registro existente. En otras palabras, estamos anidando compomentes React ya existentes y personalizados. Bien, ¿cierto?
Cuando trabajamos con contenido dinámico (en este caso, registros), necesitamos proporcionar una propiedad `key` a los elementos generados dinámicamente para que React no tenga problemas al refrescar nuestra UI, es por eso que enviamos `key: record.id` junto con el propio registro al crear elementos `Record`. Si no hacemos esto, recibiremos un mensaje de advertencia en la consola JS del navegador (y probablemente algunos dolores de cabeza en un futuro cercano).

Puedes echar un vistazo al código resultante de esta sección [aquí](https://github.com/fervisa/accounts-react-rails/tree/bf1d80cf3d23a9a5e4aa48c86368262b7a7bd809), o sólo los cambios introducidos por esta sección [aquí](https://github.com/fervisa/accounts-react-rails/commit/bf1d80cf3d23a9a5e4aa48c86368262b7a7bd809).
### Comunicación padre-hijo: Creación de registros
Ahora que estamos mostrando todos los registros existentes, sería bueno incluir un formulario para crear nuevos registros. Agrerguemos esta nueva característica a nuestra aplicación React/Rails.
Primero, tenemos que añadir el método de `create` a nuestros controlador Rails (no te olvides de utilizar _strong_params_ ):
~~~ruby
# app/controllers/records_controller.rb
class RecordsController < ApplicationController
...
def create
@record = Record.new(record_params)
if @record.save
render json: @record
else
render json: @record.errors, status: :unprocessable_entity
end
end
private
def record_params
params.require(:record).permit(:title, :amount, :date)
end
end
~~~
Luego, tenemos que construir un componente React para manejar la creación de nuevos registros. El componente tendrá su propio estado para almacenar la fecha, título y la cantidad. Crear un nuevo archivo `record_form.js.coffee` en `javascripts/components` con el siguiente código:
~~~coffee
# app/assets/javascripts/components/record_form.js.coffee
@RecordForm = React.createClass
getInitialState: ->
title: ''
date: ''
amount: ''
render: ->
React.DOM.form
className: 'form-inline'
React.DOM.div
className: 'form-group'
React.DOM.input
type: 'text'
className: 'form-control'
placeholder: 'Date'
name: 'date'
value: @state.date
onChange: @handleChange
React.DOM.div
className: 'form-group'
React.DOM.input
type: 'text'
className: 'form-control'
placeholder: 'Title'
name: 'title'
value: @state.title
onChange: @handleChange
React.DOM.div
className: 'form-group'
React.DOM.input
type: 'number'
className: 'form-control'
placeholder: 'Amount'
name: 'amount'
value: @state.amount
onChange: @handleChange
React.DOM.button
type: 'submit'
className: 'btn btn-primary'
disabled: !@valid()
'Create record'
~~~
Nada pretencioso, sólo un sencillo formulario Bootstrap _in line_. Observa cómo estamos definiendo el atributo `value` para _setear_ el valor de entrada y el atributo `onChange` para agregar un método que será llamado cada que se presione una tecla; el método `handleChange` utilizará el atributo `nombre` para detectar qué entrada disparó el evento y actualizar su valor relacionado en el estado `state`:
~~~coffee
# app/assets/javascripts/components/record_form.js.coffee
@RecordForm = React.createClass
...
handleChange: (e) ->
name = e.target.name
@setState "#{ name }": e.target.value
...
~~~
Sólo estamos usando interpolación de cadenas para definir dinámicamente las llaves de nuestro objeto, equivalente a `@setState title: e.target.value` cuando `name` es igual a _title_. Pero, ¿por qué tenemos que utilizar `@setState`? ¿Por qué no podemos simplemente _setear_ el valor deseado de `@state` como solemos hacer en objetos normales en JS? Porque `@setState` realizará 2 acciones:
1. Actualizar el estado del componente
2. Agendar una verificación/repintado de la UI basado en el nuevo estado
Es muy importante tener en cuenta esta información cada vez que utilizamos `state` dentro de nuestros componentes.
Veamos el botón de _enviar_, justo al final del método `render`:
~~~coffee
@RecordForm = React.createClass
...
render: ->
...
React.DOM.form
...
React.DOM.button
type: 'submit'
className: 'btn btn-primary'
disabled: !@valid()
'Create record'
~~~
Definimos un atributo `disabled` con el valor de `!valid()`, lo que significa que vamos a implementar un método `valid` para evaluar si los datos ingrersados por el usuario son correctos.
~~~coffee
# app/assets/javascripts/components/record_form.js.coffee
@RecordForm = React.createClass
...
valid: ->
@state.title && @state.date && @state.amount
~~~
Por simplicidad sólo vamos a validar cadenas vacías para atributos dentro del `state`. De esta manera, cada vez que el estado se actualice, el botón "Crear registro" se activará/desactivará dependiendo de la validez de los datos.


Ahora que tenemos nuestro controlador y formulario en su lugar, es momento de _submitear_ nuestro nuevo registro al servidor. Tenemos que manejar el evento `submit` del formulario. Para lograr esto, tenemos que añadir un atributo `onSubmit` a nuestro formulario y un nuevo método `handleSubmit` (de la misma forma que manejamos los eventos `onChange` antes):
~~~coffee
# app/assets/javascripts/components/record_form.js.coffee
@RecordForm = React.createClass
...
handleSubmit: (e) ->
e.preventDefault()
$.post '', { record: @state }, (data) =>
@props.handleNewRecord data
@setState @getInitialState()
, 'JSON'
render: ->
React.DOM.form
className: 'form-inline'
onSubmit: @handleSubmit
...
~~~
Revisemos el nuevo método línea por línea:
1. Evitar el submit HTTP del formulario
2. Hacer POST de la nueva información de `record` al URL actual
3. Callback de éxito
El _callback_ `success` es la clave de este proceso. Después de crear el nuevo registro exitosamente, _alguien_ será notificado sobre esta acción y `state` se restaurará a su valor inicial. ¿Recuerdas cuando mencioné que los componentes se comunican con otros componentes a través de propiedades (`@props`)? Bueno, es esto. Nuestro componente actual envía datos al componente padre a través de `@props.handleNewRecord` para notificar de la existencia de un nuevo registro.
Como ya habrás adivinado, donde quiera que creemos nuestro elemento `RecordForm`, tenemos que pasarle una propiedad `handleNewRecord` con la referencia de un método, algo así como `React.createElement RecordForm, handleNewRecord:addRecord`. Bueno, el componente padre `Records` es el "donde quiera". Dado que tiene un estado con todos los registros existentes, necesitamos actualizar su estado con el registro recién creado.
Añade el nuevo método `addRecord` dentro `records.js.coffee` y crea el nuevo elemento `RecordForm`, justo después `h2` (dentro del método `render`).
~~~coffee
# app/assets/javascripts/components/records.js.coffee
@Records = React.createClass
...
addRecord: (record) ->
records = @state.records.slice()
records.push record
@setState records: records
render: ->
React.DOM.div
className: 'records'
React.DOM.h2
className: 'title'
'Records'
React.createElement RecordForm, handleNewRecord: @addRecord
React.DOM.hr null
...
~~~
Refresca tu navegador, rellena el formulario con un nuevo registro, haz clic en "Create record"... Sin suspenso esta vez, se añadió el registro casi de inmediato y el formulario se limpia después del _submit_. Refrezca de nuevo sólo para asegurarte que el servidor ha almacenado la nueva información.

Si has utilizado otros frameworks JS junto con Rails (por ejemplo, AngularJS) para construir cosas similares, es posible que hayas tenido problemas porque sus peticiones POST no incluyen el token CSRF que Rails necesita, así que, ¿por qué no tuvimos el mismo problema? Fácil, porque estamos usando `jQuery` para interactuar con nuestro backend y el driver `jquery_ujs` de rails incluye automáticamente el token `CSRF` en cada petición AJAX por nosotros. ¡Bien!
Puedes revisar el código resultante de esta sección [aquí](https://github.com/fervisa/accounts-react-rails/tree/f4708e19f8be929471bc0c8c2bda93f36b9a7f23), o sólo los cambios introducidos por esta sección [aquí](https://github.com/fervisa/accounts-react-rails/commit/f4708e19f8be929471bc0c8c2bda93f36b9a7f23).
### Componentes reutilizables: Indicadores de Cantidad
¿Qué sería de una aplicación sin algunos (bonitos) indicadores? Añadamos algunas recuadros en la parte superior de la ventana con un poco de información útil. Nuestro objetivo de esta sección es mostrar tres valores: cantidad total de crédito, cantidad total de débito y el balance. Esto parece un trabajo para tres componentes, ¿o tal vez sólo uno con propiedades?
Podemos construir un nuevo componente `AmountBox` que recibirá tres propiedades: `amount`, `text` y `type`. Crea un nuevo archivo llamado `amount_box.js.coffee` en `javascripts/componentes/` y pega el siguiente código:
~~~coffee
# app/assets/javascripts/components/amount_box.js.coffee
@AmountBox = React.createClass
render: ->
React.DOM.div
className: 'col-md-4'
React.DOM.div
className: "panel panel-#{ @props.type }"
React.DOM.div
className: 'panel-heading'
@props.text
React.DOM.div
className: 'panel-body'
amountFormat(@props.amount)
~~~
Estamos usando elemento de panel de Bootstrap para mostrar la información en forma de bloques, y _seteamos_ el color mediante la propiedad `type`. También hemos incluido un método muy simple para formatear la cantidad llamado `amountFormat` que lee la propiedad `amount` y la muestra en formato de moneda.
Para tener una solución completa, necesitamos crear este elemento (tres veces) dentro de nuestro componente principal, mandando las propiedades requeridas dependiendo de los datos que queremos mostrar. Construyamos primero los métodos para calcular. Abre el componente `Records` y añade los siguientes métodos:
~~~coffee
# app/assets/javascripts/components/records.js.coffee
@Records = React.createClass
...
credits: ->
credits = @state.records.filter (val) -> val.amount >= 0
credits.reduce ((prev, curr) ->
prev + parseFloat(curr.amount)
), 0
debits: ->
debits = @state.records.filter (val) -> val.amount < 0
debits.reduce ((prev, curr) ->
prev + parseFloat(curr.amount)
), 0
balance: ->
@debits() + @credits()
...
~~~
`credits` suma todos los registros con una cantidad mayor a 0, `debits` suma todos los registros con una cantidad menor que 0 y balance no necesita explicación. Ahora que tenemos los métodos para hacer cálculos en su lugar, sólo tenemos que crear los elementos `AmountBox` dentro del método `render` (justo arriba del componente `RecordForm`):
~~~coffee
# app/assets/javascripts/components/records.js.coffee
@Records = React.createClass
...
render: ->
React.DOM.div
className: 'records'
React.DOM.h2
className: 'title'
'Records'
React.DOM.div
className: 'row'
React.createElement AmountBox, type: 'success', amount: @credits(), text: 'Credit'
React.createElement AmountBox, type: 'danger', amount: @debits(), text: 'Debit'
React.createElement AmountBox, type: 'info', amount: @balance(), text: 'Balance'
React.createElement RecordForm, handleNewRecord: @addRecord
...
~~~
¡Hemos terminado con esta funcionalidad! Refresca el navegador, deberías ver tres recuadros que muestran las cantidades que hemos calculado anteriormente. ¡Pero espera! ¡Hay más! Crea un nuevo registro y ve la magia...

Puedes ver el código resultante de esta sección [aquí](https://github.com/fervisa/accounts-react-rails/tree/8d6f0a4fb62f2a9abd5d34d502461388863302cb), o sólo los cambios introducidos por esta sección [aquí](https://github.com/fervisa/accounts-react-rails/commit/8d6f0a4fb62f2a9abd5d34d502461388863302cb).
### `setState`/`replaceState`: Eliminación de registros
La siguiente funcionalidad en nuestra lista es poder eliminar registros. Necesitamos una nueva columna `Actions` en nuestra tabla de registros, esta columna tendrá un botón "Delete" para cada registro, con una UI bastante estándar. Al igual que en el ejemplo anterior, tenemos que crear el método `destroy` en nuestro controlador Rails:
~~~ruby
# app/controllers/records_controller.rb
class RecordsController < ApplicationController
...
def destroy
@record = Record.find(params[:id])
@record.destroy
head :no_content
end
...
end
~~~
Ese es todo el código del lado del servidor que necesitaremos para esta funcionalidad. Ahora, abre tu componente React `Records` y añade la columna _Actions_ en la posición más a la derecha de la cabecera de la tabla:
~~~coffee
# app/assets/javascripts/components/records.js.coffee
@Records = React.createClass
...
render: ->
...
# almost at the bottom of the render method
React.DOM.table
React.DOM.thead null,
React.DOM.tr null,
React.DOM.th null, 'Date'
React.DOM.th null, 'Title'
React.DOM.th null, 'Amount'
React.DOM.th null, 'Actions'
React.DOM.tbody null,
for record in @state.records
React.createElement Record, key: record.id, record: record
~~~
Y, por último, abre el componente `Record` y añade una columna adicional con un link a _Delete_:
~~~coffee
# app/assets/javascripts/components/record.js.coffee
@Record = React.createClass
render: ->
React.DOM.tr null,
React.DOM.td null, @props.record.date
React.DOM.td null, @props.record.title
React.DOM.td null, amountFormat(@props.record.amount)
React.DOM.td null,
React.DOM.a
className: 'btn btn-danger'
'Delete'
~~~
Guarda el archivo, refreca tu navegador y ... ¡Tenemos un botón inútil sin eventos asociados a él!

Añadamos funcionalidad. Como hemos aprendido de nuestro componente `RecordForm`, el camino a seguir es:
1. Detectar un evento dentro del componente `Record` hijo (onClick)
2. Realizar una acción (enviar una solicitud _DELETE_ al servidor en este caso)
3. Notificar al componente padre `Records` acerca de esta acción (envío/recepción de un método a través de _props_)
4. Actualizar el estado del componente `Record`
Para implementar el paso 1, podemos agregar un manejador para `onClick` a `Registro` de la misma manera que añadimos un manejador para `onSubmit` a `RecordForm` para crear nuevos registros. Afortunadamente para nosotros, React implementa la mayoría de los eventos comunes de navegadores de una forma normalizada, por lo que no tenemos que preocuparnos por la compatibilidad entre navegadores (puedes vera la lista de eventos completos [aquí](http://facebook.github.io/react/docs/events.html#supported-events)).
Re-abre el componente `Record`, añade un nuevo método `handleDelete` y un atributo `onClick` a nuestro botón "inútil", como se ve a continuación:
~~~coffee
# app/assets/javascripts/components/record.js.coffee
@Record = React.createClass
handleDelete: (e) ->
e.preventDefault()
# yeah... jQuery doesn't have a $.delete shortcut method
$.ajax
method: 'DELETE'
url: "/records/#{ @props.record.id }"
dataType: 'JSON'
success: () =>
@props.handleDeleteRecord @props.record
render: ->
React.DOM.tr null,
React.DOM.td null, @props.record.date
React.DOM.td null, @props.record.title
React.DOM.td null, amountFormat(@props.record.amount)
React.DOM.td null,
React.DOM.a
className: 'btn btn-danger'
onClick: @handleDelete
'Delete'
~~~
Cuando el botón de borrado recibe el clic, `handleDelete` envía una petición AJAX al servidor para borrar el registro en el _backend_ y, después de esto, se notifica al componente padre de esta acción a través del manejador `handleDeleteRecord` disponible mediante _props_. Esto significa que tenemos que ajustar la creación de elementos `Record` en el componente padre para incluir la propiedad extra `handleDeleteRecord`, y propiamente implementar el método en el padre:
~~~coffee
# app/assets/javascripts/components/records.js.coffee
@Records = React.createClass
...
deleteRecord: (record) ->
records = @state.records.slice()
index = records.indexOf record
records.splice index, 1
@replaceState records: records
render: ->
...
# almost at the bottom of the render method
React.DOM.table
React.DOM.thead null,
React.DOM.tr null,
React.DOM.th null, 'Date'
React.DOM.th null, 'Title'
React.DOM.th null, 'Amount'
React.DOM.th null, 'Actions'
React.DOM.tbody null,
for record in @state.records
React.createElement Record, key: record.id, record: record, handleDeleteRecord: @deleteRecord
~~~
Básicamente, nuestro método `deleteRecord` copia el estado del componente `records` actual, realiza una búsqueda del registro que desea borrar, lo elimina de la colección y actualiza el estado del componente, operaciones estándar de JavaScript.
Hemos introducido una nueva forma de interactuar con el _estado_, `replaceState`; la principal diferencia entre `setstate` y `replaceState` es que el primero sólo actualizará un atributo del objeto _state_, el segundo sobreescribe completamente el estado actual del componente con cualquier nuevo objeto que le enviemos.
Después de la actualización de esta última pieza de código, refrescamos la ventana del navegador y tratamos de eliminar un registro. Deben de suceder un par de cosas:
1. Los registros deben desaparecer de la tabla y ...
2. Los indicadores deben actualizar las cantidades de inmediato, no se requiere ningún código adicional

Casi terminamos con nuestra aplicación, pero antes implementar nuestra última funcionalidad, podemos aplicar un pequeño refactor y, al mismo tiempo, introducir una nueva funcionaldad de React.
Puedes ver el código resultante de esta sección [aquí](https://github.com/fervisa/accounts-react-rails/tree/1a4dc646e53fecebc821c709347aae774e9ef170), o sólo los cambios introducidos por esta sección [aquí](https://github.com/fervisa/accounts-react-rails/commit/1a4dc646e53fecebc821c709347aae774e9ef170).
# Refactor: _Helpers_ de estado
Hasta aquí, tenemos un par de métodos donde el estado se actualiza sin dificultad dado que nuestros datos no son precisamente "complejos", pero imagina una aplicación más compleja con un estado JSON multi-nivel. Puedes imaginarte realizando copias profundas y malabares con tus datos de estado. React incluye algunos bonitos _helpers_ para el estado que ayudan con parte del trabajo pesado, sin importar qué tan profundo es el estado, estos _helpers_ te permitirán manipularlo con más libertad utilizando un lenguaje de consulta de tipo _MongoDB_ (o al menos eso es de lo que dice la [documentación de React](https://facebook.github.io/react/docs/update.html)).
Antes de utilizar estos _helpers_, primero tenemos que configurar nuestra aplicación Rails para incluirlos. Abre el archivo de configuración `appication.rb` de tu proyecto y añade `config.react.addons = true` en la parte inferior del bloque `Aplicación`:
~~~ruby
# config/application.rb
...
module Accounts
class Application < Rails::Application
...
config.react.addons = true
end
end
~~~
Para que los cambios surtan efecto, reinicia el servidor de Rails. Repito, *reinicia el servidor de Rails*. Ahora tenemos acceso a los _helpers_ de estado mediante `React.addons.update`, que procesarán nuestro objeto de estado (o cualquier otro objeto que enviemos a él) y aplicará los comandos proporcionados. Los dos comandos que usaremos son `$push` y `$splice` (tomo prestada la explicación de estos comandos de la [documentación oficial de React](https://facebook.github.io/react/docs/update.html#available-commands)):
* `{$push: array}` `push()` all the items in array on the target.
* `{$splice: array of arrays}` for each item in `arrays` call `splice()` on the target with the parameters provided by the item.
Estamos a punto de simplificar `addRecord` y `deleteRecord` del componente `Record` usando estos _helpers_, como sigue:
~~~coffee
# app/assets/javascripts/components/records.js.coffee
@Records = React.createClass
...
addRecord: (record) ->
records = React.addons.update(@state.records, { $push: [record] })
@setState records: records
deleteRecord: (record) ->
index = @state.records.indexOf record
records = React.addons.update(@state.records, { $splice: [[index, 1]] })
@replaceState records: records
~~~
Más corto, más elegante y con los mismos resultados. Puedes refrescar el navegador y asegurarte que nada se rompió.
Puedes ver el código resultante de esta sección [aquí](https://github.com/fervisa/accounts-react-rails/tree/d19127f40ae2f795a30b7de6470cde95d3734eee), o sólo los cambios introducidos por esta sección [aquí](https://github.com/fervisa/accounts-react-rails/commit/d19127f40ae2f795a30b7de6470cde95d3734eee).
# Flujo reactivo de datos: Edición de registros
Para la funcionalidad final, añadiremos un botón extra de edición, al lado del botón Borrar en nuestra tabla de registros. Cuando se haga clic en este botón Editar, se cambiará toda la fila de un estado de sólo lectura a un estado editable, mostrando un formulario en línea en el que el usuario pueda actualizar el contenido del registro. Después de enviar el contenido actualizado o cancelar la acción, la fila del registro volverá a su estado inicial de sólo lectura.
Como ya habrán adivinado por el párrafo anterior, tenemos que manejar datos mutables para alternar el estado de cada registro dentro de nuestro componente `Record`. Este es un caso de uso de lo que React llama _flujo reactivo de datos_. Añadamos una bandera de edición y un método `handleToggle` a `record.js.coffee`:
~~~coffee
# app/assets/javascripts/components/record.js.coffee
@Record = React.createClass
getInitialState: ->
edit: false
handleToggle: (e) ->
e.preventDefault()
@setState edit: !@state.edit
...
~~~
La bandera `edit` tendrá un valor por defecto de `false` y `handleToggle` cambiará `edit` de falso a verdadero y viceversa, sólo tenemos que disparar `handleToggle` a partir de un evento `onClick` del usuario.
Ahora, tenemos que manejar dos versiones de filas (de formulario y de sólo lectura) y mostrarlas de forma condicional dependiendo de `edit`. Por suerte para nosotros, siempre y cuando nuestro método `render` devuelva un elemento React, podemos llevar a cabo cualquier acción en él; podemos definir un par de métodos auxiliares `recordRow` y `recordForm` y llamarlos condicionalmente dentro de `render` en función del contenido de `@state.edit`.
Ya tenemos una primera versión de `recordRow`, es nuestro método `render` actual. Pasemos el contenido de `render` a nuestro nuevo método `recordRow` y añadamos algo de código adicional:
~~~coffee
# app/assets/javascripts/components/record.js.coffee
@Record = React.createClass
...
recordRow: ->
React.DOM.tr null,
React.DOM.td null, @props.record.date
React.DOM.td null, @props.record.title
React.DOM.td null, amountFormat(@props.record.amount)
React.DOM.td null,
React.DOM.a
className: 'btn btn-default'
onClick: @handleToggle
'Edit'
React.DOM.a
className: 'btn btn-danger'
onClick: @handleDelete
'Delete'
...
~~~
Sólo agregamos un elemento `React.DOM.a` adicional que escucha eventos `onClick` para llamar a `handleToggle`.
Continuemos, la implementación de `recordForm` tendría una estructura similar, pero con _inputs_ de entrada en cada celda. Utilicemos un nuevo atributo `ref` para hacer accesibles nuestras entradas. Ya que este componente no maneja un estado, este nuevo atributo permitirá que nuestro componente lea los datos provistos por el usuario por medio de `@refs`:
~~~coffee
# app/assets/javascripts/components/record.js.coffee
@Record = React.createClass
...
recordForm: ->
React.DOM.tr null,
React.DOM.td null,
React.DOM.input
className: 'form-control'
type: 'text'
defaultValue: @props.record.date
ref: 'date'
React.DOM.td null,
React.DOM.input
className: 'form-control'
type: 'text'
defaultValue: @props.record.title
ref: 'title'
React.DOM.td null,
React.DOM.input
className: 'form-control'
type: 'number'
defaultValue: @props.record.amount
ref: 'amount'
React.DOM.td null,
React.DOM.a
className: 'btn btn-default'
onClick: @handleEdit
'Update'
React.DOM.a
className: 'btn btn-danger'
onClick: @handleToggle
'Cancel'
...
~~~
No tengas miedo, este método puede parecer grande, pero es sólo nuestra sintaxis tipo HAML. Nota que llamamos a `@handleEdit` cuando el usuario hace clic en el botón "Update". Utilicemos un flujo similar a la implementación para eliminar registros.
¿Notas algo diferente en cómo se están creando `React.DOM.inputs`? Estamos utilizando `defaultValue` en lugar de `value` para asignar los valores de entrada iniciales, esto es porque *el usar `value` sin `onChange` acabará creando entradas de sólo lectura*.
Por último, el método `render` se reduce al siguiente código:
~~~coffee
# app/assets/javascripts/components/record.js.coffee
@Record = React.createClass
...
render: ->
if @state.edit
@recordForm()
else
@recordRow()
~~~
Puedes refescar tu navegador para jugar con el nuevo comportamiento, pero no presentará ningún cambio todavía ya que no hemos implementado la funcionalidad real.


Para manejar las actualizaciones de registros, tenemos que añadir el método `update` a nuestro controlador Rails:
~~~ruby
# app/controllers/records_controller.rb
class RecordsController < ApplicationController
...
def update
@record = Record.find(params[:id])
if @record.update(record_params)
render json: @record
else
render json: @record.errors, status: :unprocessable_entity
end
end
...
end
~~~
De regreso a nuestro componente `Record`, tenemos que implementar el método `handleEdit` que enviará una petición _AJAX_ al servidor con la información actualizada de `record`, después notificará al componente padre enviando la versión actualizada del registro a través del método `handleEditRecord`, este método se recibirá a través de `@props`, de la misma manera que lo hicimos antes, al eliminar de registros:
~~~coffee
# app/assets/javascripts/components/record.js.coffee
@Record = React.createClass
...
handleEdit: (e) ->
e.preventDefault()
data =
title: React.findDOMNode(@refs.title).value
date: React.findDOMNode(@refs.date).value
amount: React.findDOMNode(@refs.amount).value
# jQuery doesn't have a $.put shortcut method either
$.ajax
method: 'PUT'
url: "/records/#{ @props.record.id }"
dataType: 'JSON'
data:
record: data
success: (data) =>
@setState edit: false
@props.handleEditRecord @props.record, data
...
~~~
Para simplificar, no vamos a validar los datos del usuario, sólo los leeremos por medio de `React.findDOMNode(@refs.fieldName).value` y los enviaremos tal cual al backend. Actualizar el estado para cambiar al modo de edición en `success` no es obligatorio, pero el usuario nos lo agradecerá.
Por último, pero no menos importante, sólo tenemos que actualizar el estado del componente `Records` para sobrescribir el registro anterior con la nueva versión del registro hijo y dejar que React realice su magia. La implementación podría verse así:
~~~coffee
# app/assets/javascripts/components/records.js.coffee
@Records = React.createClass
...
updateRecord: (record, data) ->
index = @state.records.indexOf record
records = React.addons.update(@state.records, { $splice: [[index, 1, data]] })
@replaceState records: records
...
render: ->
...
# almost at the bottom of the render method
React.DOM.table
React.DOM.thead null,
React.DOM.tr null,
React.DOM.th null, 'Date'
React.DOM.th null, 'Title'
React.DOM.th null, 'Amount'
React.DOM.th null, 'Actions'
React.DOM.tbody null,
for record in @state.records
React.createElement Record, key: record.id, record: record, handleDeleteRecord: @deleteRecord, handleEditRecord: @updateRecord
~~~
Como hemos aprendido en la sección anterior, usar `React.addons.update` para cambiar nuestro estado podría resultar en métodos más concretos. El enlace final entre `Records` y `Record` es el método `updateRecord` enviado a través de la propiedad `handleEditRecord`.
Refresca el navegador por última vez y trata de actualizar algunos registros existentes, observa cómo las recuadros de cantidad en la parte superior de la página mantienen un seguimiento de cada cambio en los registros.

¡Hemos terminado! Sonríe, ¡acabamos de construir una pequeña aplicación Rails + React desde cero!
Puedes ver el código resultante de esta sección [aquí](https://github.com/fervisa/accounts-react-rails/tree/1a62dd0e48b31aa55659e0035e754cee1776aa61), o sólo los cambios introducidos por esta sección [aquí](https://github.com/fervisa/accounts-react-rails/commit/1a62dd0e48b31aa55659e0035e754cee1776aa61).
# Comentarios finales: React.js - simplicidad y flexibilidad
Hemos examinado algunas de las funcionalidades de React y hemos aprendido que apenas si introduce nuevos conceptos. He escuchado comentarios de gente diciendo X o Y _framewrork_ JavaScript tiene una curva de aprendizaje empinada debido a todos los nuevos conceptos que introduce, pero no es el caso React, que implementa conceptos básicos de JavaScript, como manejadores de eventos y _bindings_, por lo que es fácil de adoptar y aprender. Una vez más, uno de sus puntos fuertes es su sencillez.
También aprendimos cómo integrarlo en el pipeline de Rails y lo bien que se entiende con CoffeeScript, jQuery, Turbolinks, y el resto de la orquesta Rails. Pero esta no es la única forma de lograr los resultados deseados. Por ejemplo, si no usas Turbolinks (por lo tanto, no es necesario `react_ujs`) puedes utilizar [Rails Assets](https://rails-assets.org/) en lugar de la gema `react-rails`; podrías utilizar [JBuilder](https://github.com/rails/jbuilder) para construir respuestas _JSON_ más complejas en lugar de la prestación de los objetos _JSON_, y cosas por el estilo, y seguir obteniendo los mismos maravillosos resultados.
React definitivamente aumentará tus habilidades de frontend, lo que la hace una gran biblioteca para tener entre tus herramientas Rails.
<file_sep>/source/posts/2014/2014-04-09-coding-dojo-12-abril-2014.html.markdown
---
title: Coding Dojo - 12 Abril 2014
date: 2014-04-09 01:16 UTC
tags: dojo, comunidad
---
Para comenzar las actividades del mes de abril, la comunidad **oaxaca.rb** extiende la invitación a los programadores de Oaxaca (y zonas aledañas) al **4o Coding Dojo**. Se realizará el **sábado 12 de abril** en las instalaciones de la **Secretaría de Desarrollo Económico**; la dirección es **Matamoros #102, Centro. Oaxaca de Juárez Oaxaca**.
<div class="text-center" markdown="1">
[](https://www.eventbrite.com/e/coding-dojo-tickets-11244212743)
</div>
Puedes registrarte en el [evento de Eventbrite](https://www.eventbrite.com/e/coding-dojo-tickets-11244212743). Si ya has asistido anteriormente y conoces a alguien que pueda estar interesado en aprender metodologías de programación y de paso el lenguaje Ruby, invítalo con toda confianza (ya sabes, tenemos *kata* de bienvenida).
La maquina virtual que se utiliza en el Dojo está disponible en [este enlace](https://mega.co.nz/#!gNUWDQSS!UTuITd8SrT3sMbvAInYRbWBMI0Cy4_ToYPUckX7w59M). Si tienes alguna duda, puedes dejarla en la sección de comentarios (en la parte inferior). ¡Nos vemos el sábado!
<file_sep>/source/posts/2014/2014-03-21-agradecimiento-a-desarrollo-economico.html.markdown
---
title: Agradecimiento a Desarrollo Económico
date: 2014-03-21 15:52 UTC
tags: comunidad, gracias
---
Agradecemos al Secretario de Desarrollo Económico del municipio de Oaxaca de Juárez, el Lic. <NAME> del Campo, que junto con el apoyo de la [Dirección de Capacitación y Empleo](https://www.facebook.com/desarrollo.economicooaxacadejuarez) es que fue posible la realización de nuestro segundo Dojo en sus instalaciones ubicadas en la calle de Matamoros #102 Centro.
Toda la comunidad de Oaxaca.rb esta muy agradecida y esperamos poder seguir contanto con su apoyo.

<file_sep>/source/posts/2014/2014-03-05-agradecimiento-a-pypo.html.markdown
---
title: Agradecimiento a PyPO
date: 2014-03-05 05:36 UTC
tags: comunidad, gracias
---
Queremos agradecer de manera muy especial al Lic. <NAME>, Gerente de la Empresa [PyPO: Pintura y Publicidad de Oaxaca](http://www.pypo.mx/) por facilitarnos sus instalaciones ubicadas en la Calle Emiliano Zapata No. 412. Trinidad de las Huertas, en la Cd. de Oaxaca. Para la realización de nuestro evento.
No podemos dejar de agradecer a [<NAME>](http://twitter.com/eeecorona), un miembro entusiasta de la Comunidad Ruby de Oaxaca quién realizó toda la gestión con la gerencia de PyPO para lograr que este evento se pudiera realizar.
Esperamos seguir contando con su invaluable apoyo.
<file_sep>/source/posts/2014/2014-04-16-como-subir-un-post.html.markdown
---
title: Cómo subir un Post
date: 2014-04-16 16:11 UTC
tags: middleman, github, comunidad
---
Subir un post a **oaxaca.rb** es muy sencillo, solo debes seguir los siguientes pasos y asi aportar conocimiento a la comunidad Ruby de Oaxaca.
El primer paso es crear un cuenta [Github](https://github.com) si es que aún no la tienen.
Si acabas de crear la cuenta de **Github** debes crear tus llaves [SSH](https://help.github.com/articles/generating-ssh-keys).
Mandar un correo con tu nombre de usuario de **Github** al correo **<EMAIL>** y esperar el correo de confirmación de que te has unido al grupo.
#### Clonar el proyecto
**En terminal**
Clona el proyecto
``git clone <EMAIL>:oaxacarb/oaxacarb.github.io.git``
Entras a la carpeta de tu proyecto
``cd oaxacarb.github.io``
Cámbiate a la rama Source
``git checkout source``
> La rama source es donde se subirá el código para que éste pueda ser deployado al servidor.
#### Crear el articulo
Para crear el artículo desde terminal puedes chacer
``middleman article "nombre de tu articulo"``
> Este comando creara un archivo con una estampa de tiempo para que empieces a trabajar sobre el, tendra el siguiente formato. Ejemplo de este Post "2014-03-04-como-subir-un-post.html.markdown"
Dentro de tu IDE favorito puedes editar el contenido del articulo con sintaxis [Markdown](http://daringfireball.net/projects/markdown/syntax)
Puedes ver tus cambios reflejados antes de subirlos dentro de tu localhost en el puerto 4567 con el comando
``middleman server``
Ya que tu artículo esta listo, debes subir tus cambios al repositorio de **Github** para posteriormente subirlo al servidor.
Agregar tus cambios al commit que se va subir a Github
``git add . -A``
Agregar el comentario al commit
``git commit -m "comentario"``
Subir los cambios a github
``git push origin source``
> Es importante que el push se haga hacia source porque ahi es donde se tendra el código
Finalmente, subirlo a servidor
``middleman deploy``
Nota: Las veces posteriores que subas un Post debes descargar las actualizaciones que tenga el proyecto, que algun otro miembro de la comunidad haya subido un post, cambios de diseño, etc., con el siguiente comando
``git pull``
<file_sep>/source/posts/2015/2015-05-01-platica-mezcal-con-trailblazer-por-nick-sutterer.html.markdown
---
title: "Plática: Mezcal con TrailBlazer por <NAME>"
date: 2015-05-01 18:30 UTC
tags: platica, comunidad
---
Después de dejar un rato abandonada la página nos dimos cuenta que olvidamos poner la plática ["Mezcal con TrailBlazer"](https://www.youtube.com/embed/x3xITElQe78) que [<NAME>](https://twitter.com/apotonick) presentó en una de las reuniones de la comunidad.
<center>
<iframe width="300" height="215" src="https://www.youtube.com/embed/x3xITElQe78?rel=0" frameborder="0" allowfullscreen></iframe>
</center>
¡Muchas gracias Nick!, por tan interesante plática, y esperamos verte pronto en Oaxaca.
<file_sep>/source/posts/2015/2015-05-05-platica-introduccion-a-git.html.markdown
---
title: "Plática: Introducción a Git"
date: 2015-05-05 03:19 UTC
tags: platica, comunidad
---
El día sábado 2 de Mayo de 2015, se llevó acabo la plática introductoria a [Git](http://git-scm.com/).
La cual, dio a conocer las ventajas de usarlo en los diferentes proyectos que se realizan día con día.
Con [Git](http://git-scm.com/) se puede llevar un mejor control en los proyectos, y más cuando el proyecto es realizado por varias
personas, porque [Git](http://git-scm.com/) lleva un registro de todos los cambios que se hacen y quiénes los hacen, y si por algún motivo se realizan cambios no deseados, estos cambios se pueden deshacer.
Ahora veamos como iniciar un proyecto con [Git](http://git-scm.com/) y algunos de los principales comandos.
Lo primero que debemos de hacer es crear una carpeta la cual sera el directorio para el proyecto,
posteriormente accedemos a ella.

Hasta estos momentos sería el directorio de un proyecto normal, Ahora con el comando **git init** le indicaremos que
usaremos git como controlador de versiones en este directorio.

Si se ejecuta el comando **git status** (el cual indica el estado del directorio de trabajo), se observa que el directorio esta vacío.

Ahora iniciamos el proyecto creando un archivo **README**, el cual indica de qué trata el proyecto

Antes de continuar, hay algo que se debe tener en cuenta, al usar un controlador de versiones, en este caso **Git**, los archivos o directorios del proyecto
pueden ser catalogados en 3 estados,
1. **Working directory**
(en el que actualmente se encuentra el archivo **README**)
2. **Staging area**
3. **Repository**
Ahora si volvemos a ejecutar el comando **git status** se observa que git ha detectado el archivo **README** el cual lo cataloga como **Untracked file**
porque aún no ha sido agregado ese cambio.

Git nos indica que debemos hacer uso del comando **git add**.
Ejecutamos **git add README** para agregar el cambio del proyecto, en este caso se ha creado el archivo **README**
y nuevamente ejecutamos el comando **git status** y se observa que **git** a detectado un nuevo archivo **README**
Ahora el archivo **README** se encuentra en el **Staging area**

Para pasar el cambio del **Staging area** al **repositorio** en este caso es un **repositorio local**
se necesita ejecutar el comando **git commit** con la opción **-m** se puede pasar un mensaje al ejecutar el comando el cual indica
cual ha sido el cambio en el proyecto.
Y nuevamente ejecutamos el comando **git status** y se observa que los cambios han sido guardados en el repositorio local,

Otro comando muy útil es **git log** el cual muestra los **commit** que se han ejecutado en todo el proyecto, mostrando el usuario y fecha en que se llevo acabo el commit. Por ahora solo tenemos uno, donde se guardó el cambio (la creación del archivo **README**).

Ahora crearemos un archivo **prueba.rb** el cual solo mostrara un mensaje
y si hacemos **git status** se observa que git lo detecta como archivo **untracked file**
para guardar los cambios tenemos que ejecutar el comando anterior
1. **git add**


Ejecutamos **git status** y se observa que git lo detecta como un archivo nuevo

Actualmente el archivo **prueba.rb** se encuentra en el **Staging area** si queremos modificar el archivo **prueba.rb** por que nos falto agregar algo
y después guardarlo como un solo cambio. Se puede ejecutar **git reset prueba.rb** este comando quitará el archivo del **Staging area** y ahora su estado será **Working directory**.
Si ejecutamos **git status** se observa que git lo detecta como un **untracked file**

1. Editamos el archivo **prueba.rb**

2. Agregamos el cambio **git add prueba.rb** pasandolo al **Staging area**
3. Para guardar los cambio en el repositorio ejecutamos
**git commit -m "Agregando archivo de prueba.rb"**
4. Ejecutamos **git status** y se observa que ya los cambios han sido guardados

También se puede observar que los cambios han sido guardados con ayuda del plugin [vim-airline](https://github.com/bling/vim-airline)
el cual muestra el nombre de la rama en este caso **master** y cuando hay cambios, uno se percata que aparece una **✗** y cuando los cambios han sido guardados aparece una **✓**
Ahora si ejecutamos **git log** se observa que aparecen dos commit, indicando los cambios, también se puede usar la opción **-p** la cual
da información más detallada con respecto a los cambios.


Si editamos un archivo y queremos descartar los cambios, se puede ejecutar **git checkout "nombre del archivo"**, omitiendo las comillas,
esto siempre y cuando el archivo esté en **Working area**. Si ya se encuentra en **Staging area** debemos ejecutar el comando antes visto
**git reset "nombre del archivo"** y posteriormente **git checkout "nombre del archivo"**, veamos un ejemplo
1. Editar el archivo

2. **git status** se observa que el archivo ha sido modificado
3. **git checkout prueba.rb** se borran los cambios hechos al archivo
4. **git status** se observa que ya no hay ningún cambio

Esto fue una introducción a git, realmete faltan muchos comandos y como referencia pongo el libro [Git Pro](http://git-scm.com/book/en/v2) el cual se encuentra como documentación de git, que les ayudara a entender más a fondo [Git](http://git-scm.com/)
<file_sep>/source/posts/2014/2014-05-02-agradecimiento-a-flisol-oaxaca.html.markdown
---
title: Agradecimiento a FLISOL Oaxaca
date: 2014-05-02 20:53 UTC
tags: comunidad, gracias
---
Queremos agradecer a los organizadores del FLISOL Oaxaca 2014, especialmente a [@urielmania](http://twitter.com/urielmania) por las atenciones brindadas para que pudiéramos llevar el Coding Dojo al FLISOL, el cual se llevó a cabo en el Centro Cultura Heriberto Pazos (Ccuherpo), ubicado en Camino al Rosario #308, Santa Lucía del Camino.
Esperamos seguir contando con su apoyo en futuros eventos.

<file_sep>/source/posts/2014/2014-03-04-arranca-la-comunidad-ruby-de-oaxaca.html.markdown
---
title: "Coding Dojo: Arranca la comunidad ruby de Oaxaca"
date: 2014-03-04 05:36 UTC
tags: comunidad, dojo
---
El día 26 de febrero de 2014 tuvo lugar el **primer Coding Dojo de Oaxaca**, marcando también el inicio de esta **comunidad de programadores ruby de Oaxaca**; durante el evento resaltaron los siguientes puntos:
* Hubo gran variedad de personas, desde estudiantes de nivel licenciatura, desarrolladores en empresas privadas y desarrolladores en dependencias gubernamentales.
* Se practicó Pair Programming, TDD. (Utilizando Ruby y [RSpec](http://rspec.info/)).
* Se despertó mucho interés, tanto que los participantes solicitaron que se hiciera el evento cada 15 días.
* Se practicó con una kata sencilla ([FizzBuzz](http://en.wikipedia.org/wiki/Fizz_buzz)), que para ser la primera vez de muchos de los participantes, fue excelente.
* Sirvió como presentación para la comunidad Ruby de Oaxaca. ([@oaxacarb](http://twitter.com/oaxacarb) en twitter).
* Y por supuesto, nos divertimos mucho.

En la retrospectiva del evento saltaron a la vista algunos puntos que mejoraremos en los siguientes eventos:
* La instalación de la máquina virtual llevó mucho tiempo. Será un requisito para la siguiente ocasión.
* Se dividirá en 2 grupos, avanzados y principiantes, para permitir que los que tengan un mejor nivel puedan hacer katas más avanzadas.
* Buscaremos hacer otros eventos como reuniones informales para abordar temas de interés de muchos participantes, como TDD con Rails y cuestiones de ese tipo.
Les compartimos la liga a algunas fotos tomadas durante el evento [aqui](https://plus.google.com/107461695051836920312/posts/d1qbu2THi37).
<file_sep>/source/posts/2017/2017-08-09-trivia-como-borrar-un-metodo-completo.html.markdown
---
title: "Trivia vim 1: ¿Como borrar un metodo completo?"
date: 2017-08-09 11:07 UTC
tags: trivia, comunidad, vim
---
~~~ruby
# Trivia vim 1:
# Si el cursor está ubicado sobre la letra "r" de la palabra "bar"
# ¿Cuál es la forma más rápida para borrar el método foo completo?
# By @thotmx
def baz
qux
end
def foo
bar
end
def blag
bla
end
~~~
<file_sep>/source/posts/2023/2023-04-19-pimp-mi-cv.html.markdown
---
title: Plática "Pimp mi CV"
date: 2023-04-19 00:00 UTC
tags: [evento, empleo, cv]
---
El **Sábado 6 de Mayo de 2023** tendremos la plática **Pimp mi CV** por [<NAME>](https://twitter.com/hendrixmar). En la que se hablará de cómo potenciar el alcance de tu CV y tu perfil en LinkedIn para obtener más entrevistas en empresas internacionales.
Si quieres acompañarnos en este evento, te esperamos en [Presa Chicoasén 102, Presa San Felipe, 68024 Oaxaca de Juárez, Oax](https://maps.app.goo.gl/xT5p7eyKHJYRGRdj9) . [¡Aparta tu lugar aquí!](https://bit.ly/41D3Ged) Tenemos **cupo limitado**.
La plática también será transmitida por Facebook: [https://www.facebook.com/oaxacarb](https://www.facebook.com/oaxacarb)
Agradecemos a la diputada [<NAME>](https://twitter.com/SoyGabyPerezMx) por el apoyo con el espacio para la realización de este evento.<file_sep>/source/posts/2014/2014-07-22-coding-dojo-25-julio-2014.html.markdown
---
title: Coding Dojo - 25 Julio 2014
date: 2014-07-22 20:57 UTC
tags: dojo, comunidad
---
La comunidad **oaxaca.rb** extiende la invitación a los programadores de Oaxaca al **10o Coding Dojo**. Se realizará el **viernes 25 de julio** en las instalaciones del **Impact Hub**, las cuales se encuentran en **<NAME> Roo 211, Centro. Oaxaca de Juárez Oaxaca**, a unos pasos del jardín Conzatti.
<div class="text-center" markdown="1">
[](https://www.eventbrite.com/e/coding-dojo-tickets-12356900823)
</div>
Puedes registrarte en el [evento de Eventbrite](http://www.eventbrite.com/e/coding-dojo-tickets-12356900823).
La maquina virtual que se utiliza en el Dojo está disponible en [este enlace](https://mega.co.nz/#!VU0GhRgB!Vhl0Vjc_xqZILoc1WKyMY4f4RbeAZQBCaZBOtSUhKl4). Si tienes alguna duda, puedes dejarla en la sección de comentarios (en la parte inferior). ¡Nos vemos el viernes!
<file_sep>/source/posts/2015/2015-01-24-recuento-global-day-of-coderetreat-oaxaca-2014.html.markdown
---
title: "Recuento: Global Day of CodeRetreat Oaxaca 2014"
date: 2015-01-24 22:34 UTC
tags: evento, comunidad
---
El día 15 de Noviembre de 2014 realizamos el evento [Global Day of CodeRetreat 2014](http://globalday.coderetreat.org) en el cual convivimos con nuevos compañeros y tratamos de resolver el ploblema del [Juego De La Vida](http://es.wikipedia.org/wiki/Juego_de_la_vida) durante las 8 horas que duró el evento.

BREAK_ARTICLE
Durante el desarrollo del CodeRetreat, nos enfocamos en practicas técnicas como TDD(Test-Driven Development) y Pair Programming, para mejorar el dominio de dichas técnicas.
Algo interesante de este Code Retreat es que además de utilizar el lenguaje Ruby, se utilizó Java, lo cual ayudó a los participantes a explorar nuevos lenguajes y formas de solución.

Agradecemos a todos los asistentes por su activa participación y entusiasmo. Y los invitamos a participar en las actividades de la comunidad oaxaca.rb.


<file_sep>/source/posts/2017/2017-09-21-vuejs-primeros-pasos-en-vuejs.html.markdown
---
title: "Vuejs: Primeros pasos en vuejs"
date: 2017-09-21 11:16 UTC
tags: comunidad, javascript, vuejs
---
### ¿Que es vuejs?
Vue es un framewoek progresivo para la creación de interfaces de usuario.
Vue se centra sólo en la capa de vista y es muy fácil de captar e integrar con otras bibliotecas o proyectos existentes.
### ¿Por qué Vue?
Por la facilidad de aprender, es muy ligero.
### Instalación
Existen varias formas de [instalar](https://vuejs.org/v2/guide/installation.html) vuejs.
* Agregando el [CDN](https://unpkg.com/vue).
* Atravez de NPM ```npm install vue```.
* Atravez de Bower ```bower install vue```.
* Atravez del [CLI](https://github.com/vuejs/vue-cli).
## Jugando con Vue.js
Cabe mencionar que es **reactivo** (*Two Way Data *), si cambias desde la vista la variable ```message``` en el modelo "data" tambien cambia.
Si abrimos la consola y tecleamos ```app.message = "Hola, vuejs" ``` cambiará lo que ve en ```{{ message }}``` por el nuevo texto.
### Estructura base
<script async src="//jsfiddle.net/juanvqz/dt2usnm7/7/embed/"></script>
<hr>
### Condicional
<script async src="//jsfiddle.net/juanvqz/hsqwx0ey/embed/"></script>
<hr>
### Iterar un array
<script async src="//jsfiddle.net/juanvqz/dqr32r25/8/embed/"></script>
<hr>
### Evento click
<script async src="//jsfiddle.net/juanvqz/zhbucqge/embed/"></script>
<hr>
La caracteristica más importante de Vuejs es que se pueden hacer componentes, en el proximo post hare un editor de markdown para ver como trabajar con componentes.
Si quieres aprender màs de Vuejs, hay muchos videos y la documentación es muy buena.
### Más de Vuejs
1. [Guia Vuejs](https://vuejs.org/v2/guide/).
2. [Documentacion Vuejs](https://vuejs.org/v2/api/).
3. [Ejemplos de Vuejs](https://vuejs.org/v2/examples/).
Coméntanos como te fue...
<file_sep>/source/posts/2015/2015-07-11-convenciones-sobre-la-estructura-de-directorios-en-rspec-y-minitest.html.markdown
---
title: Convenciones sobre la estructura de directorios en RSpec y Minitest
date: 2015-07-11 15:31 UTC
tags: ruby, rspec, minitest
---
Al crear un nuevo proyecto en Ruby, la estructura básica es poner el código en un directorio llamado `lib`. Además, podemos agregar un directorio `test` o `spec` para nuestros archivos de prueba. No es obligatorio, pero es una convención que deberíamos seguir, no solo porque nuestra estructura de directorios será más intuitiva, sino también porque algunos frameworks de testing así lo asumen.
Si queremos usar Rspec, el directorio se debe llamar `spec`. Si queremos usar Minitest, podemos nombrarlo de cualquier forma, pero es común nombrarlo `test` o también `spec`.
## RSpec
Veamos un ejemplo básico con RSpec.
Estructura de directorios:
~~~
fizz_buzz_rspec
├── lib
│ └── fizz_buzz.rb
└── spec
└── fizz_buzz_spec.rb
~~~
El contenido de los archivos:
~~~ruby
#spec/fizz_buzz_spec.rb
require 'fizz_buzz'
describe FizzBuzz do
it 'returns "1" when receives 1' do
expect(FizzBuzz.new.convert(1).to eq '1'
end
end
#lib/fizz_buzz.rb
class FizzBuzz
def convert(n)
'1'
end
end
~~~
Es sólo la primera prueba para un proyecto fizz buzz.
Ahora, simplemente podemos ejecutar `rspec`:
~~~
[fizz_buzz_rspec]$ rspec
.
Finished in 0.00151 seconds (files took 0.1615 seconds to load)
1 example, 0 failures
~~~
Estoy empezando con una prueba en verde porque el resultado no es tan verboso como si la prueba fallara, pero ya sabemos que debemos empezar una prueba en rojo, ¿cierto? ¿Cierto? :)
Como vemos, no necesitamos ninguna configuración extra. En nuestro archivo `fizz_buzz_spec` requerimos el archivo `fizz_buzz` y nada más. De hecho, no necesitamos requerir la biblioteca `rspec` y no necesitamos especificar dónde están nuestros archivos de prueba. Simplemente ejecutamos el comando `rspec` desde la línea de comandos dentro de nuestro proyecto y Rspec se encargó del resto.
¿Qué hubiera pasado si nuestro directorio `spec` fuera nombrado de manera distinta? Digamos
~~~
fizz_buzz_rspec
├── lib
│ └── fizz_buzz.rb
└── my_testing_directory
└── fizz_buzz_spec.rb
~~~
Bien, en test caso, si ejecutamos el comando `rspec`, no se encontrará ninguna prueba para ejecutar.
~~~
[fizz_buzz_rspec]$ rspec
No examples found.
Finished in 0.00031 seconds (files took 0.07711 seconds to load)
0 examples, 0 failures
~~~
Debemos ejecutar el comando indicando el directorio.
~~~
[fizz_buzz_rspec]$ rspec my_testing_directory
.
Finished in 0.00151 seconds (files took 0.1615 seconds to load)
1 example, 0 failures
~~~
Además, es importante seguir la convención de nombres del archivo spec. RSpec espera que todos los archivos de pruebas termien con `_spec`. En nuestro caso, `fizz_buzz_spec.rb`. Si lo renombramos, RSpec no lo ejecutará. Veamos:
~~~
fizz_buzz_rspec
├── lib
│ └── fizz_buzz.rb
└── spec
└── fizz_buzz_testing_file.rb
~~~
Intentemos ejecutar:
~~~
[fizz_buzz_rspec]$ rspec
No examples found.
Finished in 0.00031 seconds (files took 0.07711 seconds to load)
0 examples, 0 failures
~~~
De nuevo, RSpec no cargó nuestro archivo porque no sigue la convención de nombrado. Si lo renombramos de nuevo `fizz_buzz_spec.rb`, funcionará.
Si observamos el archivo de pruebas, podemos ver que no necesitamos ninguna configuración especial para cargar el archivo `fizz_buzz.rb`, además de requerirlo claro está. RSpec asume que nuestro código está en el directorio `lib` y por eso es que puede carglo correctamente. Intentemos renombrar el directorio `lib` y veamos qué pasa.
~~~
fizz_buzz_rspec
├── main
│ └── fizz_buzz.rb
└── spec
└── fizz_buzz_spec.rb
~~~
Si tratamos de ejecutar `rspec`.
~~~
[fizz_buzz_rspec]$ rspec
[...]core_ext/kernel_require.rb:54:in `require': cannot load such file -- fizz_buzz (LoadError)
...
[...]spec/fizz_buzz_spec.rb:1:in `<top (required)>'
...
~~~
Falla por el `require` (la primera línea del archivo de pruebas). No encuentra un archivo `fizz_buzz.rb`, que presupone en el directorio `lib` (que nosotros acabamos de renombrar). Así que, lo renombramos de nuevo `lib` y todo funciona de nuevo.
Como podemos ver, es mejor apegargse a las convenciones cuando usamos RSpec.
### `spec_helper`
Es común usar un archivo `spec_helper`. Cuando nuestro proyecto crece, necesitamos incluir más bibliotecas de pruebas, o agregar más tareas para hacer antes o después de ejecutar la prueba. Por ejemplo, podríamos querer incluir `shoulda`, o limpiar la base de datos. Estas tareas afectan muchos archivos de pruebas, así que, es mejor tenerlas en su propio archivo e incluirlo en los otros archivos. Nuestro ejemplo no necesita nada más, pero quiero mostrar cómo sería si lo necesitase.
Digamos que queremos usar la gema `rspec-given`. Después de instarlar, necesitamos agregar esta línea al archivo `fizz_buzz_spec.rb`:
~~~ruby
#spec/fizz_buzz_spec.rb
require 'rspec/given'
~~~
En nuestro proyecto sólo tenemos un archivo, pero si tuviéramos más, tendríamos que agregar esta línea a cada archivo de pruebas. Para evitar eso, podemos unar un `spec_helper`.
Primero necesitamos crear un archivo `spec_helper.rb` en nuestro directorio `spec`.
~~~
fizz_buzz_rspec
├── lib
│ └── fizz_buzz.rb
└── spec
├── fizz_buzz_spec.rb
└── spec_helper.rb
~~~
Ahora necesitamos cambiar el archivo de pruebas.
~~~ruby
#spec/fizz_buzz_spec.rb
require 'spec_helper'
require 'fizz_buzz'
describe FizzBuzz do
Given(:fizz_buzz) { FizzBuzz.new }
When(:result) { fizz_buzz.convert(1) }
Then { result == '1' }
end
~~~
Si lo ejecutamos ahora, se ejecuta correctamente. No importa dónde está nuestro archivo de pruebas (por ejemplo, podría estar en `spec/models/inbox/fizz_buzz_spec.rb`), siempre podrá requerir el archivo `spec_helper` con `require 'spec_helper'`.
En proyectos más grandes, la ventaja de un archivo `spec_helper` es más notorio. Veamos un archivo `spec_helper` de Rails, sólo como ejemplo:
~~~ruby
#rails_project/spec/spec_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'shoulda-matchers'
require 'rspec/autorun'
RSpec.configure do |config|
config.use_transactional_fixtures = true
config.order = "random"
end
~~~
Carga todas las bibliotecas que necesita para trabajar y configura RSpec para usar _fixtures_ transaccionales y ejecutar las pruebas en orden aleatorio.
Nota que en esta ocasión, `spec_helper` es sólo un archivo más, puede ser nombrado de diferente manera y seguirá funcionando siempre y cuando sea requerido con el nombre correcto.
## Minitest
Minitest nos permite nombrar nuestros directorios de la forma que queramos, pero necesitamos tenerlo en cuenta porque es importante cuando ejecutemos nuestras pruebas.
Sólo para seguir las convenciones, creé el proyecto con una estructura muy similar a la de RSpec.
~~~
fizz_buzz_minitest
├── lib
│ └── fizz_buzz.rb
└── test
└── fizz_buzz_test.rb
~~~
El contenido de los archivos:
~~~ruby
#test/fizz_buzz_test.rb
require 'minitest/autorun'
require 'fizz_buzz'
describe FizzBuzz do
it 'returns "1" when receives 1' do
assert '1', FizzBuzz.new.convert(1)
end
end
#lib/fizz_buzz.rb
class FizzBuzz
def convert(n)
'1'
end
end
~~~
Lo primero que me gustaría señalar es que en Minitest es obligatorio requerir la bibilioteca Minitest, específicamente `minitest/autorun`, que provee de todo lo que necesitamos para ejecutar la prueba (por ejemplo, los métodos de aserciones y la capacidad de que el archivo se ejecute automáticamente). Nota que estoy usando la sintaxis _spec_ aquí, pero también es posible usar la clásica sintaxis de minitest. Puedes ver un poco de las bases en el post de la [Kata Minitest: Rompiendo la parálisis inicial](/2015/05/01/kata-minitest-rompiendo-la-paralisis-inicial.html).
Ahora, tristemente, no tenemos un comando `minitest` para ejecutar, como lo teníamos con RSpec. Minitest is un framework de pruebas muy básico (pero muy poderoso). Una de sus fortalezas es que que no es un DSL como RSpec, sino Ruby puro (aunque por la sintaxis que estamos usando nostros, sí hacemos uso de un DSL). De cualquier forma, para ejecutar nuestras pruebas, solo necesitamos ejecutar Ruby.
~~~
[fizz_buzz_minitest]$ ruby test/fizz_buzz_test.rb
[...]core_ext/kernel_require.rb:54:in `require': cannot load such file -- fizz_buzz (LoadError)
...
from test/fizz_buzz_test.rb:1:in `<main>'
~~~
Humm, al parecer, sí ejecutó algo, pero no funcionó correctamente. Lo que pasó aquí es que no fue posible cargar el archivo `fizz_buzz`. Afortunadamente, es algo fácil de solucionar. Ruby incluye `require_relative` para requerir un archivo especificando una ruta relativa. Esta ruta debe ser construida con base en la ruta del archivo actual. En nuestro caso, nuestro archivo de pruebas está dentro de un directorio `test`, así que tenemos que indicar que nos moveremos un directorio atrás (esto se hace con dos puntos `..`) para llegar al directorio base del proyecto y entonces agregar la ruta al archivo requerido.
Nuestro archivo de prueba ahora se ve de esta manera:
~~~ruby
#test/fizz_buzz_test.rb
require 'minitest/autorun'
require_relative '../lib/fizz_buzz'
describe FizzBuzz do
it 'returns "1" when receives 1' do
assert '1', FizzBuzz.new.convert(1)
end
end
~~~
Podemos ejecutar nuestras pruebas de nuevo.
~~~
[fizz_buzz_minitest]$ ruby test/fizz_buzz_test.rb
Run options: --seed 21470
# Running:
.
Finished in 0.000718s, 1393.3787 runs/s, 1393.3787 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
~~~
Ahora funciona. Nota que el comando se debe ejecutar desde el directorio base del proyecto, no desde `lib` o `test`.
Sin embargo, hay un pequeño problema con esta aproximación. Si reordenamos la estructura de directorios, ya sea `test` o `lib`, necesitaremos cambiar también las rutas relativas que hayamos utilizado. Por ejemplo:
~~~
fizz_buzz_minitest
├── lib
│ └── models
│ └── fizz_buzz.rb
└── test
└── models
└── fizz_buzz_test.rb
~~~
Entonces necesitamos cambiar la ruta relativa a:
~~~ruby
require_relative '../../lib/models/fizz_buzz'
~~~
En nuestro ejemplo, tenemos sólo un archivo, pero en un proyecto real, esto sería un gran problema.
Afortunadamente, tenemos una alternativa. Podemos ejecutar nuestra archivo de pruebas especificando en la línea de comandos dónde debe Ruby buscar los archivos requeridos. Es decir, desde la línea de comandos podemos indicar que directorios deben ser precargados. Con nuestra estructua inicial, podemos ejecutar la prueba de esta manera:
~~~
[fizz_buzz_minitest]$ ruby -I lib test/fizz_buzz_test.rb
Run options: --seed 2633
# Running:
.
Finished in 0.000820s, 1220.1178 runs/s, 1220.1178 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
~~~
Usamos la opción `-I`, indicando que Ruby debe cargar de inicio el directorio `lib`.
Nota que con minitest, no importa cómo se nombran los directorios, simplemente funciona. Ejemplo:
~~~
fizz_buzz_minitest
├── my_own_directory
│ └── fizz_buzz.rb
└── my_testing_directory
└── fizz_buzz_test.rb
~~~
Ejecutamos la prueba:
~~~
[fizz_buzz_minitest]$ ruby -I my_own_directory test/fizz_buzz_testing_file.rb
Run options: --seed 31542
# Running:
.
Finished in 0.000719s, 1389.9584 runs/s, 1389.9584 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
~~~
Todo funciona. Esto es porque no estamos ejecutando el conjunto completo de pruebas, como lo hacemos con RSpec. En este aso, estamos sólo ejecutando un archivo y especificamos qué directorio debe ser cargado.
### `test_helper`
De la misma manera que usamos un archivo `spec_helper`, podemos usar un `test_helper` en minitest. Nota que el nombre del archivo no importa, pero `test_helper` es un nombre ampliamente usado cuando se trabaja con minitest.
Podemos crear un archivo `test_helper.rb` en nuestro directorio `test`.
~~~
fizz_buzz_minitest
├── lib
│ └── fizz_buzz.rb
└── test
├── fizz_buzz_test.rb
└── test_helper.rb
~~~
El contenido de nuestro `test_helper` será un poco mejor que el `spec_helper`, porque ahora podemos agregar un poco de código al menos.
~~~ruby
require 'minitest/autorun'
require 'minitest/pride'
~~~
Extrajimos el `rquire` del autorun de Minitest al `test_helper`, y además requerimos `pride`, una pequeña biblioteca de Minitest que colorea la salida.
Ahora necesitamos cambiar el `require` de nuestro archivo de pruebas.
~~~ruby
#spec/fizz_buzz_test.rb
require 'test_helper'
require 'fizz_buzz'
describe FizzBuzz do
it 'returns "1" when receives 1' do
assert '1', FizzBuzz.new.convert(1)
end
end
~~~
Y tratamos de ejecutarlo:
~~~
[fizz_buzz_minitest]$ ruby -I lib test/fizz_buzz_test.rb
[...]core_ext/kernel_require.rb:54:in `require': cannot load such file -- test_helper (LoadError)
...
from spec/fizz_buzz_test.rb:1:in `<main>'
~~~
Ups, algo falló.
La razón es que el archivo requerido no pudo se cargado. Indicamos a Ruby que debía cargar el directorio `lib`, pero `test_helper` no está ahí, sino en el directorio `test`. Bien, para este caso, podemos usar `require_relative`, pero podemos tener el mismo problema potencial: si movemos los archivos a otros directorios, todos las rutas pasadas a `require_relative` deben ser actualizadas también.
De nuevo, la mejor opción es especificar que Ruby debe cargar otro directorio cuando ejecute nuestro archivo de prueba. Podemos hacerlo agregando el directorio `test` a la lista (separado por dos puntos `:`).
~~~
[fizz_buzz_minitest]$ ruby -I lib:test test/fizz_buzz_test.rb
Run options: --seed 64180
# Running:
.
Fabulous run in 0.000797s, 1254.2865 runs/s, 1254.2865 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
~~~
Y... todo funciona de nuevo.
Como podemos ver, Minitest no asume una estructura de directorios específica porque podemos indicar sus dependencias como opciones en línea de comandos. Sin embargo, se recomienda usar la estructura que hemos visto aquí porque es una muy difundida. Cualquier desarrollador podría imaginar dónde encontrar qué archivos y es fácil de crecer si queremos usar rake (por ejemplo) para ejecutar nuestras pruebas en lotes. Aunque esto último es un tema que dejaremos para un siguiente post.
| 3819299329ee24e832f1d446c6bc43f7d7f79500 | [
"Markdown",
"JavaScript",
"Ruby"
] | 44 | Markdown | oaxacarb/oaxacarb.github.io | abda60d59acb988d7c64e9c81c422f5e27fb558f | 391dd45b9675b88627db698767b2fa83987a3c1d |
refs/heads/main | <repo_name>nishu123a/hospitalmanagementsystem<file_sep>/hospital1/patientupdate.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hospital</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style_donors.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="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<!--navbar-->
<center><h1 style='background-color:skyblue;color:blue;font-size:50px;margin:0px;'>Welcome to the Patient management system<h1></center>
<?php
require('dbconnect.php');
if(isset($_POST['updated'])){
$email = $_POST['did'];
$exist="select * from register where Email = '$email' ";
$q="UPDATE register SET status = 'N/A' WHERE Email = '$email'";
$qt=mysqli_query($connect,$exist);
$r=mysqli_num_rows($qt);
if($r>0 && $connect->query($q)){
echo "<html>
<body style='vertical-align:top;'>
<div class='alert alert-success alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Success!</strong> Status updated.
</div>
</body>
</html>";
}
else{
echo " <html>
<body style='vertical-align:top;'>
<div class='alert alert-danger alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Warning!</strong> Patient doesn't exist with the given email.
</div>
</body>
</html>";
}
}
?>
<!--form-->
<div class="container" >
<div class="col-md-12">
<div class="row w3-border-bottom">
<div><h1 style="text-align: center;">Update Patient</h1></div>
</div>
<form action="patientupdate.php" method="post" style="margin-left: 300px;width:80%;">
<div class ="row">
<div class="col-md-6">
<div class="col-md-10" >
<div class="form-group">
<label>Patient Email</label>
<input type="text" class="form-control input-lg" id="did" name="did" placeholder="Enter ID" required>
</div>
<div class="form-group">
<label>status</label>
<input type="text" class="form-control input-lg" id="status" name="status" placeholder="Enter status" required>
</div>
<button type="submit" class="btn" style="margin-left:70px;" name='removed' >Update Patient</button>
</div>
</div>
</div>
</form>
</div>
</div><br>
</body>
</html><file_sep>/hospital1/patientadd.php
<!DOCTYPE html>
<html lang="en">
<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>register</title>
<link rel="stylesheet"href="registration.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="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<?php
require('dbconnect.php');
if(isset($_POST['rsubmit'])){
$name=$_POST['name'];
$age=$_POST['age'];
$email=$_POST['email'];
$phone=$_POST['phoneno'];
$password=$_POST['password'];
$gender=$_POST['gender'];
$write = "INSERT INTO register(Name,Age,Mobile,Email,Password,Gender) VALUES ('$name', '$age', '$phone', '$email', '$password', '$gender')";
$duplicate="select * from register where Email='$email'";
$q=mysqli_query($connect,$duplicate);
$r=mysqli_num_rows($q);
if($r>0){
echo " <html>
<body style='display: inline-block;vertical-align: top;'>
<div class='alert alert-danger alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Warning!</strong> Patient Already exists with the given email.
</div>
</body>
</html>";
}
else{
if($connect->query($write))
echo " <html>
<body style='display: inline-block;vertical-align: top;'>
<div class='alert alert-success alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Success!</strong> registered as a Patient.
</div>
</body>
</html>";
}
}
?>
<div class="container">
<div class="title">Add Patient </div>
<div class="content">
<form action="patientadd.php" method='post'>
<div class="user-details">
<div class="input-box">
<span class="details">Full Name</span>
<input type="text" name="name" placeholder="Enter your name" required>
</div>
<div class="input-box">
<span class="details">Age</span>
<input type="text" name="age" placeholder="Enter your age" required>
</div>
<div class="input-box">
<span class="details">Email</span>
<input type="email" name="email" placeholder="Enter your email" required>
</div>
<div class="input-box">
<span class="details">Phone Number</span>
<input type="number" name="phoneno" placeholder="Enter your number" required>
</div>
<div class="input-box">
<span class="details">Password</span>
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" required>
</div>
<div class="input-box">
<span class="details">Confirm Password</span>
<input type="password" name="cpassword" placeholder="Confirm your password" required>
</div>
</div>
<div class="gender-details">
<input type="radio" name="gender" id="dot-1" value='m'>
<input type="radio" name="gender" id="dot-2" value='f'>
<input type="radio" name="gender" id="dot-3" value='-'>
<span class="gender-title">Gender</span>
<div class="category">
<label for="dot-1">
<span class="dot one"></span>
<span class="gender">Male</span>
</label>
<label for="dot-2">
<span class="dot two"></span>
<span class="gender">Female</span>
</label>
<label for="dot-3">
<span class="dot three"></span>
<span class="gender">Prefer not to say</span>
</label>
</div>
</div>
<div class="button">
<input type="submit" name="rsubmit" value="Register">
</div>
</form>
</div>
</div>
</body>
</html>
<file_sep>/hospital1/appointment.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hospital</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style_donors.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="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<style>
body{
background: linear-gradient(to bottom, #3366ff 0%, #3333cc 100%);
}
</style>
<body>
<?php
require('dbconnect.php');
if(isset($_POST['requestm'])){
$check1='select* from appointment';
$q1=mysqli_query($connect,$check1);echo "<center><h1 style='background-color:#00004d;color:wheat;font-size:50px;margin:0;'>Welcome to the Hospital management system<h1><br>
<h3 style='backkground-color:#00004d;color:white;'>APPOINTMENT INFORMATION</h3><br><br><br><br><br><br>";
echo " <table id='myTable1' class='table table-striped table-bordered' style='width:80%;margin-left: 30px;margin-top: -200px;'>
<thead style='font-size:20px; background-color:#00004d:color:wheat;'>
<tr>
<th>Patientname</th>
<th>Doctorid</th>
<th>Status</th>
<th>Patientid</th>
<th>Paintentphone</th>
<th>Doctorphone</th>
<th>Appointmenttime</th>
<th>Appointmentdate</yth>
</tr>
</thead>";
while($row1=mysqli_fetch_array($q1)){
echo("<tr style='font-size:18px;'><th>" .$row1['Patientname']."</th><th>".$row1['Doctorid']."</th><th>".$row1['Status']."</th><th>".$row1['Patientid']."</th><th>".$row1['Patientphone']."</th><th>".$row1['Doctorphone']."</th><th>".$row1['Appointmenttime']."</th><th>".$row1['Appointmentdate']."</th><br><br>");
}
echo "</table><br><br><br>";
echo "</table><br><br><br>";
echo " <center>
<table>
<form action='patientadd.php' method='POST'>
<tr>
<input type='submit' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;' value='Add new Patient' name='addpatient'>
</tr>
</form>
<form action='patientdelete.php' method='POST'>
<tr>
<input type='submit' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;' value='Remove Patient' name='removepatientr'>
</tr>
</form>
<form action='uppatient.php' method='POST'>
<tr>
<input type='submit' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;' value='Update Patient' name='updatepatient'>
</tr>
</form>
<form action='index.html' method='POST'>
<tr>
<input type='submit' value='Go To Home Page' name='homepg' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;'>
</tr>
</form>
</table>
</center><br><br>";
}
?>
<file_sep>/hospital1/managedoc.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hospital</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style_donors.css">
<link rel="stylesheet" href="registration.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="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<?php
require('dbconnect.php');
//doctor
if(isset($_POST['daddp'])){
$did = $_POST['did'];
$exist="select * from doctordata where Doctorid = '$did' ";
$q="UPDATE doctordata SET Status = '$_POST[status]',Name='$_POST[name]',Email='$_POST[email]',Phoneno='$_POST[phone]',Department='$_POST[department]' WHERE Doctorid = '$did'";
$qt=mysqli_query($connect,$exist);
$r=mysqli_num_rows($qt);
if($r>0 && $connect->query($q)){
echo "<html>
<body style='vertical-align:top;display:inline-block;'>
<div class='alert alert-success alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Success!</strong> Status updated.
</div>
</body>
</html>";
}
else{
echo " <html>
<body style='verical-align:top;display:inline-block;'>
<div class='alert alert-danger alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Warning!</strong> Doctor doesn't exist with the given Id.
</div>
</body>
</html>";
}
}
?>
<div class="container">
<div class="title"> Update Profile</div>
<div class="content">
<form action="managedoc.php" method='post'>
<div class="user-details">
<div class="input-box">
<span class="details">Full Name</span>
<input type="text" name="name" placeholder="Enter your name" required>
</div>
<div class="input-box">
<span class="details">Id</span>
<input type="text" name="did" placeholder="Enter your id" required>
</div>
<div class="input-box">
<span class="details">Status</span>
<input type="text" name="status" placeholder="Enter status" required>
</div>
<div class="input-box">
<span class="details">Department</span>
<input type="text" name="department" placeholder="Enter Department" required>
</div>
<div class="input-box">
<span class="details">Phone</span>
<input type="number" name="phone" placeholder="Enter Department" required>
</div>
<div class="input-box">
<span class="details">Email </span>
<input type="email" name="email" placeholder="Enter Department" required>
</div>
</div>
<div class="button">
<input type="submit" name="daddp" value="Update">
</div>
</form>
</div>
</div>
</body>
</html>
<file_sep>/hospital1/Nursedelete.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Nurse</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style_donors.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="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<style>
body{
background: #4d4dff;
}
</style>
</head>
<body>
<!--navbar-->
<center><h1 style='background-color:#00004d;color:white;font-size:45px;margin:0;'>Welcome to the Nurse management system<h1></center>
<?php
require('dbconnect.php');
if(isset($_POST['removen'])){
$nid = $_POST['nid'];
$exist="select * from nurse where Nurseid = '$nid' ";
$q="delete from nurse where Nurseid = '$nid' ";
$qt=mysqli_query($connect,$exist);
$r=mysqli_num_rows($qt);
if($r>0 && $connect->query($q)){
echo "<html>
<body style='float:top;'>
<div class='alert alert-success alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Success!</strong> Data removed.
</div>
</body>
</html>";
}
else{
echo " <html>
<body style='float:top;'>
<div class='alert alert-danger alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Warning!</strong> Nurse doesn't exist with the given Id.
</div>
</body>
</html>";
}
}
?>
<!--form-->
<div class="container" >
<div class="col-md-12">
<div class="row w3-border-bottom">
<center><h1 style="text-align: center;display:inline;color:white;background:#00004d;border-radius:4px;">Remove Nurse</h1></center>
</div>
<form action="Nursedelete.php" method="post" style="margin-left: 300px;width:80%;">
<div class ="row">
<div class="col-md-6">
<div class="col-md-10" >
<div class="form-group">
<label style="color:#00004d">Nurse ID</label>
<input type="text" class="form-control input-lg" id="id" name="nid" placeholder="Enter ID" required style="background:#00004d;color:white;">
</div>
<button type="submit" class="btn" style="margin-left:70px;color:white;background:#00004d;" name='removen' >Remove Nurse</button>
</div>
</div>
</div>
</form>
</div>
</div><br>
</body>
</html><file_sep>/hospital1/manage.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hospital</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style_donors.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="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<style>
body{
background: linear-gradient(to left, #3333ff 0%, #6699ff 100%);
}
</style>
</head>
<body>
<?php
require('dbconnect.php');
if(isset($_POST['donorm'])){
$check1='select* from doctordata';
$q1=mysqli_query($connect,$check1);
echo "<center><h1 style='margin:0; background:linear-gradient(to bottom, #000099 0%, #000066 100%);color:wheat;font-size:50px;margin:0;'>Welcome to the Doctor management system<h1><br>
<h3 style='color:wheat;background: linear-gradient(to bottom, #000099 0%, #000066 100%); width:40px,height:60px;'>DOCTOR AND THEIR INFORMATION</h3><br><br><br><br><br><br> ";
echo " <table id='myTable1' class='table table-striped table-bordered' style='width:80%;margin-left: 30px;margin-top: -50%;'>
<thead style='font-size:20px; background-color:#00004d;color:wheat;'>
<tr>
<th>Name</th>
<th>Doctorid</th>
<th>Status</th>
<th>Department</th>
<th>Phone</th>
<th>Email</th>
</tr>
</thead>";
while($row1=mysqli_fetch_array($q1)){
echo("<tr style='font-size:18px;'><th>" .$row1['Name']."</th><th>".$row1['Doctorid']."</th><th>".$row1['Status']."</th><th>".$row1['Department']."</th><th>".$row1['Phoneno']."</th><th>".$row1['Email']."</th><br><br>");
}
echo "</table><br><br><br>";
echo " <center>
<table>
<form action='doctoradd.php' method='POST'>
<tr>
<input type='submit' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;' value='Add new Doctor' name='addpatient'>
</tr>
</form>
<form action='doctorremove.php' method='POST'>
<tr>
<input type='submit' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;' value='Remove Doctor' name='removepatientr'>
</tr>
</form>
<form action='doctorupdate.php' method='POST'>
<tr>
<input type='submit' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;' value='Update Doctor' name='updatepatient'>
</tr>
</form>
<form action='index.html' method='POST'>
<tr>
<input type='submit' value='Go To Home Page' name='homepg' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;'>
</tr>
</form>
</table>
</center><br><br>";
}
//nurse
else if(isset($_POST['rem'])){
$check1='select * from nurse';
$q1=mysqli_query($connect,$check1);
echo "<center><h1 style='background-color:#00004d;margin:0;color:wheat;font-size:50px;'>Welcome to the Nurse management system<h1><br>
<h3 style='color:wheat;bakground;color:#00004d;'>NURSE AND THEIR INFORMATION</h3><br><br><br><br><br><br>";
echo " <table id='myTable1' class='table table-striped table-bordered' style='width:80%;margin-left: 30px;margin-top: -35%;'>
<thead style='font-size:20px; background-color:#00004d;color:wheat;'>
<tr>
<th>Name</th>
<th>Nurseid</th>
<th>status</th>
</tr>
</thead>";
while($row1=mysqli_fetch_array($q1)){
echo("<tr style='font-size:18px;'><th>" .$row1['Name']."</th><th>".$row1['Nurseid']."</th><th>".$row1['status']."</th><br><br>");
}
echo "</table><br><br><br>";
echo " <center>
<table>
<form action='Nurseadd.php' method='POST'>
<tr>
<input type='submit' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;' value='Add new Nurse' name='addpatient'>
</tr>
</form>
<form action='Nursedelete.php' method='POST'>
<tr>
<input type='submit' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;' value='Remove Nurse' name='removepatientr'>
</tr>
</form>
<form action='Nurseupdate.php' method='POST'>
<tr>
<input type='submit' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;' value='Update Nurse' name='updatepatient'>
</tr>
</form>
<form action='index.html' method='POST'>
<tr>
<input type='submit' value='Go To Home Page' name='homepg' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;'>
</tr>
</form>
</table>
</center><br><br>";
}
//patient
else if(isset($_POST['requestm'])){
$check1='select * from register';
$q1=mysqli_query($connect,$check1);
echo "<center><h1 style='background:#00004d;margin:0;color:wheat;font-size:50px;'>Welcome to the Patient management system<h1><br>
<h3 style='color:wheat;background: linear-gradient(to bottom, #000099 0%, #000066 100%); width:40px,height:60px;'>PATIENTS AND THEIR INFORMATION</h3><br><br><br><br><br><br>";
echo " <table id='myTable1' class='table table-striped table-bordered' style='width:80%;margin-left: 30px;margin-top:-35%;'>
<thead style='font-size:20px; background-color:#00004d;color:wheat;'>
<tr>
<th>Name</th>
<th>Age</th>
<th>Mobile</th>
<th>Email</th>
<th>Password</th>
<th>Gender</th>
</tr>
</thead>";
while($row1=mysqli_fetch_array($q1)){
echo("<tr style='font-size:18px;'><th>" .$row1['Name']."</th><th>".$row1['Age']."</th><th>".$row1['Mobile']."</th><th>".$row1['Email']."</th><th>".$row1['Password']."</th><th>".$row1['Gender']."</th><br><br>");
}
echo "</table><br><br><br>";
echo " <center>
<table>
<form action='patientadd.php' method='POST'>
<tr>
<input type='submit' style='background-color:#00004d;color:wheat;font-size:15px;color:wheat;padding:12px 14px;' value='Add new Patients' name='addpatient'>
</tr>
</form>
<form action='patientdelete.php' method='POST'>
<tr>
<input type='submit' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;' value='Remove Patients' name='removepatientr'>
</tr>
</form>
<form action='uppatient.php' method='POST'>
<tr>
<input type='submit' style='background-color:#00004d;font-size:15px;color:wheat;padding:12px 14px;' value='Update Patients' name='updatepatient'>
</tr>
</form>
<form action='index.html' method='POST'>
<tr>
<input type='submit' value='Go To Home Page' name='homepg' style='background-color:#00004d;font-size:15px;color:white;padding:12px 14px;'>
</tr>
</form>
</table>
</center><br><br>";
}
?>
<footer class="foo" >Your safety,our priority</footer>
</html><file_sep>/hospital1/doctoradd.php
<!DOCTYPE html>
<html lang="en">
<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>doctoradd</title>
<link rel="stylesheet"href="registration.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="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
</body>
<?php
require('dbconnect.php');
if(isset($_POST['daddp'])){
$name=$_POST['name'];
$did=$_POST['id'];
$status=$_POST['status'];
$depart=$_POST['department'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$write = "INSERT INTO doctordata(Name,Doctorid,Status,Department,Phoneno,Email) VALUES ('$name', '$did', '$status', '$depart','$phone','$email')";
$duplicate="select * from doctordata where Doctorid='$did'";
$q=mysqli_query($connect,$duplicate);
$r=mysqli_num_rows($q);
if($r>0){
echo " <html>
<body style='display: inline-block;vertical-align: top;'>
<div class='alert alert-danger alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Warning!</strong> Doctors Already exists with the given Id.
</div>
</body>
</html>";
}
else{
if($connect->query($write))
echo " <html>
<body style='display: inline-block;vertical-align: top;'>
<div class='alert alert-success alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Success!</strong> registered as a Doctors.
</div>
</body>
</html>";
}
}
?>
<div class="container">
<div class="title"> Add Doctor</div>
<div class="content">
<form action="doctoradd.php" method='post'>
<div class="user-details">
<div class="input-box">
<span class="details">Full Name</span>
<input type="text" name="name" placeholder="Enter your name" required>
</div>
<div class="input-box">
<span class="details">Id</span>
<input type="text" name="id" placeholder="Enter your id" required>
</div>
<div class="input-box">
<span class="details">Status</span>
<input type="text" name="status" placeholder="Enter status" required>
</div>
<div class="input-box">
<span class="details">Department</span>
<input type="text" name="department" placeholder="Enter Department" required>
</div>
<div class="input-box">
<span class="details">Phone</span>
<input type="text" name="phone" placeholder="Enter phone" required>
</div>
<div class="input-box">
<span class="details">Email </span>
<input type="text" name="email" placeholder="Enter Email" required>
</div>
</div>
<div class="button">
<input type="submit" name="daddp" value="Add Doctor">
</div>
</form>
</div>
</div>
</html>
<file_sep>/hospital1/doctlogin.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hospital</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{
background: linear-gradient(to left, #3333ff 0%, #6699ff 100%);
margin:0px;
}
</style>
</head>
<body>
<nav style='background-color:#0f0f3d;overflow:hidden;border:2px solid blue;margin:0px'>
<a href="index.html" style='display:block;margin:0px;color:wheat; padding:14px 30px;float:left;font-size:xx-large;text-decoration:none'>Home</a>
<a href="About.html" style='display:block;margin:0px;color:wheat; padding:14px 30px;float:left;font-size:xx-large;text-decoration:none'>About us</a>
<a href="contact.php" style='display:block;margin:0px;color:wheat; padding:14px 30px;float:left;font-size:xx-large;text-decoration:none'>Contact us</a>
<a href="patientlogin.php" style='display:block;margin:0px;color:wheat; padding:14px 30px;float:left;font-size:xx-large;text-decoration:none'>Patient Login</a>
<a href="logindoc.php" style='display:block;margin:0px;color:wheat; padding:14px 30px;float:left;font-size:xx-large;text-decoration:none'>Doctors Login</a>
<a href="alogin.php" style='display:block;margin:0px;color:wheat; padding:14px 30px;float:left;font-size:xx-large;text-decoration:none;'>Admin Login</a>
</nav>
<?php
require('dbconnect.php');
if(isset($_POST['dlogin'])){
$email=$_POST['email'];
$password=$_POST['password'];
$query="select * from doctorlogin where Email='$email' and Password='$password'";
$q = mysqli_query($connect , $query);
$row=mysqli_num_rows($q);
if($row>0){
echo " <center style='width:400px;left:50%;position:absolute;top:50%;border-radius:10px; background: linear-gradient(to bottom, #66ccff 0%, #3333cc 100%);transform:translate(-50%,-50%)'>
<h1 style='text-align:center;padding:0px 0px 20px 0px;color:#00004d;'> Doctor<h1>
<form action='managedoc.php' method='POST'style='padding:0px 40px;box-sizing:border-box;'>
<table style='padding: 0 20px 30px;'>
<tr>
<td>
<input type='submit' value='My profile' name='donorm' style='background:#00004d;color:wheat;border-radius:30px;padding: 10px 30px'>
</td>
</tr>
</form>
<form action='appointment.php' method='POST'style='padding:0px 40px;box-sizing:border-box;'>
<tr>
<td>
<input type='submit' value='My Appointment' name='requestm' style='background:#00004d;color:wheat;border-radius:30px;padding: 10px 30px'>
</td>
</tr>
</form>
</center>";
}
else{
echo "<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Nunito+Sans:400,400i,700,900&display=swap' rel='stylesheet'>
</head>
<style>
body {
text-align: center;
padding: 40px 0;
background: #EBF0F5;
}
h1 {
color: #850303;
font-family: 'Nunito Sans', 'Helvetica Neue', sans-serif;
font-weight: 900;
font-size: 40px;
margin-bottom: 10px;
}
p {
color:#850303;
font-family: 'Nunito Sans", "Helvetica Neue', sans-serif;
font-size:20px;
margin: 0;
}
i {
color: #850303;
font-size: 100px;
line-height: 200px;
margin-left:-15px;
}
.card {
background: white;
padding: 60px;
border-radius: 4px;
box-shadow: 0 2px 3px #C8D0D8;
display: inline-block;
margin: 0 auto;
}
</style>
<body>
<div class='card'>
<div style='border-radius:200px; height:200px; width:200px; background: #ffcccc; margin:0 auto;'>
<i class='checkmark'>×</i>
</div>
<h1>Warning</h1>
<p>Invalid Username Or Password!</p>
<br><br>
<center><form action='logindoc.php' method='post'> <input type='submit' value ='Go to Login Page' style='color: white;padding: 15px 32px;text-align: center;text-decoration: none;font-size: 16px;margin: 4px 2px;border-radius: 10px;background-color:#004280;border:none;border-bottom: 2px solid black;'> </form></center>
</div>
</body>
</html>";
}
}
?><file_sep>/hospital1/contact.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hospital</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="contact.css">
<style>
body{
background: linear-gradient(to left, #3333ff 0%, #6699ff 100%);
margin:0px;
}
</style>
</head>
<body>
<nav style='background-color:#0f0f3d;overflow:hidden;border:2px solid blue;margin:0px'>
<a href="index.html" style='display:block;margin:0px;color:wheat; padding:7px 14px;float:left;font-size:xx-large;text-decoration:none'>Home</a>
<a href="About.html" style='display:block;margin:0px;color:wheat; padding:7px 15px;float:left;font-size:xx-large;text-decoration:none'>About us</a>
<a href="contact.php" style='display:block;margin:0px;color:wheat; padding:7px 15px;float:left;font-size:xx-large;text-decoration:none'>Contact us</a>
<a href="patientlogin.php" style='display:block;margin:0px;color:wheat; padding:7px 15px;float:left;font-size:xx-large;text-decoration:none'>Patient Login</a>
<a href="logindoc.php" style='display:block;margin:0px;color:wheat; padding:7px 14px;float:left;font-size:xx-large;text-decoration:none'>Doctors Login</a>
<a href="alogin.php" style='display:block;margin:0px;color:wheat; padding:7px 14px;float:left;font-size:xx-large;text-decoration:none;'>Admin Login</a>
</nav>
<?php
require('dbconnect.php');
if(isset($_POST['sendp'])){
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phoneno'];
$msg=$_POST['msg'];
$write = "INSERT INTO contactdata(name,phoneno,email,msg) VALUES ('$name', '$phone', '$email', '$msg')";
$duplicate="select * from contactdata where Email='$email'";
$q=mysqli_query($connect,$duplicate);
$r=mysqli_num_rows($q);
if($r>0){
echo " <html>
<body style='display: inline-block;vertical-align: top;'>
<div class='alert alert-danger alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Warning!</strong>This email has already sent a query.
</div>
</body>
</html>";
}
else{
if($connect->query($write))
echo " <html>
<body style='display: inline-block;vertical-align: top;'>
<div class='alert alert-success alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Success!</strong> Your query has been sent. We will reach out to you soon.
</div>
</body>
</html>";
}
}
?>
<div class="container">
<h1 style="color:#00004d;">Connect with us</h1>
<p>We would love to respond to your queries and help you succeed.Feel free to get in touch with us</p>
<div class="contact-box">
<div class="contact-left">
<h3>Send Your Request</h3>
<form action="contact.php" method='post'>
<div class="input-row">
<div class="input-group">
<label>Name</label>
<input type="text" name="name" placeholder="<NAME>">
</div>
<div class="input-group">
<label>Phone</label>
<input type="number" name="phoneno"placeholder ="+91 9894568876">
</div>
</div> <div class="input-row">
<div class="input-group">
<label>Email</label>
<input type="email" name="email" placeholder="<EMAIL>">
</div>
</div>
<label>Message</label>
<textarea name="msg" rows="5" placeholder="Your Message"></textarea>
<button type="submit" name="sendp">Send</button>
</form>
</div>
<div class="contact-right">
<h3>Reach Us</h3>
<table>
<tr>
<td>Email</td>
<td><EMAIL></td>
</tr>
<tr>
<td>Phone</td>
<td>+91 9568993945</td>
</tr>
<tr>
<td>Address</td>
<td>kalamessary,kochi,kerala</td>
</tr>
</table>
</div>
</div>
</div>
</html><file_sep>/hospital1/Nurseadd.php
<!DOCTYPE html>
<html lang="en">
<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>register</title>
<link rel="stylesheet"href="registration.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="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<?php
require('dbconnect.php');
if(isset($_POST['naddp'])){
$name=$_POST['name'];
$nid=$_POST['id'];
$status=$_POST['status'];
$write = "INSERT INTO nurse(Name,Nurseid,status) VALUES ('$name', '$nid', '$status')";
$duplicate="select * from nurse where Nurseid='$nid'";
$q=mysqli_query($connect,$duplicate);
$r=mysqli_num_rows($q);
if($r>0){
echo " <html>
<body style='display: inline-block;vertical-align: top;'>
<div class='alert alert-danger alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Warning!</strong> Nurse Already exists with the given id.
</div>
</body>
</html>";
}
else{
if($connect->query($write))
echo " <html>
<body style='display: inline-block;vertical-align: top;'>
<div class='alert alert-success alert-dismissible'>
<a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>
<strong>Success!</strong> registered as a Nurse.
</div>
</body>
</html>";
}
}
?>
<div class="container">
<div class="title"> Nurse Registration</div>
<div class="content">
<form action="Nurseadd.php" method='post'>
<div class="user-details">
<div class="input-box">
<span class="details">Full Name</span>
<input type="text" name="name" placeholder="Enter your name" required>
</div>
<div class="input-box">
<span class="details">Id</span>
<input type="text" name="id" placeholder="Enter your id" required>
</div>
<div class="input-box">
<span class="details">Status</span>
<input type="text" name="status" placeholder="Enter status" required>
</div>
</div>
<div class="button">
<input type="submit" name="naddp" value="Register">
</div>
</form>
</div>
</div>
</body>
</html><file_sep>/hospital1/dbconnect.php
<?php
$connect = mysqli_connect('localhost', 'root', '','hospital') or die(mysqli_connect_error());
?> | 1301566e3fad217ce0638817cd7373e8295bcdbb | [
"PHP"
] | 11 | PHP | nishu123a/hospitalmanagementsystem | 058894de4d866451bad12ad44569aafea430cd6d | ba036d32c8ea4740d7dc910e0988b7526537690c |
refs/heads/main | <repo_name>kennethmartingagno/inventory-flask<file_sep>/db.py
import sqlite3
conn = sqlite3.connect("storage.db")
cur = conn.cursor()
conn.execute("PRAGMA FOREIGN_KEYS = 1")
conn.execute("""CREATE TABLE Sales (
transaction_datetime DATETIME DEFAULT CURRENT_TIMESTAMP,
code_id INTEGER PRIMARY KEY
)""")
conn.execute("""CREATE TABLE Coffee (
size TEXT NOT NULL,
type TEXT NOT NULL,
quantity INTEGER NOT NULL,
id INTEGER PRIMARY KEY AUTOINCREMENT,
code_id INTEGER,
FOREIGN KEY (code_id) REFERENCES Sales (code_id)
)""")
conn.execute("""CREATE TABLE Inventory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
size TEXT NOT NULL,
type TEXT NOT NULL,
quantity INTEGER NOT NULL
)""")
conn.execute("""CREATE TABLE Users (
username TEXT,
password <PASSWORD>
)""")
conn.close()<file_sep>/main.py
from flask import Flask, render_template, request, redirect, url_for, flash
import sqlite3
app = Flask(__name__)
app.config['SECRET_KEY'] = 'MMCAXcUQxV'
@app.route("/")
def login():
return render_template("login.html")
@app.route("/login-user", methods=['POST', 'GET'])
def login_user():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
with sqlite3.connect("storage.db") as conn:
cur = conn.cursor()
cur.execute("SELECT * FROM Users WHERE username=? AND password =?", (username, password))
if not cur.fetchone():
flash("ACCOUNT NOT REGISTERED")
return redirect(url_for("login"))
else:
flash("SUCCESFUL LOG IN")
return redirect(url_for("orders"))
@app.route("/sign-up")
def signup():
return render_template("signup.html")
@app.route("/register", methods=['POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['<PASSWORD>']
with sqlite3.connect("storage.db") as conn:
cur = conn.cursor()
cur.execute("INSERT INTO Users (username, password) VALUES (?,?)", (username, password))
conn.commit()
flash('SIGN UP SUCCESSFUL')
return redirect(url_for("login"))
@app.route("/order")
def orders():
conn = sqlite3.connect("storage.db")
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("SELECT * FROM Coffee")
data_coffee = cur.fetchall()
cur.execute("SELECT * FROM Sales")
data_sales = cur.fetchall()
return render_template("orders.html", coffees=data_coffee, sales=data_sales)
@app.route("/add-order", methods=['POST'])
def add_order():
if request.method == 'POST':
size = request.form['size']
type = request.form['type']
quantity = int(request.form['quantity'])
with sqlite3.connect("storage.db") as conn:
cur = conn.cursor()
cur.execute("INSERT INTO Coffee (size, type, quantity) VALUES (?,?,?)", (size, type, quantity))
cur.execute("INSERT INTO Sales (transaction_datetime) VALUES (DATETIME())")
cur.execute("""
UPDATE Inventory
SET quantity=quantity-?
WHERE size=? AND type=?
""", (quantity, size, type))
conn.commit()
return redirect(url_for("orders"))
@app.route("/add-inventory", methods=['POST'])
def add_inventory():
if request.method == 'POST':
size = request.form['size']
type = request.form['type']
quantity = request.form['quantity']
with sqlite3.connect("storage.db") as conn:
cur = conn.cursor()
cur.execute("INSERT INTO Inventory(size, type, quantity) VALUES (?,?,?)", (size, type, quantity))
conn.commit()
return redirect(url_for("inventory"))
@app.route("/inventory")
def inventory():
conn = sqlite3.connect("storage.db")
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("SELECT * FROM Inventory")
data = cur.fetchall()
return render_template("inventory.html", items=data)
@app.route("/edit-inventory/<id>", methods=['POST', 'GET'])
def edit_inventory(id):
conn = sqlite3.connect("storage.db")
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("SELECT * FROM Inventory WHERE id=?", (id,))
data = cur.fetchall()
cur.close()
return render_template("edit.html", item=data[0])
@app.route("/update-inventory/<id>", methods=['POST'])
def update_inventory(id):
if request.method == 'POST':
size = request.form['size']
type = request.form['type']
quantity = request.form['quantity']
with sqlite3.connect("storage.db") as conn:
cur = conn.cursor()
cur.execute("""
UPDATE Inventory
SET size=?,
type=?,
quantity=?
WHERE id=?
""", (size, type, quantity, id))
conn.commit()
return redirect(url_for("inventory"))
@app.route("/delete-inventory/<string:id>", methods=['POST', 'GET'])
def delete_inventory(id):
conn = sqlite3.connect("storage.db")
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("DELETE FROM Inventory WHERE id=?", (id,))
conn.commit()
return redirect(url_for("inventory"))
if __name__ == "__main__":
app.run(debug=True) | e3fd6dd9733ff9a0b2cd3fd458f5b7e44132db23 | [
"Python"
] | 2 | Python | kennethmartingagno/inventory-flask | 1e9f155d9f53de0574cbd650d6a5994e5e9a6af8 | 3242f3eb2b2e2bc8f6faee19be4379365a6d2d2c |
refs/heads/master | <repo_name>JosimarGomes/miniquiz-react-native<file_sep>/src/actions/xp-action.js
import {UPDATE_XP} from './constants';
export const updateXp = (result)=>{
console.log('no action', result)
const _result = result == 'correct' ? 50 : -25;
return{
type: UPDATE_XP,
payload:_result
}
}<file_sep>/src/components/Background.js
import React from 'react';
import { StyleSheet } from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
const Background = (props)=>{
return(
<LinearGradient colors={['#b8c4d2', '#fff', '#f5f6f8']} style={styles.container}>
{props.children}
</LinearGradient>
)
};
export default Background;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
padding:20
}
});<file_sep>/src/screens/Home.js
import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, Dimensions, FlatList, Animated, TouchableOpacity, Easing, Alert, Modal } from 'react-native';
import * as Animatable from 'react-native-animatable';
import { connect } from 'react-redux';
import { Icon } from 'react-native-elements';
import {selectdeck, deletedeck} from '../actions/deck-action';
import PushNotification from 'react-native-push-notification';
import AppNotifications from '../helpers/pushnotifications';
import Background from '../components/Background';
import Button from '../components/Button';
import Deck from '../components/Deck';
import HomeHoc from '../hoc/Home-hoc';
import Avatar from '../components/Avatar';
import Camera from '../components/Camera';
const { width, height } = Dimensions.get('window');
class Home extends Component {
constructor(props){
super(props)
this.state = {
animationbutton: "",
selecteddeck: null,
showCamera: false
};
this.animatedFlex = new Animated.Value(0);
}
componentDidMount() {
AppNotifications.start();
}
componentWillUnmount(){
AppNotifications.finish();
}
newquiz(){
this.props.navigation.navigate('NewDeck');
}
selectDeck(deck){
const {selecteddeck} = this.state;
const {id, title} = deck;
if(selecteddeck === id)
return this.setState({selecteddeck:null});
if(selecteddeck !== null)
return this.setState({selecteddeck:id});
this.props.selectdeck(id);
this.props.navigation.navigate('DeckDetail',{title});
}
_deleteDeck(deck){
Alert.alert(
'Eita, vai excluir',
'O deck será excluído. Deseja continuar?',
[
{text: 'Cancelar', onPress: () => false},
{text: 'Excuir', onPress: () => this._confirmDelete()},
],
// { cancelable: false }
)
}
_confirmDelete(){
this.props.deletedeck(this.state.selecteddeck);
this.setState({selecteddeck:null});
}
selectOptionsDeck(selecteddeck){
this.setState({selecteddeck});
this._animateSelect();
}
_animateSelect(){
this.animatedFlex.setValue(0);
Animated.parallel([
Animated.timing(this.animatedFlex,{
toValue : 1,
duration : 600,
// easing:Easing.bounce
easing: Easing.elastic(4)
}).start()
]);
}
renderdecks(item, index){
const {deckanimation, selecteddeck} = this.state;
return <Deck {...item}
onPress={()=>this.selectDeck(item)}
animation={deckanimation}
onLongPress={()=>this.selectOptionsDeck(item.id)}
selected={selecteddeck === item.id}
/>
}
openCamera(){
this.setState({showCamera: true});
}
closeCamera(){
this.setState({showCamera:false})
}
render() {
const animatedFlex = this.animatedFlex.interpolate({
inputRange: [0, 1],
outputRange: [0, 1]
});
const {xp, user, userphoto} = this.props;
const name = user.name || "<NAME>";
return (
<Background>
<Modal
animationType={"slide"}
transparent={true}
visible={this.state.showCamera}
onRequestClose={()=>this.closeCamera()}
>
<Camera closeCamera={()=>this.closeCamera()} />
</Modal>
<Avatar name={name} value={xp} userphoto={userphoto} onPressPhoto={()=>this.openCamera()} />
<View style={styles.decklist}>
<FlatList
data={ this.props.decks }
extraData={ this.state.selecteddeck }
keyExtractor={ (item, index) => index }
renderItem={ ({item, index}) => this.renderdecks(item,index)}
horizontal={ false }
numColumns={ 3 }
onEndReachedThreshold={ 0.5 }
showsVerticalScrollIndicator={false}
/>
</View>
{
this.state.selecteddeck ?
<Animated.View style={[styles.footerEdit,{flex: animatedFlex}]}>
<TouchableOpacity onPress={()=>this._deleteDeck()} style={{flexDirection:'row'}}>
<Icon size={24} name={'md-trash'} type='ionicon' color={'orange'} style={{bottom:4}} />
<Text style={styles.textFooter}>Excluir</Text>
</TouchableOpacity>
<TouchableOpacity onPress={()=>this.setState({selecteddeck:null})} style={{flexDirection:'row'}}>
<Text style={styles.textFooter}>Cancelar</Text>
</TouchableOpacity>
</Animated.View>
:
<Button
label={'NOVO QUIZ'}
background={'orange'} color={'#fff'}
onPress={ ()=>this.newquiz()}
/>
}
</Background>
);
}
}
const mapStateToProps = ({decks, xp, user, userphoto})=>{
return{
decks, xp, user, userphoto
}
}
export default connect(mapStateToProps, { selectdeck, deletedeck })(HomeHoc(Home));
const styles = StyleSheet.create({
header: {
flex:0.5,
padding: 15
},
decklist:{
flex: 5,
marginTop: 30,
marginBottom: 10,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'stretch',
width: width,
},
footerEdit: {
flexDirection:'row',
width: width,
height:20,
alignItems:'center',
justifyContent:'space-around'
},
textFooter: {
fontWeight:'bold',
fontSize:20,
color: 'orange',
marginLeft:10
}
});<file_sep>/src/actions/deck-action.js
import {LOAD_DECK, LOAD_DECK_SUCCESS, ADD_DECK, SELECT_DECK, DELETE_DECK} from './constants';
export const selectdeck = (id)=>{
return{
type: SELECT_DECK,
id
}
}
export const adddeck = (newdeck)=>{
return{
type: ADD_DECK,
newdeck
}
}
export const deletedeck = (id)=>{
return{
type: DELETE_DECK,
id
}
}<file_sep>/src/components/Button.js
import React, { Component } from 'react';
import * as Animatable from 'react-native-animatable';
import { Icon } from 'react-native-elements';
import { View, Text, TouchableOpacity, StyleSheet, ActivityIndicator, Dimensions } from 'react-native';
const { width, height } = Dimensions.get('window');
export default class Button extends Component{
state = {
animation: 'bounceInLeft'
}
onPressButton(){
this.props.onPress();
}
render(){
const {animation} = this.state;
const {onPress, background, borderColor, color, label, iconName} = this.props;
return(
<Animatable.View style={{flex:1}} animation={animation} delay={500}>
<TouchableOpacity activeOpacity={.6} onPress={()=>onPress&&this.onPressButton()}>
<View style={[styles.btnPill, {backgroundColor:background}]}>
<Text style={[styles.label,{color:color || '#000'}]}>{label}</Text>
<Icon name={iconName || 'md-arrow-forward'} type='ionicon' color={'#fff'} size={25}/>
</View>
</TouchableOpacity>
</Animatable.View>
)
}
}
const styles = StyleSheet.create({
btnPill : {
flexDirection:'row',
minWidth : width * 0.8,
minHeight : 50,
borderRadius : 8,
justifyContent : 'center',
alignItems : 'center',
backgroundColor : '#56c941',
marginBottom: 20,
paddingVertical:5,
paddingHorizontal:7
},
label: {
marginLeft:5,
marginRight:5,
fontSize: 20
}
})<file_sep>/src/components/ProgressBar.js
import React, { Component } from 'react';
import { View, Animated, Easing, StyleSheet, Text } from 'react-native';
export default class ProgressBar extends Component {
constructor(props) {
super(props)
this.state = {
progress: new Animated.Value(0),
updateProgress : 0
}
style = styles;
easing = Easing.inOut(Easing.ease),
easingDuration = 500
}
componentWillReceiveProps(nextProps) {
const { progress } = nextProps;
if(progress&&progress!=this.props.progress)
this.update(nextProps.progress)
}
render() {
const fillWidth = this.state.progress.interpolate({
inputRange: [0, 1],
outputRange: [0 * this.props.style.width, 1 * this.props.style.width],
});
return (
<View style={styles.container}>
<View style={[styles.background, this.props.backgroundStyle, this.props.style]}>
<Animated.View style={[styles.fill, this.props.fillStyle, { width: fillWidth }]}/>
</View>
<Text>{this.props.description}</Text>
</View>
);
}
update(updateProgress) {
Animated.timing(this.state.progress, {
easing: this.easing,
duration: this.easingDuration,
toValue: updateProgress
}).start();
}
};
const styles = StyleSheet.create({
container: {
height:30
},
background: {
backgroundColor: '#bbbbbb',
height: 5,
overflow: 'hidden'
},
fill: {
backgroundColor: '#43C047',
height: 5
}
});
<file_sep>/src/sagas/workers/card-worker.js
import { takeLatest, call, put, select } from 'redux-saga/effects';
import { ADD_CARD, SELECT_DECK_SUCCESS, SELECT_CARD, SELECT_CARD_SUCCESS, LOAD_DECK_SUCCESS } from '../../actions/constants';
function* addcard({newcard}){
const _deck = yield select(({deck}) => deck);
_deck[0].questions.push(newcard);
yield put({type: SELECT_DECK_SUCCESS, payload:_deck});
yield put({ type: LOAD_DECK_SUCCESS, payload: [] });
}
function* selectcard({card}){
yield put({type: SELECT_CARD_SUCCESS, payload: card})
}
export function* cardWorkers(){
yield takeLatest(ADD_CARD, addcard);
yield takeLatest(SELECT_CARD, selectcard)
}<file_sep>/src/reducers/card-reducer.js
import { SELECT_CARD_SUCCESS } from '../actions/constants';
export const card = (state={}, action)=>{
switch(action.type){
case SELECT_CARD_SUCCESS:
return action.payload;
default :
return state;
}
}<file_sep>/src/screens/Quiz.js
import React, { Component } from 'react';
import { StyleSheet, Text, View, Dimensions, TouchableOpacity, Modal } from 'react-native';
import { connect } from 'react-redux';
import { NavigationActions } from 'react-navigation';
import Background from '../components/Background';
import Button from '../components/Button';
import { Icon } from 'react-native-elements';
import "babel-polyfill";
import {updateXp} from '../actions/xp-action';
import Xp from '../components/Xp';
import EndQuiz from '../components/EndQuiz';
import ProgressBar from '../components/ProgressBar';
const { width, height } = Dimensions.get('window');
const returnToHomeAction = NavigationActions.reset({
index: 0,
key : null,
actions: [
NavigationActions.navigate({ routeName: 'Home'})
]
});
class Card extends Component {
constructor(props){
super(props);
this.state = {
viewanswer: false,
card: {},
showEndQuiz: false,
progress: 0,
description: "",
result: {}
};
this._questions = [];
this._count = 0;
this._correctquestions = 0;
this._results = [
];
}
componentDidMount(){
this.startQuiz();
}
setanswer(result=null){
if(result) this.updateScore(result);
this.handlerQuestions();
}
updateScore(result){
if(result == 'correct')
this._correctquestions++;
this.props.updateXp(result);
}
handlerQuestions(){
const question = this._questions.next();
if(question.done === true)
return this.endQuiz();
this._count++;
const {questions} = this.props;
const total = questions.length;
const {progress, description} = this.calculatebarprogress(total, this._count);
this.setState({
card: question.value,
viewanswer: false,
description,
progress
});
}
startQuiz(){
const {questions} = this.props;
this._questions = questions[Symbol.iterator]();
this._count = 0;
this._correctquestions = 0;
this.handlerQuestions();
}
endQuiz(){
const {questions} = this.props;
const total = questions.length;
const score = this.calculatescore(total, this._correctquestions);
const result = this.getresult(score);
this.setState({showEndQuiz: true, result})
}
restartQuiz(){
this.startQuiz();
this.setState({showEndQuiz: false})
}
feedbackButtons(){
return (
<View style={styles.butonfeedback}>
<TouchableOpacity style={[styles.correct, styles.buttonfeedback]} onPress={()=>this.setanswer('correct')}>
<Text style={styles.textbutton}>CORRETO</Text>
<Icon name={'md-checkmark-circle'} type='ionicon' color={'#fff'} size={25}/>
</TouchableOpacity>
<TouchableOpacity style={[styles.incorrect, styles.buttonfeedback]} onPress={()=>this.setanswer('incorrect')}>
<Text style={styles.textbutton}>INCORRETO</Text>
<Icon name={'md-close-circle'} type='ionicon' color={'#fff'} size={25}/>
</TouchableOpacity>
</View>
)
}
viewanswer(){
this.setState({viewanswer:true})
}
//colocar num helper
calculatebarprogress(total, count){
return {
progress: (count / total),
description: `${count} de ${total}`
}
}
//colocar num helper
calculatescore(total, score){
if(score == 0) return score;
const result = (score / total) * 100;
return result.toFixed(2);
}
//colocar num helper
getresult(value){
if(value < 20)
return {title: "Que vergonha...", color: "orange", icon: "md-sad", value};
if(value < 50)
return {title: "Precisa melhorar", color: "orange", icon: "md-thumbs-down", value};
if(value >= 50 && value <= 60)
return {title: "Nada mal.", color: "#56c941", icon: "md-thumbs-up", value};
if(value >= 60 && value <= 75)
return {title: "Muito bom.", color: "#56c941", icon: "md-thumbs-up", value};
if(value > 75 && value <= 95)
return {title: "Ótimo, parabéns!", color: "#56c941", icon: "md-trophy", value};
if(value > 95)
return {title: "Mestre Jedi!!", color: "#56c941", icon: "md-planet", value};
}
render() {
const {viewanswer, card, progress, description, result} = this.state;
const {question, answer} = card;
return (
<Background>
<Modal
onRequestClose={() => {} }
animationType={"slide"}
visible={this.state.showEndQuiz}
>
<EndQuiz
returnToHome={()=>this.props.navigation.dispatch(returnToHomeAction)}
restartQuiz={()=>this.restartQuiz()}
{...result}
/>
</Modal>
<View style={styles.progressBar}>
<ProgressBar progress={progress} style={{width:width * 0.8}} description={description}/>
</View>
<View style={styles.sectiontop}>
<View style={{marginVertical:20}}>
<Text style={styles.pergunta}>{question}</Text>
{
viewanswer&&
<Text style={styles.resposta}>{`Resposta: ${answer}`}</Text>
}
</View>
</View>
<View style={styles.sectionbottom}>
{
viewanswer ?
this.feedbackButtons()
:
<Button
label={'VER RESPOSTA'}
background={'#43C047'} color={'#fff'}
onPress={ ()=>this.viewanswer()}
/>
}
</View>
</Background>
);
}
}
const mapStateToProps = ({questions})=>{
return{
questions
}
}
export default connect(mapStateToProps, {updateXp})(Card);
const styles = StyleSheet.create({
sectiontop:{
flex: 2,
alignItems: 'center',
justifyContent: 'center',
padding: 10
},
sectionbottom:{
flex: 1,
justifyContent: 'flex-end'
},
pergunta: {
fontSize: 20,
fontWeight: 'bold',
color: '#000',
},
resposta: {
fontSize: 20
},
correct: {
backgroundColor: '#43C047'
},
buttonfeedback: {
flexDirection: 'row',
padding: 10,
width: width * 0.4,
borderRadius: 20,
justifyContent: 'center',
alignItems: 'center'
},
incorrect: {
backgroundColor: 'orange'
},
butonfeedback: {
flex:2,
justifyContent: 'space-around'
},
textbutton: {
color: '#fff',
textAlign: 'center',
marginRight: 8
}
});<file_sep>/src/reducers/xp-reducer.js
import {UPDATE_XP} from '../actions/constants';
export const xp = (state=0, action)=>{
switch(action.type){
case UPDATE_XP:
console.log(action.payload)
return (state + action.payload);
default :
return state;
}
}<file_sep>/src/screens/DeckDetail.js
import React, { Component } from 'react';
import { StyleSheet, Text, View, FlatList, Image, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import {iniciarquiz} from '../actions/quiz-action';
import Background from '../components/Background';
import Button from '../components/Button';
class DeckDetail extends Component {
constructor(props){
super(props);
}
addcards(){
this.props.navigation.navigate('NewCard');
}
_iniciarquiz(){
const {deck} = this.props;
this.props.iniciarquiz(deck.questions);
const params = {title: deck.title};
this.props.navigation.navigate('Quiz', params);
}
buttonaddcards(){
return(
<TouchableOpacity style={styles.btnadd} onPress={()=>this.addcards()}>
<Text style={{color:'#fff', fontSize:35}}>+</Text>
</TouchableOpacity>
)
}
headercomponent(){
const {deck} = this.props;
const {title, questions} = deck;
const label = questions.length == 1 ? 'pergunta' : 'perguntas';
return(
<View style={{marginVertical:20}}>
<Text style={styles.subtitulo}>{`${questions.length} ${label}`}</Text>
</View>
)
}
renderquestoes(){
return <Image source={require('../img/interrogacao.png')} style={styles.imageicon} resizeMode={'contain'}/>
}
render() {
const {deck} = this.props;
const {questions} = deck;
return (
<Background>
<View style={styles.sectiontop}>
<FlatList
ListHeaderComponent={this.headercomponent()}
data={ questions }
keyExtractor={ (item, index) => index }
renderItem={ ({item, index}) => this.renderquestoes(item,index)}
horizontal={ false }
numColumns={ 7 }
onEndReachedThreshold={ 0.5 }
showsVerticalScrollIndicator={false}
ListFooterComponent={this.buttonaddcards()}
/>
</View>
{
questions.length > 0 &&
<View style={styles.sectionbottom}>
<Button
label={'INICIAR'}
background={'#43C047'} color={'#fff'}
onPress={ ()=>this._iniciarquiz()}
/>
</View>
}
</Background>
);
}
}
const mapStateToProps = ({deck})=>{
return{
deck: deck[0]
}
}
export default connect(mapStateToProps, {iniciarquiz})(DeckDetail);
const styles = StyleSheet.create({
sectiontop:{
flex: 2,
alignItems: 'center',
justifyContent: 'center',
},
sectionbottom:{
flex: 0.5,
justifyContent: 'flex-end'
},
subtitulo:{
textAlign: 'center'
},
imageicon:{
margin:10,
width:25,
height:25
},
btnadd: {
backgroundColor: '#43C047',
width:50,
height:50,
borderRadius: 25,
alignItems: 'center',
justifyContent: 'center',
marginTop:20
}
});<file_sep>/README.md
# MobileFlashCard Project - MiniQuiz
Este é o projeto MobileFlashCard, do Nanodegree de React da Udacity. Turma Setembro/17
Este projeto foi desenvolvido e testado apenas em Android.
Este projeto foi desenvolvido utilizando códigos nativo, com o comando react-native init.
## Preparando o ambiente
O ambiente de desenvolvimento requer alguns ajustes, como a instalação do react-native-cli, Java SE Development Kit (JDK),
Android SDK, além de configurar as variáveis de ambiente.
O processo é simples, e fortemente documentado em:
http://facebook.github.io/react-native/docs/getting-started.html
Obs: escolha a opção: Building Projects with Native Code
## Iniciando
Para iniciar o projeto:
* clone o projeto com `https://github.com/JosimarGomes/miniquiz.git`
* instale as dependências com `npm install`
* faça o link das dependências nativas com `react-native link`
* inicie o servidor de desenvolvimento com `npm start`
* conecte seu dispositivo ANDROID pelo cabo USB e habilite o modo desenvolvedor
* abra uma nova guia no terminal e digite `react-native run-android`
## Adicione quiz de estudos
* Adicione quiz e aprimore seus estudos.
* Inicie um quiz e veja como está a sua evolução
* Obs: para excluir o quiz, basta pressioná-lo por alguns segundos
* Seja notificado no dia em que não estudar (para testar, basta passar o parâmetro true na função que chama a data. Isso faz com que a notificação seja disparada em 10 segundos)
<file_sep>/src/components/EndQuiz.js
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Dimensions, Image} from 'react-native';
import * as Animatable from 'react-native-animatable';
import { NavigationActions } from 'react-navigation';
import { Icon } from 'react-native-elements';
import Button from '../components/Button';
const { width, height } = Dimensions.get('window');
export default (props)=>{
const {icon, msg, title, value, color} = props;
return(
<View style={styles.container}>
<Animatable.View animation={"bounceIn"} style={styles.item}>
<Icon name={icon} type='ionicon' color={color} delay={500} size={95}/>
<Text style={styles.title}>{title}</Text>
</Animatable.View>
<Animatable.View animation={"zoomInDown"} delay={800} style={[styles.item, {flex:1.5}]}>
<Text style={styles.msg}>Você acertou</Text>
<Text style={styles.result}>{value}%</Text>
<Text style={styles.msg}>das questões.</Text>
</Animatable.View>
<View style={styles.item}>
<Button
label={'Refazer'}
background={'orange'} color={'#fff'}
onPress={ ()=>props.restartQuiz()}
iconName={'md-redo'}
/>
<Button
label={'Voltar'}
background={'#43C047'} color={'#fff'}
onPress={ ()=>props.returnToHome()}
iconName={'md-home'}
/>
</View>
</View>
)
}
const styles = StyleSheet.create({
container : {
flex : 1,
justifyContent: 'center',
alignItems: 'center',
paddingTop: 30
},
item: {
margin: width * 0.022,
flex:1.2,
alignItems:'center',
justifyContent: 'center'
},
title: {
fontSize:25,
fontWeight: 'bold',
textAlign: 'center'
},
msg: {
fontSize: 20,
textAlign: 'center'
},
result: {
fontSize:55,
fontWeight: 'bold',
textAlign: 'center'
}
})<file_sep>/src/actions/constants.js
//DECK
export const LOAD_DECK = 'load_deck';
export const LOAD_DECK_SUCCESS = 'load_deck_success';
export const ADD_DECK = 'add_deck';
export const DELETE_DECK = 'delete_deck';
export const SELECT_DECK = 'select_deck';
export const SELECT_DECK_SUCCESS = 'select_deck_success';
export const DELETE_DECK_SUCCESS = 'delete_deck_succes';
//CARD
export const ADD_CARD = 'add_card';
export const SELECT_CARD = 'select_card';
export const SELECT_CARD_SUCCESS = 'select_card_success';
//QUIZ
export const INICIAR_QUIZ = 'iniciar_quiz';
export const INICIAR_QUIZ_SUCCESS = 'iniciar_quiz_success';
//XP
export const UPDATE_XP = 'update_xp';
//USER
export const ADD_NAME_USER = 'add_name_user';
export const ADD_PHOTO = 'add_photo';<file_sep>/src/screens/NewCard.js
import React, { Component } from 'react';
import { StyleSheet, Text, View, Dimensions, TextInput, Alert } from 'react-native';
import { NavigationActions } from 'react-navigation';
import {addcard} from '../actions/card-action';
import { connect } from 'react-redux';
import Background from '../components/Background';
import Button from '../components/Button';
const { width, height } = Dimensions.get('window');
class NewCard extends Component {
constructor(props){
super(props);
this.state = {
question: "",
answer: ""
}
}
addcard(){
const {question, answer} = this.state;
if(!question || !answer) {
return Alert.alert(
':(',
'Digite a pergunta e a resposta.',
[
{text: 'Cancelar', onPress: () => false},
],
// { cancelable: false }
)
}
const newcard = {question, answer};
const {deck} = this.props;
const {title} = deck[0];
const returnAction = NavigationActions.reset({
index: 1,
key : null,
actions: [
NavigationActions.navigate({ routeName: 'Home'}),
NavigationActions.navigate({ routeName: 'DeckDetail', params: {title}})
]
});
this.props.addcard(newcard);
this.props.navigation.dispatch(returnAction);
}
render() {
const {question, answer} = this.state;
return (
<Background>
<View style={styles.sectiontop}>
<Text style={styles.text}>Nova Pergunta</Text>
<TextInput
style={styles.textinput}
onChangeText={(question) => this.setState({question})}
value={question}
placeholder={'Digite a pergunta aqui'}
placeholderTextColor={'#ccc'}
/>
<Text style={styles.text}>Resposta</Text>
<TextInput
style={styles.textinput}
onChangeText={(answer) => this.setState({answer})}
value={answer}
placeholder={'Digite a resposta aqui'}
placeholderTextColor={'#ccc'}
/>
</View>
<View style={styles.sectionbottom}>
<Button
label={'SALVAR'}
background={'#43C047'} color={'#fff'}
onPress={ ()=>this.addcard()}
/>
</View>
</Background>
);
}
}
const mapStateToProps = ({deck})=>{
return{
deck
}
}
export default connect(mapStateToProps, {addcard})(NewCard);
const styles = StyleSheet.create({
sectiontop:{
flex: 2,
justifyContent: 'center'
},
sectionbottom:{
flex: 1
},
text: {
fontSize: 25
},
textinput: {
height: 40,
width: width * 0.9
}
});<file_sep>/src/hoc/Home-hoc.js
import React, { Component } from 'react';
import Login from '../screens/Login';
import { connect } from 'react-redux';
export default HomeHoc = (WrappedComponent)=>{
class EnhancedComponent extends Component{
render(){
const { user } = this.props;
if( user&&user.name ){
return <WrappedComponent { ...this.props }/>
}
return <Login />;
}
}
const mapStateToProps = ({user})=>{
return{
user
}
}
return connect(mapStateToProps)(EnhancedComponent);
}<file_sep>/src/components/Xp.js
import React from 'react';
import { StyleSheet, View, Text, TouchableOpacity } from 'react-native';
import { Icon } from 'react-native-elements';
const Xp = (props)=>{
return(
<View style={{flexDirection:'row'}}>
<Icon name={'md-star-outline'} type='ionicon' size={15}/>
<Text style={{fontWeight: 'bold'}}> {props.value}xp</Text>
</View>
)
};
export default Xp;<file_sep>/src/sagas/index.js
import { takeLatest,fork, all } from 'redux-saga/effects';
import * as deck from './workers/deck-worker';
import * as card from './workers/card-worker';
import * as quiz from './workers/quiz-worker';
export default function* rootSaga(){
yield all([
...Object.values(deck).map(fork),
...Object.values(card).map(fork),
...Object.values(quiz).map(fork)
])
}<file_sep>/src/actions/user-action.js
import {ADD_NAME_USER, ADD_PHOTO} from './constants';
export const addname = (name)=>{
return{
type: ADD_NAME_USER,
payload: {name}
}
}
export const addphotouser = (photo)=>{
return{
type: ADD_PHOTO,
payload: photo
}
}<file_sep>/src/components/Deck.js
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, Dimensions, Image} from 'react-native';
import * as Animatable from 'react-native-animatable';
import { Icon } from 'react-native-elements';
const { width, height } = Dimensions.get('window');
export default (props)=>{
const {title, questions} = props;
return(
<TouchableOpacity activeOpacity={.6} onPress={()=>props.onPress() || false} onLongPress={()=>props.onLongPress() || false}>
<Animatable.View animation={"bounceIn"} style={styles.deck}>
<Image source={require('../img/bgdeck.png')} style={styles.deckbg} resizeMode='cover' />
<View style={styles.content}>
<Text style={styles.title}>{title}</Text>
{
props.selected&&<Icon name='md-checkmark-circle' size={35} type='ionicon' color='orange'/>
}
<Text style={styles.card}>{`${questions.length} cartas`}</Text>
</View>
</Animatable.View>
</TouchableOpacity>
)
}
const styles = StyleSheet.create({
deck: {
width: width * 0.29,
height: width * 0.40,
margin: width * 0.022,
},
deckbg: {
flex:1,
width: width * 0.29,
height: width * 0.40,
position:'absolute',
borderRadius: 5
},
content: {
flex:1,
justifyContent: 'space-between',
padding:5
},
title: {
color: '#fff',
fontSize: 16,
textAlign: 'center'
},
card: {
color: '#fff',
textAlign: 'center'
}
})<file_sep>/src/screens/Login.js
import React, { Component } from 'react';
import { Image, View, TextInput, Alert } from 'react-native';
import { connect } from 'react-redux';
import Background from '../components/Background';
import Button from '../components/Button';
import {addname} from '../actions/user-action';
class Login extends Component {
state = {
name: ""
}
startQuiz(){
const {name} = this.state;
if(!name) {
return Alert.alert(
':(',
'Digite um nome para começar!',
[
{text: 'Ok, vou digitar', onPress: () => false}
],
// { cancelable: false }
)
}
this.props.addname(name);
}
render() {
const {name} = this.state;
return (
<Background>
<View style={{flex:1,alignItems: 'center'}}>
<View style={{flex:1, justifyContent:'center'}}>
<Image source={require('../img/logo.png')} resizeMode={'contain'}style={{width:160, height:95}} />
</View>
<View style={{flex:1}}>
<TextInput
style={{height:40, width:300}}
onChangeText={(name) => this.setState({name})}
value={name}
placeholder={'Digite seu nome'}
placeholderTextColor={'#ccc'}
/>
<Button
label={'COMEÇAR!'}
background={'orange'} color={'#fff'}
onPress={ ()=>this.startQuiz()}
/>
</View>
</View>
</Background>
);
}
}
const mapStateToProps = ({user})=>{
return{
user
}
}
export default connect(mapStateToProps, {addname})(Login);<file_sep>/src/actions/quiz-action.js
import {INICIAR_QUIZ} from './constants';
export const iniciarquiz = (questions)=>{
return{
type: INICIAR_QUIZ,
questions
}
}<file_sep>/src/helpers/pushnotifications.js
import React, { Component } from 'react';
import {AppState, AsyncStorage} from 'react-native';
import PushNotification from 'react-native-push-notification';
import store from '../configs/store';
const NOTIFICATION_KEY = 'Notifications:miniquiz';
const NOTIFICATION_ID = 123;
const AppNotifications = {
start(){
PushNotification.configure({
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
},
});
AppState.addEventListener('change', this.handleAppStateChange);
},
finish(){
AppState.removeEventListener('change', this.handleAppStateChange);
},
handleAppStateChange(appState) {
if(appState === 'background')
AppNotifications.addNotification();
else if (appState === 'active')
AppNotifications.removeNotification();
},
addNotification(){
AsyncStorage.getItem(NOTIFICATION_KEY)
.then(JSON.parse)
.then(data => {
if (data === null) {
const date = AppNotifications._getDateNotification();
const message = AppNotifications._getMessageNotification();
PushNotification.localNotificationSchedule({
message,
date,
id: NOTIFICATION_ID,
userInfo: {
id: NOTIFICATION_ID
},
repeatType: 'day',
});
AsyncStorage.setItem(NOTIFICATION_KEY, JSON.stringify(NOTIFICATION_ID))
}
})
.catch(error => {
console.log('erro', error.message)
})
},
removeNotification(){
AsyncStorage.getItem(NOTIFICATION_KEY)
.then(JSON.parse)
.then(data => {
PushNotification.cancelLocalNotifications({
id: data
});
AsyncStorage.removeItem(NOTIFICATION_KEY);
})
.catch(error => {
console.log('erro', error.message)
})
},
_getDateNotification(test=false){
// para testar notificação. Notifica depois de 10 segundos
if(test)
return new Date(Date.now() + (10 * 1000)) ;
let tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
return new Date(tomorrow);
},
_getMessageNotification(){
const {user:{name}} = store.getState();
return `${name}, você ainda não estudou hoje!`
}
}
export default AppNotifications;
<file_sep>/src/sagas/workers/quiz-worker.js
import { takeLatest, put} from 'redux-saga/effects';
import {INICIAR_QUIZ, INICIAR_QUIZ_SUCCESS} from '../../actions/constants';
function* iniciarquiz({questions}){
// validações antes de inicar o quiz
yield put({type: INICIAR_QUIZ_SUCCESS, payload: questions})
}
export function* quizWorkers(){
yield takeLatest(INICIAR_QUIZ, iniciarquiz);
}<file_sep>/src/sagas/workers/deck-worker.js
import { takeLatest, call, put, select } from 'redux-saga/effects';
import { ADD_DECK, LOAD_DECK_SUCCESS, LOAD_DECK, SELECT_DECK, SELECT_DECK_SUCCESS, DELETE_DECK, DELETE_DECK_SUCCESS } from '../../actions/constants';
import uuidv1 from 'uuid/v1';
import { deletedeck } from '../../actions/deck-action';
function* adddecks({newdeck}){
newdeck['questions'] = [];
newdeck['id'] = uuidv1();
yield put({ type: SELECT_DECK_SUCCESS, payload:[newdeck] });
yield put({ type: LOAD_DECK_SUCCESS, payload: [newdeck] });
}
function* selectdeck({id}){
const deck = yield select(({decks}) => decks.filter(deck=>deck.id == id));
yield put({type: SELECT_DECK_SUCCESS, payload:deck})
}
function* deletedecks({id}){
const decks = yield select(({decks}) => decks.filter(deck=>deck.id != id));
yield put({type: DELETE_DECK_SUCCESS, payload:decks})
}
export function* deckWorkers(){
yield takeLatest(ADD_DECK, adddecks);
yield takeLatest(SELECT_DECK, selectdeck);
yield takeLatest(DELETE_DECK, deletedecks);
}
<file_sep>/src/actions/card-action.js
import {ADD_CARD, SELECT_CARD} from './constants';
export const addcard = (newcard)=>{
return{
type: ADD_CARD,
newcard
}
}
export const selectcard = (card)=>{
console.log('no action', card)
return{
type: SELECT_CARD,
card
}
}
| 3bafdac8fa773f19b73769ee8445da8d074efd6e | [
"JavaScript",
"Markdown"
] | 26 | JavaScript | JosimarGomes/miniquiz-react-native | decd3b869f6c60b2363d2ff4ee4df808f113d1b0 | 83abd11a3234778f4f0f7e2d7426ec7e291ae555 |
refs/heads/main | <repo_name>Lambda1107/money250<file_sep>/Book.cpp
#include <iostream>
#include <iomanip>
#include <cstring>
#include "Book.h"
using namespace std;
Book::Book(int _num, char _name[50], char _author[50], double _price, char _press[50], int _pressYear)
{
num = _num;
strcpy(name, _name);
strcpy(author, _author);
price = _price;
strcpy(press, _press);
pressYear = _pressYear;
}
Book::Book()
{
}
Book::~Book()
{
}
void Book::printInformation()
{
cout << setw(10) << num
<< setw(10) << name
<< setw(10) << author
<< setw(10) << price
<< setw(10) << press
<< setw(10) << pressYear << endl;
}
<file_sep>/main.cpp
#include <iostream>
#include "Book.h"
#include "method.h"
using namespace std;
books *HEADP = nullptr;
int main()
{
int option = 0;
init();
printInterface();
do
{
cout << "请选择操作: ";
if (!check(option) /*或者option超出范围*/)
{
continue;
}
switch (option)
{
case 1: //显示图书数据
listBooks();
break;
case 2: //插入图书数据
insertBook();
break;
case 3: //删除图书数据
deleteBook();
break;
case 4: //修改图书数据
modifyBook();
break;
case 5: //数据查询
findBook();
break;
case 6: //数据排序
sortBook();
break;
case 7: //数据保存
store();
break;
case 8: //退出
break;
default:
err();
break;
}
} while (option != QUIT);
store();
cout << "感谢使用" << endl;
}<file_sep>/Book.h
#pragma once
class Book {
public:
int num;
char name[50];
char author[50];
double price;
char press[50];
int pressYear;
char info[6][50];
void printInformation();
Book(/* args */);
Book(int _num, char _name[50], char _author[50], double _price, char _press[50], int _pressYear);
~Book();
};
<file_sep>/method.h
#pragma once
//功能
#include <cstring>
#include <iostream>
#include "Book.h"
#include "utils.h"
using namespace std;
//全局定义
#define QUIT 8
#define ERR 9
#define OK 10
//主功能函数
void init();
void printInterface();
void listBooks();
void insertBook();
void deleteBook();
void modifyBook();
void findBook();
void sortBook();
<file_sep>/utils.h
#pragma once
//小组件
#include <iostream>
#include <fstream>
#include "Book.h"
using namespace std;
//链表结构声明
struct books
{
Book data;
books *next;
};
extern books *HEADP;
void init(); //创建链表
void store(); //保存链表
void printInterface(); //index
//找pos位置
bool findPos(int pos, books *&pBooks);
//用户输入图书信息
bool inputBookInfo(books *tmpBooks);
//遍历链表查找信息
void findSomething(char input[50], int way);
//链表的冒泡函数
void bobbleSort(books *head, int way, int order);
//全局错误
void err();
//各种输入检查
template <typename T>
bool check(T &pos)
{
if (!(cin >> pos))
{
cin.clear();
cin.sync();
err();
return false;
}
return true;
}<file_sep>/method.cpp
//功能
#include <fstream>
#include "method.h"
#include "utils.h"
#include "Book.h"
#include <iomanip>
using namespace std;
void listBooks()
{
books *p = HEADP;
// cout << "进入listbook" << endl;
if (!p)
{
cout << "图书数据为空" << endl;
return;
}
cout << setw(10) << "书籍编号"
<< setw(10) << "书名"
<< setw(10) << "作者"
<< setw(10) << "价格"
<< setw(10) << "出版社"
<< setw(10) << "出版年份" << endl;
while (p)
{
p->data.printInformation();
p = p->next;
}
}
void insertBook()
{
int pos;
books *dummuHead = new books;
dummuHead->next = HEADP;
books *pBooks = dummuHead;
cout << "请输入要插入到的位置: ";
if (!check(pos))
{
err();
return;
}
if (pos <= 0)
{
err();
return;
}
if (!findPos(pos - 1, pBooks))
{ //找到它前面一个位置
return;
}
books *tmpBooks = new books;
inputBookInfo(tmpBooks);
tmpBooks->next = pBooks->next;
pBooks->next = tmpBooks;
HEADP = dummuHead->next;
delete dummuHead;
}
void deleteBook()
{
int pos;
cout << "请输入要删除的位置: ";
if (!check(pos))
{
err();
return;
}
books *dummuHead = new books;
dummuHead->next = HEADP;
books *pBooks = dummuHead;
if (!findPos(pos - 1, pBooks))
{
//找要删除对象的前一个结点
return;
}
if (!pBooks->next)
{
err();
return;
}
books *ptmp = pBooks->next;
pBooks->next = pBooks->next->next;
delete ptmp;
HEADP = dummuHead->next;
delete dummuHead;
}
void modifyBook()
{
int pos;
cout << "请输入要修改的位置: ";
if (!check(pos))
{
err();
return;
}
books *dummuHead = new books;
dummuHead->next = HEADP;
books *pBooks = dummuHead;
if (!findPos(pos, pBooks))
{
return;
}
inputBookInfo(pBooks);
HEADP = dummuHead->next;
delete dummuHead;
}
void findBook()
{
char input[50];
int option = 0;
do
{
//输出提示
cout << " 图书查询方式" << endl;
cout << endl;
cout << "[1] 图书编号" << endl;
cout << endl;
cout << "[2] 书名" << endl;
cout << endl;
cout << "[3] 作者" << endl;
cout << endl;
cout << "[4] 价格" << endl;
cout << endl;
cout << "[5] 出版商" << endl;
cout << endl;
cout << "[6] 出版年份" << endl;
cout << endl;
cout << "[7] 返回上一级功能" << endl;
cout << endl;
cout << "请输入查询方式: ";
if (!check(option) || option > 7 || option < 1)
{
err();
continue;
}
switch (option)
{
case 1:
cout << "请输入编号 ";
if (!check(input))
{
err();
return;
}
findSomething(input, 0);
break;
case 2:
cout << "请输入书名 ";
if (!check(input))
{
err();
return;
}
findSomething(input, 1);
break;
case 3:
cout << "请输入作者 ";
if (!check(input))
{
err();
return;
}
findSomething(input, 2);
break;
case 4:
cout << "请输入价格 ";
if (!check(input))
{
err();
return;
}
findSomething(input, 3);
break;
case 5:
cout << "请输入出版社 ";
if (!check(input))
{
err();
return;
}
findSomething(input, 4);
break;
case 6:
cout << "请输入出版时间 ";
if (!check(input))
{
err();
return;
}
findSomething(input, 5);
break;
case 7:
option = QUIT;
break;
default:
err();
break;
}
} while (option != QUIT);
}
void sortBook()
{
//输出提示
cout << " 排序方式" << endl;
cout << endl;
cout << "[1] 图书编号" << endl;
cout << endl;
cout << "[2] 书名" << endl;
cout << endl;
cout << "[3] 作者" << endl;
cout << endl;
cout << "[4] 价格" << endl;
cout << endl;
cout << "[5] 出版商" << endl;
cout << endl;
cout << "[6] 出版年份" << endl;
cout << endl;
cout << "[7] 返回上一级功能" << endl;
cout << endl;
int method; //按照不同的元素排序
if (!check(method))
{
err();
return;
}
if (method == 7)
return;
if (method < 1 || method > 7)
{
err();
return;
}
cout << " 顺序选择:【0】升序, 【1】降序 ";
int order = 0; //0升序,1降序
if (!check(order))
{
err();
return;
}
bobbleSort(HEADP, method, order);
}
<file_sep>/utils.cpp
//小组件
#include <iostream>
#include <fstream>
#include "utils.h"
#include <cstring>
#include <stdlib.h>
#include <iomanip>
#include "Book.h"
using namespace std;
void init() //创建链表,从二进制文件中读入
{
HEADP = nullptr; //没数据的话在下面return是个空指针
fstream fin("database.dat", ios::binary | ios::in);
if (!fin)
return;
HEADP = new books;
books *pbooks = HEADP;
books *pbooks1 = pbooks;
while (!fin.eof() && fin.peek() != EOF)
{
pbooks1 = pbooks;
fin.read((char *)(&pbooks->data), sizeof(Book));
pbooks->next = new books;
pbooks = pbooks->next;
} //读到文件尾了就退出
delete pbooks;
pbooks1->next = NULL;
fin.close();
}
void printInterface()
{
system("cls");
cout << " 图书管理" << endl;
cout << endl;
cout << "[1] 显示图书数据" << endl;
cout << endl;
cout << "[2] 插入图书数据" << endl;
cout << endl;
cout << "[3] 删除图书数据" << endl;
cout << endl;
cout << "[4] 修改图书数据" << endl;
cout << endl;
cout << "[5] 数据查询" << endl;
cout << endl;
cout << "[6] 数据排序" << endl;
cout << endl;
cout << "[7] 数据保存" << endl;
cout << endl;
cout << "[8] 退出程序" << endl;
cout << endl;
}
void err()
{
cout << "输入内容有误!请检查输入!" << endl;
}
bool findPos(int pos, books *&pBooks)
{
for (int i = 0; i < pos; i++)
{
if (!pBooks)
{
err();
return false;
}
//cout << "go next" << endl; //方便dbug
pBooks = pBooks->next;
}
if (!pBooks)
{
err();
return false;
}
return true;
}
void findSomething(char input[50], int way)
{
books *p = HEADP;
if (!p)
{
cout << "图书数据为空" << endl;
}
bool if_find = false;
while (p)
{
if (strcmp(p->data.info[way], input) == 0)
{
if (!if_find)
{
cout << setw(10) << "书籍编号"
<< setw(10) << "书名"
<< setw(10) << "作者"
<< setw(10) << "价格"
<< setw(10) << "出版社"
<< setw(10) << "出版年份" << endl;
}
p->data.printInformation();
if_find = true;
}
p = p->next;
}
if (!if_find)
{
cout << "未查询到相关信息" << endl;
}
}
bool inputBookInfo(books *tmpBooks)
{
cout << "图书编号: ";
if (!check(tmpBooks->data.num))
{
return false;
}
cout << "图书名称: ";
if (!check(tmpBooks->data.name))
{
return false;
}
cout << "作者: ";
if (!check(tmpBooks->data.author))
{
return false;
}
cout << "价格: ";
if (!check(tmpBooks->data.price))
{
return false;
}
cout << "出版社: ";
if (!check(tmpBooks->data.press))
{
return false;
}
cout << "出版年份: ";
if (!check(tmpBooks->data.pressYear))
{
return false;
}
sprintf(tmpBooks->data.info[0], "%d", tmpBooks->data.num);
strcpy(tmpBooks->data.info[1], tmpBooks->data.name);
strcpy(tmpBooks->data.info[2], tmpBooks->data.author);
sprintf(tmpBooks->data.info[3], "%lf", tmpBooks->data.price);
strcpy(tmpBooks->data.info[4], tmpBooks->data.press);
sprintf(tmpBooks->data.info[5], "%d", tmpBooks->data.pressYear);
//test
// cout << "here" << endl;
// for (int i = 0; i < 6; i++)
// {
// cout << tmpBooks->data.info[i] << endl;
// }
return true;
}
void store()
{
//跟load一样的,二进制存法
fstream fout("database.dat", ios::binary | ios::out);
books *pbooks = HEADP;
while (pbooks)
{
fout.write((char *)(&pbooks->data), sizeof(Book));
pbooks = pbooks->next;
}
delete pbooks;
fout.close();
}
void bobbleSort(books *head, int way, int order)
{
if (head == NULL || head->next == NULL)
{
cout << "无需要排序的数据" << endl;
return;
}
books *p = head;
bool j = 1;
while (j)
{
j = 0;
while (p->next)
{
bool b; //升序
bool t;
switch (way)
{
case 1:
b = p->data.num > p->next->data.num;
t = p->data.num == p->next->data.num;
break;
case 2:
b = strcmp(p->data.name, p->next->data.name) > 0;
t = p->data.name == p->next->data.name;
break;
case 3:
b = strcmp(p->data.author, p->next->data.author) > 0;
t = p->data.author == p->next->data.author;
break;
case 4:
b = p->data.price > p->next->data.price;
t = p->data.price == p->next->data.price;
break;
case 5:
b = strcmp(p->data.press, p->next->data.press) > 0;
t = p->data.press == p->next->data.press;
break;
case 6:
b = p->data.pressYear > p->next->data.pressYear;
t = p->data.pressYear == p->next->data.pressYear;
break;
default:
break;
}
if (order == 1) //改为降序
b = !b;
if (b && !t)
{
j = 1;
swap(p->data, p->next->data);
}
p = p->next;
}
p = head;
}
} | 9c962930406f44147f9bcbd27481a652ea1a5cd7 | [
"C++"
] | 7 | C++ | Lambda1107/money250 | 4bb12408a9e6bbe4d5fb6236ecde64502a45ed6f | f2216b7c75eb5caacdc4de24c62493dbd5f0830e |
refs/heads/master | <repo_name>dinhtrung/websocket-broker<file_sep>/go.mod
module github.com/dinhtrung/websocket-broker
go 1.14
require (
github.com/gorilla/mux v1.8.0
github.com/gorilla/websocket v1.4.2
github.com/namsral/flag v1.7.4-pre
)
<file_sep>/README.md
# Golang Websocket
This app is a simple websocket server that have the following function:
* Run a HTTP server in port `18844`
* Listen for websocket connection in `/ws` endpoint. Browser can connect to it via `ws://IP:18844/ws` endpoint.
* Other app can send HTTP POST to `/msg` endpoint and the websocket server will broadcast the message to its client.
## Build and Run
```
$ go build ws.go
$ ./ws
```
With bundle
```
$ go get -u github.com/go-bindata/go-bindata/...
$ ~/go/bin/go-bindata -fs -prefix "static/" static/
$ go build ws.go bindata.go
```
<file_sep>/main.go
package main
import (
"bufio"
"io/ioutil"
"log"
"net"
"net/http"
"github.com/namsral/flag"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
)
var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan string)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
/* kvStorage store temporary data in a map */
var kvStorage = make(map[string]string)
// FlagOptions contain runtime options
type FlagOptions struct {
HTTP string
TCP string
WsPath string
MsgPath string
KeyPath string
}
func main() {
o := ParseFlagOptions()
// 0 - setup TCP connection
// listen on all interfaces
ln, _ := net.Listen("tcp", o.TCP)
go handleTCPMsg(ln)
// 1
fs := http.FileServer(http.Dir("./static"))
// 2
router := mux.NewRouter()
router.Handle("/", fs) // handle tcpMsg
// router.Handle("/", fs)
router.HandleFunc(o.KeyPath+"/{key}", kvSave).Methods("POST")
router.HandleFunc(o.KeyPath+"/{key}", kvGet).Methods("GET")
router.HandleFunc(o.MsgPath, msgHandler).Methods("POST")
router.HandleFunc(o.WsPath, wsHandler)
go echo()
log.Printf("Websocket server on port: " + o.HTTP)
log.Fatal(http.ListenAndServe(o.HTTP, router))
}
/* writer write message into channel */
func writer(coord string) {
broadcast <- coord
}
/* msgHandler read message send from HTTP server and push it into channel */
func msgHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
go writer(string(body))
}
/* wsHandler handle new websocket connection */
func wsHandler(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
}
log.Printf("New client connected")
clients[ws] = true
}
/* kvSave store the value on specified key */
func kvSave(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
vars := mux.Vars(r)
key := vars["key"]
body, _ := ioutil.ReadAll(r.Body)
kvStorage[key] = string(body)
w.Write(body)
}
/* kvGet return value stored on provided key */
func kvGet(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
vars := mux.Vars(r)
key := vars["key"]
w.Write([]byte(kvStorage[key]))
}
/* handleTCPMsg open a new TCP server and listen for new messages */
func handleTCPMsg(ln net.Listener) {
defer ln.Close()
log.Printf("listen for messages on port 15000")
for {
rw, e := ln.Accept()
if e != nil {
log.Fatal(e)
}
go handleTCPConnection(rw)
}
}
/* handleTCPConnection receive message from TCP Connection and send into channel */
func handleTCPConnection(c net.Conn) {
log.Printf("New connection established: %s", c.RemoteAddr().String())
// run loop forever (or until ctrl-c)
for {
// will listen for message to process ending in newline (\n)
message, err := bufio.NewReader(c).ReadString('\n')
if err != nil {
// handle error
return
}
go writer(message)
}
c.Close()
}
/* Send the messsages received on msgHandler to connected websocket clients */
func echo() {
for {
val := <-broadcast
// latlong := fmt.Sprintf("%f %f %s", val.Lat, val.Long)
// send to every client that is currently connected
for client := range clients {
err := client.WriteMessage(websocket.TextMessage, []byte(val))
if err != nil {
log.Printf("Websocket error: %s", err)
client.Close()
delete(clients, client)
}
}
}
}
// ParseFlagOptions parse runtime flag from environment variables or flags.
func ParseFlagOptions() *FlagOptions {
o := &FlagOptions{
HTTP: ":18844",
TCP: ":15000",
WsPath: "/ws",
MsgPath: "/msg",
KeyPath: "/key",
}
flag.StringVar(&o.HTTP, "http", o.HTTP, "HTTP address to listen to")
flag.StringVar(&o.TCP, "tcp", o.TCP, "TCP address to listen to")
flag.StringVar(&o.WsPath, "wspath", o.WsPath, "HTTP path for web socket client to connect to")
flag.StringVar(&o.MsgPath, "msgpath", o.MsgPath, "HTTP path for sending message to")
flag.StringVar(&o.KeyPath, "keypath", o.KeyPath, "HTTP path for get and set consul data")
flag.Usage = func() {
log.Printf("Options:\n")
flag.PrintDefaults()
}
flag.Parse()
return o
}
| 4f56dbd5c7f66c94cf41ac4d59009b537d70847a | [
"Markdown",
"Go Module",
"Go"
] | 3 | Go Module | dinhtrung/websocket-broker | f2d4ab91565469c1974db6656ca0e3b01d8335de | e0deae332edc06b048bcd54e9cc6dc95b4c996a1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.