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>Georggue/Eggstasy<file_sep>/Assets/Scripts/SoundManager.cs
using UnityEngine;
using System.Collections;
using DG.Tweening;
public class SoundManager : MonoBehaviour
{
public AudioSource platzhalter;
public enum Sound
{
HitNote,
MissNote,
WinSound,
LoseSound,
BunnySoundNormal,
BunnySoundRage,
BunnySoundHit
}
public void PlaySound(Sound sound)
{
AudioSource source = null;
switch (sound)
{
case Sound.HitNote:
break;
case Sound.MissNote:
break;
case Sound.WinSound:
break;
case Sound.LoseSound:
break;
case Sound.BunnySoundNormal:
break;
case Sound.BunnySoundRage:
break;
case Sound.BunnySoundHit:
break;
default:
source = null;
break;
}
if (source != null)
PlaySound(source);
}
private void PlaySound(AudioSource sound)
{
if (!sound.isPlaying)
{
sound.Play();
sound.DORewind();
}
}
// Use this for initialization
public static SoundManager Instance;
void Start()
{
Instance = this;
}
void Awake()
{
Instance = this;
}
// Update is called once per frame
void Update()
{
}
}<file_sep>/Assets/Scripts/ActivatorScript.cs
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.Events;
public class ActivatorScript : MonoBehaviour
{
public KeyCode Key;
private SpriteRenderer sr;
private bool active = false;
private GameObject note;
private Color old;
private GameManager gm;
private bool inputAllowed = true;
private ParticleSystem BloodForTheBloodGod;
void Awake()
{
sr = GetComponentInChildren<SpriteRenderer>();
}
// Use this for initialization
void Start()
{
gm = FindObjectOfType<GameManager>();
BloodForTheBloodGod = GameObject.FindGameObjectWithTag("HasiParticles").GetComponent<ParticleSystem>();
old = sr.color;
}
// Update is called once per frame
void Update()
{
if (!inputAllowed) return;
if (Input.GetKeyDown(Key) && active)
{
StartCoroutine(Pressed());
if (note != null)
ThrowBack(note);
active = false;
}
else if (Input.GetKeyDown(Key) && !active)
{
StartCoroutine(Disable());
}
}
private IEnumerator Disable()
{
inputAllowed = false;
sr.color = Color.red;
yield return new WaitForSeconds(0.5f);
sr.color = old;
inputAllowed = true;
}
public UnityAction HasiHit = delegate { };
public float HurlTime;
private void ThrowBack(GameObject obj)
{
obj.GetComponentInChildren<EggNote>().Speed = 0;
obj.layer = 10;
obj.transform.DOMove(new Vector3(0, 1.5f, 0), HurlTime);
obj.transform.DOScale(new Vector3(0.05f, 0.05f, 0.05f), HurlTime);
obj.transform.Rotate(Vector3.right,180f);
StartCoroutine(TriggerHasiHit(obj));
}
private IEnumerator TriggerHasiHit(GameObject obj)
{
yield return new WaitForSeconds(HurlTime);
BloodForTheBloodGod.Play();
gm.RequestHasiHit();
Destroy(obj);
}
private void OnTriggerEnter2D(Collider2D other)
{
active = true;
if (other.gameObject.CompareTag("Note"))
{
note = other.gameObject;
}
}
private void OnTriggerExit2D(Collider2D other)
{
active = false;
}
private IEnumerator Pressed()
{
sr.color = new Color(0, 0, 0);
yield return new WaitForSeconds(0.05f);
sr.color = old;
}
}<file_sep>/Assets/Scripts/GameManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
using DG.Tweening;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Debug = UnityEngine.Debug;
using Random = UnityEngine.Random;
public class GameManager : MonoBehaviour
{
public int SelectedLevel;
public GameObject CityHealthText;
public int CityMaxHealth;
private Text CityText;
private int currentCityHealth;
private int currentHasiHealth;
private bool endOfGame;
private Text EndText;
public int Level1BPM;
public int Level2BPM;
public float Frequency;
public GameObject GameEndText;
public GameObject LevelUpText;
public GameObject GameWinScreen;
public GameObject GameLoseScreen;
private SpriteRenderer hasi;
private Image hasiDamageImg;
private Image houseLeftImg;
private Image houseRightImg;
private SpriteRenderer city;
public GameObject HasiGameObject;
public GameObject CityGameObject;
public GameObject HasiHealthText;
public int HasiMaxHealth;
//private Text HasiText;
public float SpawnOffset;
private NoteList list = new NoteList();
[NotNull] public GameObject NotePrefab;
private List<GameObject> Notes = new List<GameObject>();
public UnityAction RequestCityHit = delegate { };
public UnityAction RequestHasiHit = delegate { };
private readonly Stopwatch timer = new Stopwatch();
private UnityAction TriggerNote = delegate { };
public List<GameObject> Fires;
private UnityAction TriggerUpdateText = delegate { };
private int maxAmount = 1;
private Text lvlUp;
private void SpawnNote()
{
//list.Notes.Add(new Note{timePos = timer.Elapsed.TotalSeconds.ToString(CultureInfo.InvariantCulture
List<int> existing = new List<int>();
var amount = Random.Range(1, maxAmount + 1);
for (int i = 0; i < amount; i++)
{
int column = 0;
bool newItem = false;
while (!newItem)
{
column = Random.Range(0, 7);
if (!existing.Contains(column) && column != 3)
{
newItem = true;
}
}
existing.Add(column);
Vector3 pos = Vector3.zero;
if (column < 3f)
{
pos = new Vector3(-2.8f + column * 1f, 5.5f, 0f);
}
else if (column > 3f)
{
pos = new Vector3(2.8f - ((column - 4) * 1f), 5.5f, 0f);
}
var note = Instantiate(NotePrefab, pos, Quaternion.identity);
if (SelectedLevel == 2) note.GetComponent<EggNote>().Speed *= 2;
}
}
private void Serialize()
{
var serializer = new XmlSerializer(typeof(NoteList));
using (var stream = new FileStream(@"D:\song1.xml", FileMode.Create))
{
serializer.Serialize(stream, list);
}
}
private void Deserialize()
{
var serializer = new XmlSerializer(typeof(NoteList));
using (var stream = new FileStream(@"D:\song1.xml", FileMode.Open))
{
list = serializer.Deserialize(stream) as NoteList;
}
}
private void GenerateNoteList()
{
foreach (var note in list.Notes)
{
var column = Random.Range(0, 7);
Debug.Log(column);
var yPos = Convert.ToDouble(note.timePos);
var pos = new Vector3(-4.5f + column * 1.5f, 6 + (float)yPos, 0f);
Instantiate(NotePrefab, pos, Quaternion.identity);
}
}
private void DecrementHasiHealth()
{
if (currentHasiHealth > 0)
currentHasiHealth--;
TriggerUpdateText();
StartCoroutine(HasiHit());
}
private IEnumerator HasiHit()
{
Color col = new Color(1f, 99f / 255f, 99f / 255f);
hasi.color = col;
// HasiText.color = col;
yield return new WaitForSeconds(0.05f);
hasi.color = Color.white;
//HasiText.color = Color.black;
hasiDamageImg.fillAmount = 1f - (float)currentHasiHealth / HasiMaxHealth;
}
private int fireCounter = 0;
private void DecrementCityHealth()
{
if (currentCityHealth > 0)
currentCityHealth--;
TriggerUpdateText();
houseLeftImg.fillAmount = 1f - (float)currentCityHealth / CityMaxHealth;
houseRightImg.fillAmount = 1f - (float)currentCityHealth / CityMaxHealth;
StartCoroutine(CityHit());
if (currentCityHealth % 5 == 0)
{
if (fireCounter < Fires.Count)
{
Fires[fireCounter].SetActive(true);
fireCounter++;
}
}
}
public void CloseGame()
{
Application.Quit();
}
public void StartGame(int level)
{
SelectedLevel = level;
var menu = GameObject.FindGameObjectWithTag("Menu");
menu.SetActive(false);
timer.Reset();
timer.Start();
if (SelectedLevel == 1)
{
Frequency = Level1BPM / 120f;
}
else if (SelectedLevel == 2)
{
Frequency = Level2BPM / 240f;
}
TriggerNote += SpawnNote;
GameObject.FindObjectOfType<CameraSound>().StartMusic(SelectedLevel);
StartCoroutine(StartTimer());
StartCoroutine(Difficulty());
}
private IEnumerator CityHit()
{
Color col = new Color(1f, 99f / 255f, 99f / 255f);
city.color = col;
//CityText.color = Color.white;
yield return new WaitForSeconds(0.05f);
// CityText.color = Color.black;
city.color = Color.white;
}
private void Start()
{
lvlUp = LevelUpText.GetComponentInChildren<Text>();
city = CityGameObject.GetComponentInChildren<SpriteRenderer>();
hasi = HasiGameObject.GetComponentInChildren<SpriteRenderer>();
hasiDamageImg = GameObject.FindGameObjectWithTag("HasiDamage").GetComponent<Image>();
houseLeftImg = GameObject.FindGameObjectsWithTag("HousesDamage")[0].GetComponent<Image>();
houseRightImg = GameObject.FindGameObjectsWithTag("HousesDamage")[1].GetComponent<Image>();
RequestHasiHit += DecrementHasiHealth;
RequestCityHit += DecrementCityHealth;
TriggerUpdateText += UpdateTexts;
//HasiText = HasiHealthText.GetComponentInChildren<Text>();
// CityText = CityHealthText.GetComponentInChildren<Text>();
EndText = GameEndText.GetComponentInChildren<Text>();
currentHasiHealth = HasiMaxHealth;
currentCityHealth = CityMaxHealth;
//HasiText.text = "Hasi: " + HasiMaxHealth;
//CityText.text = "City: " + CityMaxHealth;
//Deserialize();
//GenerateNoteList();
//GameObject.FindObjectOfType<CameraSound>().BeatFired += SpawnNote;
//GameObject.FindObjectOfType<AudioProcessor>().PlaybackFinished += Serialize;
}
private void UpdateTexts()
{
if (endOfGame) return;
// HasiText.text = "Hasi: " + currentHasiHealth;
//CityText.text = "City: " + currentCityHealth;
if (currentCityHealth == 0)
{
//EndText.text = "You Lose!";
GameLoseScreen.SetActive(true);
GameObject.FindObjectOfType<CameraSound>().StopMusic();
GameLoseScreen.GetComponentInChildren<AudioSource>().Play();
endOfGame = true;
}
if (currentHasiHealth == 0)
{
GameWinScreen.SetActive(true);
GameObject.FindObjectOfType<CameraSound>().StopMusic();
GameWinScreen.GetComponentInChildren<AudioSource>().Play();
//EndText.text = "You Win!";
endOfGame = true;
}
if (endOfGame) StartCoroutine(Reset());
}
private IEnumerator Reset()
{
yield return new WaitForSeconds(10.5f);
SceneManager.LoadScene(0);
}
private bool difficultySwitch = false;
private IEnumerator Difficulty()
{
for (var j = 0; j < 3; j++)
{
float waitForSeconds = 25f;
if (SelectedLevel == 2) waitForSeconds /= 2;
yield return new WaitForSeconds(waitForSeconds);
if (difficultySwitch)
{
Frequency /= 1.5f;
}
else
{
maxAmount++;
}
StartCoroutine(ShowLvlUp(difficultySwitch));
difficultySwitch = !difficultySwitch;
}
}
private IEnumerator ShowLvlUp(bool difficulty)
{
if (difficulty)
lvlUp.text = "Speed up";
else
{
lvlUp.text = "Difficulty up";
}
yield return new WaitForSeconds(1.5f);
lvlUp.text = "";
}
private IEnumerator StartTimer()
{
while (true)
{
TriggerNote();
yield return new WaitForSeconds(Frequency);
}
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Escape)) SceneManager.LoadScene(0);
}
public class Note
{
[XmlAttribute("timePos")] public string timePos;
}
[XmlRoot("NoteList")]
public class NoteList
{
[XmlArray("Notes")] [XmlArrayItem("Note")] public List<Note> Notes = new List<Note>();
}
}<file_sep>/Assets/Scripts/CameraSound.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class CameraSound : MonoBehaviour
{
public UnityAction BeatFired = delegate { };
public AudioSource Level1Music;
public AudioSource Level2Music;
void Start()
{
//Select the instance of AudioProcessor and pass a reference
//to this object
//AudioProcessor processor = FindObjectOfType<AudioProcessor>();
//processor.onBeat.AddListener(onOnbeatDetected);
//processor.onSpectrum.AddListener(onSpectrum);
}
public void StartMusic(int level)
{
switch (level)
{
case 1: Level1Music.PlayDelayed(2f);
break;
case 2: Level2Music.PlayDelayed(0.9f);
break;
}
}
public void StopMusic()
{
Level1Music.Stop();
Level2Music.Stop();
}
//this event will be called every time a beat is detected.
//Change the threshold parameter in the inspector
//to adjust the sensitivity
void onOnbeatDetected()
{
//Debug.Log("Beat!!!");
BeatFired();
//todo: spawn new Note on random Line;
}
//This event will be called every frame while music is playing
void onSpectrum(float[] spectrum)
{
//The spectrum is logarithmically averaged
//to 12 bands
for (int i = 0; i < spectrum.Length; ++i)
{
Vector3 start = new Vector3(i, 0, 0);
Vector3 end = new Vector3(i, spectrum[i], 0);
Debug.DrawLine(start, end);
}
}
}
|
2132528fa3270764c9575ee2143c85b2f66429cc
|
[
"C#"
] | 4 |
C#
|
Georggue/Eggstasy
|
b11b7a25f5058bddf2adef2b499ecc755842bbed
|
dd3e3f83370cdd822c5ac737ead2ae607b156bac
|
refs/heads/master
|
<file_sep>#include <iostream>
#include <cv.h>
#include <highgui.h>
#include <vector>
#include <math.h>
#include <iomanip>
#define NUM_POINTS 4
#define DIMENSION 2
#define IMG_WINDOW_WIDTH 600
#define IMG_WINDOW_HEIGHT 450
#define WINDOW_X 400
#define WINDOW_Y 150
#define WINDOW_X2 200
#define WINDOW_Y2 50
#define WINDOW_X_SHIFT 15
#define WINDOW_Y_SHIFT 30
#define WINDOW_SCALE 0.6
void onMouse(int event,int x,int y,int flags,void* param);
bool flag = 0;
double a_arr[NUM_POINTS*DIMENSION]={};//match point array
double b_arr[NUM_POINTS*DIMENSION]={};
int main()
{
//matrix
CvMat src_point;
CvMat dst_point;
//==========================get pixel from a.jpg==============================//
//load image
IplImage *Imagea = cvLoadImage("a.jpg", CV_LOAD_IMAGE_COLOR);
//creat window
cvNamedWindow("a.jpg", 0);
//move window
cvMoveWindow("a.jpg",WINDOW_X,WINDOW_Y);
//resize window
cvResizeWindow("a.jpg",IMG_WINDOW_WIDTH,IMG_WINDOW_HEIGHT);
//set mouse call back function
cvSetMouseCallback("a.jpg",onMouse,NULL);
//show image a
cvShowImage("a.jpg",Imagea);
//wait key "Esc" or get enough information
std::cout<<"a圖套合到b圖"<<std::endl;
std::cout<<"請在圖中以滑鼠點選四個匹配點"<<std::endl;
flag = 0;
while(true){
if(cvWaitKey(10)==27 || flag)
break;
}
//set matrix
src_point = cvMat( NUM_POINTS, DIMENSION, CV_64FC1, a_arr);
//release
cvDestroyWindow("a.jpg");
//==========================get pixel from b.jpg==============================//
//load image
IplImage *Imageb = cvLoadImage("b.jpg", CV_LOAD_IMAGE_COLOR);
//creat window
cvNamedWindow("b.jpg", 0);
//move window
cvMoveWindow("b.jpg",WINDOW_X,WINDOW_Y);
//resize window
cvResizeWindow("b.jpg",IMG_WINDOW_WIDTH,IMG_WINDOW_HEIGHT);
//set mouse call back function
cvSetMouseCallback("b.jpg",onMouse,NULL);
//show image b
cvShowImage("b.jpg",Imageb);
//wait key "Esc" or get enough information
std::cout<<"請依上圖點選順序在此圖中選出四個匹配點"<<std::endl;
flag = 0;
while(true){
if(cvWaitKey(10)==27 || flag)//exit
break;
}
//set matrix
dst_point = cvMat( NUM_POINTS, DIMENSION, CV_64FC1, b_arr);
//release
cvDestroyWindow("b.jpg");
//==========================find Homography matrix==============================//
double h_arr[3*3]={};
CvMat H= cvMat( 3, 3, CV_64FC1, h_arr);
cvFindHomography(&src_point,&dst_point,&H);
//output homograghy matrix
std::cout<<"The homograghy matrix is:"<<std::endl;
for ( int i = 0; i < 3; i++ ) {
for ( int j = 0; j < 3; j++ )
std::cout <<std::setw(12)<<cvmGet(&H, i, j);
std::cout<<std::endl;
}
//==========================output image==============================//
//Sourse image
//creat window
cvNamedWindow("Sourse image", 0);
//move window
cvMoveWindow("Sourse image",WINDOW_X2,WINDOW_Y2);
//resize window
cvResizeWindow("Sourse image",IMG_WINDOW_WIDTH*WINDOW_SCALE,IMG_WINDOW_HEIGHT*WINDOW_SCALE);
//show image a
cvShowImage("Sourse image",Imagea);
//Destination image
//creat window
cvNamedWindow("Destination image", 0);
//move window
cvMoveWindow("Destination image",WINDOW_X2+IMG_WINDOW_WIDTH*WINDOW_SCALE+WINDOW_X_SHIFT,WINDOW_Y2);
//resize window
cvResizeWindow("Destination image",IMG_WINDOW_WIDTH*WINDOW_SCALE,IMG_WINDOW_HEIGHT*WINDOW_SCALE);
//show image a
cvShowImage("Destination image",Imageb);
//Perspective image
IplImage *Imagep = cvCreateImage(cvSize(Imagea->width,Imagea->height), IPL_DEPTH_8U, 3);
//Perspective operation
cvWarpPerspective(Imagea,Imagep,&H,CV_INTER_LINEAR+(CV_WARP_FILL_OUTLIERS),cvScalarAll(0));
//creat window
cvNamedWindow("Perspective image", 0);
//move window
cvMoveWindow("Perspective image",WINDOW_X2,WINDOW_Y2+IMG_WINDOW_HEIGHT*WINDOW_SCALE+WINDOW_Y_SHIFT);
//resize window
cvResizeWindow("Perspective image",IMG_WINDOW_WIDTH*WINDOW_SCALE,IMG_WINDOW_HEIGHT*WINDOW_SCALE);
//show image a
cvShowImage("Perspective image",Imagep);
//Add destination and perspective image together
//create image
IplImage *Image_add = cvCreateImage(cvSize(Imagea->width,Imagea->height), IPL_DEPTH_8U, 3);
//add image
cvAddWeighted(Imageb,0.5,Imagep,0.5,0,Image_add);
//creat window
cvNamedWindow("ADD image", 0);
//move window
cvMoveWindow("ADD image",WINDOW_X2+IMG_WINDOW_WIDTH*WINDOW_SCALE+WINDOW_X_SHIFT,WINDOW_Y2+IMG_WINDOW_HEIGHT*WINDOW_SCALE+WINDOW_Y_SHIFT);
//resize window
cvResizeWindow("ADD image",IMG_WINDOW_WIDTH*WINDOW_SCALE,IMG_WINDOW_HEIGHT*WINDOW_SCALE);
//show add image
cvShowImage("ADD image",Image_add);
//wait for key
while(cvWaitKey(10)!=27);
cvDestroyAllWindows();
system("cls");
//==========================get pixel from b.jpg==============================//
//creat window
cvNamedWindow("b.jpg", 0);
//move window
cvMoveWindow("b.jpg",WINDOW_X,WINDOW_Y);
//resize window
cvResizeWindow("b.jpg",IMG_WINDOW_WIDTH,IMG_WINDOW_HEIGHT);
//set mouse call back function
cvSetMouseCallback("b.jpg",onMouse,NULL);
//show image b
cvShowImage("b.jpg",Imageb);
//wait key "Esc" or get enough information
std::cout<<"b圖套合到a圖"<<std::endl;
std::cout<<"請在圖中以滑鼠點選四個匹配點"<<std::endl;
flag = 0;
while(true){
if(cvWaitKey(10)==27 || flag)//exit
break;
}
//set matrix
src_point= cvMat( NUM_POINTS, DIMENSION, CV_64FC1, a_arr);
//release
cvDestroyWindow("b.jpg");
//==========================get pixel from a.jpg==============================//
//creat window
cvNamedWindow("a.jpg", 0);
//move window
cvMoveWindow("a.jpg",WINDOW_X,WINDOW_Y);
//resize window
cvResizeWindow("a.jpg",IMG_WINDOW_WIDTH,IMG_WINDOW_HEIGHT);
//set mouse call back function
cvSetMouseCallback("a.jpg",onMouse,NULL);
//show image a
cvShowImage("a.jpg",Imagea);
//wait key "Esc" or get enough information
std::cout<<"請依上圖點選順序在此圖中選出四個匹配點"<<std::endl;
flag = 0;
while(true){
if(cvWaitKey(10)==27 || flag)
break;
}
//set matrix
dst_point = cvMat( NUM_POINTS, DIMENSION, CV_64FC1, b_arr);
//release
cvDestroyWindow("a.jpg");
//==========================find Homography matrix==============================//
//double h_arr[3*3]={};
//CvMat H= cvMat( 3, 3, CV_64FC1, h_arr);
cvFindHomography(&src_point,&dst_point,&H);
//output homograghy matrix
std::cout<<"The homograghy matrix is:"<<std::endl;
for ( int i = 0; i < 3; i++ ) {
for ( int j = 0; j < 3; j++ )
std::cout <<std::setw(12)<<cvmGet(&H, i, j);
std::cout<<std::endl;
}
//==========================output image==============================//
//Sourse image
//creat window
cvNamedWindow("Sourse image", 0);
//move window
cvMoveWindow("Sourse image",WINDOW_X2,WINDOW_Y2);
//resize window
cvResizeWindow("Sourse image",IMG_WINDOW_WIDTH*WINDOW_SCALE,IMG_WINDOW_HEIGHT*WINDOW_SCALE);
//show image a
cvShowImage("Sourse image",Imageb);
//Destination image
//creat window
cvNamedWindow("Destination image", 0);
//move window
cvMoveWindow("Destination image",WINDOW_X2+IMG_WINDOW_WIDTH*WINDOW_SCALE+WINDOW_X_SHIFT,WINDOW_Y2);
//resize window
cvResizeWindow("Destination image",IMG_WINDOW_WIDTH*WINDOW_SCALE,IMG_WINDOW_HEIGHT*WINDOW_SCALE);
//show image a
cvShowImage("Destination image",Imagea);
//Perspective image
//IplImage *Imagep = cvCreateImage(cvSize(Imagea->width,Imagea->height), IPL_DEPTH_8U, 3);
//Perspective operation
cvWarpPerspective(Imageb,Imagep,&H,CV_INTER_LINEAR+(CV_WARP_FILL_OUTLIERS),cvScalarAll(0));
//creat window
cvNamedWindow("Perspective image", 0);
//move window
cvMoveWindow("Perspective image",WINDOW_X2,WINDOW_Y2+IMG_WINDOW_HEIGHT*WINDOW_SCALE+WINDOW_Y_SHIFT);
//resize window
cvResizeWindow("Perspective image",IMG_WINDOW_WIDTH*WINDOW_SCALE,IMG_WINDOW_HEIGHT*WINDOW_SCALE);
//show image a
cvShowImage("Perspective image",Imagep);
//Add destination and perspective image together
//create image
//IplImage *Image_add = cvCreateImage(cvSize(Imagea->width,Imagea->height), IPL_DEPTH_8U, 3);
//add image
cvAddWeighted(Imagea,0.5,Imagep,0.5,0,Image_add);
//creat window
cvNamedWindow("ADD image", 0);
//move window
cvMoveWindow("ADD image",WINDOW_X2+IMG_WINDOW_WIDTH*WINDOW_SCALE+WINDOW_X_SHIFT,WINDOW_Y2+IMG_WINDOW_HEIGHT*WINDOW_SCALE+WINDOW_Y_SHIFT);
//resize window
cvResizeWindow("ADD image",IMG_WINDOW_WIDTH*WINDOW_SCALE,IMG_WINDOW_HEIGHT*WINDOW_SCALE);
//show add image
cvShowImage("ADD image",Image_add);
//wait for key
while(cvWaitKey(10)!=27);
//release
cvReleaseImage(&Imagea);
cvReleaseImage(&Imageb);
cvReleaseImage(&Imagep);
cvReleaseImage(&Image_add);
cvDestroyAllWindows();
//system("pause");
}
void onMouse(int Event,int x,int y,int flags,void* param)
{
static int point_count = 0;
static int click_count = 0;
static int x_index = 0;
if(Event==1){//mouse lefrt click
point_count++;
click_count++;
printf("%d( %d, %d) \n",point_count,x,y);
if(click_count<=NUM_POINTS){
a_arr[x_index] = x;
a_arr[x_index+1] = y;
x_index+=2;
}else{
b_arr[x_index] = x;
b_arr[x_index+1] = y;
x_index+=2;
}
if(point_count == NUM_POINTS){//get enough points
flag = 1;
point_count = 0;
x_index = 0;
}else
flag = 0;
}
//printf("( %d, %d) ",x,y);
//printf("The Event is : %d ",Event);
//printf("The flags is : %d \n",flags);
// printf("The param is : %d\n",param);
}<file_sep>#include <cv.h>
#include <highgui.h>
#include <vector>
//#include <iostream>
//using std::cout;
//using std::endl;
using std::vector;
IplImage* Convolution(IplImage* src,vector<int> const mask[])
{
vector<int> search[9];//row;col
search[0].push_back(-1);search[0].push_back(-1);
search[1].push_back(-1);search[1].push_back(0);
search[2].push_back(-1);search[2].push_back(1);
search[3].push_back(0);search[3].push_back(-1);
search[4].push_back(0);search[4].push_back(0);
search[5].push_back(0);search[5].push_back(1);
search[6].push_back(1);search[6].push_back(-1);
search[7].push_back(1);search[7].push_back(0);
search[8].push_back(1);search[8].push_back(1);
//output image
IplImage* out_img = cvCreateImage(cvSize(src->width,src->height),IPL_DEPTH_8U ,1);
//set all pixel to "0"
for(int row=0;row<src->width;row++){
for(int col=0;col<src->height;col++){
out_img->imageData[row*src->width+col] = 0;
}
}
//convolution
for(int row=1;row<src->width-1;row++){
for(int col=1;col<src->height-1;col++){
int conv_pixel = 0;
size_t cnt = 0;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
vector<int>::iterator it = search[cnt].begin();
int tag_row = row+(*it);it++;
int tag_col = col+(*it);
int tag_pixel = tag_row*(src->width)+tag_col;
conv_pixel+=mask[i][j]*src->imageData[tag_pixel];
cnt++;
}
}
out_img->imageData[row*src->width+col] = (uchar)conv_pixel;
}
}
return out_img;
}
void main()
{
//Read image
IplImage *Image = cvLoadImage("Baboon.jpg", CV_LOAD_IMAGE_COLOR);
IplImage *Gray = cvCreateImage(cvSize(Image->width,Image->height),IPL_DEPTH_8U ,1);
IplImage *Binary = cvCreateImage(cvSize(Image->width,Image->height),IPL_DEPTH_8U ,1);
IplImage *X_Edge = cvCreateImage(cvSize(Image->width,Image->height),IPL_DEPTH_8U ,1);
IplImage *Y_Edge = cvCreateImage(cvSize(Image->width,Image->height),IPL_DEPTH_8U ,1);
IplImage *Edge = cvCreateImage(cvSize(Image->width,Image->height),IPL_DEPTH_8U ,1);
//Step1: 將輸入圖像轉成灰階圖像並二值化
cvCvtColor(Image, Gray, CV_RGB2GRAY);
//Step2: 將灰階圖像二值化
cvThreshold(Gray, Binary, 120, 255, CV_THRESH_BINARY);
//Step3: 定義 Mask
//int Mask_X[3][3]={{-1,0,1},{-2,0,2},{-1,0,1}};
//int Mask_Y[3][3]={{-1,-2,-1},{0,0,0},{1,2,1}};
vector<int> Mask_X[3];
Mask_X[0].push_back(-1); Mask_X[0].push_back(0); Mask_X[0].push_back(1);
Mask_X[1].push_back(-2); Mask_X[1].push_back(0); Mask_X[1].push_back(2);
Mask_X[2].push_back(-1); Mask_X[2].push_back(0); Mask_X[2].push_back(1);
vector<int> Mask_Y[3];
Mask_Y[0].push_back(-1); Mask_Y[0].push_back(-2); Mask_Y[0].push_back(-1);
Mask_Y[1].push_back(0); Mask_Y[1].push_back(0); Mask_Y[1].push_back(0);
Mask_Y[2].push_back(1); Mask_Y[2].push_back(2); Mask_Y[2].push_back(1);
//Step4: 與 Mask 做Convolution的動作已找出 X 方向的邊緣
X_Edge = Convolution(Binary,Mask_X);
//Step5: 與 Mask 做Convolution的動作已找出 Y 方向的邊緣
Y_Edge = Convolution(Binary,Mask_Y);
//Step6: 將 X 方向與 Y 方向的邊緣資訊相加
cvAdd(X_Edge, Y_Edge, Edge);
//Step7: 防止 Pixel 的灰階值超過 255
cvThreshold(Edge, Edge, 254, 255, CV_THRESH_BINARY);
//show original image
cvNamedWindow(" Load Image", CV_WINDOW_AUTOSIZE);
cvShowImage(" Load Image", Image);
//show Gray image
cvNamedWindow(" Gray Image", CV_WINDOW_AUTOSIZE);
cvShowImage(" Gray Image", Gray);
//show Binary image
cvNamedWindow(" Binary Image", CV_WINDOW_AUTOSIZE);
cvShowImage(" Binary Image", Binary);
//show X_Edge image
cvNamedWindow(" X_Edge Image", CV_WINDOW_AUTOSIZE);
cvShowImage(" X_Edge Image", X_Edge);
//show Y_Edge image
cvNamedWindow(" Y_Edge Image", CV_WINDOW_AUTOSIZE);
cvShowImage(" Y_Edge Image", Y_Edge);
//show Edge image
cvNamedWindow(" Edge Image", CV_WINDOW_AUTOSIZE);
cvShowImage(" Edge Image", Edge);
//wait for key
cvWaitKey(0);
//release
cvDestroyWindow(" Load Imag");
cvDestroyWindow(" Gray Imag");
cvDestroyWindow(" Binary Imag");
cvDestroyWindow(" X_Edge Imag");
cvDestroyWindow(" Y_Edge Imag");
cvDestroyWindow(" Edge Imag");
cvReleaseImage(&Image);
cvReleaseImage(&Gray);
cvReleaseImage(&Binary);
cvReleaseImage(&X_Edge);
cvReleaseImage(&Y_Edge);
cvReleaseImage(&Edge);
}<file_sep>#include <iostream>
#include <cv.h>
#include <highgui.h>
#include <vector>
#include <math.h>
using std::vector;
using std::string;
using std::cout;
using std::endl;
#define WINDOW_WIDTH 600
#define WINDOW_HEIGHT 450
#define WINDOW_X 400
#define WINDOW_Y 200
#define WINDOW_X_SHIFT 15
#define WINDOW_Y_SHIFT 30
#define ANGLE_RESU 0.1
#define LINE_TH 30
#define PI 3.14159265
bool click_flag = false;
int center_x = 0;
int center_y = 0;
void onMouse(int Event,int x,int y,int flags,void* param)
{
if(Event==1){
center_x = x;
center_y = y;
click_flag = true;
}
}
void ShowImageOnWindow(IplImage* img,string window_name,
size_t window_width = WINDOW_WIDTH,
size_t window_height = WINDOW_HEIGHT,
size_t x = WINDOW_X,size_t y = WINDOW_Y)
{
//create window
cvNamedWindow(window_name.c_str(), 0);
//move window
cvMoveWindow(window_name.c_str(),x,y);
//resize window
cvResizeWindow(window_name.c_str(),window_width,window_height);
//set mouse call back function
cvSetMouseCallback(window_name.c_str(),onMouse,NULL);
//show image
cvShowImage(window_name.c_str(),img);
//wait for key
while(cvWaitKey(10)!=27 && !click_flag);
click_flag = false;
cvDestroyAllWindows();
}
int main()
{
//LOAD IMAGE
cout<<"原圖"<<endl;
cout<<"(滑鼠點擊圖片或按ESC鍵離開)"<<endl;
IplImage *Image = cvLoadImage("2.bmp");
ShowImageOnWindow(Image,"Load Image ");
system("cls");
//CONVERT TO GRAY IMAGE
cout<<"灰階圖"<<endl;
cout<<"(滑鼠點擊圖片或按ESC鍵離開)"<<endl;
IplImage *gary_image = cvCreateImage(cvGetSize(Image),Image->depth,1);
cvCvtColor(Image, gary_image, CV_BGR2GRAY);
ShowImageOnWindow(gary_image,"Gary Image ");
system("cls");
//DETECT EDGE USING CANNY
cout<<"Canny 邊緣偵測"<<endl;
cout<<"(滑鼠點擊圖片或按ESC鍵離開)"<<endl;
IplImage *edge_image = cvCreateImage(cvGetSize(Image),Image->depth,1);
cvCanny(gary_image,edge_image, 60 , 20, 3 );
ShowImageOnWindow(edge_image,"Edge Image ");
system("cls");
//SMOOTH
cvSmooth(edge_image,edge_image);
//ShowImageOnWindow(edge_image,"Smooth Edge Image ");
//ENFORCE EDGE
IplImage *X_Edge =cvCreateImage(cvGetSize(Image),IPL_DEPTH_16S,1);
IplImage *Y_Edge =cvCreateImage(cvGetSize(Image),IPL_DEPTH_16S,1);
IplImage *S_Edge =cvCreateImage(cvGetSize(Image),IPL_DEPTH_32F,1);
IplImage *S_Edge8u =cvCreateImage(cvGetSize(X_Edge),IPL_DEPTH_8U,1);
cvSobel(edge_image, X_Edge, 1, 0, 3);
cvSobel(edge_image, Y_Edge, 0, 1, 3);
cvPow(X_Edge, X_Edge, 2);
cvPow(Y_Edge, Y_Edge, 2);
cvAdd(X_Edge, Y_Edge, Y_Edge);
cvConvertScale(Y_Edge,S_Edge,1,0);
cvPow(S_Edge, S_Edge, 0.5);
cvConvertScaleAbs(S_Edge,S_Edge8u,1,0);
cvThreshold(edge_image, S_Edge8u, 20, 255,CV_THRESH_BINARY);
cout<<"強化邊緣"<<endl;
cout<<"(滑鼠點擊圖片或按ESC鍵離開)"<<endl;
ShowImageOnWindow(S_Edge8u,"Enforce Edge Image ");
system("cls");
//SEARCH LINES
IplImage *tar_img = edge_image;
cout<<"請點選圓心"<<endl;
ShowImageOnWindow(S_Edge8u,"Target Image");
//center_x = tar_img->width/2;
//center_y = tar_img->height/2;
cout<<"Center: ("<<center_x<<","<<center_y<<")"<<endl;
vector<vector<int>> Lines;//{start_x,start_y,end_x,end_y}...
for(double a=0;a<360;a+=ANGLE_RESU){
int count = 0;
int start_x = center_x;
int start_y = center_y;
for(int x=0;x<tar_img->width/2;x++){
int y = 0;
int x_shift = 0;
int y_shift = 0;
if(a>0 && a<90){
y = x*tan(a*PI/180);
x_shift = x;
y_shift = y;
}else if(a>90 && a<=180){
y = x*tan((180-a)*PI/180);
x_shift = -x;
y_shift = y;
}else if(a>180 && a<270){
y = x*tan((a-180)*PI/180);
x_shift = -x;
y_shift = -y;
}else if(a>270 && a<=360){
y = x*tan((360-a)*PI/180);
x_shift = x;
y_shift = -y;
}
int pixel_x = center_x+x_shift;
int pixel_y = center_y+y_shift;
if(pixel_x<=tar_img->width && pixel_x>=0 && pixel_y<=tar_img->height && pixel_y>=0){
int pixel_value = tar_img->imageData[pixel_x+pixel_y*tar_img->width];
if(pixel_value>0){
count++;
if(count>=LINE_TH){
vector<int> points;
points.push_back(start_x);
points.push_back(start_y);
points.push_back(pixel_x);//end_x
points.push_back(pixel_y);//end_y
Lines.push_back(points);
}
}else{
count = 0;
start_x = pixel_x;
start_y = pixel_y;
}
}
}
}
for(int i=0;i<Lines.size();i++){
CvPoint from = cvPoint(Lines[i][0],Lines[i][1]);
CvPoint end = cvPoint(Lines[i][2],Lines[i][3]);
cvLine( Image, from, end, CV_RGB( 255, 0, 0 ) ,1);
}
cout<<"偵測垂直於地面之直線"<<endl;
cout<<"(滑鼠點擊圖片或按ESC鍵離開)"<<endl;
ShowImageOnWindow(Image,"Final Result");
//release
cvReleaseImage(&Image);
cvReleaseImage(&gary_image);
cvReleaseImage(&edge_image);
cvReleaseImage(&X_Edge);
cvReleaseImage(&Y_Edge);
cvReleaseImage(&S_Edge);
cvReleaseImage(&S_Edge8u);
cvDestroyAllWindows();
return 0;
}<file_sep>#include <stdlib.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>
int main (int argc, char* const argv[])
{
//Load image
IplImage* leftImage = cvLoadImage("cones2.png");
IplImage* rightImage = cvLoadImage("cones6.png");
IplImage* groundTruth = cvLoadImage("conesdisp2.png");
//RGB to Gray
IplImage* grayLeftImage = cvCreateImage(cvSize(leftImage->width, leftImage->height), IPL_DEPTH_8U, 1);
IplImage* grayRightImage = cvCreateImage(cvSize(rightImage->width, rightImage->height), IPL_DEPTH_8U, 1);
cvCvtColor(leftImage, grayLeftImage, CV_RGB2GRAY);
cvCvtColor(rightImage, grayRightImage, CV_RGB2GRAY);
//Define disparity map
IplImage* disparityImage = cvCreateImage(cvSize(leftImage->width, leftImage->height), IPL_DEPTH_8U, 1);
cvSetZero(disparityImage);
//Define parameters
int windowSize = 9;
int w = (int)(windowSize-1)/2;
int disparityRange = 64;
int disparity = 0;
float scale = 4;
//Scaning image
int Height = grayLeftImage->height;
int Width = grayLeftImage->width;
bool det_flag = false;
for(int y=0; y<Height; y++){
for(int x=0; x<Width; x++){
int ssd = 255*255*9*9;//max value
//Disparity Range
for(int d=-disparityRange; d<=0; d++){
//scaning window
int tmp_ssd = 0;
det_flag = false;
for(int j=-w;j<=w;j++){
for(int i=-w;i<=w;i++){
if((x+i+d)>=0 && (x+i+d)<Width && (y+j)>=0 && (y+j)<Height){
det_flag = true;
int left_pixel = ((uchar*)(grayLeftImage->imageData+grayLeftImage->widthStep*(y+j)))[x+i];
int right_pixel = ((uchar*)(grayRightImage->imageData+grayRightImage->widthStep*(y+j)))[x+i+d];
tmp_ssd+=(left_pixel-right_pixel)*(left_pixel-right_pixel);
}
}
}
if(tmp_ssd<ssd && det_flag){
ssd = tmp_ssd;
disparity = -d;
}
}
//build diparity map
disparityImage->imageData[y*disparityImage->widthStep+x] = (int)disparity*scale;
}
}
//Compare diparity map with ground truth
//Calculate error rate
int sumOfSub = 0;
int sumOfGT = 0;
float ErrorRate = 0;
for(int y=0; y<disparityImage->height; y++)
{
for(int x=0; x<disparityImage->width; x++)
{
sumOfSub += abs(((uchar*)(groundTruth->imageData+groundTruth->widthStep*y))[x] - ((uchar*)(disparityImage->imageData+disparityImage->widthStep*y))[x]);
sumOfGT += ((uchar*)(groundTruth->imageData+groundTruth->widthStep*y))[x];
}
}
ErrorRate = (float)sumOfSub/sumOfGT;
printf("┐¨╗~▓vČ░%f", ErrorRate);
//Show image
cvNamedWindow("Right Image", CV_WINDOW_AUTOSIZE);
cvShowImage("Right Image", rightImage);
cvNamedWindow("Left Image", CV_WINDOW_AUTOSIZE);
cvShowImage("Left Image", leftImage);
cvNamedWindow("Ground Truth", CV_WINDOW_AUTOSIZE);
cvShowImage("Ground Truth", groundTruth);
cvNamedWindow("Disparity Image", CV_WINDOW_AUTOSIZE);
cvShowImage("Disparity Image", disparityImage);
//Release
cvWaitKey(0);
cvReleaseImage(&grayRightImage);
cvReleaseImage(&grayLeftImage);
cvReleaseImage(&groundTruth);
cvReleaseImage(&disparityImage);
cvDestroyWindow("Left Image");
cvDestroyWindow("Right Image");
cvDestroyWindow("Ground Truth");
cvDestroyWindow("Dispairty Image");
return 0;
}
<file_sep>#include "cv.h"
#include "highgui.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <math.h>
#include <iomanip>
using std::string;
using std::vector;
using std::cout;
using std::endl;
using std::setprecision;
#define XO 512
#define YO 384
FILE* Open_file(string name)
{
FILE* f;
if((f=fopen(name.c_str(),"r"))==NULL)
{
printf("cannot open file\n");
exit(1);
}
return f;
}
void PrintMatrix(CvMat *Matrix,int Rows,int Cols)
{
for(int i=0;i<Rows;i++){
for(int j=0;j<Cols;j++){
cout<<Matrix->data.db[i*Cols+j]<<" ";
}
cout<<endl;
}
}
void Save2vec(FILE* fp,vector<double>& data)
{
while(!feof(fp)){
float tmp = 0;
fscanf(fp,"%f",&tmp);
data.push_back((double)tmp);
}
data.pop_back();
int cnt = 0;
for(int i=0;i<data.size();i++){
if(cnt == 3){
data[i] = -(data[i]-XO);
}else if(cnt == 4){
data[i] = -(data[i]-YO);
cnt = 0;
continue;
}
cnt++;
}
}
void Conv_vec2cvMat(vector<double> src,int row,int col,CvMat* arr)
{
double* Data = new double[src.size()];
std::copy(src.begin(),src.end(),Data);
*arr = cvMat(row,col,CV_64FC1,Data);
}
int main()
{
//Open file
FILE* fp = NULL;
string file_name("Nonconplanar_pts.txt");
fp = Open_file(file_name);
//Read file
vector<double> data;
Save2vec(fp,data);
fclose(fp);
//Convert to Opencv matrix
CvMat Matrix_Data;
int data_size = data.size();
Conv_vec2cvMat(data,data_size/5,5,&Matrix_Data);
//Find matrix A
vector<double> a_arr;
for(int i=0;i<data_size/5;i++){
double x,y;//camera
double X,Y,Z;//world
X = Matrix_Data.data.db[i*5];
Y = Matrix_Data.data.db[i*5+1];
Z = Matrix_Data.data.db[i*5+2];
x = Matrix_Data.data.db[i*5+3];
y = Matrix_Data.data.db[i*5+4];
a_arr.push_back(x*X);
a_arr.push_back(x*Y);
a_arr.push_back(x*Z);
a_arr.push_back(x);
a_arr.push_back(-y*X);
a_arr.push_back(-y*Y);
a_arr.push_back(-y*Z);
a_arr.push_back(-y);
}
//Convert to Opencv matrix
int a_arr_size = a_arr.size();
CvMat Matrix_A;
Conv_vec2cvMat(a_arr,a_arr_size/8,8,&Matrix_A);
//Find matrix V
int m = Matrix_A.rows;
int n = Matrix_A.cols;
CvMat *W=cvCreateMat(m,n,CV_64FC1);
CvMat *U=cvCreateMat(m,m,CV_64FC1);
CvMat *V=cvCreateMat(n,n,CV_64FC1);
cvSVD(&Matrix_A,W,U,V);
//Get vector V
vector<double> v_vec;
for(int i=0;i<8;i++){
v_vec.push_back(V->data.db[i*8+7]);
}
//Get parameters
double gama=0;
double alpha=0;
double gama2 = (v_vec[0]*v_vec[0]+v_vec[1]*v_vec[1]+v_vec[2]*v_vec[2]);
gama = sqrt(gama2);
double alpha_gama = (v_vec[4]*v_vec[4]+v_vec[5]*v_vec[5]+v_vec[6]*v_vec[6]);
alpha = sqrt(alpha_gama)/gama;
double r21 = v_vec[0]/gama;
double r22 = v_vec[1]/gama;
double r23 = v_vec[2]/gama;
double Ty = v_vec[3]/gama;
double r11 = v_vec[4]/alpha/gama;
double r12 = v_vec[5]/alpha/gama;
double r13 = v_vec[6]/alpha/gama;
double Tx = v_vec[7]/alpha/gama;
double r31 = r12*r23-r13*r22;
double r32 = -(r11*r23-r13*r21);
double r33 = r11*r22-r12*r21;
double Tz = 0;
double fx = 0;
double fy = 0;
CvMat *A=cvCreateMat(m,2,CV_64FC1);
CvMat *b=cvCreateMat(m,1,CV_64FC1);
CvMat *A_T=cvCreateMat(2,m,CV_64FC1);
CvMat *A_TA=cvCreateMat(2,2,CV_64FC1);
CvMat *AAA=cvCreateMat(2,m,CV_64FC1);
CvMat *matrix_x=cvCreateMat(2,1,CV_64FC1);
for(int i=0;i<m;i++){
double x,y;//camera
double X,Y,Z;//world
X = Matrix_Data.data.db[i*5];
Y = Matrix_Data.data.db[i*5+1];
Z = Matrix_Data.data.db[i*5+2];
x = Matrix_Data.data.db[i*5+3];
y = Matrix_Data.data.db[i*5+4];
A->data.db[i*2] = x;
A->data.db[i*2+1] = r11*X+r12*Y+r13*Z+Tx;
b->data.db[i] = -x*(r31*X+r32*Y+r33*Z);
}
cvTranspose(A,A_T);
cvmMul(A_T,A,A_TA);
cvmInvert(A_TA,A_TA);
cvmMul(A_TA,A_T,AAA);
cvmMul(AAA,b,matrix_x);
Tz = matrix_x->data.db[0];
fx = matrix_x->data.db[1];
fy = fx/alpha;
system("cls");
cout<<"Parameters"<<endl;
cout<<"Gama: "<<setprecision(6)<<gama<<endl;
cout<<"Alpha: "<<setprecision(6)<<alpha<<endl;
cout<<"Transport: "<<endl;
cout<<setprecision(6)<<Tx<<"\t"<<setprecision(6)<<Ty<<"\t"<<setprecision(6)<<Tz<<endl;
cout<<"Rotation: "<<endl;
cout<<setprecision(6)<<r11<<"\t"<<setprecision(6)<<r12<<"\t"<<setprecision(6)<<r13<<endl;
cout<<setprecision(6)<<r21<<"\t"<<setprecision(6)<<r22<<"\t"<<setprecision(6)<<r23<<endl;
cout<<setprecision(6)<<r31<<"\t"<<setprecision(6)<<r32<<"\t"<<setprecision(6)<<r33<<endl;
cout<<"Focal length: "<<endl;
cout<<"fx: "<<setprecision(6)<<fx<<endl;
cout<<"fy: "<<setprecision(6)<<fy<<endl;
system("pause");
return 0;
}<file_sep>#include <visp/vpConfig.h>
#include <visp/vpImage.h>
#include <visp/vpImageIo.h>
#include <visp/vpMbEdgeTracker.h>
#include <visp/vpOpenCVGrabber.h>
#include <visp/vpDisplayOpenCV.h>
#include <visp/vpDisplayGDI.h>
#include <visp/vpDisplayX.h>
int main()
{
int number=0;
vpImage<unsigned char> I;
char inputimage[300];
sprintf(inputimage,"video/box_0.jpg");
vpImageIo::readJPEG(I,inputimage);
#if defined VISP_HAVE_X11
vpDisplayX displaywindow;
#elif defined VISP_HAVE_GDI
vpDisplayGDI displaywindow;
#elif defined VISP_HAVE_OPEN_CV
vpDisplayOpenCV displaywindow;
#endif
displaywindow.init(I, 0, 0, "OUTPUT") ;
vpMbEdgeTracker tracker;
vpHomogeneousMatrix cMo;
tracker.loadConfigFile("box.xml");
vpCameraParameters camera;
tracker.getCameraParameters(camera);
tracker.loadModel("box.wrl");
tracker.initClick(I,"box",0);
tracker.track(I);
tracker.getPose(cMo);
tracker.display(I,cMo,camera,vpColor::red,1);
vpDisplay::flush(I);
while(number<318){
sprintf(inputimage,"video/box_%d.jpg",number);
vpImageIo::readJPEG(I,inputimage);
vpDisplay::display(I);
tracker.track(I);
tracker.getPose(cMo);
tracker.display(I,cMo,camera,vpColor::red,1);
vpDisplay::displayFrame(I,cMo,camera,0.05,vpColor::blue);
vpDisplay::flush(I);
//system("pause");
number++;
}
return 0;
}
|
205aa5acd872ae2c7b073ccaee205ecdcaad8ce2
|
[
"C++"
] | 6 |
C++
|
BlakePan/3DTV-homework
|
14fee95352d2292b5efd29e3b5b7c1ce211dbe0c
|
948a29e13aee83e969e91a387ff6e6cd3d0fa18a
|
refs/heads/master
|
<repo_name>KoreaGD/react-crud-users-api<file_sep>/README.md
# react-crud-users-api
Complete CRUD made with react, consuming a json api using JSON-Server.
# Access us at: https://react-crud-users.vercel.app/
<file_sep>/src/components/Templates/Nav.jsx
import './Nav.css';
import React from 'react';
import NavItem from '../NavItem'
export default props =>
<aside className="menu-area">
<nav className="menu">
<NavItem to="/"
icon="home" label="Início" />
<NavItem to="/users"
icon="user" label="Usuários" />
</nav>
</aside>
|
b8ae8958d95ce2ce4d43389cfb1b4bf88a89e743
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
KoreaGD/react-crud-users-api
|
3669fe2a47d5fd039e08418951fb3fea64376432
|
62a9e7ef7bfd184c829dab34af6e0eebb5d44f7e
|
refs/heads/master
|
<repo_name>MichaelNZ85/Programming3<file_sep>/src/passignment1/WetBulbComparator.java
/**
* Comparator class for wet bulb temperature
*/
package passignment1;
import java.util.*;
import java.io.*;
public class WetBulbComparator implements Comparator<Weather>
{
/**
* Compare method - compares the wet bulb values of two Weather objects
* @param Weather one - first Weather object
* @param Weather two - second Weather object
*/
public int compare(Weather one, Weather two)
{
return (int) (one.getTempWetBulb()*100 - two.getTempWetBulb()*100);
}
}<file_sep>/src/passignment1/WeatherStation.java
/**
* WeatherStation class (utilities class) - contains basic methods for manipulating weather data
*/
package passignment1;
import java.util.*;
import java.io.*;
/**
* @author <NAME>
*
*/
public class WeatherStation
{
/**
* Load method - reads weather data from CSV file and puts it into an ArrayList
* @param myWeather - an arrayList of Weather
*/
public static void load(ArrayList<Weather> myWeather)
{
BufferedReader reader;
String line;
int date;
int dayOfYear;
int time;
double airTemp;
double tempWetBulb;
int relativeHumidity;
double dewPoint;
int index = 0;
try
{
reader = new BufferedReader(new FileReader("weatherdata3.csv"));
while(((line = reader.readLine())!= null))
{
String[] fields = line.split(",");
date = Integer.parseInt(fields[1]);
dayOfYear = Integer.parseInt(fields[2]);
time = Integer.parseInt(fields[3]);
airTemp = Double.parseDouble(fields[4]);
tempWetBulb = Double.parseDouble(fields[5]);
relativeHumidity = Integer.parseInt(fields[6]);
dewPoint = Double.parseDouble(fields[7]);
myWeather.add(new Weather(date, dayOfYear, time, airTemp, tempWetBulb, relativeHumidity, dewPoint));
}
}
catch(IOException e)
{
System.out.println("there was a file problem");
e.printStackTrace();
}
}
/**
* Finds the max air temperature
* @param data - an ArrayList of Weather objecs
* @return max - the maximum air temperature value
*/
public static double findAirTempMax(ArrayList<Weather> data)
{
double max = data.get(0).getAirTemp();
for(int i = 0; i < data.size(); i++)
{
if((data.get(i).getAirTemp()) > max)
{
max = data.get(i).getAirTemp();
}
}
return max;
}
/**
* Finds the min air temperature
* @param data - an ArrayList of Weather objecs
* @return min - the minimum air temperature value
*/
public static double findAirTempMin(ArrayList<Weather> data)
{
double min = data.get(0).getAirTemp();
for(int i = 0; i < data.size(); i++)
{
if((data.get(i).getAirTemp()) < min)
{
min = data.get(i).getAirTemp();
}
}
return min;
}
/**
* Finds the max relative humidity
* @param data - an ArrayList of Weather objecs
* @return max - the maximum relative humidity value
*/
public static int findRelativeHumidityMin(ArrayList<Weather> data)
{
int min = data.get(0).getRelativeHumidity();
for(int i = 0; i < data.size(); i++)
{
if((data.get(i).getRelativeHumidity()) < min)
{
min = data.get(i).getRelativeHumidity();
}
}
return min;
}
/**
* Searches the ArrayList of Weather for a particular date's values
* @param data - an ArrayList of Weather objecs
* @param searchDate - the date to search for
* @return data.get(i) - the corresponding Weather object
*/
public static Weather search(ArrayList<Weather> data, int searchDate)
{
boolean found = false;
Weather weather = null;
Weather noResult = new Weather(0,0,0, 0.0, 0.0, 0, 0.0);
for(int i = 0; i < data.size(); i++)
{
if(data.get(i).getDate() == searchDate)
{
weather = data.get(i);
found = true;
}
/*else
{
return noResult;
}*/
}
if (found == false){
return noResult;
} else {
return weather;
}
}
}
<file_sep>/src/passignment1/AssignmentApp.java
package passignment1;
import java.util.*;
/**
* @author <NAME>
*
*/
public class AssignmentApp
{
/**
* Starts the program
* @param args
*/
public static void main(String[] args)
{
ArrayList<Weather> myWeather = new ArrayList<Weather>();
WeatherStation.load(myWeather);
Gui myGui = new Gui(myWeather);
myGui.setVisible(true);
}
}
<file_sep>/src/passignment1/Fields.java
package passignment1;
/**
*
* @author <NAME>
*
*/
public enum Fields {
AirTemp, TempWetBulb, RelativeHumidity, DewPoint;
}
<file_sep>/src/passignment1/Gui.java
package passignment1;
import java.awt.BorderLayout;
import java.util.*;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTabbedPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
/**
*
* @author <NAME>
* GUI class - creates form
*
*/
public class Gui extends JFrame
{
private JPanel contentPane;
private ArrayList<Weather> data;
private int index = 0;
private final JLabel lblDate = new JLabel("Date");
private final JTextField datetf = new JTextField();
private final JLabel lblTime = new JLabel("Time");
private final JTextField timetf = new JTextField();
private final JLabel lblAirTemperature = new JLabel("Air Temperature (\u00B0C)");
private final JLabel lblWetBulbTemperature = new JLabel("Wet Bulb Temperature (\u00B0C)");
private final JLabel lblRelativeHumidity = new JLabel("Relative Humidity (%)");
private final JLabel lblDewPointTemperature = new JLabel("Dew Point Temperature (\u00B0C)");
private final JTextField airtemptf = new JTextField();
private final JTextField wetbulbtf = new JTextField();
private final JTextField relhumtf = new JTextField();
private final JTextField dewpointtf = new JTextField();
private final JButton btnNext = new JButton("Next");
private final JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
private final JPanel RecordPanel = new JPanel();
private final JPanel TablePanel = new JPanel();
private final JScrollPane scrollPane = new JScrollPane();
private final JTable table = new JTable();
private final JButton btnPrevious = new JButton("Previous");
private DefaultTableModel tm;
private final JPanel CalculationPanel = new JPanel();
private final JLabel lblDayOfYear = new JLabel("Day of Year");
private final JTextField dayofyeartf = new JTextField();
private final JLabel lblMaximumAirTemperature = new JLabel("Max Air Temperature");
private final JTextField maxairtemptf = new JTextField();
private final JButton btnNewButton = new JButton("Get Max Air Temp");
private final JTextField searchtf = new JTextField();
private final JLabel lblSearchForDate = new JLabel("Search for Date (YYYYMMDD)");
private final JButton btnSearch = new JButton("Search");
private final JButton srtDewPointBtn = new JButton("Sort by Dew Point");
private final JButton srtRelHumBtn = new JButton("Sort by Relative Humidity");
private final JButton srtWetBulbBtn = new JButton("Sort by Wet Bulb Temp");
private final JButton srtAirTempBtn = new JButton("Sort by Air Temp");
private final JLabel lblMinAirTemperature = new JLabel("Min Air Temperature");
private final JTextField minairtemptf = new JTextField();
private final JButton btnGetMinAir = new JButton("Get Min Air Temp");
private final JLabel lblMinRelativeHumidity = new JLabel("Min Relative Humidity");
private final JTextField minrelhumtf = new JTextField();
private final JButton btnGetMinRelative = new JButton("Get Min Relative Humidity");
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public Gui(ArrayList<Weather> data)
{
minrelhumtf.setBounds(133, 123, 86, 20);
minrelhumtf.setColumns(10);
minairtemptf.setBounds(412, 8, 86, 20);
minairtemptf.setColumns(10);
searchtf.setBounds(464, 122, 86, 20);
searchtf.setColumns(10);
maxairtemptf.setBounds(144, 8, 86, 20);
maxairtemptf.setColumns(10);
dayofyeartf.setBounds(388, 5, 86, 20);
dayofyeartf.setColumns(10);
this.data = data;
datetf.setText(Integer.toString(data.get(0).getDate()));
timetf.setText(Integer.toString(data.get(0).getTime()));
dayofyeartf.setText(Integer.toString(data.get(0).getDayOfYear()));
airtemptf.setText(Double.toString(data.get(0).getAirTemp()));
wetbulbtf.setText(Double.toString(data.get(0).getTempWetBulb()));
relhumtf.setText(Integer.toString(data.get(0).getRelativeHumidity()));
dewpointtf.setText(Double.toString(data.get(0).getDewPoint()));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 732, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
tabbedPane.setBounds(10, 11, 696, 364);
contentPane.add(tabbedPane);
tabbedPane.addTab("Record", null, RecordPanel, null);
RecordPanel.setLayout(null);
lblDate.setBounds(10, 8, 49, 14);
RecordPanel.add(lblDate);
datetf.setBounds(58, 5, 86, 20);
RecordPanel.add(datetf);
datetf.setColumns(10);
lblTime.setBounds(149, 8, 54, 14);
RecordPanel.add(lblTime);
timetf.setBounds(213, 5, 86, 20);
RecordPanel.add(timetf);
timetf.setColumns(10);
lblAirTemperature.setBounds(10, 94, 161, 14);
RecordPanel.add(lblAirTemperature);
lblWetBulbTemperature.setBounds(10, 125, 175, 14);
RecordPanel.add(lblWetBulbTemperature);
lblRelativeHumidity.setBounds(6, 156, 159, 14);
RecordPanel.add(lblRelativeHumidity);
lblDewPointTemperature.setBounds(10, 187, 193, 14);
RecordPanel.add(lblDewPointTemperature);
airtemptf.setBounds(213, 94, 86, 20);
RecordPanel.add(airtemptf);
airtemptf.setColumns(10);
wetbulbtf.setBounds(213, 125, 86, 20);
RecordPanel.add(wetbulbtf);
wetbulbtf.setColumns(10);
relhumtf.setBounds(213, 156, 86, 20);
RecordPanel.add(relhumtf);
relhumtf.setColumns(10);
dewpointtf.setBounds(213, 187, 86, 20);
RecordPanel.add(dewpointtf);
dewpointtf.setColumns(10);
btnNext.setBounds(213, 231, 86, 23);
RecordPanel.add(btnNext);
/**
* Create event handler for previous button
*/
btnPrevious.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
if(index >= 0)
{
index--;
datetf.setText(Integer.toString(data.get(index).getDate()));
timetf.setText(Integer.toString(data.get(index).getTime()));
airtemptf.setText(Double.toString(data.get(index).getAirTemp()));
wetbulbtf.setText(Double.toString(data.get(index).getTempWetBulb()));
relhumtf.setText(Integer.toString(data.get(index).getRelativeHumidity()));
dewpointtf.setText(Double.toString(data.get(index).getDewPoint()));
}else
{
index = 0;
datetf.setText(Integer.toString(data.get(index).getDate()));
timetf.setText(Integer.toString(data.get(index).getTime()));
airtemptf.setText(Double.toString(data.get(index).getAirTemp()));
wetbulbtf.setText(Double.toString(data.get(index).getTempWetBulb()));
relhumtf.setText(Integer.toString(data.get(index).getRelativeHumidity()));
dewpointtf.setText(Double.toString(data.get(index).getDewPoint()));
}
}
});
btnPrevious.setBounds(10, 231, 89, 23);
RecordPanel.add(btnPrevious);
lblDayOfYear.setBounds(309, 8, 94, 14);
RecordPanel.add(lblDayOfYear);
RecordPanel.add(dayofyeartf);
RecordPanel.add(searchtf);
lblSearchForDate.setBounds(425, 97, 175, 14);
RecordPanel.add(lblSearchForDate);
/**
* action listener for search button
*/
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
int dateSearchedFor = Integer.parseInt(searchtf.getText());
Weather result = WeatherStation.search(data, dateSearchedFor);
datetf.setText(Integer.toString(result.getDate()));
dayofyeartf.setText(Integer.toString(result.getDayOfYear()));
timetf.setText(Integer.toString(result.getTime()));
airtemptf.setText((Double.toString(result.getAirTemp())));
wetbulbtf.setText((Double.toString(result.getTempWetBulb())));
relhumtf.setText(Integer.toString(result.getRelativeHumidity()));
dewpointtf.setText(Double.toString((result.getDewPoint())));
if(result.getDate() == 0)
{
JOptionPane.showMessageDialog(null, "Date not found");
}
}
});
btnSearch.setBounds(464, 152, 89, 23);
RecordPanel.add(btnSearch);
tabbedPane.addTab("Table", null, TablePanel, null);
TablePanel.setLayout(null);
scrollPane.setBounds(10, 11, 671, 264);
TablePanel.add(scrollPane);
/**
* declare table model
*/
tm = new DefaultTableModel(
new Object[][]{},
new String[] {"Date", "Day of Year" ,"Time", "Air Temp", "Wet Bulb Temp", "Relative Humidity", "Dew Point Temp"});
table.setModel(tm);
//table.setAutoCreateRowSorter(true);
/**
* Creates event handlers for sort buttons
*/
scrollPane.setViewportView(table);
srtDewPointBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DewPointCompare dpc = new DewPointCompare();
Collections.sort(data, dpc);
drawTable();
}
});
srtDewPointBtn.setBounds(521, 286, 147, 23);
TablePanel.add(srtDewPointBtn);
srtRelHumBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
RelativeHumidityCompare rhc = new RelativeHumidityCompare();
Collections.sort(data,rhc);
drawTable();
}
});
srtRelHumBtn.setBounds(336, 286, 176, 23);
TablePanel.add(srtRelHumBtn);
srtWetBulbBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
WetBulbComparator wbc = new WetBulbComparator();
Collections.sort(data, wbc);
drawTable();
}
});
srtWetBulbBtn.setBounds(157, 286, 166, 23);
TablePanel.add(srtWetBulbBtn);
srtAirTempBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AirTempCompare atc = new AirTempCompare();
Collections.sort(data, atc);
drawTable();
}
});
srtAirTempBtn.setBounds(10, 286, 128, 23);
TablePanel.add(srtAirTempBtn);
tabbedPane.addTab("Calculations", null, CalculationPanel, null);
CalculationPanel.setLayout(null);
lblMaximumAirTemperature.setBounds(10, 11, 150, 14);
CalculationPanel.add(lblMaximumAirTemperature);
CalculationPanel.add(maxairtemptf);
/**
* button event handler for max air temp button
*/
btnNewButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
maxairtemptf.setText(Double.toString(WeatherStation.findAirTempMax(data)));
}
});
btnNewButton.setBounds(43, 36, 143, 23);
CalculationPanel.add(btnNewButton);
lblMinAirTemperature.setBounds(286, 11, 116, 14);
CalculationPanel.add(lblMinAirTemperature);
/**
* button event handler for min air temp button
*/
CalculationPanel.add(minairtemptf);
btnGetMinAir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
minairtemptf.setText(Double.toString(WeatherStation.findAirTempMin(data)));
}
});
btnGetMinAir.setBounds(347, 36, 151, 23);
CalculationPanel.add(btnGetMinAir);
lblMinRelativeHumidity.setBounds(10, 126, 126, 14);
CalculationPanel.add(lblMinRelativeHumidity);
CalculationPanel.add(minrelhumtf);
/**
* button event handler for min relative humidity button
*/
btnGetMinRelative.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
minrelhumtf.setText(Integer.toString(WeatherStation.findRelativeHumidityMin(data)));
}
});
btnGetMinRelative.setBounds(10, 157, 176, 23);
CalculationPanel.add(btnGetMinRelative);
drawTable();
createABarChartTab();
}
/**
* Create bar chart method
*/
public void createABarChartTab()
{
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (int i = 0; i < data.size();i++)
{
dataset.addValue(data.get(i).getAirTemp(), "temp", Integer.toString(data.get(i).getDayOfYear()));
}
JFreeChart chart = ChartFactory.createBarChart("Temperature throughout the year", "Day of Year", "Temperature", dataset, PlotOrientation.VERTICAL, true,true,false);
ChartPanel GraphPanel = new ChartPanel(chart);
tabbedPane.add("Temperature throughout the year", GraphPanel);
}
/**
* Draws the table
*/
public void drawTable()
{
tm.setRowCount(0);
for(int i = 0; i < 266; i++)
{
Object[] object = new Object[7];
object[0] = data.get(i).getDate();
object[1] = data.get(i).getDayOfYear();
object[2] = data.get(i).getTime();
object[3] = data.get(i).getAirTemp();
object[4] = data.get(i).getTempWetBulb();
object[5] = data.get(i).getRelativeHumidity();
object[6] = data.get(i).getDewPoint();
tm.addRow(object);
}
/**
* Event handler for next button
*/
btnNext.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
index++;
datetf.setText(Integer.toString(data.get(index).getDate()));
dayofyeartf.setText(Integer.toString(data.get(index).getDayOfYear()));
timetf.setText(Integer.toString(data.get(index).getTime()));
airtemptf.setText(Double.toString(data.get(index).getAirTemp()));
wetbulbtf.setText(Double.toString(data.get(index).getTempWetBulb()));
relhumtf.setText(Integer.toString(data.get(index).getRelativeHumidity()));
dewpointtf.setText(Double.toString(data.get(index).getDewPoint()));
}
});
}
}
<file_sep>/README.md
# Programming3
This was my assignment for Programming 3. We had to get a set of data and then create a program that would read in the data, perform some calculations and display a graph.
|
da136a22f9865addb9944a5748ace7c3a189ed6e
|
[
"Markdown",
"Java"
] | 6 |
Java
|
MichaelNZ85/Programming3
|
9c669c7c93e3a4d1e23001116b61ea0c5960c387
|
87d447e1df6b0ed2e7d66319605fa6efe89fd3f9
|
refs/heads/master
|
<repo_name>snow88/graphics_lineclipping<file_sep>/midpointsubdivision.cpp
#include<iostream>
#include<graphics.h>
# define LEFT 1
# define RIGHT 4
# define TOP 8
# define BOTTOM 2
using namespace std;
int xmin, xmax, ymin, ymax;
void rectangle_wind(int xmin, int ymin, int xmax, int ymax)
{
int x,y;
y=ymin;
for(x=xmin; x<=xmax; x++)
putpixel(x,y,WHITE);
y=ymax;
for(x=xmin; x<=xmax; x++)
putpixel(x,y,WHITE);
x=xmin;
for(y=ymin; y<=ymax; y++)
putpixel(x,y,WHITE);
x=xmax;
for(y=ymin; y<=ymax; y++)
putpixel(x,y,WHITE);
}
int gencode(float x, float y)
{
int code=0;
if (x<xmin)
code|= LEFT;
if (x>xmax)
code|=RIGHT;
if (y<ymin)
code|=TOP;
if (y>ymax)
code|=BOTTOM;
return code;
}
void midpointsubdivision(float x1, float y1, float x2, float y2)
{
start:
int code1 = gencode(x1,y1);
int code2 = gencode(x2,y2);
if (code1==0 && code2==0)
{
line(x1,y1,x2,y2);
return;
}
else if ((code1 & code2)!=0)
return;
float xm, ym;
xm=(x1+x2)/2;
ym=(y1+y2)/2;
int codem = gencode(xm,ym);
if (codem!=0)
{
if ((code1 & codem)!=0)
{
x1=xm;
y1=ym;
goto start;
}
else if ((code2 & codem)!=0)
{
x2=xm;
y2=ym;
goto start;
}
}
int p1pm=0, pmp2=0;
if (codem==0)
{
if (code1==0 && codem==0)
{
line(x1,y1,xm,ym);
pmp2=1;
goto label;
}
else if (code2==0 && codem==0)
{
line(xm,ym,x2,y2);
p1pm=1;
goto label;
}
}
p1pm=1;
pmp2=1;
label:
if (p1pm==1)
{
int codem1, xm1,ym1;
do {
xm1 = (x1+xm)/2;
ym1 = (y1+ym)/2;
codem1 = gencode(xm1,ym1);
if(codem1!=0)
{
x1=xm1;
y1=ym1;
}
else
{
line(xm1,ym1,xm,ym);
xm=xm1;
ym=ym1;
}
}
while (x1!=xmin && x1!=xmax && y1!=ymin && y1!=ymax);
x1=xm;
y1=ym;
}
if (pmp2==1)
{
int codem2, xm2, ym2;
do {
xm2 = (x2+xm)/2;
ym2 = (y2+ym)/2;
codem2 = gencode(xm2,ym2);
if(codem2!=0)
{
x2=xm2;
y2=ym2;
}
else
{
line(xm2,ym2,xm,ym);
xm=xm2;
ym=ym2;
}
}
while (x2!=xmin && x2!=xmax && y2!=ymin && y2!=ymax);
x2=xm;
y2=ym;
}
}
int main()
{
int gd=DETECT, gm;
initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
int x1,y1,x2,y2;
cout<<"Enter xmin, ymin, xmax, ymax for rectangular window"<<endl;
cin>>xmin>>ymin>>xmax>>ymax;
rectangle_wind(xmin, ymin, xmax, ymax);
cout<<"Enter x1,y1,x2,y2 for original line"<<endl;
cin>>x1>>y1>>x2>>y2;
line(x1,y1,x2,y2);
cout<<"Press any key to clip line"<<endl;
char ch;
cin>>ch;
cleardevice();
rectangle_wind(xmin, ymin, xmax, ymax);
midpointsubdivision(x1,y1,x2,y2);
getch();
closegraph();
return 0;
}
<file_sep>/cyrusbeck_lineclipping.cpp
#include<iostream>
#include<algorithm>
#include<graphics.h>
using namespace std;
void rectangle_wind(int xmin, int ymin, int xmax, int ymax)
{
int x,y;
y=ymin;
for(x=xmin; x<=xmax; x++)
putpixel(x,y,WHITE);
y=ymax;
for(x=xmin; x<=xmax; x++)
putpixel(x,y,WHITE);
x=xmin;
for(y=ymin; y<=ymax; y++)
putpixel(x,y,WHITE);
x=xmax;
for(y=ymin; y<=ymax; y++)
putpixel(x,y,WHITE);
}
void line_majormovt(int xminl, int yminl, int xmaxl, int ymaxl, int lcolor)
{
float x=xminl;
float y=yminl;
float dx = xmaxl-xminl;
float dy = ymaxl-yminl;
float m = dy/dx;
if(abs((int)dy)<abs((int)dx))
{
putpixel(x,y,lcolor);
while(x<=xmaxl)
{
y+=m;
x++;
putpixel(x,y,lcolor);
}
}
else
{
putpixel(x,y,lcolor);
while(y<=ymaxl)
{
x+=1/m;
y++;
putpixel(x,y,lcolor);
}
}
}
void clip_line(int xmin, int ymin, int xmax, int ymax, int xminl, int yminl, int xmaxl, int ymaxl)
{
//normals
int left[]={-1,0};
int bottom[]={0,1};
int right[]={1,0};
int top[]={0,-1};
float p2_p1[]={xmaxl-xminl, ymaxl-yminl};
float pe[]={xmin, ymin};
float tleft=(pe[0]-xminl)/p2_p1[0];
pe[0]=xmin;
pe[1]=ymax;
float tbottom=(ymin-pe[1])/(-p2_p1[1]);
pe[0]=xmax;
pe[1]=ymax;
float tright=(xminl-pe[0])/(-p2_p1[0]);
pe[0]=xmax;
pe[1]=ymin;
float ttop=(pe[1]-yminl)/p2_p1[1];
float s_ent[5];
s_ent[0]=0;
int i=1;
float s_ext[5];
int j=0;
if(tleft>0 && tleft<1)
{
s_ent[i]=tleft;
i++;
}
if(ttop>0 && ttop<1)
{
s_ent[i]=ttop;
i++;
}
if(tright>0 && tright<1)
{
s_ext[j]=tright;
j++;
}
if(tbottom>0 && tbottom<1)
{
s_ext[j]=tbottom;
j++;
}
s_ext[j]=1;
j++;
float *t_ent = max_element(s_ent,s_ent+i);
float *t_ext = min_element(s_ext,s_ext+j);
float pt_ent[]= {xminl+(*t_ent)*p2_p1[0], yminl+(*t_ent)*p2_p1[1]};
float pt_ext[]= {xminl+(*t_ext)*p2_p1[0], yminl+(*t_ext)*p2_p1[1]};
cleardevice();
rectangle_wind(xmin, ymin, xmax, ymax);
line_majormovt(pt_ent[0],pt_ent[1],pt_ext[0],pt_ext[1],WHITE);
}
int main()
{
int gd=DETECT, gm;
initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
int xmin, ymin, xmax, ymax;
int xminl, yminl, xmaxl, ymaxl;
cout<<"Enter xmin, ymin, xmax, ymax for rectangular window"<<endl;
cin>>xmin>>ymin>>xmax>>ymax;
rectangle_wind(xmin, ymin, xmax, ymax);
cout<<"Enter xmin, ymin, xmax, ymax for original line"<<endl;
cin>>xminl>>yminl>>xmaxl>>ymaxl;
line_majormovt(xminl, yminl, xmaxl, ymaxl, WHITE);
cout<<"Press any key to clip line"<<endl;
char ch;
cin>>ch;
clip_line(xmin, ymin, xmax, ymax, xminl, yminl, xmaxl, ymaxl);
getch();
closegraph();
return 0;
}
<file_sep>/cohensutherland_lineclipping.cpp
#include<iostream>
#include<graphics.h>
# define LEFT 1
# define RIGHT 4
# define TOP 8
# define BOTTOM 2
using namespace std;
int xmin, xmax, ymin, ymax;
void rectangle_wind(int xmin, int ymin, int xmax, int ymax)
{
int x,y;
y=ymin;
for(x=xmin; x<=xmax; x++)
putpixel(x,y,WHITE);
y=ymax;
for(x=xmin; x<=xmax; x++)
putpixel(x,y,WHITE);
x=xmin;
for(y=ymin; y<=ymax; y++)
putpixel(x,y,WHITE);
x=xmax;
for(y=ymin; y<=ymax; y++)
putpixel(x,y,WHITE);
}
int gencode(float x, float y)
{
int code=0;
if (x<xmin)
code|= LEFT;
if (x>xmax)
code|=RIGHT;
if (y<ymin)
code|=TOP;
if (y>ymax)
code|=BOTTOM;
return code;
}
void cohensutherland(float x1, float y1, float x2, float y2)
{
bool done=false;
int code1, code2;
do {
code1 = gencode(x1,y1);
code2 = gencode(x2,y2);
if (code1==0 && code2==0)
{
line(x1,y1,x2,y2);
done = true;
}
else if ((code1 & code2)!=0)
{
done = true;
}
else if ((code1 & code2)==0 && (code1 | code2)!=0)
{
int codeout;
float x,y;
if (code1!=0)
codeout=code1;
else
codeout=code2;
if(codeout & TOP)
{
x = x1 + (x2-x1)*(ymin-y1)/(y2-y1);
y = ymin;
}
else if(codeout & BOTTOM)
{
x = x1 + (x2-x1)*(ymax-y1)/(y2-y1);
y = ymax;
}
else if(codeout & RIGHT)
{
y = y1 + (y2-y1)*(xmax-x1)/(x2-x1);
x = xmax;
}
else if(codeout & LEFT)
{
y = y1 + (y2-y1)*(xmin-x1)/(x2-x1);
x = xmin;
}
if (codeout==code1)
{
x1=x;
y1=y;
code1=gencode(x1,y1);
}
else
{
x2=x;
y2=y;
code1=gencode(x2,y2);
}
}
}
while(!done);
line(x1,y1,x2,y2);
}
int main()
{
int gd=DETECT, gm;
initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
int x1,y1,x2,y2;
cout<<"Enter xmin, ymin, xmax, ymax for rectangular window"<<endl;
cin>>xmin>>ymin>>xmax>>ymax;
rectangle_wind(xmin, ymin, xmax, ymax);
cout<<"Enter x1,y1,x2,y2 for original line"<<endl;
cin>>x1>>y1>>x2>>y2;
line(x1,y1,x2,y2);
cout<<"Press any key to clip line"<<endl;
char ch;
cin>>ch;
cleardevice();
rectangle_wind(xmin, ymin, xmax, ymax);
cohensutherland(x1,y1,x2,y2);
getch();
closegraph();
return 0;
}
|
2459f8c9047be9ed06e38183441de1b97fa61b9b
|
[
"C++"
] | 3 |
C++
|
snow88/graphics_lineclipping
|
ce8af3814e94f0300c448f0fdcffc5e7c3d404b3
|
519cdca623480d3fe9efb3f9b8439ecb0c104c5d
|
refs/heads/master
|
<repo_name>TobiasMR/AEVB<file_sep>/main.lua
-- <NAME> - <<EMAIL>>
require 'torch'
require 'nn'
require 'nngraph'
require 'optim'
nngraph.setDebug(false)
local VAE = require 'VAE'
require 'KLDCriterion'
require 'GaussianCriterion'
require 'Sampler'
--For loading data files
require 'load'
cmd = torch.CmdLine()
cmd:text()
cmd:text()
cmd:text('Training a Variational Autoencoder')
cmd:text()
cmd:text('Options')
cmd:option('-seed',123,'initial random seed')
cmd:option('-dataset','mnist','mnist|frey')
cmd:option('-hidden_layer_size', 400, 'size of the hidden layer of the encoder and decoder')
cmd:option('-latent_space_size', 20, 'dimensionality of the latent space')
cmd:option('-batch_size', 100, 'batch size')
cmd:text()
-- parse input params
params = cmd:parse(arg)
local continuous
if params.dataset == "mnist" then
continuous = false
else
continuous = true
end
data = load(continuous)
local input_size = data.train:size(2)
local latent_variable_size = params.latent_space_size
local hidden_layer_size = params.hidden_layer_size
torch.manualSeed(params.seed)
local encoder = VAE.get_encoder(input_size, hidden_layer_size, latent_variable_size)
local decoder = VAE.get_decoder(input_size, hidden_layer_size, latent_variable_size, continuous)
local input = nn.Identity()()
local mean, log_var = encoder(input):split(2)
local z = nn.Sampler()({mean, log_var})
local reconstruction, reconstruction_var, model
if continuous then
reconstruction, reconstruction_var = decoder(z):split(2)
model = nn.gModule({input},{reconstruction, reconstruction_var, mean, log_var})
criterion = nn.GaussianCriterion()
else
reconstruction = decoder(z)
model = nn.gModule({input},{reconstruction, mean, log_var})
criterion = nn.BCECriterion()
criterion.sizeAverage = false
end
-- Some code to draw computational graph
-- dummy_x = torch.rand(dim_input)
-- model:forward({dummy_x})
-- Uncomment to get structure of the Variational Autoencoder
-- graph.dot(.fg, 'Variational Autoencoder', 'VA')
KLD = nn.KLDCriterion()
local parameters, gradients = model:getParameters()
local config = {
learningRate = 0.001
}
local state = {}
epoch = 0
while true do
epoch = epoch + 1
local lowerbound = 0
local tic = torch.tic()
local shuffle = torch.randperm(data.train:size(1))
-- This batch creation is inspired by szagoruyko CIFAR example.
local indices = torch.randperm(data.train:size(1)):long():split(params.batch_size)
indices[#indices] = nil
local N = #indices * params.batch_size
local tic = torch.tic()
for t,v in ipairs(indices) do
xlua.progress(t, #indices)
local inputs = data.train:index(1,v)
local opfunc = function(x)
if x ~= parameters then
parameters:copy(x)
end
model:zeroGradParameters()
local reconstruction, reconstruction_var, mean, log_var
if continuous then
reconstruction, reconstruction_var, mean, log_var = unpack(model:forward(inputs))
reconstruction = {reconstruction, reconstruction_var}
else
reconstruction, mean, log_var = unpack(model:forward(inputs))
end
local err = criterion:forward(reconstruction, inputs)
local df_dw = criterion:backward(reconstruction, inputs)
local KLDerr = KLD:forward(mean, log_var)
local dKLD_dmu, dKLD_dlog_var = unpack(KLD:backward(mean, log_var))
if continuous then
error_grads = {df_dw[1], df_dw[2], dKLD_dmu, dKLD_dlog_var}
else
error_grads = {df_dw, dKLD_dmu, dKLD_dlog_var}
end
model:backward(inputs, error_grads)
local batchlowerbound = err + KLDerr
return batchlowerbound, gradients
end
x, batchlowerbound = optim.adam(opfunc, parameters, config, state)
lowerbound = lowerbound + batchlowerbound[1]
end
print("Epoch: " .. epoch .. " Lowerbound: " .. lowerbound/N .. " time: " .. torch.toc(tic))
if lowerboundlist then
lowerboundlist = torch.cat(lowerboundlist,torch.Tensor(1,1):fill(lowerbound/N),1)
else
lowerboundlist = torch.Tensor(1,1):fill(lowerbound/N)
end
if epoch % 2 == 0 then
torch.save('save/parameters.t7', parameters)
torch.save('save/state.t7', state)
torch.save('save/lowerbound.t7', torch.Tensor(lowerboundlist))
end
end
|
d78fda31bc0e77aa8064edfdf19f8f79f7c1cada
|
[
"Lua"
] | 1 |
Lua
|
TobiasMR/AEVB
|
78b780f69d5d5136b49bcaff7da96eabb34de31a
|
48db953c46470f27b9149d8a17b1a8fcc12a97d3
|
refs/heads/master
|
<file_sep>package com.example.meetup.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.meetup.R
import com.example.meetup.room.model.User
class FriendRecyclerAdapter(
val context: Context,
private val users: List<User>,
val itemClickListener: OnItemClickListener): RecyclerView.Adapter<FriendRecyclerAdapter.ViewHolder>() {
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val nameText: TextView = itemView.findViewById(R.id.card_user_name)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.card_user,parent,false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val user = users[position]
with(holder) {
nameText.text = user.name
itemView.setOnClickListener {
// replace chat fragment with this user id
itemClickListener.onItemClicked(user)
}
}
}
override fun getItemCount() = users.size
interface OnItemClickListener {
fun onItemClicked(user: User)
}
}<file_sep>package com.example.meetup.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.meetup.R
import com.example.meetup.room.model.User
import com.google.android.material.button.MaterialButton
class SuggestionRecyclerAdapter(
val context: Context,
private val users: List<User>,
private val itemClickListener: OnItemClickListener): RecyclerView.Adapter<SuggestionRecyclerAdapter.ViewHolder>() {
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val nameText: TextView = itemView.findViewById(R.id.card_suggestion_user_name)
val sendRequest: MaterialButton = itemView.findViewById(R.id.send_hello_request)
val removeSuggestion: MaterialButton = itemView.findViewById(R.id.remove_suggestion)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.card_suggestion_friend,parent,false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val user = users[position]
with(holder) {
nameText.text = user.name
sendRequest.setOnClickListener {
// replace chat fragment with this user id
itemClickListener.onItemClickedSuggestion(user, true)
}
removeSuggestion.setOnClickListener {
itemClickListener.onItemClickedSuggestion(user, false)
}
}
}
override fun getItemCount() = users.size
interface OnItemClickListener {
fun onItemClickedSuggestion(user: User, flag: Boolean)
}
}<file_sep>package com.example.meetup.repository
import android.app.Application
import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.annotation.WorkerThread
import androidx.lifecycle.MutableLiveData
import com.example.meetup.BASE_URL
import com.example.meetup.LOG_TAG
import com.example.meetup.R
import com.example.meetup.room.ChatDatabase
import com.example.meetup.room.model.Message
import com.example.meetup.room.model.User
import com.example.meetup.service.WebService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
class MainRepository(val app: Application) {
val friends = MutableLiveData<List<User>>()
val suggestions = MutableLiveData<List<User>>()
val requests = MutableLiveData<List<User>>()
val chats = arrayListOf<Message>()
var userId = -1
val newMessage = MutableLiveData<Boolean>()
val networkConnection = MutableLiveData<Boolean>()
private val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(provideOkHttpClient())
.addConverterFactory(MoshiConverterFactory.create())
.build()
private val service = retrofit.create(WebService::class.java)
private val sharedPref = app.getSharedPreferences(app.getString(R.string.SHARED_PREF), Context.MODE_PRIVATE)
private val database = ChatDatabase.getInstance(app)
//3 the Coroutine runs using the Main (UI) dispatcher
private val coroutineScope = CoroutineScope(Dispatchers.IO)
init {
userId = getId()
newMessage.value = false
}
private fun getId() = sharedPref.getInt("id", 0)
@WorkerThread
suspend fun updateToken(id: Int, token: String) {
if(networkConnection.value == false) {
} else {
try {
service.updateToken(id, token).body()
} catch (e: Throwable) {
Log.d(LOG_TAG, e.message)
} catch(e: Exception) {
Log.d(LOG_TAG, e.message)
}
}
}
@WorkerThread
suspend fun getFriends(id: Int) {
var items = database.chatDao().getFriends()
friends.postValue(items)
try {
items = service.getFriends(id).body()
?: emptyList()
withContext(Dispatchers.IO) {
// upload to local database
database.chatDao().deleteFriends()
database.chatDao().insertFriends(items)
}
friends.postValue(items)
} catch (e: Throwable) {
Log.d(LOG_TAG, e.message)
} catch(e: Exception) {
Log.d(LOG_TAG, e.message)
}
}
@WorkerThread
suspend fun getFriendRequests(userId: Int) {
if(networkConnection.value == false) {
// get from local
} else {
try {
val serviceData = service.getFriendRequests(userId).body()
?: emptyList()
requests.postValue(serviceData)
Log.d(LOG_TAG, "getFriendRequests :- $serviceData")
newMessage.postValue(newMessage.value != true)
} catch (e: Throwable) {
Log.d(LOG_TAG, e.message)
} catch(e: Exception) {
Log.d(LOG_TAG, e.message)
}
}
}
@WorkerThread
suspend fun getInterestedUsers(map : HashMap<String,String>) {
if(networkConnection.value == false) {
} else {
try {
val serviceData = service.allInterestedUsers(map).body()
?: emptyList()
updateSuggestions(serviceData)
Log.d(LOG_TAG, "getInterestedUser :- $serviceData")
newMessage.postValue(newMessage.value != true)
} catch (e: Throwable) {
Log.d(LOG_TAG, e.message)
} catch(e: Exception) {
Log.d(LOG_TAG, e.message)
}
}
}
private fun updateSuggestions(serviceData: List<User>) {
val items = arrayListOf<User>()
for(user in serviceData) {
if(friends.value?.contains(user) == true ||
user.id == userId)
continue
items.add(user)
}
suggestions.postValue(items)
}
@WorkerThread
suspend fun getUserInterests(id: Int) {
var items = database.chatDao().getUserInterests()
if(items.isNullOrEmpty()) {
try {
items = service.userIntrests(id).body() ?: emptyList()
database.chatDao().insertUserInterests(items)
// delete prev interest and now add new interest
} catch (e: Throwable) {
Log.d(LOG_TAG, e.message)
} catch (e: Exception) {
Log.d(LOG_TAG, e.message)
}
}
withContext(Dispatchers.IO) {
val map = hashMapOf<String, String>()
for (item in items) {
map[item.id.toString()] = item.name
}
getInterestedUsers(map)
}
}
@WorkerThread
suspend fun makeFriends(friendId: Int) {
if(networkConnection.value == false) {
} else {
val serviceData = service.makeFriends(userId, friendId).body() ?: false
withContext(Dispatchers.Main) {
Toast.makeText(app, serviceData.toString(), Toast.LENGTH_SHORT).show()
}
}
}
@WorkerThread
suspend fun addFriendRequests(friendId: Int) {
if(networkConnection.value == false) {
} else {
val serviceData = service.addFriendRequests(userId, friendId).body() ?: false
withContext(Dispatchers.Main) {
Toast.makeText(app, serviceData.toString(), Toast.LENGTH_SHORT).show()
}
}
}
@WorkerThread
suspend fun removeFriendRequests(friendId: Int) {
if(networkConnection.value == false) {
} else {
val serviceData = service.removeFriendRequests(userId, friendId).body() ?: false
withContext(Dispatchers.Main) {
Toast.makeText(app, serviceData.toString(), Toast.LENGTH_SHORT).show()
}
}
}
fun callInitialMethod() {
coroutineScope.launch {
getFriends(userId)
getUserInterests(userId)
getFriendRequests(userId)
}
}
private fun provideOkHttpClient(): OkHttpClient? {
val okhttpClientBuilder = OkHttpClient.Builder()
okhttpClientBuilder.connectTimeout(10, TimeUnit.SECONDS)
okhttpClientBuilder.readTimeout(10, TimeUnit.SECONDS)
okhttpClientBuilder.writeTimeout(10, TimeUnit.SECONDS)
return okhttpClientBuilder.build()
}
}<file_sep>package com.example.meetup.ui.login.fragment
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.meetup.R
import com.example.meetup.ui.login.viewmodel.LoginViewModel
class LoginFragment : Fragment() {
private lateinit var viewModel : LoginViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate (R.layout.fragment_login, container, false)
val layoutSignUp = view.findViewById<View>(R.id.layout_signup_fragment)
val layoutLogin = view.findViewById<View>(R.id.layout_login_fragment)
val changeToSignUp = view.findViewById<TextView>(R.id.login_to_signUp)
val changeToLogin = view.findViewById<TextView>(R.id.signup_to_login)
val loginButton = view.findViewById<Button>(R.id.login_button)
val signUpButton = view.findViewById<Button>(R.id.sign_button)
val loginEmail = view.findViewById<EditText>(R.id.login_email)
val loginPassword = view.findViewById<EditText>(R.id.login_password)
val signUpName = view.findViewById<EditText>(R.id.sign_name)
val signUpNumber = view.findViewById<EditText>(R.id.sign_number)
val signUpEmail = view.findViewById<EditText>(R.id.sign_email)
val signUpPassword = view.findViewById<EditText>(R.id.sign_password)
viewModel = ViewModelProvider(requireActivity()).get(LoginViewModel::class.java)
changeToSignUp.setOnClickListener {
it.hideKeyboard()
layoutLogin.visibility = View.GONE
layoutSignUp.visibility = View.VISIBLE
}
changeToLogin.setOnClickListener {
it.hideKeyboard()
layoutSignUp.visibility = View.GONE
layoutLogin.visibility = View.VISIBLE
}
loginButton.setOnClickListener {
it.hideKeyboard()
val stringEmail = loginEmail.text.toString()
val stringPassword = loginPassword.text.toString()
if(stringEmail.isEmpty() || stringPassword.isEmpty()) {
Toast.makeText(requireActivity(),"Please fill all fields",Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
viewModel.loginUser(stringEmail, stringPassword)
}
signUpButton.setOnClickListener {
it.hideKeyboard()
val stringName = signUpName.text.toString()
val stringNumber = signUpNumber.text.toString()
val stringEmail = signUpEmail.text.toString()
val stringPassword = <PASSWORD>()
if (stringName.isEmpty() || stringEmail.isEmpty() || stringPassword.isEmpty()) {
Toast.makeText(requireActivity(), "Please fill all fields", Toast.LENGTH_SHORT)
.show()
return@setOnClickListener
}
viewModel.signUpUser(stringName, stringEmail, stringPassword)
}
return view
}
private fun View.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
}<file_sep>package com.example.meetup.ui.chat
import android.net.ConnectivityManager
import android.net.Network
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.example.meetup.MainApplication
import com.example.meetup.R
import com.example.meetup.ui.chat.viewmodel.ChatViewModel
import io.socket.client.IO
import io.socket.client.Socket
import io.socket.engineio.client.transports.WebSocket
import java.net.URISyntaxException
class ChatActivity : AppCompatActivity() {
private lateinit var viewModel: ChatViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat)
val nm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
viewModel = ViewModelProvider(this).get(ChatViewModel::class.java)
viewModel.chatRepo.friendId = intent.getIntExtra("userid",-1)
viewModel.chatRepo.friendName= intent.getStringExtra("username")
showNetworkState(nm)
}
private fun showNetworkState(nm: ConnectivityManager) {
nm.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
//Network Connected
viewModel.chatRepo.callInitialMethod()
// for syncing chat
viewModel.chatRepo.networkConnection.postValue(true)
}
override fun onLost(network: Network) {
super.onLost(network)
// NetWork Disconnected
viewModel.chatRepo.networkConnection.postValue(false)
}
})
}
override fun onResume() {
super.onResume()
viewModel.chatRepo.callInitialMethod()
}
}<file_sep>package com.example.meetup.ui.main.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.example.meetup.R
import com.example.meetup.ui.main.viewmodel.MainViewModel
class NotificationFragment : Fragment() {
private lateinit var recyclerView: RecyclerView
private lateinit var viewModel: MainViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_notification, container, false)
viewModel = ViewModelProvider(requireActivity()).get(MainViewModel::class.java)
recyclerView = view.findViewById(R.id.notification_recycler_view)
return view
}
}<file_sep>package com.example.meetup.ui.main
import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.Network
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.ViewPager
import com.example.meetup.LOG_TAG
import com.example.meetup.MainApplication
import com.example.meetup.NETWORK_REQ_CODE
import com.example.meetup.R
import com.example.meetup.adapter.SectionsPagerAdapter
import com.example.meetup.receiver.FCMessageReceiver
import com.example.meetup.ui.main.viewmodel.MainViewModel
import com.google.android.material.tabs.TabLayout
import com.google.firebase.messaging.FirebaseMessaging
import io.socket.client.IO
import io.socket.client.Socket
import io.socket.engineio.client.transports.WebSocket
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.net.URISyntaxException
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: MainViewModel
private lateinit var fcMessageReceiver: BroadcastReceiver
private lateinit var filter: IntentFilter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// fcMessageReceiver = FCMessageReceiver(this)
// filter = IntentFilter("com.example.meetup.newMessage")
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
if(!checkPermission())
ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_NETWORK_STATE), NETWORK_REQ_CODE)
val nm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
showNetworkState(nm)
val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
val viewPager: ViewPager = findViewById(R.id.view_pager)
viewPager.adapter = sectionsPagerAdapter
val tabs: TabLayout = findViewById(R.id.tabs)
tabs.setupWithViewPager(viewPager)
getToken()
viewModel.mainRepo.callInitialMethod()
}
private fun getToken() {
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
if (task.isSuccessful) {
val sharedPref = getSharedPreferences(resources.getString(R.string.SHARED_PREF), Context.MODE_PRIVATE)
val id = sharedPref.getInt("id", -1)
CoroutineScope(Dispatchers.IO).launch {
if (id != -1)
viewModel.mainRepo.updateToken(id, task.result.toString())
}
}
}
}
private fun checkPermission() : Boolean {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE)
!= PackageManager.PERMISSION_GRANTED) {
return false
}
return true
}
private fun showNetworkState(nm: ConnectivityManager) {
nm.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
//Network Connected
viewModel.mainRepo.networkConnection.postValue(true)
viewModel.mainRepo.callInitialMethod()
}
override fun onLost(network: Network) {
super.onLost(network)
// NetWork Disconnected
viewModel.mainRepo.networkConnection.postValue(false)
}
})
}
}<file_sep>package com.example.meetup
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import android.widget.Toast
import androidx.annotation.WorkerThread
import com.example.meetup.service.WebService
import io.socket.client.IO
import io.socket.client.Socket
import io.socket.engineio.client.transports.WebSocket
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.net.URISyntaxException
class MainApplication : Application() {
// Here make a socket instance
private val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create())
.build()
private val service = retrofit.create(WebService::class.java)
// so that keeps alive though app
override fun onCreate() {
super.onCreate()
val sharedPref = getSharedPreferences(getString(R.string.SHARED_PREF), Context.MODE_PRIVATE)
val userId = getId(sharedPref)
}
private fun getId(sharedPref: SharedPreferences) = sharedPref.getInt("id", 0)
}<file_sep>package com.example.meetup.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.meetup.R
import com.example.meetup.room.model.User
import com.google.android.material.button.MaterialButton
class RequestRecyclerAdapter(
val context: Context,
private val users: List<User>,
private val itemClickListener: OnItemClickListener): RecyclerView.Adapter<RequestRecyclerAdapter.ViewHolder>() {
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val nameText: TextView = itemView.findViewById(R.id.card_request_user_name)
val acceptRequest: MaterialButton = itemView.findViewById(R.id.accept_request)
val declineRequest: MaterialButton = itemView.findViewById(R.id.decline_request)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.card_accept_request,parent,false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val user = users[position]
with(holder) {
nameText.text = user.name
acceptRequest.setOnClickListener {
// replace chat fragment with this user id
itemClickListener.onItemClickedRequest(user, true)
}
declineRequest.setOnClickListener {
itemClickListener.onItemClickedRequest(user, false)
}
}
}
override fun getItemCount() = users.size
interface OnItemClickListener {
fun onItemClickedRequest(user: User, flag: Boolean)
}
}<file_sep>package com.example.meetup.room.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "friends")
data class User (
@PrimaryKey
val id : Int,
val name : String,
val email : String,
val password : String,
val status : String?,
val lastseen : String?,
val socketid : String?,
val token : String?
)<file_sep>package com.example.meetup.ui.main.fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.example.meetup.R
import com.example.meetup.adapter.FriendRecyclerAdapter
import com.example.meetup.room.model.User
import com.example.meetup.ui.chat.ChatActivity
import com.example.meetup.ui.main.viewmodel.MainViewModel
class UserFragment : Fragment(), FriendRecyclerAdapter.OnItemClickListener {
private lateinit var recyclerView : RecyclerView
private lateinit var recyclerAdapter : FriendRecyclerAdapter
private lateinit var viewModel : MainViewModel
companion object {
private var mInstance = UserFragment()
fun getInstance(): UserFragment {
return mInstance
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_user, container, false)
viewModel = ViewModelProvider(requireActivity()).get(MainViewModel::class.java)
recyclerView = view.findViewById(R.id.user_recycler_view)
if(!viewModel.mainRepo.friends.value.isNullOrEmpty()) {
recyclerAdapter = FriendRecyclerAdapter(requireActivity(),
viewModel.mainRepo.friends.value!!,this)
recyclerView.adapter = recyclerAdapter
recyclerAdapter.notifyDataSetChanged()
}
viewModel.mainRepo.friends.observe(requireActivity()) {
recyclerAdapter = FriendRecyclerAdapter(requireActivity(),it,this)
recyclerView.adapter = recyclerAdapter
recyclerAdapter.notifyDataSetChanged()
}
return view
}
override fun onItemClicked(user: User) {
// go to chat fragment
val intent = Intent(requireActivity(), ChatActivity::class.java)
intent.putExtra("userid",user.id)
intent.putExtra("username",user.name)
startActivity(intent)
}
}<file_sep>package com.example.meetup.ui.chat.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.example.meetup.repository.ChatRepository
class ChatViewModel(app: Application): AndroidViewModel(app) {
val chatRepo = ChatRepository(app)
}<file_sep>package com.example.meetup.ui.login.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.meetup.R
import com.example.meetup.ui.login.viewmodel.LoginViewModel
class SplashFragment : Fragment() {
private lateinit var viewModel : LoginViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_splash, container, false)
// check login
viewModel = ViewModelProvider(requireActivity()).get(LoginViewModel::class.java)
viewModel.loginRepo.isLogin()
return view
}
}<file_sep>package com.example.meetup.room.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
@Entity(tableName = "chats")
data class Message(
@PrimaryKey
val messageid : Int,
val senderid : Int,
val receiverid : Int,
val message : String,
val messagetype : Int,
val filelink : String?,
val sendtime : String
)
<file_sep>package com.example.meetup.repository
import android.app.Application
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast
import androidx.annotation.WorkerThread
import androidx.lifecycle.MutableLiveData
import com.example.meetup.BASE_URL
import com.example.meetup.LOG_TAG
import com.example.meetup.R
import com.example.meetup.room.ChatDatabase
import com.example.meetup.room.model.Interest
import com.example.meetup.room.model.User
import com.example.meetup.room.model.UserInterest
import com.example.meetup.service.WebService
import com.example.meetup.ui.main.MainActivity
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
class LoginRepository(val app : Application) {
val networkConnection = MutableLiveData<Boolean>() // network connection
var chipSet = MutableLiveData<MutableSet<String>>() // add interest
val loginStat = MutableLiveData<Boolean>() // login state
var firstTime = false
val interests = MutableLiveData<List<Interest>>() // all interests
val userInterests = MutableLiveData<List<UserInterest>>() // user interests
private val sharedPref = app.getSharedPreferences(app.getString(R.string.SHARED_PREF), Context.MODE_PRIVATE)
private val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create())
.build()
private val service: WebService = retrofit.create(WebService::class.java)
private val database = ChatDatabase.getInstance(app) // local database
@WorkerThread
suspend fun getLoginUser(email : String,password : String) {
if(networkConnection.value == false) {
withContext(Dispatchers.Main) {
Toast.makeText(app, "No Network Connection", Toast.LENGTH_SHORT).show()
}
} else {
val serviceData = service.loginUser(email, password).body() ?: emptyList()
withContext(Dispatchers.Main) {
if (serviceData.isEmpty()) {
Toast.makeText(app, "Login error : Incorrect Email or Password", Toast.LENGTH_SHORT).show()
}
}
if (serviceData.isNotEmpty()) saveUser(serviceData[0])
}
}
@WorkerThread
suspend fun getSignUpUser(name: String,email: String,password: String) {
if(networkConnection.value == false) {
withContext(Dispatchers.Main) {
Toast.makeText(app, "No Network Connection", Toast.LENGTH_SHORT).show()
}
} else {
val serviceData = service.signUpUser(name, email, password).body() ?: emptyList()
withContext(Dispatchers.Main) {
if (serviceData.isEmpty()) {
Toast.makeText(app, "SignUp error : " +
"If you have already have an account with this email " +
"then please try to login",
Toast.LENGTH_SHORT).show()
}
}
if (serviceData.isNotEmpty()) saveUser(serviceData[0])
}
}
@WorkerThread
suspend fun getAddInterests(map : HashMap<String,String>) {
if(networkConnection.value == false) {
} else {
val serviceData = service.addInterest(map).body() ?: false
withContext(Dispatchers.Main) {
if (!serviceData) {
Toast.makeText(app, "Error !!!", Toast.LENGTH_SHORT).show()
} else {
// add to local database
val items = arrayListOf<UserInterest>()
for (item in map.entries) {
items.add(UserInterest(item.key.toInt(), item.value))
}
withContext(Dispatchers.IO) {
database.chatDao().insertUserInterests(items)
}
Toast.makeText(app, "Interests Added Successfully !!!", Toast.LENGTH_SHORT).show()
val intent = Intent(app, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or
Intent.FLAG_ACTIVITY_NO_HISTORY or
Intent.FLAG_ACTIVITY_NEW_TASK
app.startActivity(intent)
}
}
}
}
@WorkerThread
suspend fun getInterests() {
if(networkConnection.value == false) {
} else {
try {
val serviceData = service.getInterests().body() ?: emptyList()
interests.postValue(serviceData)
// delete prev interest and now add new interest
withContext(Dispatchers.IO) {
database.chatDao().deleteInterests()
database.chatDao().insertInterests(serviceData)
}
} catch (e: Throwable) {
Log.d(LOG_TAG, e.message ?: "Error")
} catch(e: Exception) {
Log.d(LOG_TAG, e.message ?: "Error")
}
}
}
@WorkerThread
suspend fun getUserInterests(id: Int) {
if(networkConnection.value == false) {
} else {
try {
val serviceData = service.userIntrests(id).body() ?: emptyList()
// delete prev interest and now add new interest
withContext(Dispatchers.IO) {
database.chatDao().deleteUserInterests()
database.chatDao().insertUserInterests(serviceData)
userInterests.postValue(serviceData)
}
} catch (e: Throwable) {
Log.d(LOG_TAG, e.message ?: "Error")
} catch(e: Exception) {
Log.d(LOG_TAG, e.message ?: "Error")
}
}
}
private fun saveUser(user: User) {
with(sharedPref.edit()) {
putBoolean("login", true)
putInt("id", user.id)
putString("name", user.name)
putString("email", user.email)
putString("password", <PASSWORD>)
putString("token", user.token)
putString("socketid", user.socketid)
commit()
}
loginStat.postValue(true)
firstTime = true
}
fun isLogin() : Boolean {
return sharedPref.getBoolean("login",false).also { this.loginStat.value = it }
}
fun signUpUser(stringName: String, stringEmail: String, stringPassword: String) {
CoroutineScope(Dispatchers.IO).launch {
getSignUpUser(stringName, stringEmail, stringPassword)
}
}
fun loginUser(stringEmail: String, stringPassword: String) {
CoroutineScope(Dispatchers.IO).launch {
getLoginUser(stringEmail, stringPassword)
}
}
private fun getUserId() = sharedPref.getInt("id", 0)
fun addInterests() {
if(interests.value.isNullOrEmpty()) return
val map = HashMap<String,String>()
val id = getUserId().toString()
for(item in interests.value!!)
if(chipSet.value?.contains(item.name) == true)
map[item.id.toString()] = id
CoroutineScope(Dispatchers.IO).launch {
getAddInterests(map)
}
}
fun interests() {
CoroutineScope(Dispatchers.IO).launch {
val items = database.chatDao().getInterests()
if (items.isEmpty()) {
getInterests()
} else {
interests.postValue(items)
}
}
}
fun userInterests() {
CoroutineScope(Dispatchers.IO).launch {
val items = database.chatDao().getUserInterests()
if (items.isEmpty()) {
getUserInterests(getUserId())
} else {
userInterests.postValue(items)
}
}
}
}<file_sep>package com.example.meetup.room
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.meetup.room.model.Interest
import com.example.meetup.room.model.Message
import com.example.meetup.room.model.User
import com.example.meetup.room.model.UserInterest
@Dao
interface ChatDao {
@Query("SELECT * FROM interests")
fun getInterests(): List<Interest>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertInterests(interests: List<Interest>)
@Query("DELETE FROM interests")
fun deleteInterests()
@Query("SELECT * FROM userinterests")
fun getUserInterests(): List<UserInterest>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertUserInterests(interests: List<UserInterest>)
@Query("DELETE FROM userinterests")
fun deleteUserInterests()
@Query("SELECT * FROM friends")
fun getFriends(): List<User>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertFriends(users : List<User>)
@Query("DELETE FROM friends")
fun deleteFriends()
@Query("SELECT * FROM chats WHERE " +
"(senderid = :senderId AND receiverid = :receiverId) " +
"OR (senderid = :receiverId AND receiverid = :senderId)")
fun getChats(senderId: Int,receiverId: Int): List<Message>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertChat(message: Message)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertChats(message: List<Message>)
@Query("DELETE FROM chats")
fun deleteChats()
}<file_sep>package com.example.meetup.ui.login.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.lifecycle.ViewModelProvider
import com.example.meetup.R
import com.example.meetup.ui.login.viewmodel.LoginViewModel
import com.google.android.material.button.MaterialButton
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
class AddInterestFragment : Fragment() {
private lateinit var viewModel : LoginViewModel
private lateinit var listView : ListView
private lateinit var interests : ArrayList<String>
private lateinit var adapter : ArrayAdapter<String>
private lateinit var chipGroup: ChipGroup
private lateinit var chipCountText: TextView
private lateinit var addInterestButton: MaterialButton
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_add_interest, container, false)
viewModel = ViewModelProvider(requireActivity()).get(LoginViewModel::class.java)
listView = view.findViewById(R.id.chip_list_view)
chipGroup = view.findViewById(R.id.chip_list_group)
chipCountText = view.findViewById(R.id.notify_chip_count)
addInterestButton = view.findViewById(R.id.btn_add_interest)
viewModel.loginRepo.interests()
chipGroup.clearCheck()
for(item in viewModel.loginRepo.chipSet.value ?: emptySet()) {
addChipItem(item)
}
listView.setOnItemClickListener { _, _, position, _ ->
val name = interests[position]
if(viewModel.loginRepo.chipSet.value?.contains(name) == true) {
return@setOnItemClickListener
}
addChipItem(name)
}
addInterestButton.setOnClickListener {
// create array list and send it
viewModel.loginRepo.addInterests()
}
viewModel.loginRepo.interests.observe(requireActivity()) {
interests = ArrayList()
for(item in it) {
interests.add(item.name)
}
adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, interests)
listView.adapter = adapter
}
return view
}
private fun addChipItem(name: String) {
val chip = Chip(requireActivity())
chip.text = name
chip.isCloseIconVisible = true
chipGroup.addView(chip)
viewModel.loginRepo.chipSet.value?.add(name)
chip.setOnCloseIconClickListener {
chipGroup.removeView(it)
viewModel.loginRepo.chipSet.value?.remove(name)
checkChipCount()
}
checkChipCount()
}
private fun checkChipCountUtils(): Boolean {
return viewModel.loginRepo.chipSet.value?.size == 0
}
private fun checkChipCount() {
if(checkChipCountUtils()) {
chipCountText.visibility = View.VISIBLE
} else {
chipCountText.visibility = View.GONE
}
}
}<file_sep>package com.example.meetup
const val LOG_TAG = "LOGGING"
const val BASE_URL = "https://meetup-app7663.herokuapp.com/"
const val NOTIFICATION_ID = 108
const val CHANNEL_ID = "com.example.meetup.MeetUpChannelID"
const val CHANNEL_NAME = "com.example.meetup.MeetUpChannel"
const val NETWORK_REQ_CODE = 1002<file_sep>package com.example.meetup.ui.login.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.example.meetup.repository.LoginRepository
class LoginViewModel(app: Application): AndroidViewModel(app) {
val loginRepo = LoginRepository(app)
init {
loginRepo.chipSet.value = mutableSetOf()
}
fun signUpUser(stringName: String, stringEmail: String, stringPassword: String) {
loginRepo.signUpUser(stringName, stringEmail, stringPassword)
}
fun loginUser(stringEmail: String, stringPassword: String) {
loginRepo.loginUser(stringEmail, stringPassword)
}
}<file_sep>package com.example.meetup.service
import com.example.meetup.room.model.Interest
import com.example.meetup.room.model.Message
import com.example.meetup.room.model.User
import com.example.meetup.room.model.UserInterest
import retrofit2.Call
import retrofit2.Response
import retrofit2.http.*
interface WebService {
@GET("api/v1/getFriends")
suspend fun getFriends(
@Query("id") id: Int
) : Response<List<User>>
@GET("api/v1/getFriendRequests")
suspend fun getFriendRequests(
@Query("id") id: Int
) : Response<List<User>>
@GET("api/v1/makeFriends")
suspend fun makeFriends(
@Query("firstid") firstId: Int,
@Query("secondid") secondId: Int
) : Response<Boolean>
@GET("api/v1/addFriendRequests")
suspend fun addFriendRequests(
@Query("firstid") firstId: Int,
@Query("secondid") secondId: Int
) : Response<Boolean>
@GET("api/v1/removeFriendRequests")
suspend fun removeFriendRequests(
@Query("firstid") firstId: Int,
@Query("secondid") secondId: Int
) : Response<Boolean>
@GET("api/v1/addChatOneMessage")
suspend fun addChatOneMesssage(
@Query("senderid") senderId: Int,
@Query("receiverid") receiverId: Int,
@Query("message") message: String
): Response<List<Message>>
@GET("api/v1/userInterests")
suspend fun userIntrests(
@Query("userid") userId: Int
): Response<List<UserInterest>>
@FormUrlEncoded
@POST("api/v1/allInterestedUsers")
suspend fun allInterestedUsers(
@FieldMap(encoded = true) map: HashMap<String,String>
) : Response<List<User>>
@GET("api/v1/allInterests")
suspend fun getInterests() : Response<List<Interest>>
@GET("api/v1/chatOne")
suspend fun getChatsOneToOne(
@Query("senderid") senderId: Int,
@Query("receiverid") receiverId: Int
) : Response<List<Message>>
@GET("api/v1/chatAll")
suspend fun getChatsAll(
@Query("id") id: Int,
) : Response<List<Message>>
@GET("api/v1/groupChatAll")
suspend fun getGroupChatsAll(
@Query("id") id: Int,
) : Response<List<Message>>
@GET("api/v1/login")
suspend fun loginUser(
@Query("email") email : String,
@Query("password") password : String
) : Response<List<User>>
@GET("api/v1/signUp")
suspend fun signUpUser(
@Query("name") name : String,
@Query("email") email : String,
@Query("password") password : String
) : Response<List<User>>
@FormUrlEncoded
@POST("api/v1/addInterests")
suspend fun addInterest(
@FieldMap(encoded = true) map: HashMap<String,String>
) : Response<Boolean>
@GET("api/v1/updateToken")
suspend fun updateToken(
@Query("id") id : Int,
@Query("token") token : String
) : Response<Boolean>
@GET("api/v1/updateLastSeen")
suspend fun updateLastSeen(
@Query("id") id : Int,
@Query("lastseen") lastSeen : String
) : Response<Boolean>
}
<file_sep>package com.example.meetup.room.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "interests")
data class Interest(
@PrimaryKey
val id : Int,
val name : String
)
<file_sep>package com.example.meetup.ui.main.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.example.meetup.R
import com.example.meetup.adapter.FriendRecyclerAdapter
import com.example.meetup.adapter.RequestRecyclerAdapter
import com.example.meetup.adapter.SuggestionRecyclerAdapter
import com.example.meetup.room.model.User
import com.example.meetup.ui.main.viewmodel.MainViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class ShowFriendFragment : Fragment(),RequestRecyclerAdapter.OnItemClickListener,
SuggestionRecyclerAdapter.OnItemClickListener{
private lateinit var requestRecyclerView : RecyclerView
private lateinit var suggestionRecyclerView : RecyclerView
private lateinit var requestRecyclerAdapter : RequestRecyclerAdapter
private lateinit var suggestionRecyclerAdapter : SuggestionRecyclerAdapter
private lateinit var viewModel : MainViewModel
companion object {
private var mInstance = ShowFriendFragment()
fun getInstance(): ShowFriendFragment {
return mInstance
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_show_friend, container, false)
viewModel = ViewModelProvider(requireActivity()).get(MainViewModel::class.java)
requestRecyclerView = view.findViewById(R.id.request_recycler_view)
suggestionRecyclerView = view.findViewById(R.id.suggestion_recycler_view)
if(!viewModel.mainRepo.requests.value.isNullOrEmpty()) {
requestRecyclerAdapter = RequestRecyclerAdapter(requireActivity(),
viewModel.mainRepo.requests.value!!,this)
requestRecyclerView.adapter = requestRecyclerAdapter
requestRecyclerAdapter.notifyDataSetChanged()
}
if(!viewModel.mainRepo.suggestions.value.isNullOrEmpty()) {
suggestionRecyclerAdapter = SuggestionRecyclerAdapter(requireActivity(),
viewModel.mainRepo.suggestions.value!!,this)
suggestionRecyclerView.adapter = suggestionRecyclerAdapter
suggestionRecyclerAdapter.notifyDataSetChanged()
}
viewModel.mainRepo.suggestions.observe(requireActivity()) {
suggestionRecyclerAdapter = SuggestionRecyclerAdapter(requireActivity(), it,this)
suggestionRecyclerView.adapter = suggestionRecyclerAdapter
suggestionRecyclerAdapter.notifyDataSetChanged()
}
viewModel.mainRepo.requests.observe(requireActivity()) {
requestRecyclerAdapter = RequestRecyclerAdapter(requireActivity(), it,this)
requestRecyclerView.adapter = requestRecyclerAdapter
requestRecyclerAdapter.notifyDataSetChanged()
}
return view
}
override fun onItemClickedRequest(user: User, flag: Boolean) {
// accept request
if(flag) {
// user accepted request
CoroutineScope(Dispatchers.IO).launch {
viewModel.mainRepo.makeFriends(user.id)
}
} else {
// user declines request
CoroutineScope(Dispatchers.IO).launch {
viewModel.mainRepo.removeFriendRequests(user.id)
}
}
}
override fun onItemClickedSuggestion(user: User, flag: Boolean) {
// suggestion
if(flag) {
// user sent hello request
CoroutineScope(Dispatchers.IO).launch {
viewModel.mainRepo.addFriendRequests(user.id)
}
} else {
// remove from suggestion
// store it locally
CoroutineScope(Dispatchers.IO).launch {
// TODO
}
}
}
}<file_sep>package com.example.meetup.service
import android.R
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.PRIORITY_HIGH
import com.example.meetup.CHANNEL_ID
import com.example.meetup.CHANNEL_NAME
import com.example.meetup.NOTIFICATION_ID
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
class MyFCMService : FirebaseMessagingService() {
private var token: String? = null
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
val title = remoteMessage.data["title"]
val messageid = remoteMessage.data["messageid"]
val senderid = remoteMessage.data["senderid"]
val receiverid = remoteMessage.data["receiverid"]
val message = remoteMessage.data["message"]
val sendtime = remoteMessage.data["sendtime"]
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
/*
val intent = Intent()
intent.action = "com.example.meetup.newMessage"
intent.putExtra("messageid", messageid)
intent.putExtra("senderid", senderid)
intent.putExtra("receiverid", receiverid)
intent.putExtra("message", message)
intent.putExtra("sendtime", sendtime)
sendBroadcast(intent)
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = createNotificationChannel()
manager.createNotificationChannel(channel)
}
val notification: Notification = createNotification(this, title, "$message")
// manager.notify(NOTIFICATION_ID, notification)
}
@RequiresApi(api = Build.VERSION_CODES.O)
private fun createNotificationChannel(): NotificationChannel {
return NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
}
private fun createNotification(context: Context, title: String?, desc: String): Notification {
return NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(title)
.setContentText(desc)
.setSubText(desc)
.setSmallIcon(R.drawable.sym_contact_card)
.setPriority(PRIORITY_HIGH)
.setAutoCancel(true)
.build()
}
fun getToken(): String? {
return token
}
override fun onNewToken(s: String) {
super.onNewToken(s)
token = s
Log.d("DATA", s)
}
}<file_sep>package com.example.meetup.room.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "userinterests")
data class UserInterest(
@PrimaryKey
val id : Int,
val name : String
)<file_sep>package com.example.meetup.ui.chat.fragment
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import co.intentservice.chatui.ChatView
import co.intentservice.chatui.ChatView.TypingListener
import co.intentservice.chatui.models.ChatMessage
import com.example.meetup.*
import com.example.meetup.room.model.Message
import com.example.meetup.ui.chat.ChatActivity
import com.example.meetup.ui.chat.viewmodel.ChatViewModel
import com.google.android.material.appbar.MaterialToolbar
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import io.socket.emitter.Emitter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*
class ChatFragment : Fragment() {
private lateinit var toolbar: MaterialToolbar
private lateinit var chatView : ChatView
private lateinit var viewModel : ChatViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val manager = requireActivity().getSystemService(NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = createNotificationChannel()
manager.createNotificationChannel(channel)
}
viewModel = ViewModelProvider(requireActivity()).get(ChatViewModel::class.java)
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_chat, container, false)
chatView = view.findViewById(R.id.chat_view)
toolbar = view.findViewById<MaterialToolbar>(R.id.chat_toolbar)
(activity as AppCompatActivity).setSupportActionBar(toolbar)
toolbar.title = viewModel.chatRepo.friendName
toolbar.setNavigationOnClickListener {
requireActivity().finish()
}
addMessages(viewModel.chatRepo.chats)
viewModel.chatRepo.newMessage.observe(requireActivity()) {
addMessages(viewModel.chatRepo.chats)
}
chatView.setOnSentMessageListener { // perform actual message sending
// viewModel.chatRepo.addMessage(chatView.inputEditText.text.toString())
val obj = JSONObject()
obj.put("senderid", viewModel.chatRepo.userId)
obj.put("receiverid", viewModel.chatRepo.friendId)
obj.put("message", chatView.inputEditText.text.toString())
if(viewModel.chatRepo.mSocket?.connected() == true)
viewModel.chatRepo.mSocket?.emit("newMessage", obj)
else
viewModel.chatRepo.addMessage(chatView.inputEditText.text.toString())
true
}
chatView.setTypingListener(object : TypingListener {
override fun userStartedTyping() {
// will be called when the user starts typing
// toolbar.subtitle = "Friend is typing ..."
val obj = JSONObject()
obj.put("id", viewModel.chatRepo.userId)
obj.put("value", true)
viewModel.chatRepo.mSocket?.emit("typing", obj)
}
override fun userStoppedTyping() {
// will be called when the user stops typing
val obj = JSONObject()
obj.put("id", viewModel.chatRepo.userId)
obj.put("value", false)
viewModel.chatRepo.mSocket?.emit("typing", obj)
}
})
// to enable options menu
setHasOptionsMenu(true)
viewModel.chatRepo.networkConnection.observe(requireActivity()) {
if(it == true) {
addSocketListener()
} else {
removeSocketListener()
}
}
return view
}
private fun addSocketListener() {
if(viewModel.chatRepo.mSocket?.connected() == false) {
viewModel.chatRepo.mSocket?.connect()
}
viewModel.chatRepo.mSocket?.off()
viewModel.chatRepo.mSocket?.on("typing", onTyping)
viewModel.chatRepo.mSocket?.on("newMessage", onNewMessage)
}
private fun removeSocketListener() {
viewModel.chatRepo.mSocket?.off()
viewModel.chatRepo.mSocket?.disconnect()
}
private fun addMessages(messages: List<Message>) {
chatView.clearMessages() // orientation change
for(item in messages) {
val type = if(item.senderid == viewModel.chatRepo.userId) ChatMessage.Type.SENT else ChatMessage.Type.RECEIVED
val date = item.sendtime
val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
val parsedDate: Long = inputFormat.parse(date).time
addMessage(item.message, parsedDate, type)
}
}
private fun addMessage(message: String, parsedDate: Long ,type: ChatMessage.Type) {
val msg = ChatMessage(message, parsedDate, type)
chatView.addMessage(msg)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.chat_menu, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when(item.itemId) {
R.id.clearChat -> {
chatView.clearMessages()
true
}
else -> super.onOptionsItemSelected(item)
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private fun createNotificationChannel(): NotificationChannel {
return NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
}
private fun createNotification(context: Context, title: String?, desc: String): Notification {
return NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(title)
.setSubText("Message")
.setContentText(desc)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.build()
}
private var onTyping = Emitter.Listener {
val id = JSONObject(it[0].toString())["id"] as Int
val value = JSONObject(it[0].toString())["value"] as Boolean
CoroutineScope(Dispatchers.Main).launch {
if (viewModel.chatRepo.friendId == id) {
if (value)
toolbar.subtitle = viewModel.chatRepo.friendName + " is typing ..."
else
toolbar.subtitle = null
}
}
}
private var onNewMessage = Emitter.Listener {
val moshi: Moshi = Moshi.Builder().build()
val adapter: JsonAdapter<Message> = moshi.adapter(Message::class.java)
val msg = adapter.fromJson(it[0].toString())
val senderid = JSONObject(it[0].toString())["senderid"] as Int
val receiverid = JSONObject(it[0].toString())["receiverid"] as Int
if((senderid == viewModel.chatRepo.friendId &&
receiverid == viewModel.chatRepo.userId) ||
(senderid == viewModel.chatRepo.userId &&
receiverid == viewModel.chatRepo.friendId)) {
CoroutineScope(Dispatchers.Main).launch {
if (msg != null) {
Log.d(LOG_TAG, "On New Message Listener:- $msg")
viewModel.chatRepo.addToLocalDatabase(msg)
viewModel.chatRepo.chats.add(msg)
viewModel.chatRepo.newMessage.postValue(
viewModel.chatRepo.newMessage.value != true)
}
}
}
else {
/*if(receiverid == viewModel.chatRepo.userId) {
val notification: Notification = createNotification(requireActivity(),
"New Message", "$message")
manager.cancelAll()
manager.notify(NOTIFICATION_ID, notification)
}*/
}
}
override fun onDestroy() {
super.onDestroy()
removeSocketListener()
}
override fun onStart() {
super.onStart()
addSocketListener()
}
}
<file_sep>package com.example.meetup.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.lifecycle.ViewModelProvider
import com.example.meetup.room.model.Message
import com.example.meetup.ui.main.MainActivity
import com.example.meetup.ui.main.viewmodel.MainViewModel
class FCMessageReceiver(val mainActivity: MainActivity) : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
/*Log.d("LOGGING", intent?.getStringExtra("messageid")+
intent?.getStringExtra("senderid")+
intent?.getStringExtra("receiverid")+
intent?.getStringExtra("message")+
intent?.getStringExtra("sendtime"))*/
if(intent?.action == "com.example.meetup.newMessage") {
val viewModel = ViewModelProvider(mainActivity).get(MainViewModel::class.java)
val messageid = intent.getStringExtra("messageid")?.toInt() ?: -1
val senderid = intent.getStringExtra("senderid")?.toInt() ?: -1
val receiverid = intent.getStringExtra("receiverid")?.toInt() ?: -1
val message = intent.getStringExtra("message") ?: ""
val sendtime = intent.getStringExtra("sendtime") ?: ""
val newMessage = Message(messageid, senderid, receiverid, message!!, 0, "", sendtime)
viewModel.mainRepo.chats.add(newMessage)
viewModel.mainRepo.newMessage.value = viewModel.mainRepo.newMessage.value != true
}
}
}<file_sep>package com.example.meetup.ui.main.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.example.meetup.repository.MainRepository
class MainViewModel(app : Application) : AndroidViewModel(app) {
var mainRepo : MainRepository = MainRepository(app)
}<file_sep>package com.example.meetup.room
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.meetup.room.model.Interest
import com.example.meetup.room.model.Message
import com.example.meetup.room.model.User
import com.example.meetup.room.model.UserInterest
@Database(
entities = [
User::class,
Message::class,
Interest::class,
UserInterest::class
],
version = 5,
exportSchema = true
)
abstract class ChatDatabase : RoomDatabase() {
abstract fun chatDao(): ChatDao
companion object {
private var instance: ChatDatabase? = null
@Synchronized
fun getInstance(ctx: Context): ChatDatabase {
if (instance == null) {
}
instance = Room.databaseBuilder(
ctx.applicationContext, ChatDatabase::class.java,
"meetUp_database"
)
.fallbackToDestructiveMigration()
.build()
return instance!!
}
}
}<file_sep>package com.example.meetup.ui.login
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.Network
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import androidx.core.app.ActivityCompat
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavOptions
import androidx.navigation.Navigation
import com.example.meetup.NETWORK_REQ_CODE
import com.example.meetup.R
import com.example.meetup.ui.chat.ChatActivity
import com.example.meetup.ui.main.MainActivity
import com.example.meetup.ui.login.viewmodel.LoginViewModel
class LoginActivity : AppCompatActivity() {
private lateinit var viewModel : LoginViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
if(!checkPermission())
ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_NETWORK_STATE), NETWORK_REQ_CODE)
val nm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
showNetworkState(nm)
viewModel.loginRepo.loginStat.observe(this) {
if(it) viewModel.loginRepo.userInterests()
else {
Navigation.findNavController(this, R.id.nav_host_login)
.navigate(R.id.splash_to_loginFragment,
null,
NavOptions.Builder().setPopUpTo(R.id.splashFragment,true)
.build())
}
}
viewModel.loginRepo.userInterests.observe(this) { it ->
if(it.isEmpty()) {
if(viewModel.loginRepo.firstTime) {
Navigation.findNavController(this, R.id.nav_host_login)
.navigate(R.id.login_to_addInterestFragment,
null,
NavOptions.Builder().setPopUpTo(R.id.splashFragment, true)
.build())
} else {
Navigation.findNavController(this, R.id.nav_host_login)
.navigate(R.id.splash_to_addInterestFragment,
null,
NavOptions.Builder().setPopUpTo(R.id.splashFragment, true)
.build())
}
} else {
Handler().postDelayed({
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}, 2000)
viewModel.loginRepo.networkConnection.observe(this) {
if(it) {
// if you want your app to start only on
// network available
}
}
}
}
}
private fun showNetworkState(nm: ConnectivityManager) {
nm.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
//Network Connected
viewModel.loginRepo.networkConnection.postValue(true)
}
override fun onLost(network: Network) {
super.onLost(network)
// NetWork Disconnected
viewModel.loginRepo.networkConnection.postValue(false)
}
})
}
private fun checkPermission() : Boolean {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE)
!= PackageManager.PERMISSION_GRANTED) {
return false
}
return true
}
}<file_sep>package com.example.meetup.repository
import android.app.Application
import android.content.Context
import android.util.Log
import androidx.annotation.WorkerThread
import androidx.lifecycle.MutableLiveData
import com.example.meetup.BASE_URL
import com.example.meetup.LOG_TAG
import com.example.meetup.R
import com.example.meetup.room.ChatDatabase
import com.example.meetup.room.model.Message
import com.example.meetup.service.WebService
import io.socket.client.IO
import io.socket.client.Socket
import io.socket.engineio.client.transports.WebSocket
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.net.URISyntaxException
class ChatRepository(val app: Application) {
var friendName = ""
val chats = arrayListOf<Message>()
var userId = -1
var friendId = -1
val newMessage = MutableLiveData<Boolean>()
val networkConnection = MutableLiveData<Boolean>()
var mSocket: Socket? = getSocket()
private val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(MoshiConverterFactory.create())
.build()
private val service = retrofit.create(WebService::class.java)
private val sharedPref = app.getSharedPreferences(app.getString(R.string.SHARED_PREF), Context.MODE_PRIVATE)
private val database = ChatDatabase.getInstance(app)
init {
userId = getId()
newMessage.value = false
}
fun addMessage(message: String) {
CoroutineScope(Dispatchers.IO).launch {
uploadMessage(userId,friendId,message)
}
}
private fun getId() = sharedPref.getInt("id", 0)
@WorkerThread
suspend fun getOneToOneChats(receiverId: Int) {
val serviceData = database.chatDao().getChats(userId, receiverId)
chats.clear()
chats.addAll(serviceData)
newMessage.postValue(newMessage.value != true)
if(networkConnection.value == true) {
try {
val serviceData = service.getChatsOneToOne(userId, receiverId).body() ?: emptyList()
chats.clear()
chats.addAll(serviceData)
database.chatDao().deleteChats()
database.chatDao().insertChats(serviceData)
newMessage.postValue(newMessage.value != true)
Log.d(LOG_TAG, serviceData.toString())
} catch (e: Throwable) {
Log.d(LOG_TAG, e.message)
} catch (e: Exception) {
Log.d(LOG_TAG, e.message)
}
}
}
@WorkerThread
suspend fun uploadMessage(userId: Int,friendId: Int,message: String) {
if(networkConnection.value == false) {
} else {
try {
val serviceData = service.addChatOneMesssage(userId, friendId, message).body()
?: emptyList()
// chats.clear()
chats.add(serviceData[0])
addToLocalDatabase(serviceData[0])
newMessage.postValue(newMessage.value != true)
} catch (e: Throwable) {
Log.d(LOG_TAG, e.message ?: "Error")
} catch(e: Exception) {
Log.d(LOG_TAG, e.message ?: "Error")
}
}
}
fun callInitialMethod() {
CoroutineScope(Dispatchers.IO).launch {
getOneToOneChats(friendId)
// getUserInterests(userId)
// getFriendRequests(userId)
// getFriends(userId)
// getAllChats(userId)
}
}
private fun getSocket() : Socket? {
var mSocket: Socket? = null
val options = IO.Options()
options.transports = arrayOf(WebSocket.NAME)
options.reconnection = true //reconnection
options.query = "userId=$userId"
options.forceNew = true
try {
//creating socket instance
mSocket = IO.socket("https://meetup-app7663.herokuapp.com/", options)
} catch (e: URISyntaxException) {
// Toast.makeText(this,e.message, Toast.LENGTH_SHORT).show()
Log.d(LOG_TAG, e.message ?: "Error")
}
mSocket?.connect()
return mSocket
}
@WorkerThread
suspend fun updateLastSeen(userId: Int, online: Boolean) {
if(online) {
service.updateLastSeen(userId,"online")
} else {
val time = System.currentTimeMillis().toString()
service.updateLastSeen(userId, time)
}
}
fun addToLocalDatabase(message: Message) {
CoroutineScope(Dispatchers.IO).launch {
database.chatDao().insertChat(message)
}
}
}
|
574219c9e54013fec57f2d5a6e0ebed4642bfa0c
|
[
"Kotlin"
] | 30 |
Kotlin
|
vishalsingh7663/MeetUp-Frontend
|
a5d41932535feb102e572bd033c7981c10fd19b0
|
8273e3154bb77a492978f500540e4a8d2f08ee2c
|
refs/heads/master
|
<repo_name>sowmya-padmanabhi/OS-Nachos-Simulating-schedule-process<file_sep>/code/threads/person.h
//
// Created by sowmya on 9/20/2018.
//
#ifndef NACHOS_PERSON_H
#define NACHOS_PERSON_H
#include "../lib/list.h"
class Person {
public:
Person(int sequence, int priority, int timeWash, int totalClothes);
Person();
virtual ~Person();
int getPersonPriority() const;
int getPersonSequence() const;
int getTotalClothes() const;
int getTimeWash() const ;
bool operator == (Person per) {
if(this->getPersonSequence() == per.getPersonSequence())
return true;
else return false;
}
private:
int priority;
int sequence;
long washTime;
int clothes;
};
#endif //NACHOS_PERSON_H
<file_sep>/code/threads/request.cc
#include "request.h"
#include <stdlib.h>
#include <iostream>
int seat = 0;
void Request ::setNumPassengers(int numOfPass) {
numPassenger = numOfPass;
}
int Request :: getNumberOfPassengers() const {
return numPassenger;
}
void Request :: setDepartureCity(char departureCity) {
departCity = departureCity;
}
char Request :: getDepartureCity() const {
return departCity;
}
void Request :: setDestinationCity(char destinationCity) {
destCity = destinationCity;
}
char Request :: getDestinationCity() const {
return destCity;
}
int Request :: setRequestId(int requestID) {
reqID = requestID;
}
int Request :: getRequestId() const {
return reqID;
}
void Request ::setSeatNumbers(int seatNumbers) {
seatNum[seat]=seatNumbers;
seat++;
}
int Request ::getSeatNumbers(int newseat) const {
return seatNum[newseat];
}
int Request :: seatarray_size(){
int seatsize = sizeof(seatNum)/sizeof(seatNum[0]);
return seatsize;
}
Request::Request() {
// cout << "Constructor";
}
Request::~Request() {
// cout << "Destructor";
}
<file_sep>/code/threads/request.h
//
// Created by sowmya on 9/29/2018.
//
#ifndef NACHOS_REQUEST_H
#define NACHOS_REQUEST_H
#include "../lib/list.h"
class Request{
private:
int reqID;
int numPassenger;
int * seatNum;
char departCity;
char destCity;
// List<int> seatsNumb;
public:
// Declaring the methods required.
Request();
~Request();
int setRequestId(int requestID);
int getRequestId() const;
void setNumPassengers(int numOfPass);
int getNumberOfPassengers() const;
void setSeatNumbers(int seatNumbers);
int getSeatNumbers(int i) const;
void setDepartureCity(char departureCity);
char getDepartureCity() const ;
void setDestinationCity(char destinationCity);
char getDestinationCity() const ;
int seatarray_size();
List<int> *seatsNumb = new List<int>();
friend void FlightReservation();
friend void reserveSeat(int ID);
};
void FlightReservation();
void reserveSeat(int ID);
#endif // NACHOS_REQUEST_H
<file_sep>/code/threads/person.cc
//
// Created by sowmya on 9/20/2018.
//
#include "person.h"
#include <iostream>
#include <stdlib.h>
Person::Person(int sequence, int priority, int timeWash, int totalClothes) {
this->sequence = sequence;
this->priority = priority;
this->clothes = totalClothes;
this->washTime = timeWash;
}
int Person::getPersonPriority() const {
return priority;
}
int Person::getPersonSequence() const {
return sequence;
}
int Person::getTimeWash() const {
return washTime;
}
int Person::getTotalClothes() const {
return clothes;
}
Person::Person(){}
Person::~Person(){}
<file_sep>/code/threads/threadtest.cc
#include "kernel.h"
#include "main.h"
#include "thread.h"
#include "person.h"
#include "../lib/list.h"
#include "request.h"
#include "bitmap.h"
#include "scheduler.h"
using namespace std;
void
SimpleThread(int which)
{
int num;
for (num = 0; num < 5; num++) {
printf("*** thread %d looped %d times\n", which, num);
printf("Hello World!");
kernel->currentThread->Yield();
}
}
// ---- Compare function to compare higher priority between two person----
int comparePriority(Person per1, Person per2){
if(per1.getPersonPriority() < per2.getPersonPriority())
return -1;
else if(per1.getPersonPriority() > per2.getPersonPriority())
return 1;
else return 0;
}
// ---- Print function to print out each person and associated information of the person ----
void print(Person per){
std::cout << "Person with the sequence number: " << per.getPersonSequence() << ", priority number: " << per.getPersonPriority() << ", has " << per.getTotalClothes() << " number of clothes and needs total of " << per.getTimeWash() << " time to finish washing the clothes\n";
}
// ---- Simunation 1 ----
void simulation1(int numb){
// ---- Using the existing SortedList function to sort the Person list- highest priority to lowest priority----
SortedList<Person> *sortPerson = new SortedList<Person>(comparePriority);
int seq = 0;
int timeTotal = 0;
//----Generating 20 Persons----
for(int i=0; i<numb; i++){
Person per(seq++, rand()%20, rand()%30, rand()%50);
sortPerson->Insert(per);
}
//---- Printing the Person order ----
std::cout << "\n***************Simulation 1 Running *****************\n \n Laundry line up according to priority \n \n ";
ListIterator<Person> list = sortPerson;
sortPerson->Apply(print);
std::cout << "\n _________ Simulation 1 begins.....__________\n\n";
int order = 0;
Person prevPerson;
while (!list.IsDone()){
Person per = sortPerson->Front();
timeTotal += per.getTimeWash();
std::cout << "The order is " << order++ << ": ";
print(per);
if(prevPerson.getPersonSequence() != NULL)
std::cout << "Person with the sequence number" << prevPerson.getPersonSequence() << " leaves the room. This person took a total time of " << prevPerson.getTimeWash() << " to finish washing all the clothes.\n";
else
std::cout << "\n";
prevPerson = per;
list.Next();
sortPerson->RemoveFront();
}
std::cout << "\nThe Total time taken for washing clothes of all 20 people are: " << timeTotal << "\n";
}
//---- Function to determine the highest priority for Simulation 2 ----
Person highPriorityPerson(List<Person> *list){
int highest = 0;
Person newHigh;
List<Person> *temp = list;
ListIterator<Person> list1 = temp;
while (!list1.IsDone()) {
Person per = list1.Item();
if (per.getPersonPriority() >= highest) {
newHigh = per;
highest = per.getPersonPriority();
}
list1.Next();
}
return newHigh;
}
//---- Simulation 2 ----
void simulation2(int numb){
List<Person> *newPerson = new List<Person>();
int seq = 0;
int timeTotal = 0;
//---- Generation 20 Persons
for(int i=0; i<numb; i++){
Person per(seq++, rand()%10, rand()%30, rand()%50);
newPerson->Append(per);
}
//----Printing the Person oreder ----
std::cout << "\n*************** Simulation 2 Running *******************\n \n Laundry line up according to priority \n \n Highest Priority = 0 Lowest Priority = 9 \n\n";
ListIterator<Person> list = newPerson;
newPerson->Apply(print);
std::cout << "\n____________Simulation 2 begins.....______________\n\n";
int order = 0;
Person prevPerson;
while(!list.IsDone() && newPerson->NumInList()!=0){
Person current = highPriorityPerson(newPerson);
timeTotal += current.getTimeWash();
std::cout << "The order is " << order++ << ": ";
print(current);
if(prevPerson.getPersonSequence() != NULL)
std::cout << "Person with the sequence number " << prevPerson.getPersonSequence() << " leaves the room. This person took a total time of " << prevPerson.getTimeWash() << " to finish washing all the clothes.\n";
else
std::cout << "\n";
newPerson->Remove(current);
// list.Next();
prevPerson = current;
}
std::cout << "\nThe total time taken for washing clothes of all 20 people are: " << timeTotal << "\n";
}
// -----------------------Lab Assignment 3 ------------------------------------------------
//Declaring global variables required.
int n = 0;
Request *req;
int i;
Bitmap *bm = new Bitmap(20);
List<Request *> *grantedRequests = new List<Request *>();
List<Request *> *discardedRequests = new List<Request *>();
List<int> *seatNo = new List<int>;
List<Thread *> *cityB = new List<Thread *>();
List<Thread *> *cityC = new List<Thread *>();
List<Thread *> *cityD = new List<Thread *>();
List<Thread *> *cityE = new List<Thread *>();
int probability;
void reserveSeat(int threadID){
char cities[] = {'A','B','C','D','E'};
req = new Request();
req->setRequestId(rand()%100);
req->setNumPassengers((rand()%5)+1);
req->setDepartureCity(cities[i]);
probability = (rand()%100);
int s[req->getNumberOfPassengers()];
//Assigning destination city based on probability generated for random numbers.
switch (req->getDepartureCity()){
case 'A': if(probability>0 && probability<=25){
req->setDestinationCity(cities[1]);
}
else if(probability>25 && probability<50){
req->setDestinationCity(cities[2]);
}
else if(probability>50 && probability<75){
req->setDestinationCity(cities[3]);
}
else{
req->setDestinationCity(cities[4]);
}
break;
case 'B': if(probability>0 && probability<=35){
req->setDestinationCity(cities[2]);
}
else if(probability>35 && probability<=75){
req->setDestinationCity(cities[3]);
}
else if(probability>75 && probability<=100){
req->setDestinationCity(cities[4]);
}
break;
case 'C': if(probability>0 && probability<=50){
req->setDestinationCity(cities[3]);
}
else if(probability>50 && probability<=100){
req->setDestinationCity(cities[4]);
}
break;
case 'D': req->setDestinationCity(cities[4]);
break;
default: req->setDestinationCity(cities[4]);
}
//Displaying the required details for each request.
cout << " The departure City is: " << req->getDepartureCity() << "\n";
cout << " The Request ID is: " << req->getRequestId() << "\n";
cout << " Number of Passengers for this request is: " << req->getNumberOfPassengers() << "\n";
cout << " The destination city for this request is: " << req->getDestinationCity() << "\n";
//Checking if seats are available in the flight for the current request. If there are seats available, then request is granted else request is discarded.
int seatsAvailable = bm->NumClear();
cout << " The number of seats available at this point are: " << seatsAvailable <<"\n";
if(bm->NumClear() >= req->getNumberOfPassengers()) {
cout << " Requests granted. \n";
//Using Bitmap's FindAndSet method to assign seat numbers.
for (int m = 0; m < req->getNumberOfPassengers(); m++) {
s[m] = bm->FindAndSet();
cout <<" The seat number is: "<< s[m] << "\n";
}
//Checking if the request is at its current destination, if it is, append it.
switch(req->getDestinationCity()) {
case 'B': cityB->Append(kernel->currentThread); cout << "\n";
break;
case 'C': cityC->Append(kernel->currentThread); cout << "\n";
break;
case 'D': cityD->Append(kernel->currentThread); cout << "\n";
break;
case 'E': cityE->Append(kernel->currentThread); cout << "\n";
break;
default : cout << "\nError. Has to be one of the given destination city.\n";
break;
}
//Interrupts are turned off before calling the Sleep or the ReadyToRun functions.
kernel->interrupt->SetLevel(IntOff);
kernel->currentThread->Sleep(FALSE);
int sz = sizeof(s)/(sizeof(s[0]));
for(int a = 0; a < sz ; a++){
cout<<" Seat clearing out for Request ID "<<req->getRequestId() <<" is - "<< s[a] << "\n ";
}
kernel->currentThread->Finish();
}
else {
discardedRequests->Append(req);
cout << "** Flight is full. Request denied**.\n";
cout << "\n";
kernel->currentThread->Finish();
}
}
//The flight function starts here.
void FlightReservation() {
srand(time(NULL));
//The outer for loop with in the flight function to generate threads and functions for 5 cities.
for ( i = 0; i < 5; i++) {
if (i > 0){
cout<<"\n";
//If the departure city is anything other than A, it enters the switch case, the respective cases execute to iterate through the thread list and puts the thread in the ready to run list and starts yielding.
switch (i) {
case 1 : {
cout << "************************Destination City B*************************************\n";
ListIterator<Thread *> *iterReq1 = new ListIterator<Thread *>(cityB);
while (!iterReq1->IsDone()) {
kernel->interrupt->SetLevel(IntOff);
kernel->scheduler->ReadyToRun(iterReq1->Item());
kernel->currentThread->Yield();
iterReq1->Next();
}
break;
}
case 2 : {
cout << "************************Destination City C*************************************\n";
ListIterator<Thread *> *iterReq2 = new ListIterator<Thread *>(cityC);
while (!iterReq2->IsDone()){
kernel->interrupt->SetLevel(IntOff);
kernel->scheduler->ReadyToRun(iterReq2->Item());
kernel->currentThread->Yield();
iterReq2->Next();
cout<<"\n";
}
break;
}
case 3 : {
cout << "************************Destination City D*************************************\n";
ListIterator<Thread *> *iterReq3 = new ListIterator<Thread *>(cityD);
while (!iterReq3->IsDone()){
kernel->interrupt->SetLevel(IntOff);
kernel->scheduler->ReadyToRun(iterReq3->Item());
kernel->currentThread->Yield();
iterReq3->Next();
cout<<"\n";
}
break;
}
case 4 : {
cout << "********************************************************************************\n";
ListIterator<Thread *> *iterReq4 = new ListIterator<Thread *>(cityE);
while (!iterReq4->IsDone()){
kernel->interrupt->SetLevel(IntOff);
kernel->scheduler->ReadyToRun(iterReq4->Item());
kernel->currentThread->Yield();
iterReq4->Next();
// cout<<"\n";
}
break;
}
default : cout << "\n Error.\n ";
}
//After each city's execution, the occupancy rate of the flight at that point is calculated and displayed.
cout << " The occupancy rate is: "<< 20 - (bm->NumClear()) << "/20\n";
cout<<"\n The available seats are : "; bm->Print();cout<<endl;
//A list iterator is declared and defined to iterate through a list of requests that have been discarded and displayed that request's requestID.
if(i==4){
ListIterator<Request *> *rejectedRequest = new ListIterator<Request *>(discardedRequests);
while (!rejectedRequest->IsDone()){
cout <<" The rejected requests are: " << rejectedRequest->Item()->getRequestId() << "\n";
rejectedRequest->Next();
}
kernel->currentThread->Finish();
}
}
//The inner for loop to generate upto 5 flight threads for each city.
Thread *flightThread[6];
for (int j = 1; j <= 5; j++){
flightThread[j] = new Thread("flight thread");
flightThread[j]->Fork((VoidFunctionPtr) reserveSeat, (void *) j);
kernel->currentThread->Yield();
}
}
}
void
ThreadTest()
{
//The main thread object is created and forked which calls the flight function.
Thread *mainThread = new Thread("main thread");
mainThread->Fork((VoidFunctionPtr) FlightReservation, (void *) 1);
kernel->currentThread->Yield();
//Thread *t = new Thread("forked thread");
//t->Fork((VoidFunctionPtr) SimpleThread, (void *) 1);
//---- Calling Simulation 1 ----
//simulation1(20);
//---- Calling Simulation 2 ----
//simulation2(20);
//SimpleThread(0);
}
|
23f0fd6394bb2b6a46e68429077dfdc257a8c560
|
[
"C++"
] | 5 |
C++
|
sowmya-padmanabhi/OS-Nachos-Simulating-schedule-process
|
33b8170e250a66977203e2a7ca083e95dcd39228
|
2359ac47993155b25fb249e6b790252d0046571b
|
refs/heads/master
|
<file_sep>2018.03.27 | update | commit initial installer version
* update/00000_commit-initial-installer
<file_sep>#!/bin/bash
# Build Oracle Mobile Cloud - Enterprise.
# Will install Oracle PaaS Services: DBCS & Stack Manager template for OMCe.
#
# Note: Initial version created by: <EMAIL>
#vars..
#assign args to vars..
echo " " >>/tmp/tf-debug.log
echo "mgt-script.sh -->>" >>/tmp/tf-debug.log
echo " " >>/tmp/tf-debug.log
for ARGUMENT in "$@"; do
KEY=$(echo $ARGUMENT | cut -f1 -d=)
VALUE=$(echo $ARGUMENT | cut -f2 -d=)
case "$KEY" in
a00_idIdcs) a00_idIdcs=${VALUE} ;;
a01_ociUser) a01_ociUser=${VALUE} ;;
a02_ociPass) a02_ociPass=${VALUE} ;;
a03_idDomain) a03_idDomain=${VALUE} ;;
a031_idIdcsTenant) a031_idIdcsTenant=${VALUE} ;;
a04_apiEndpoint) a04_apiEndpoint=${VALUE} ;;
a06_stgUser) a06_stgUser=${VALUE} ;;
a07_stgPass) a07_stgPass=${VALUE} ;;
a08_stgEndpointAuth) a08_stgEndpointAuth=${VALUE} ;;
a09_stgEndpoint) a09_stgEndpoint=${VALUE} ;;
e00_PaasDbcs) e00_PaasDbcs=${VALUE} ;;
e01_PaasOmce) e01_PaasOmce=${VALUE} ;;
e02_envName) e02_envName=${VALUE} ;;
e03_envNumber) e03_envNumber=${VALUE} ;;
*)
esac
done
#define local vars..
a99_svcDbcsName="${e02_envName}${e03_envNumber}dbs"
a98_svcOmceName="${e02_envName}${e03_envNumber}stk"
#debug..
echo "a00_idIdcs" = $a00_idIdcs >>/tmp/tf-debug.log
echo "a01_ociUser" = $a01_ociUser >>/tmp/tf-debug.log
echo "a02_ociPass" = $a02_ociPass >>/tmp/tf-debug.log
echo "a03_idDomain" = $a03_idDomain >>/tmp/tf-debug.log
echo "a031_idIdcsTenant" = $a031_idIdcsTenant >>/tmp/tf-debug.log
echo "a04_apiEndpoint" = $a04_apiEndpoint >>/tmp/tf-debug.log
echo "a06_stgUser" = $a06_stgUser >>/tmp/tf-debug.log
echo "a07_stgPass" = $a07_stgPass >>/tmp/tf-debug.log
echo "a08_stgEndpointAuth" = $a08_stgEndpointAuth >>/tmp/tf-debug.log
echo "a09_stgEndpoint" = $a09_stgEndpoint >>/tmp/tf-debug.log
echo "e00_PaasDbcs" = $e00_PaasDbcs >>/tmp/tf-debug.log
echo "e01_PaasOmce" = $e01_PaasOmce >>/tmp/tf-debug.log
echo "e02_envName" = $e02_envName >>/tmp/tf-debug.log
echo "e03_envNumber" = $e03_envNumber >>/tmp/tf-debug.log
#debug local vars..
logger *** TF Apply :: Remote-Exec Started ***
echo "MGT :: Remote-Exec :: Let's get started ..."
#let's get going..
echo "MGT :: Remote-Exec :: Configuaration files ..."
cp /tmp/mgt/public-yum-ol7.repo /etc/yum.repos.d/
echo "MGT :: Remote-Exec :: Configuaration files ... :: Done ..."
echo "MGT :: Remote-Exec :: Install Utils ..."
chmod +x /tmp/mgt/env/*.sh
/tmp/mgt/env/envUtils.sh a00_idIdcs=$a00_idIdcs a01_ociUser=$a01_ociUser a02_ociPass=$a02_ociPass a03_idDomain=$a03_idDomain a031_idIdcsTenant=$a031_idIdcsTenant a04_apiEndpoint=$a04_apiEndpoint a09_stgEndpoint=$a09_stgEndpoint
echo "MGT :: Remote-Exec :: Install Utils ... :: Done ..."
#tf apply operations..
echo "MGT :: Remote-Exec :: Configure Environments ..."
#dbcs..
if [ $e00_PaasDbcs = "true" ]; then
echo "ENV-1 :: Creating PaaS Service: DBCS ..."
/bin/su - root -c "/tmp/mgt/env/envPaasDbcs.sh a04_apiEndpoint=$a04_apiEndpoint a06_stgUser=$a06_stgUser a07_stgPass=$a07_stgPass a08_stgEndpointAuth=$a08_stgEndpointAuth a09_stgEndpoint=$a09_stgEndpoint e02_envName=$e02_envName e03_envNumber=$e03_envNumber" #possibly make storage as enhancement ??..
echo "ENV-1 :: Creating PaaS Service: DBCS ... :: Done ..."
fi
#omce..
if [ $e01_PaasOmce = "true" ]; then
echo "ENV-2 :: Creating PaaS Service: OMCe ..."
/bin/su - root -c "/tmp/mgt/env/envPaasOmce.sh a04_apiEndpoint=$a04_apiEndpoint a06_stgUser=$a06_stgUser a07_stgPass=$a07_stgPass a08_stgEndpointAuth=$a08_stgEndpointAuth a09_stgEndpoint=$a09_stgEndpoint e02_envName=$e02_envName e03_envNumber=$e03_envNumber" ## make storage also..
echo "ENV-2 :: Creating PaaS Service: OMCe ... :: Done ..."
fi
echo "MGT :: Remote-Exec :: Configure Environments ... :: Done ..."
echo " "
echo "MGT :: Remote-Exec :: List all services ..."
echo "---------------------------------------------------------------------------------------"
if [ $e00_PaasDbcs = "true" ]; then
echo "Service :: DBCS -->"
/bin/su - root -c "psm dbcs service -s $a99_svcDbcsName" >>/tmp/tf-debug.log
/bin/su - root -c "psm dbcs service -s $a99_svcDbcsName -of short"
fi
echo " "
if [ $e01_PaasOmce = "true" ]; then
echo "Service :: OMCe -->"
/bin/su - root -c "psm stack describe -n $a98_svcOmceName -e all" >>/tmp/tf-debug.log
/bin/su - root -c "psm stack describe -n $a98_svcOmceName -of short"
fi
echo " "
echo "MGT :: Remote-Exec :: Done ..."
logger *** TF Remote-Exec Stopped ***
<file_sep>#!/bin/bash
#vars..
#assign args to vars..
echo " " >>/tmp/tf-debug.log
echo "envUtils.sh -->>" >>/tmp/tf-debug.log
echo " " >>/tmp/tf-debug.log
for ARGUMENT in "$@"; do
KEY=$(echo $ARGUMENT | cut -f1 -d=)
VALUE=$(echo $ARGUMENT | cut -f2 -d=)
case "$KEY" in
a00_idIdcs) a00_idIdcs=${VALUE} ;;
a01_ociUser) a01_ociUser=${VALUE} ;;
a02_ociPass) a02_ociPass=${VALUE} ;;
a03_idDomain) a03_idDomain=${VALUE} ;;
a031_idIdcsTenant) a031_idIdcsTenant=${VALUE} ;;
a04_apiEndpoint) a04_apiEndpoint=${VALUE} ;;
a06_stgUser) a06_stgUser=${VALUE} ;;
a07_stgPass) a07_stgPass=${VALUE} ;;
a08_stgEndpointAuth) a08_stgEndpointAuth=${VALUE} ;;
a09_stgEndpoint) a09_stgEndpoint=${VALUE} ;;
e00_PaasDbcs) e00_PaasDbcs=${VALUE} ;;
e01_PaasOmce) e01_PaasOmce=${VALUE} ;;
e02_envName) e02_envName=${VALUE} ;;
e03_envNumber) e03_envNumber=${VALUE} ;;
*)
esac
done
#define local vars..
e99_psmCli="/home/opc/psmcli.zip"
a99_idTenant=$(echo $a09_stgEndpoint | sed 's:.*-::')
if [[ $a04_apiEndpoint =~ "us" ]]; then
a98_apiRegion="us"
elif [[ $a04_apiEndpoint =~ "emea" ]]; then
a98_apiRegion="emea"
else a98_apiRegion="aucom"
fi
#debug..
echo "a00_idIdcs" = $a00_idIdcs >>/tmp/tf-debug.log
echo "a01_ociUser" = $a01_ociUser >>/tmp/tf-debug.log
echo "a02_ociPass" = $a02_ociPass >>/tmp/tf-debug.log
echo "a03_idDomain" = $a03_idDomain >>/tmp/tf-debug.log
echo "a031_idIdcsTenant" = $a031_idIdcsTenant >>/tmp/tf-debug.log
echo "a04_apiEndpoint" = $a04_apiEndpoint >>/tmp/tf-debug.log
echo "a06_stgUser" = $a06_stgUser >>/tmp/tf-debug.log
echo "a07_stgPass" = $a07_stgPass >>/tmp/tf-debug.log
echo "a08_stgEndpointAuth" = $a08_stgEndpointAuth >>/tmp/tf-debug.log
echo "a09_stgEndpoint" = $a09_stgEndpoint >>/tmp/tf-debug.log
echo "e00_PaasDbcs" = $e00_PaasDbcs >>/tmp/tf-debug.log
echo "e01_PaasOmce" = $e01_PaasOmce >>/tmp/tf-debug.log
echo "e02_envName" = $e02_envName >>/tmp/tf-debug.log
echo "e03_envNumber" = $e03_envNumber >>/tmp/tf-debug.log
#debug local vars..
echo "a99_idTenant" = $a99_idTenant >>/tmp/tf-debug.log
#tools..
#curl..
yum install -y curl >>/tmp/tf-debug.log
#wget..
yum install -y wget >>/tmp/tf-debug.log
#mlocate
yum install -y mlocate >>/tmp/tf-debug.log
#jq
yum install -y jq >>/tmp/tf-debug.log
#oracle scl-utils
yum install -y scl-utils >>/tmp/tf-debug.log
#python..
yum install -y rh-python36 >>/tmp/tf-debug.log
export PATH=$PATH:/opt/rh/rh-python36/root/usr/bin
echo 'export PATH="$PATH:/opt/rh/rh-python36/root/usr/bin"' >> $HOME/.bashrc
#oracle psm-cli..
#download..
echo "Downloading PSM-CLI ..." >>/tmp/tf-debug.log
curl --silent -X GET -u $a01_ociUser:$a02_ociPass -H X-ID-TENANT-NAME:$a99_idTenant https://psm.$a98_apiRegion.oraclecloud.com/paas/api/v1.1/cli/$a99_idTenant/client -o psmcli.zip >>/tmp/tf-debug.log #idcs
echo "Downloading PSM-CLI ... :: Done ..." >>/tmp/tf-debug.log
#install..
if [ -f $e99_psmCli ]; then
pip install -q psmcli.zip
else
echo "Warning!! :: psm-cli downloaded may have failed, installing from a backup version ..."
pip install -q /tmp/mgt/env/envUtils/psmcli-1.1.21.zip
fi
#configure..
echo "Configure PSM-CLI ..." >>/tmp/tf-debug.log
cat << EOF > psmProfile.json
{
"username":"$a01_ociUser",
"password":"<PASSWORD>",
"identityDomain":"$a031_idIdcsTenant",
"region":"$a98_apiRegion",
"outputFormat":"json"
}
EOF
echo "Configure PSM-CLI ... :: Done ..." >>/tmp/tf-debug.log
psm setup -c psmProfile.json
<file_sep>[terraform]: https://terraform.io
[oci-c]: https://cloud.oracle.com/en_US/classic
[occ]: https://cloud.oracle.com/en_US/cloud-at-customer
[opc provider]: https://github.com/terraform-providers/terraform-provider-opc
# Terraform Installer for Oracle PaaS: DBCS & OMCe
## About
This installer is designed to automatically provision PaaS services to the Oracle [OCI-Classic (OCI-C)][oci-c] Cloud – Specifically an OMCe Stack with a supporting DBCS instance. This installer utilises the [Terraform Oracle Public Cloud Provider][opc provider].
## Solution Overview
This solution consists of a set of [Terraform][terraform] configurations & shell scripts that are used to provision the PaaS services. The installer utilises Terraform to first provision a compute instance to the cloud tenancy.
Once the compute instance has been provisioned and is running, shell scripts are then automatically copied to the compute instance and executed:
The shell scripts install:
1. OS and package dependencies
2. Oracle Cloud Platform Services Manager - Command Line Interface (PSM-CLI)
The shell scripts then use the PSM-CLI to provision:
1. DBCS
2. OMCe
The installer proceeds serially, waiting for the DBCS install to complete before initiating the OMCe installation.
Once the PaaS services have been provisioned, the management compute instance can be destroyed - leaving the OMCe solution running.
## Prerequisites
1. Download and install [Terraform][terraform] (v0.11.3 or later). Follow the link for Hashicorp [instructions](https://www.terraform.io/intro/getting-started/install.html).
2. [Terraform OPC provider](https://www.terraform.io/docs/providers/opc/index.html#) (can be pulled automatically using terraform init directive once Terraform is configured).
3. x2 user accounts in the target cloud tenancy. Currently there is a requirement that a separate user account be used to provision the object storage to be used by the OMCe stack. As a dependency to initiating a build, first create a dedicated account with the object storage administrator role.
## Quick start
### Configure the installer:
Populate the file /variables.tf with the appropriate credentials and configuration data. There are a number of variables requiring population, including credentials, REST endpoints, etc.
_Note: The /variables.tf file is self-documented – each variable has an associated supporting description._
_Note: Keys are provided for simplicity only, for long running deployments it is recommended that you replace the provided keys prior to deployment._
### Deploy the services:
Initialize Terraform:
```
$ terraform init
```
View what Terraform plans do before actually doing it:
```
$ terraform plan
```
Use Terraform to Provision resources and stand-up k8s cluster on OCI:
```
$ terraform apply
```
At this point the configuration will prompt for the following inputs before building the cluster:
````bash
$ variable "e00_PaasDbcs"
$ #Oracle DBCS install for OMCe (version:172.16.58.3, edition:EE, shape:oc3, name:OMCe-DB)
$ variable "e01_PaasOmce"
$ #Oracle Mobile Cloud - Enterprise (template: OMCe-T, requests: 100, schema prefix: OMCEWORDEV)
````
### Service Availability:
The OMCe environment will be running after the configuration is applied successfully, and the remote-exec scripts have completed. Typically, this takes around 120 minutes after `terraform apply`, and will vary depending on the overall configuration & geographic location.
Once completed, Terraform will output the public IP address of the cluster management node:
````bash
$ Apply complete! Resources: 14 added, 0 changed, 0 destroyed.
$
$ Outputs:
$
$ Master_Node_Public_IPs = [
$ 192.168.3.11
$]
````
Terraform will also output a summary of the running PaaS services in JSON format at the conclusion of the installation process.
## Notes
- Ensure that all variables are populated correctly – retrieve cloud tenancy configuration data from the appropriate cloud console screens.
- Environment Naming: Be sure to name & number the environments via the variables `e02_envName` & `e03_envNumber` - such that the build name will not overlap with existing deployments within the same cloud tenancy.
- PaaS services will be named via concatenation of these variables:
- DBCS: `${e02_envName}${e03_envNumber}dbs`
- OMCe: `${e02_envName}${e03_envNumber}stk`
- Once the installation has completed, it is possible to run the terraform destroy directive, which will remove the management IaaS instance, but leave the OMCe/DBCS service running.
- Additional environments can be provisioned within the same tenancy by modifying the variables:
- `e02_envName` & `e03_envNumber`
<file_sep>#!/bin/bash
#vars..
#assign args to vars..
echo " " >>/tmp/tf-debug.log
echo "confDbcs.sh -->>" >>/tmp/tf-debug.log
echo " " >>/tmp/tf-debug.log
for ARGUMENT in "$@"; do
KEY=$(echo $ARGUMENT | cut -f1 -d=)
VALUE=$(echo $ARGUMENT | cut -f2 -d=)
case "$KEY" in
a00_idIDCS) a00_idIDCS=${VALUE} ;;
a01_ociUser) a01_ociUser=${VALUE} ;;
a02_ociPass) a02_ociPass=${VALUE} ;;
a03_idDomain) a03_idDomain=${VALUE} ;;
a031_idIdcsTenant) a031_idIdcsTenant=${VALUE} ;;
a04_apiEndpoint) a04_apiEndpoint=${VALUE} ;;
a06_stgUser) a06_stgUser=${VALUE} ;;
a07_stgPass) a07_stgPass=${VALUE} ;;
a08_stgEndpointAuth) a08_stgEndpointAuth=${VALUE} ;;
a09_stgEndpoint) a09_stgEndpoint=${VALUE} ;;
e00_PaasDbcs) e00_PaasDbcs=${VALUE} ;;
e01_PaasOmce) e01_PaasOmce=${VALUE} ;;
e02_envName) e02_envName=${VALUE} ;;
e03_envNumber) e03_envNumber=${VALUE} ;;
*)
esac
done
#define local vars..
a99_svcName="${e02_envName}${e03_envNumber}dbs"
i99_ipAddress=$(psm dbcs service -s $a99_svcName | jq -r '.connect_descriptor_with_public_ip' | sed 's/:.*//')
#debug..
#debug local vars..
#configure database engine..
ssh -tt -q -o StrictHostKeyChecking=no -l opc ${i99_ipAddress} -i /tmp/mgt/env/envPaas/ssh/id_rsa <<'EOSSH'
#!/bin/bash
sudo su oracle
sqlplus sys/dbcs_password as sysdba
ALTER SESSION SET CONTAINER = pdb1;
ALTER PLUGGABLE DATABASE CLOSE IMMEDIATE;
ALTER PLUGGABLE DATABASE OPEN UPGRADE;
ALTER SYSTEM SET max_string_size=extended;
@${ORACLE_HOME}/rdbms/admin/utl32k.sql
ALTER PLUGGABLE DATABASE CLOSE;
ALTER PLUGGABLE DATABASE OPEN;
COMMIT;
EXIT
EOSSH
<file_sep>#!/bin/bash
#vars..
#assign args to vars..
echo " " >>/tmp/tf-debug.log
echo "envPaasDbcs.sh -->>" >>/tmp/tf-debug.log
echo " " >>/tmp/tf-debug.log
for ARGUMENT in "$@"; do
KEY=$(echo $ARGUMENT | cut -f1 -d=)
VALUE=$(echo $ARGUMENT | cut -f2 -d=)
case "$KEY" in
a00_idIDCS) a00_idIDCS=${VALUE} ;;
a01_ociUser) a01_ociUser=${VALUE} ;;
a02_ociPass) a02_ociPass=${VALUE} ;;
a03_idDomain) a03_idDomain=${VALUE} ;;
a031_idIdcsTenant) a031_idIdcsTenant=${VALUE} ;;
a04_apiEndpoint) a04_apiEndpoint=${VALUE} ;;
a06_stgUser) a06_stgUser=${VALUE} ;;
a07_stgPass) a07_stgPass=${VALUE} ;;
a08_stgEndpointAuth) a08_stgEndpointAuth=${VALUE} ;;
a09_stgEndpoint) a09_stgEndpoint=${VALUE} ;;
e00_PaasDbcs) e00_PaasDbcs=${VALUE} ;;
e01_PaasOmce) e01_PaasOmce=${VALUE} ;;
e02_envName) e02_envName=${VALUE} ;;
e03_envNumber) e03_envNumber=${VALUE} ;;
*)
esac
done
#define local vars..
a99_stgSid=$(echo $a09_stgEndpoint | sed 's:.*/::')
a98_svcName="${e02_envName}${e03_envNumber}dbs"
a96_svcStgName="${e02_envName}${e03_envNumber}dbs"
a95_svcRegion=$(echo $a04_apiEndpoint | cut -d'.' -f 2)
#debug..
echo "a00_idIdcs" = $a00_idIdcs >>/tmp/tf-debug.log
echo "a01_ociUser" = $a01_ociUser >>/tmp/tf-debug.log
echo "a02_ociPass" = $a02_ociPass >>/tmp/tf-debug.log
echo "a03_idDomain" = $a03_idDomain >>/tmp/tf-debug.log
echo "a031_idIdcsTenant" = $a031_idIdcsTenant >>/tmp/tf-debug.log
echo "a04_apiEndpoint" = $a04_apiEndpoint >>/tmp/tf-debug.log
echo "a06_stgUser" = $a06_stgUser >>/tmp/tf-debug.log
echo "a07_stgPass" = $a07_stgPass >>/tmp/tf-debug.log
echo "a08_stgEndpointAuth" = $a08_stgEndpointAuth >>/tmp/tf-debug.log
echo "a09_stgEndpoint" = $a09_stgEndpoint >>/tmp/tf-debug.log
echo "e00_PaasDbcs" = $e00_PaasDbcs >>/tmp/tf-debug.log
echo "e01_PaasOmce" = $e01_PaasOmce >>/tmp/tf-debug.log
echo "e02_envName" = $e02_envName >>/tmp/tf-debug.log
echo "e03_envNumber" = $e03_envNumber >>/tmp/tf-debug.log
#debug local vars..
#functions..
#evaluate paas status..
TIMEOUT="480"
function psm::dbcs {
echo "dbcs install status:" >>/tmp/tf-debug.log
minutesP=0 minutesC=0 counter=0 statusP=""
for ((counter=0; counter < ${TIMEOUT}; counter++)); do
statusP=$(psm dbcs service -s $1 | jq -r '.status' | cat)
if [ "${statusP}" = "In Progress" ]; then
minutesP=$((${minutesP} + 1))
echo "DBCS instance" $1 "is provisioning ("${minutesP} "min elapsed) ..."
echo ${statusP} >>/tmp/tf-debug.log
sleep 60
elif [ "${statusP}" = "Configured" ]; then
minutesC=$((${minutesC} + 1))
echo "DBCS instance" $1 "is configured, waiting for start ("${minutesC} "min elapsed) ..."
echo ${statusP} >>/tmp/tf-debug.log
sleep 60
else
echo "DBCS instance" $1 "is now running ..."
break
fi
done
}
#tf apply operations..
#provision object storage..
#authenticate..
echo "get obj storage cookie.." >>/tmp/tf-debug.log
a94_stgCookie=$(curl -sS -i -X GET \
-H "X-Storage-User: $a99_stgSid:$a06_stgUser" \
-H "X-Storage-Pass: $a07_stgPass" \
$a08_stgEndpointAuth \
| grep -A1 "X-Auth-Token:" \
| sed -ne '/:/ { s/^[^:]*:[\t\v\f ]*//p ; q0 }') >>/tmp/tf-debug.log
echo $a94_stgCookie >>/tmp/tf-debug.log
#create container..
echo "create obj storage container.." >>/tmp/tf-debug.log
curl -sS -i -X PUT \
-H "X-Auth-Token: $a94_stgCookie" \
$a09_stgEndpoint/$a96_svcStgName >>/tmp/tf-debug.log
#create dbcs instance..
cat << EOF > /home/opc/psmDbcsOmce.json
{
"serviceName": "$a98_svcName",
"version": "172.16.58.3",
"level": "PAAS",
"edition": "EE",
"region": "$a95_svcRegion",
"subscriptionType": "HOURLY",
"shape": "oc3",
"vmPublicKeyText": "ssh-rsa AAA<KEY>",
"parameters": [
{
"type": "db",
"usableStorage": "25",
"adminPassword": "<PASSWORD>",
"sid": "ORCL",
"pdbName": "PDB1",
"failoverDatabase": "no",
"backupDestination": "BOTH",
"cloudStorageContainer": "$a09_stgEndpoint\/$a96_svcStgName",
"cloudStorageUser": "$a06_stgUser",
"cloudStoragePwd": <PASSWORD>"
}
]
}
EOF
psm dbcs create-service -c /home/opc/psmDbcsOmce.json
psm::dbcs $a98_svcName
#configure database engine..
echo "ENV-1 :: Configuring DBCS SQL Engine (SQLPlus) ..."
chmod +x /tmp/mgt/env/envPaas/confDbcs.sh
/tmp/mgt/env/envPaas/confDbcs.sh e02_envName=$e02_envName e03_envNumber=$e03_envNumber export APP_PID=$! >>/tmp/tf-debug.log &
echo $APP_PID
sleep 25
echo "ENV-1 :: Configuring DBCS SQL Engine (SQLPlus) ... :: Done ..."
|
be7f1f702c18e2835ee46b575c75f8bc42fff5c4
|
[
"Markdown",
"Shell"
] | 6 |
Markdown
|
cameronsenese/opc-terraform-paas-installer-omce
|
024e96144ceb71a9db75565f6c3584fb0f287715
|
667fed6dc7322eba1d10a26e0c51bfd946a2130a
|
refs/heads/main
|
<repo_name>daliborgogic/vite-ssg<file_sep>/src/build.ts
import { join, dirname, resolve } from 'path'
import fs from 'fs-extra'
import { build as clientBuild, ssrBuild, resolveConfig, ResolvedConfig } from 'vite'
import { renderToString } from '@vue/server-renderer'
import { JSDOM } from 'jsdom'
import type { ViteSSGContext } from './index'
export async function build({ script = 'sync', mock = false } = {}) {
const mode = process.env.MODE || process.env.NODE_ENV || 'production'
const config = await resolveConfig(mode)
const cwd = process.cwd()
const root = config.root || cwd
const ssgOut = join(root, '.vite-ssg-dist')
let ssrConfig: ResolvedConfig
if (fs.existsSync(resolve(cwd, 'vite.ssg.config.js')))
ssrConfig = await resolveConfig(mode, resolve(cwd, 'vite.ssg.config.js'))
else if (fs.existsSync(resolve(cwd, 'vite.ssg.config.ts')))
ssrConfig = await resolveConfig(mode, resolve(cwd, 'vite.ssg.config.ts'))
else
ssrConfig = config
ssrConfig = {
...ssrConfig,
outDir: ssgOut,
rollupInputOptions: {
...config.rollupInputOptions,
input: {
main: join(root, './src/main.ts'),
},
preserveEntrySignatures: 'allow-extension',
},
}
console.log('[vite-ssg] Build for client + server...')
await Promise.all([
clientBuild(config),
ssrBuild(ssrConfig),
])
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { createApp } = require(join(ssgOut, '_assets/main.js')) as { createApp(client: boolean): ViteSSGContext }
const out = join(root, config.outDir || 'dist')
let indexHTML = await fs.readFile(join(out, 'index.html'), 'utf-8')
const { routes } = createApp(false)
// ignore dynamic routes
const routesPathes = routes.map(i => i.path).filter(i => !i.includes(':'))
if (script && script !== 'sync')
indexHTML = indexHTML.replace(/<script type="module" /g, `<script type="module" ${script} `)
if (mock) {
const jsdom = new JSDOM()
// @ts-ignore
global.window = jsdom.window
Object.assign(global, jsdom.window)
}
console.log('[vite-ssg] Rendering Pages...')
await Promise.all(
routesPathes.map(async(route) => {
const { app, router } = createApp(false)
router.push(route)
await router.isReady()
const content = await renderToString(app)
const relativeRoute = (route.endsWith('/') ? `${route}index` : route).slice(1)
const html = indexHTML.replace('<div id="app">', `<div id="app" data-server-rendered="true">${content}`)
await fs.ensureDir(join(out, dirname(relativeRoute)))
await fs.writeFile(join(out, `${relativeRoute}.html`), html, 'utf-8')
}),
)
await fs.remove(ssgOut)
console.log('[vite-ssg] Build finished.')
}
<file_sep>/package.json
{
"name": "vite-ssg",
"description": "Server-side generation for Vite",
"version": "0.0.12",
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"author": "<NAME> <<EMAIL>>",
"repository": {
"type": "git",
"url": "https://github.com/antfu/vite-ssg"
},
"homepage": "https://github.com/antfu/vite-ssg",
"bugs": "https://github.com/antfu/vite-ssg/issues",
"files": [
"dist",
"bin"
],
"bin": {
"vite-ssg": "bin/vite-ssg.js"
},
"scripts": {
"dev": "npm run build -- --watch",
"example:dev": "cp README.md example/README.md && npm -C example run dev",
"example:build": "cp README.md example/README.md && npm -C example run build",
"build": "tsup src/index.ts src/cli.ts --dts --format cjs,esm",
"prepublishOnly": "npm run build",
"release": "npx bumpp --commit --tag && npm publish && git push"
},
"dependencies": {
"fs-extra": "^9.0.1",
"jsdom": "^16.4.0",
"yargs": "^16.2.0"
},
"peerDependencies": {
"@vue/compiler-sfc": "^3.0.4",
"@vue/server-renderer": "^3.0.4",
"vite": "^1.0.0-rc.13",
"vue": "^3.0.4",
"vue-router": "^4.0.1"
},
"devDependencies": {
"@antfu/eslint-config": "^0.4.3",
"@types/fs-extra": "^9.0.5",
"@types/jsdom": "^16.2.5",
"@types/yargs": "^15.0.12",
"@typescript-eslint/eslint-plugin": "^4.10.0",
"@vue/compiler-sfc": "^3.0.4",
"@vue/server-renderer": "^3.0.4",
"eslint": "^7.16.0",
"rollup": "^2.35.1",
"standard-version": "^9.0.0",
"tsup": "^3.11.0",
"typescript": "^4.1.3",
"vite": "^1.0.0-rc.13",
"vue": "^3.0.4",
"vue-router": "^4.0.1"
}
}
|
d0582f5358e404ee98cb0cc4a20e278c0a0845ba
|
[
"JSON",
"TypeScript"
] | 2 |
TypeScript
|
daliborgogic/vite-ssg
|
a9d53f509cf4f204b1faed22dcd7bb35e1b1a27b
|
61bcc1ab4b9b189dacf7005c75e0765404474d30
|
refs/heads/master
|
<repo_name>moschz/Vagrant.Themes<file_sep>/README.md
Themes.Vagrant
===========
To use this vagrant maschine you need to install vagrant and virtualbox.
Needed Software
---------------
Please download and install the following software
- virtualbox https://www.virtualbox.org/
- vagrant http://downloads.vagrantup.com/ (pick the latest version for your operating system)
- git (windows: https://code.google.com/p/msysgit/)
As visual git Desktop client i think sourcetree is the best choice, but you may also use tortoisegit on winows.
- http://www.sourcetreeapp.com/
- https://code.google.com/p/tortoisegit/
First Startup
--------
To power on the virtual maschines you need to switch to the commandline.
Go into the git repository and run:
```bash
git clone https://github.com/typo3-themes/Vagrant.Themes.git typo3-themes-box
cd typo3-themes-box
vagrant up
```
This will download and initialise the basic image
(lateron this command will be blazing fast, as the base vm is already available on your system).
Other important commands
```bash
vagrant suspend
vagrant status
vagrant halt
vagrant destroy
```
Have fun!
<file_sep>/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
# Every Vagrant virtual environment requires a box to build off of.
config.vm.box = "debian-720-x32"
config.vm.box_url = "http://puppet-vagrant-boxes.puppetlabs.com/debian-73-i386-virtualbox-puppet.box"
config.vm.synced_folder ".", "/serverdata", owner: "www-data"
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine. In the example below,
# accessing "localhost:8080" will access port 80 on the guest machine.
# config.vm.network :forwarded_port, guest: 80, host: 8080
config.vm.hostname = "themes.dev"
config.vm.network :private_network, ip: "192.168.31.16"
config.vm.provision :shell, :path => "serverdata/provision/prepare.sh"
# Puppet provisioning
config.vm.provision :puppet do |puppet|
puppet.manifests_path = "serverdata/provision/manifests"
puppet.manifest_file = "default.pp"
end
config.vm.provision :shell, :path => "serverdata/provision/bootstrap.sh"
# Enable provisioning with chef solo, specifying a cookbooks path, roles
# path, and data_bags path (all relative to this Vagrantfile), and adding
# some recipes and/or roles.
#
# config.vm.provision :chef_solo do |chef|
# chef.cookbooks_path = "../my-recipes/cookbooks"
# chef.roles_path = "../my-recipes/roles"
# chef.data_bags_path = "../my-recipes/data_bags"
# chef.add_recipe "mysql"
# chef.add_role "web"
#
# # You may also specify custom JSON attributes:
# chef.json = { :mysql_password => "foo" }
# end
config.vm.provider "virtualbox" do |vm, override|
vm.name = "themes.dev"
vm.customize ["modifyvm", :id, "--memory", "1024"]
vm.customize ["modifyvm", :id, "--cpuexecutioncap", "80"]
end
config.vm.provider :vmware_fusion do |vm, override|
override.vm.box = "precise64_fusion"
override.vm.box_url = "http://files.vagrantup.com/precise64_vmware.box"
override.vm.network :private_network, ip: "192.168.35.16"
# v.gui = true
vm.vmx["memsize"] = "1024"
end
#config.vm.provider :lxc do |lxc, override|
# config.vm.box = "debian-607-x32"
# config.vm.box_url = "http://dl.dropbox.com/u/40989391/vagrant-boxes/debian-squeeze-i386.box"
#end
end
<file_sep>/serverdata/provision/bootstrap.sh
#!/usr/bin/env bash
function getExtensionFromGitHub {
echo "TYPO3 Extension $1 from $2/$3"
if [ ! -d $1/.git ]; then
rm -R -f $1
fi
if [ ! -d $1 ]; then
rm -R -f $1
git clone https://github.com/$2/$3.git $1
echo " Done"
else
echo " Already there"
cd $1
git pull
cd ..
fi
}
function getExtensionFromSvn {
echo "TYPO3 Extension $1 from $2"
if [ ! -d $1 ]; then
echo " Downloading"
rm -R -f $1
git svn clone $2 $1 --quiet
echo " Done"
else
echo " Already there"
cd $1
git svn fetch
cd ..
fi
}
function getExtensionFromGit {
echo "TYPO3 Extension from $1 from $2"
if [ ! -d $1 ]; then
echo " Downloading"
rm -R -f $1
git clone $2 $1
echo " Done"
else
echo " Already there"
cd $1
git pull
cd ..
fi
}
# ensure fast booting with grub ;)
#cp /etc/default/grub /etc/default/grub.orig
#sed -i -e 's/GRUB_TIMEOUT=\([0-9]\)\+/GRUB_TIMEOUT=0/' /etc/default/grub
#update-grub
# clean up
cp /etc/phpmyadmin/apache.conf /etc/apache2/sites-enabled/phpmyadmin
cp /vagrant/serverdata/etc/phpmyadmin/config.inc.php /etc/phpmyadmin/config.inc.php
if [ ! -d "/var/www/typo3conf" ]; then
rm -rf /var/www/*
# checkout TYPO3 from Github
cd /var/www
curl -L -o latestSource.tar.gz http://get.typo3.org/6.2
tar xzf latestSource.tar.gz
rm latestSource.tar.gz
typo3sourceDir=$(find . -mindepth 1 -maxdepth 1 -type d)
ln -s $typo3sourceDir typo3_src
ln -s typo3_src/index.php index.php
ln -s typo3_src/typo3 typo3
ln -s /serverdata/project/fileadmin fileadmin
ln -s /serverdata/project/uploads uploads
mkdir typo3conf
cd typo3conf
ln -s /serverdata/project/typo3conf/ext ext
# checkout from git ...
cd /var/www/typo3conf/ext/
fi
# copy configuration
cp /serverdata/project/typo3conf/LocalConfiguration.php /var/www/typo3conf/
cp /serverdata/project/typo3conf/PackageStates.php /var/www/typo3conf/
# import db
mysql -u root < /serverdata/serverdata/data/sql/prepare.sql
mysql -u root t3-latest < /serverdata/serverdata/data/sql/t3-latest.sql
# ensure extdir exists
if [ ! -d "/serverdata/project/typo3conf/ext" ]; then
mkdir /serverdata/project/typo3conf/ext
fi
cd /var/www/typo3conf/ext/
#base extensions
getExtensionFromGit gridelements git://git.typo3.org/TYPO3CMS/Extensions/gridelements.git
getExtensionFromGitHub belayout_tsprovider kaystrobach TYPO3.belayout_tsprovider
# typo3-themes repositories
getExtensionFromGitHub themes_distribution typo3-themes themes_distribution
getExtensionFromGitHub themes typo3-themes themes
getExtensionFromGitHub themes_gridelements typo3-themes themes_gridelements
getExtensionFromGitHub themes_builder typo3-themes themes_builder
getExtensionFromGitHub themes_library typo3-themes themes_library
getExtensionFromGitHub themes_manager typo3-themes themes_manager
getExtensionFromGitHub themes_adapter_directory typo3-themes themes_adapter_directory
getExtensionFromGitHub themes_adapter_tvframework typo3-themes themes_adapter_tvframework
getExtensionFromGitHub themes_adapter_wordpress typo3-themes themes_adapter_wordpress
getExtensionFromGitHub theme_bootstrap typo3-themes theme_bootstrap
getExtensionFromGitHub theme_bootstrap_slate typo3-themes theme_bootstrap_slate
getExtensionFromGitHub basictemplate kaystrobach TYPO3.basictemplate
# independent repositories fedext
getExtensionFromGitHub flux FluidTYPO3 flux
getExtensionFromGitHub vhs FluidTYPO3 vhs
getExtensionFromGitHub view FluidTYPO3 view
# Do this to fix a shared folder problem in vms
getExtensionFromGitHub uncache NamelessCoder uncache
# other usefull tools, not all needed until now, but interesting
getExtensionFromGitHub beskin kaystrobach TYPO3.beskin
getExtensionFromGitHub dyncss kaystrobach TYPO3.dyncss
getExtensionFromGitHub dyncss_phpsass kaystrobach TYPO3.dyncss_phpsass
getExtensionFromGitHub dyncss_less kaystrobach TYPO3.dyncss_less
getExtensionFromGitHub dyncss_scss kaystrobach TYPO3.dyncss_scss
getExtensionFromGitHub dyncss_test kaystrobach TYPO3.dyncss_test
getExtensionFromGitHub easylogin kaystrobach TYPO3.easylogin
getExtensionFromGitHub bootstrap_package benjaminkott bootstrap_package
# get svn extensions from forge :D
getExtensionFromGitHub t3jquery TYPO3-svn-archive t3jquery
getExtensionFromGitHub static_info_tables TYPO3-svn-archive static_info_tables
# import database
# clear cache
rm -R -f /serverdata/www/typo3temp/Cache
chmod 777 -R /var/www/
echo "======================================================================="
echo " Access the vm in your Browser via:"
echo " - 192.168.31.16 32bit 1GB Ram (Virtualbox Provider)"
echo "======================================================================="
|
7a1e838b2e7f5a4bb3a7814fbd599e296f3839b5
|
[
"Markdown",
"Ruby",
"Shell"
] | 3 |
Markdown
|
moschz/Vagrant.Themes
|
19a009aa4f8feb389b331e85002603d0899e0451
|
8f03f88c42949018cf7a28eb57f932082ffa5997
|
refs/heads/master
|
<file_sep>require_relative 'lib/sql_object'
class School < SQLObject
has_many :houses
end
class House < SQLObject
belongs_to :school
has_many :students
end
class Student < SQLObject
belongs_to :house
has_one_through :school, :house, :school
end
<file_sep># DB Mapper
DB Mapper is an Object Relational Mapping framework which allows manipulating a database without explicitly writing SQL statements.
### Example
You can run following commands on your computer to run demo.
1. Clone the repository into your working directory.
```
$ git clone https://github.com/echeon/db-mapper.git
```
1. Go to `db-mapper` folder and run `bundle install`.
```
$ cd db-mapper
$ bundle install
```
1. Create SQLite3 tables by running the following command.
```
$ cat wizards.sql | sqlite3 wizards.db
```
1. Then, following tables will be generated and `wizards.db` file will be created.
* `schools`
* `houses`
* `students`
1. Open `pry` and require the demo file.
```
$ pry
[1] pry(main) > require_relative 'demo'
```
This example has three models: `School`, `House`, `Student`.
```ruby
class School < SQLObject
has_many :houses
end
class House < SQLObject
belongs_to :school
has_many :students
end
class Student < SQLObject
belongs_to :house
has_one_through :school, :house, :school
end
```
1. Play around! You can also run your own example by creating your own database and models. Just don't forget to add `require_relative 'lib/sql_object'` to your model file(s). Also, they all should inherit from `SQLObject`!
## Methods
The followings are all methods available in DB Mapper. These examples show how you can use each method.
### SQLObject
- `::new`
initializes an instance with provided hash
```
[2] pry(main) > School.new(name: "Castelobruxo")
=> #<School:0x007fdda831bc98 @attributes={:name=>"Castelobruxo"}>
```
- `::columns`
takes no arguments and returns an array of column names
```
[3] pry(main)> Student.columns
=> [:id, :name, :house_id]
```
- `::all`
takes no arguments and returns all objects in a class
```
[4] pry(main) > House.all
=> [#<House:0x007fdda82e0a80 @attributes={:id=>1, :name=>"Gryffindor", :school_id=>1}>, ...]
```
- `::find(id)`
takes an integer as an argument and returns an object with matching id.
```
[5] pry(main) > Student.find(1)
=> #<Student:0x007fdda8ab9d88 @attributes={:id=>1, :name=>"<NAME>", :house_id=>1}>
```
- `#insert`
inserts a new data to the database
```
[6] pry(main) > school = School.new(name: "Castelobruxo")
[7] pry(main) > school.insert
[8] pry(main) > School.all
=> [...,
#<School:0x007fdda818aac8 @attributes={:id=>4, :name=>"Castelobruxo"}>]
```
- `#update`
saves updated attributes to the database
```
[9] pry(main) > school = School.find(1)
=> #<School:0x007fdda89b0ae0 @attributes={:id=>1, :name=>"Hogwarts"}>
[10] pry(main) > school.name = "Hogwarts School of Witchcraft and Wizardry"
[11] pry(main) > school.update
[12] pry(main) > School.find(1)
=> #<School:0x007fdda89b0ae0 @attributes={:id=>1, :name=>"Hogwarts School of Witchcraft and Wizardry"}>
```
- `#save`
saves a new record using `#insert` if it doesn't exist in the database. OR, it saves with updated attributes to the database using `#update` if the record already exists in the database
### Searchable
- `::where`
takes an hash as an argument and returns an array of one or more objects that satisfy the all conditions
```
[13] pry(main) > Student.where(name: "<NAME>")
=> [#<Student:0x007fb7e48cee90 @attributes={:id=>2, :name=>"<NAME>", :house_id=>1}>]
```
### Associatable
- `::belongs_to`
is equivalent to Rails Active Record's `belongs_to` association
```
[14] pry(main) > harry = Student.find(1)
[15] pry(main) > harry.house
=> #<House:0x007f90fe0f0578 @attributes={:id=>1, :name=>"Gryffindor", :school_id=>1}>
```
- `::has_many`
is equivalent to Rails Active Record's `has_many` association
```
[16] pry(main) > gryffindor = House.find(1)
[17] pry(main) > gryffindor.students
=> [#<Student:0x007f90fc80ee10 @attributes={:id=>1, :name=>"<NAME>", :house_id=>1}>,
#<Student:0x007f90fc80e0a0 @attributes={:id=>2, :name=>"<NAME>", :house_id=>1}>,
#<Student:0x007f90fc80dd80 @attributes={:id=>3, :name=>"<NAME>", :house_id=>1}>,
#<Student:0x007f90fc80dbc8 @attributes={:id=>4, :name=>"<NAME>", :house_id=>1}>,
#<Student:0x007f90fc80d998 @attributes={:id=>5, :name=>"<NAME>", :house_id=>1}>]
```
- `::has_one_through`
is equivalent to Rails Active Record's `has_many :through` association
```
[18] pry(main) > draco = Student.where(name: "<NAME>").first
[19] pry(main) > draco.school
=> #<School:0x007f90fc39db60 @attributes={:id=>1, :name=>"Hogwarts School of Witchcraft and Wizardry"}>
```
<file_sep>CREATE TABLE students (
id INTEGER PRIMARY KEY,
name VARCHAR(255) NOT NULL,
house_id INTEGER NOT NULL,
FOREIGN KEY(house_id) REFERENCES houses(id)
);
CREATE TABLE houses (
id INTEGER PRIMARY KEY,
name VARCHAR(255) NOT NULL,
school_id INTEGER NOT NULL,
FOREIGN KEY(school_id) REFERENCES schools(id)
);
CREATE TABLE schools (
id INTEGER PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
INSERT INTO
schools (id, name)
VALUES
(1, "Hogwarts"),
(2, "Durmstrang"),
(3, "Beauxbatons");
INSERT INTO
houses (id, name, school_id)
VALUES
(1, "Gryffindor", 1),
(2, "Hufflepuff", 1),
(3, "Ravenclaw", 1),
(4, "Slytherin", 1);
INSERT INTO
students (id, name, house_id)
VALUES
(1, "<NAME>", 1),
(2, "<NAME>", 1),
(3, "<NAME>", 1),
(4, "<NAME>", 1),
(5, "<NAME>", 1),
(6, "<NAME>", 2),
(7, "<NAME>", 2),
(8, "<NAME>", 2),
(9, "<NAME>", 2),
(10, "<NAME>", 2),
(11, "<NAME>", 3),
(12, "<NAME>", 3),
(13, "<NAME>", 3),
(14, "<NAME>", 3),
(15, "<NAME>", 3),
(16, "<NAME>", 4),
(17, "<NAME>", 4),
(18, "<NAME>", 4),
(19, "<NAME>", 4),
(20, "<NAME>", 4);
<file_sep>class AssocOptions
attr_accessor :foreign_key, :class_name, :primary_key
def model_class
class_name.constantize
end
def table_name
model_class.table_name
end
end
class BelongsToOptions < AssocOptions
def initialize(name, options = {})
defaults = {
foreign_key: :"#{name}_id",
class_name: "#{name}".singularize.camelcase,
primary_key: :id
}
@foreign_key = options[:foreign_key] || defaults[:foreign_key]
@class_name = options[:class_name] || defaults[:class_name]
@primary_key = options[:primary_key] || defaults[:primary_key]
end
end
class HasManyOptions < AssocOptions
def initialize(name, self_class_name, options = {})
defaults = {
foreign_key: :"#{self_class_name.underscore}_id",
class_name: "#{name}".singularize.camelcase,
primary_key: :id
}
@foreign_key = options[:foreign_key] || defaults[:foreign_key]
@class_name = options[:class_name] || defaults[:class_name]
@primary_key = options[:primary_key] || defaults[:primary_key]
end
end
module Associatable
def belongs_to(name, options = {})
options = BelongsToOptions.new(name, options)
self.assoc_options[name] = options
define_method(name) do
foreign_key_value = self.send(options.foreign_key)
target_model_class = options.model_class
target_model_class
.where("#{options.primary_key}" => foreign_key_value)
.first
end
end
def has_many(name, options = {})
options = HasManyOptions.new(name, self.name, options)
define_method(name) do
primary_key_value = self.send(options.primary_key)
target_model_class = options.model_class
target_model_class
.where("#{options.foreign_key}" => primary_key_value)
end
end
def assoc_options
@assoc_options ||= {}
end
def has_one_through(name, through_name, source_name)
define_method(name) do
through_options = self.class.assoc_options[through_name]
through_model_class = through_options.model_class
foreign_key_value = self.send(through_options.foreign_key)
through_object = through_model_class
.where("#{through_options.primary_key}" => foreign_key_value)
.first
source_options = through_model_class.assoc_options[source_name]
target_model_class = source_options.model_class
foreign_key_value = through_object.send(source_options.foreign_key)
target_model_class
.where("#{source_options.primary_key}" => foreign_key_value)
.first
end
end
end
|
d5cc0951515bc1630afc78bfd70188a08a544511
|
[
"Markdown",
"SQL",
"Ruby"
] | 4 |
Ruby
|
echeon/db-mapper
|
a51c7a5d95961805995358282e6d54b7ce3b8a2c
|
ee27b97c7de8131f9130bec30a2048bdf30d3ff8
|
refs/heads/master
|
<file_sep># Visual-BooksMarks-Google
<file_sep>#!/usr/bin/env python3
import os
import glob
import json
directory = os.getcwd()
for file_name in glob.glob(f"{directory}/BOOKSMARKS/*"):
with open(file=file_name, mode="r") as file:
file_contents = file.read()
json_data = json.loads(file_contents)
with open(file=f"{directory}/bookmarks.txt", mode="a") as bookfile:
for bookmark in json_data["roots"]["bookmark_bar"]["children"]:
print()
print(bookmark["name"])
print(bookmark["url"])
print()
bookfile.write(f"{bookmark['name']}\n")
bookfile.write(f"{bookmark['url']}\n")
bookfile.write(f"\n")
print(type(json_data))
<file_sep>#!/usr/bin/env python3
import os
import get
import json
with open(file="Bookmarks", mode="r") as file:
file_contents = file.read()
json_data = json.loads(file_contents)
print(type(json_data))
with open(file="bookmarks.txt", mode="w") as bookfile:
for bookmark in json_data["roots"]["bookmark_bar"]["children"]:
print()
print(bookmark["name"])
print(bookmark["url"])
print()
bookfile.write(f"{bookmark['name']}\n")
bookfile.write(f"{bookmark['url']}\n")
bookfile.write(f"\n")
|
3c675a2c855f9a87a1bde4a8c14e8f99e0352873
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
maxmaximo-github/Visual-BooksMarks-Google
|
123c9e6eb04871d3fab685ca3b4f109a5fcd1506
|
2c8bd616f13caddc809d346188de7f4d1b54782b
|
refs/heads/master
|
<repo_name>akashom53/Star-Field-WebGL<file_sep>/js/main.js
var w = window.innerWidth;
var h = window.innerHeight;
var stars = [];
var starCount = 600;
var speed = 0;
function setup(){
createCanvas(w, h, WEBGL);
background(0);
for (var i = 0; i < starCount; i++){
stars.push(new Star());
}
}
function draw() {
background(0, 0, 0);
// translate(w/2, h/2);
for (var i = 0; i < starCount; i++){
stars[i].update();
stars[i].show();
}
if (mouseX >= 0 && mouseX <= w){
speed = map(mouseX, 0, w, 0, 10);
}
}
function Star() {
this.x = floor(random(-w/2, w/2));
this.y = floor(random(-h/2, h/2));
this.z = floor(random(w));
this.r = floor(random(2));
this.update = function() {
this.z += speed;
if (this.z > w){
this.x = floor(random(-w/2, w/2));
this.y = floor(random(-h/2, h/2));
this.z = 0;
}
}
this.show = function() {
push();
noStroke();
fill(255);
translate(this.x, this.y, this.z);
sphere(this.r);
pop();
}
}<file_sep>/README.md
# Star-Field-WebGL
Same coding challenge, this time using WebGL 3D to prove to someone that it will have similar performance
[Live link](https://akashom53.github.io/Star-Field-WebGL/)
|
c9e6d39fef390d74269aa1b894c609113fcdf296
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
akashom53/Star-Field-WebGL
|
2f75e9e1c3142eb7f2cce29fe173cc7a63af131e
|
e6d2350393c6875cb1eb77562e796a22022ba67e
|
refs/heads/master
|
<file_sep>#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <stack>
#include <queue>
#include <utility>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/adjacency_list_io.hpp>
#include <boost/graph/adjacency_matrix.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/copy.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/random.hpp>
using namespace std;
/* *
* Type Declarations
*
*/
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, boost::no_property, boost::no_property, boost::no_property, boost::listS> diGraph;
typedef boost::graph_traits<diGraph>::vertex_descriptor diGraphVertex;
typedef boost::graph_traits<diGraph>::edge_descriptor diGraphEdge;
/* *
* Function Declarations
*
*/
void findAnswer(diGraph &g, stack<diGraphEdge> &canD, int cutsMade, queue<pair<int, int>> &cutEdgeList);
bool sinkSourceProperty(diGraph &g);
bool isAcyclic(diGraph &g);
bool verticesProperty(diGraph &g);
int connectedComponents(diGraph &g);
int connectedComponentScore(diGraph &g);
bool checkAnswer(diGraph &g, string answerFile);
stack<diGraphEdge> backEdges;
stack<pair<int, int>> finalCandidates;
class dfs_Visitor : public boost::default_dfs_visitor
{
public:
template < typename diGraphEdge, typename diGraph >
void back_edge(diGraphEdge e, const diGraph& g) const
{
//cout << "Found back edge from: " << boost::source(e, g) + 1 << " to: " << boost::target(e, g) + 1 << endl;
backEdges.push(e);
}
};
int main() {
clock_t start = clock();
double duration;
string t = "test.txt";
string tr = "largerGraph.txt";
string td = "14";
string tf = "15";
string sI = "8_input.txt";
string sI2 = "15_input.txt";
string sI3 = "1_input.txt";
string theFile = tf + "_input.txt";
ifstream infile( theFile ); //get data from in file
string readLine;
getline(infile, readLine);
int numVertices = atoi(readLine.c_str());
getline(infile, readLine);
int numEdges = atoi(readLine.c_str());
diGraph theGraph;
//read rest of lines from file and parse
int edgeCounter = 0;
while( getline(infile, readLine) ) {
stringstream lineStream(readLine);
int v1, v2;
lineStream >> v1;
lineStream >> v2;
//cout << "Added " << v1 << " to " << v2 << endl;
if( theFile != sI ) {
v1--;
v2--;
}
boost::add_edge(v1, v2, theGraph);
edgeCounter++;
}
diGraph theGraphCopy(theGraph);
/*
// Debugging for file inputs against graph
cout << "Vertices in graph: " << boost::num_vertices(theGraph) << " Edges in graph: " << boost::num_edges(theGraph) << " && " << edgeCounter << endl;
cout << "Vertices from file: " << numVertices << "Edges from file: " << numEdges << endl;
//*/
if( (boost::num_vertices(theGraph) != numVertices || boost::num_edges(theGraph) != numEdges) && theFile != sI2 && theFile != sI3 ) {
cout << "Input Err: vertices and edges in input file do not match edges and vertices added from other lines... check file: " << theFile << endl;
infile.close();
return -1;
}
infile.close();
cout << "Graph " + tf + " appears to be alright after loading in." << endl;
diGraphVertex tempV;
diGraphEdge tempE;
/*
BGL_FORALL_VERTICES(tempV, theGraph, diGraph) {
int inCount = boost::in_degree(tempV, theGraph);
int outCount = boost::out_degree(tempV, theGraph);
cout << "Vertex: " << tempV << " has " << inCount << " in edges and " << outCount << " out edges." << endl;
}
`*/
dfs_Visitor vis;
boost::depth_first_search(theGraph, visitor(vis));
queue<pair<int, int>> cutEdges;
//process back edges
//routine that simply deletes all back edges
diGraphEdge workingEdge;
stack<diGraphEdge> backEdgeCopy(backEdges);
while( !backEdges.empty() ) {
workingEdge = backEdges.top();
boost::remove_edge(workingEdge, theGraph);
backEdges.pop();
}
if( sinkSourceProperty(theGraph) && isAcyclic(theGraph) && verticesProperty(theGraph) ) {
cout << "success!" << endl;
duration = (clock() - start) / (double) CLOCKS_PER_SEC;
cout << "Took: " << duration << endl;
}
ofstream outFile;
outFile.open (tf + "_output_generated_by_G14.txt");
outFile << backEdgeCopy.size() << endl;
if( theFile == sI ) {
while( !backEdgeCopy.empty() ) {
outFile << boost::source(backEdgeCopy.top(), theGraph) << " " << boost::target(backEdgeCopy.top(), theGraph) << endl;
backEdgeCopy.pop();
}
}
else {
while( !backEdgeCopy.empty() ) {
outFile << boost::source(backEdgeCopy.top(), theGraph) + 1 << " " << boost::target(backEdgeCopy.top(), theGraph) + 1 << endl;
backEdgeCopy.pop();
}
}
outFile.close();
//findAnswer(theGraph, backEdges, 0, cutEdges);
string fileToCheck = tf + "_output_generated_by_G14.txt";
checkAnswer(theGraphCopy, fileToCheck);
return 0;
}
/* *
* Function Implementations
*
*
*/
void findAnswer(diGraph &g, stack<diGraphEdge> &backEdgeList, int cutsMade, queue<pair<int, int>> &cutEdgeList) {
diGraphEdge worker;
queue<pair<int, int>> edgeCuts(cutEdgeList);
stack<pair<int, pair<diGraphVertex, diGraphVertex>>> remainders;
stack<diGraphEdge> backEdgeCopy(backEdgeList);
bool atLeastOne = false;
while( !backEdgeList.empty() ) {
worker = backEdgeList.top();
backEdgeList.pop();
diGraphVertex source = boost::source(worker, g);
diGraphVertex target = boost::target(worker, g);
cout << "Graph has " << boost::num_vertices(g) << " vertices and " << boost::num_edges(g) << " edges" << endl;
boost::remove_edge(worker, g);
cout << "Removed edge from: " << source + 1 << " to: " << target + 1 << " Graph now has " << boost::num_vertices(g) << " vertices and " << boost::num_edges(g) << " edges" << endl;
if( sinkSourceProperty(g) && isAcyclic(g) && verticesProperty(g) ) {
cout << "pass" << endl;
atLeastOne = true;
edgeCuts.push(make_pair(source, target));
}
else {
remainders.push(make_pair(connectedComponentScore(g), make_pair(source, target)));
}
boost::add_edge(source, target, g);
}
if( !atLeastOne && !remainders.empty() ) { //greedy pick lowest scored edge cut and reiterate
pair<int, pair<diGraphVertex, diGraphVertex>> minimum, tempPair;
minimum = remainders.top();
while( !remainders.empty() ) {
tempPair = remainders.top();
if( tempPair.first < minimum.first ) {
minimum = remainders.top();
}
remainders.pop();
}
boost::remove_edge(minimum.second.first, minimum.second.second, g);
edgeCuts.push(make_pair(minimum.second.first, minimum.second.second));
stack<diGraphEdge> tempStack;
//need to remove the edge from backedge list to reiterate
while( !backEdgeCopy.empty() ) {
tempStack.push(backEdgeCopy.top());
backEdgeCopy.pop();
}
while( !tempStack.empty() ) {
diGraphEdge tempEdge = tempStack.top();
if( boost::source(tempEdge, g) == minimum.second.first && boost::target(tempEdge, g) == minimum.second.second ) cout << "Roger, removed edge from backedges to try" << endl;
else backEdgeCopy.push(tempStack.top());
tempStack.pop();
}
cout << "RECURSIONRECURSIONRECURSIONRECURSIONRECURSIONRECURSIONRECURSIONRECURSIONRECURSIONRECURSIONRECURSION" << endl << endl << endl;
findAnswer(g, backEdgeCopy, cutsMade+1, edgeCuts);
}
else if( !atLeastOne && remainders.empty() ) { //shouldn't happen, but is a valid case for a graph that could never be a DAG
cout << "Houston, we have a problem" << endl;
}
if( atLeastOne ) {
cout << edgeCuts.size() << endl;
while( !edgeCuts.empty() ) {
pair<int, int> temp = edgeCuts.front();
cout << temp.first + 1 << ", " << temp.second + 1 << endl;
edgeCuts.pop();
}
}
}
bool sinkSourceProperty(diGraph &g) { //must have at least one source and one sink
bool hasSink = false;
bool hasSource = false;
diGraphVertex v;
BGL_FORALL_VERTICES(v, g, diGraph) {
int inCount = boost::in_degree(v, g);
int outCount = boost::out_degree(v, g);
if( inCount == 0 ) hasSource = true;
if( outCount == 0 ) hasSink = true;
}
if( hasSink && hasSource ) return true;
else return false;
}
bool isAcyclic(diGraph &g){
vector<int> component(boost::num_vertices(g)), discover_time(boost::num_vertices(g));
vector<boost::default_color_type> color(boost::num_vertices(g));
vector<diGraphVertex> root(boost::num_vertices(g));
int numComponents = boost::strong_components(g, make_iterator_property_map(component.begin(), get(boost::vertex_index, g)),
root_map(make_iterator_property_map(root.begin(), get(boost::vertex_index, g))).
color_map(make_iterator_property_map(color.begin(),get(boost::vertex_index, g))).
discover_time_map(make_iterator_property_map(discover_time.begin(), get(boost::vertex_index, g))));
/*
cout << "Total number of components: " << numComponents << endl;
vector<int>::size_type i;
for (i = 0; i != component.size(); ++i) cout << "Vertex " << i << " is in component " << component[i] << endl;
*/
if( numComponents == boost::num_vertices(g) ) return true;
else return false;
}
bool verticesProperty(diGraph &g){ //edges cannot exceed [v(v-1)]/2
int vertices = boost::num_vertices(g);
int edges = boost::num_edges(g);
int maxEdges = ( vertices * (vertices - 1) ) / 2;
if( edges > maxEdges ) return false;
else return true;
}
int connectedComponentScore(diGraph &g) {
cout << "****************************************************************************" << endl;
cout << "****************************************************************************" << endl;
cout << "****************************************************************************" << endl << endl;
vector<int> component(boost::num_vertices(g)), discover_time(boost::num_vertices(g));
vector<boost::default_color_type> color(boost::num_vertices(g));
vector<diGraphVertex> root(boost::num_vertices(g));
int numComponents = boost::strong_components(g, make_iterator_property_map(component.begin(), get(boost::vertex_index, g)),
root_map(make_iterator_property_map(root.begin(), get(boost::vertex_index, g))).
color_map(make_iterator_property_map(color.begin(),get(boost::vertex_index, g))).
discover_time_map(make_iterator_property_map(discover_time.begin(), get(boost::vertex_index, g))));
cout << "Total number of components: " << numComponents << endl;
vector<int>::size_type i;
for (i = 0; i != component.size(); ++i) cout << "Vertex " << i << " is in component " << component[i] << endl;
cout << "****************************************************************************" << endl;
cout << "****************************************************************************" << endl;
cout << "****************************************************************************" << endl << endl;
return boost::num_vertices(g) - numComponents;
}
bool checkAnswer(diGraph &g, string answerFile) {
ifstream infile( answerFile ); //get data from in file
string readLine;
getline(infile, readLine);
int numEdges = atoi(readLine.c_str());
diGraph theGraph;
//read rest of lines from file and parse
int edgeCounter = 0;
while( getline(infile, readLine) ) {
stringstream lineStream(readLine);
int v1, v2;
lineStream >> v1;
lineStream >> v2;
if( answerFile != "8_output_generated_by_G14.txt" ) {
v1--;
v2--;
}
boost::remove_edge(v1, v2, g);
edgeCounter++;
}
if( edgeCounter != numEdges ) {
cout << "err in answer file" << endl;
return false;
}
if( sinkSourceProperty(g) && isAcyclic(g) && verticesProperty(g) ) {
cout << "checks out!" << endl;
return true;
}
else return false;
}
|
40e55f3dd59c36854e18464d66dfcabdcde93d10
|
[
"C++"
] | 1 |
C++
|
doodlebro/algowars
|
334512d6b6fcdb60f24e5e7f805ac4917063fc8c
|
8fdb8c07ee1609bbc4acd9d07572284bea6ba127
|
refs/heads/master
|
<file_sep>class Movie < ApplicationRecord
validates :title, :description, :year, :genre, presence: true
end
<file_sep>class MoviesController < ApplicationController
def index
@movies = Movie.all
# @search = params["search"]
# if @search.present?
# @description= @search["name"]
# @year = @search["name"].to_i
# @title = @search["name"]
# @places = Place.where("name ILIKE ?", "%#{@name}%").or(Place.where("description ILIKE ?", "%#{@description}%")).paginate(page: params[:page], per_page: 3)
# end
return @movies
end
def show
end
end
|
d5d574c269982471919e63c1a3ecbc9fce63539b
|
[
"Ruby"
] | 2 |
Ruby
|
gregnazarian/gregflix
|
d7adb882b9aaf10f0eba91e341096632c6c19b56
|
a70fd9101b8280554829e6f8490d2d40963a253e
|
refs/heads/master
|
<file_sep><?php
/* //componen tabs untuk meload tabs secara dinamis di lapRekap
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class ComponentTabsTuitionData extends CApplicationComponent{
public static function gettabs($idUnit){
//$model=Category::model()->findAll();
//$listdata=CHtml::listData($model,”,’name’);
$model=new Datasiswa;
$criteria = new CDbCriteria;
//$criteria->select = '*';
//$criteria->with=
//$criteria->distinct = TRUE;
//1-6 scope UNIT SD
switch ($idUnit) {
case 1:
$criteria->condition = '`levelKelasName` BETWEEN 1 AND 6';
break;
case 2:
$criteria->condition = '`levelKelasName` BETWEEN 7 AND 9';
break;
case 3:
$criteria->condition = '`levelKelasName` BETWEEN 10 AND 12';
break;
}
$criteria->group='`namaKelas`'; //menggroup murid yang ada di dalam database berdasarkan kelasnya..
$criteria->order='levelKelasName';
//$criteria->order = '`position` ASC';
$model=$model->with('kelas')->findAll($criteria);
//$listdata=CHtml::listData($model->,'namaKelas','');
ini_set('memory_limit', '-1');
//print_r($items);
//foreach ($items as $item)
//$this->items[] = array('label'=>"ACOT ".$item->kelas->namaKelas, 'url'=>'admin?Datasiswa[idlevelKelas]='.$item->kelas->idLevelkelas.'&yt0=Search');
//parent::init();
//
//return print_r($items);
return $model;
}
}
?>
<file_sep><?php
class ProfileController extends Controller
{
#static $_permissionControl = array('label' => 'Better Label');
/**
* @return array action filters
*/
public function filters()
{
return array(
'userGroupsAccessControl', // perform access control for CRUD operations
);
}
public function accessRules()
{
return array(
array('allow', // just guest can perform 'activate' and 'login' actions
#'ajax'=>false,
'users'=>array('@'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionLoad()
{
$model= Profile::model()->findByAttributes(array('ug_id' => Yii::app()->user->id));
if(isset($_POST['Profile']))
{
$this->performAjaxValidation($model);
$model->attributes=$_POST['Profile'];
$model->avatar=CUploadedFile::getInstance($model,'avatar');
if($model->save())
{
$model->avatar->saveAs('avatars/'.Yii::app()->user->name.'.jpg');
} else
Yii::app()->user->setFlash('user', 'you can just upload images.');
$this->redirect(array('/userGroups'));
}
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']))
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}<file_sep><?php
/* @var $this DataSPPsiswaController */
/* @var $model DataSPPsiswa */
$this->breadcrumbs=array(
'Data Sppsiswas'=>array('index'),
$model->idDataSiswa,
);
$this->menu=array(
array('label'=>'List DataSPPsiswa', 'url'=>array('admin')),
//array('label'=>'Create DataSPPsiswa', 'url'=>array('create')),
array('label'=>'Update DataSPPsiswa', 'url'=>array('update', 'id'=>$model->idDataSiswa)),
//array('label'=>'Delete DataSPPsiswa', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->idDataSiswa),'confirm'=>'Are you sure you want to delete this item?')),
//array('label'=>'Manage DataSPPsiswa', 'url'=>array('admin')),
);
?>
<h1>View DataSPPsiswa #<?php echo $model->idDataSiswa; ?></h1>
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'idDataSiswa',
'NoIndukSiswa',
'NamaSiswa',
'namaOrtuAyah',
'namaOrtuIbu',
'alamatTinggal',
'tempatLahir',
'tanggalLahir',
'poinValue',
'kotaAsal',
'tahunAjaranMasuk',
'nomorHp',
'contactDarurat',
'NominalSPP',
array(
'label'=>'Biaya EksKur',
'value'=>$model->biayaekskul->nominal,
),
array(
'label'=>'Biaya Ujian',
'value'=>$model->biayaujian->nominal,
),
array(
'label'=>'Biaya Cambridge Test',
'value'=>$model->biayacambridge->nominal,
),
),
)); ?>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* @var $model Datasiswa
*/
/**
* Description of Pencarian
*
* @author <NAME>
*/
class Pencarian extends CActiveRecord{
//put your code here
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'datasiswa';
}
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('NamaSiswa', 'required'),
array('NoIndukSiswa, NominalSPP, eksKur, uangUjian, uangCambridge,idlevelKelas', 'numerical', 'integerOnly'=>true),
array('NamaSiswa', 'length', 'max'=>70),
array('namaOrtuAyah, namaOrtuIbu, alamatTinggal, tempatLahir, tanggalLahir, poinValue, kotaAsal, nomorHp, contactDarurat', 'length', 'max'=>45),
array('tahunAjaranMasuk', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('idDataSiswa, NoIndukSiswa, NamaSiswa, namaOrtuAyah, namaOrtuIbu, alamatTinggal, tempatLahir, tanggalLahir, poinValue, kotaAsal, tahunAjaranMasuk, nomorHp, contactDarurat, NominalSPP, eksKur, uangUjian, uangCambridge, idlevelKelas', 'safe', 'on'=>'search'),
);
}
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'dataraportsemesterans' => array(self::HAS_MANY, 'Dataraportsemesteran', 'DataSiswa_idDataSiswa'),
'detailnilaisiswas' => array(self::HAS_MANY, 'Detailnilaisiswa', 'DataSiswa_idDataSiswa'),
'kelas'=>array(self::BELONGS_TO,'Levelkelas','idlevelKelas'),
'transaksiSPP'=>array(self::HAS_MANY,'Datatransaksispp','idDatasiswa'),
'kelakuan'=>array(self::HAS_MANY,'Catatankelakuan','idDatasiswa'),
);
}
public function attributeLabels()
{
return array(
'idDataSiswa' => 'Id Data Siswa',
'NoIndukSiswa' => 'No Induk Siswa',
'NamaSiswa' => 'Nama Siswa',
'namaOrtuAyah' => 'Nama Ortu Ayah',
'namaOrtuIbu' => 'Nama Ortu Ibu',
'alamatTinggal' => 'Alamat Tinggal',
'tempatLahir' => 'Tempat Lahir',
'tanggalLahir' => 'Tanggal Lahir',
'poinValue' => 'Poin Value',
'kotaAsal' => 'Kota Asal',
'tahunAjaranMasuk' => 'Tahun Ajaran Masuk',
'idlevelKelas' =>'Kelas',
'nomorHp' => 'Nomor Hp',
'contactDarurat' => 'Contact Darurat',
'NominalSPP' => 'Nominal Spp',
);
}
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
//$criteria->compare('idDataSiswa',$this->idDataSiswa);
$criteria->compare('NoIndukSiswa',$this->NoIndukSiswa);
$criteria->compare('NamaSiswa',$this->NamaSiswa,true);
$criteria->compare('namaOrtuAyah',$this->namaOrtuAyah,true);
$criteria->compare('namaOrtuIbu',$this->namaOrtuIbu,true);
$criteria->compare('alamatTinggal',$this->alamatTinggal,true);
$criteria->compare('tempatLahir',$this->tempatLahir,true);
$criteria->compare('tanggalLahir',$this->tanggalLahir,true);
$criteria->compare('poinValue',$this->poinValue,true);
$criteria->compare('kotaAsal',$this->kotaAsal,true);
$criteria->compare('tahunAjaranMasuk',$this->tahunAjaranMasuk,true);
$criteria->compare('idlevelKelas', $this->idlevelKelas);
$criteria->compare('nomorHp',$this->nomorHp,true);
$criteria->compare('contactDarurat',$this->contactDarurat,true);
$criteria->compare('NominalSPP',$this->NominalSPP);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>false,
/* 'pagination'=>array(
'pageSize'=>'5',
'route'=>'pencarian/AjaxSearch',
),
*
*/
));
}
public function doSearch(){
}
}
?>
<file_sep><?php
/*list variable cookie yang digunakan :
* namaFile
* errorCode
* errorMessage
* physicalLoc
* var
*/
class PendaftaranController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/layout2';
/**
* @return array action filters
*/
//public $tempfilename;
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('admin','delete','create','update','PilihanPendaftaran','ConvertExcel','ConvertExcelPerKelas','pilihKelas','DaftarMassal','xDaftarMassal','xDaftarMassal2','xdaftarMassal2perKelas','xdaftarMassal2perKelas','upload'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete','create','update','PilihanPendaftaran','ConvertExcel','ConvertExcelPerKelas','pilihKelas','DaftarMassal','xDaftarMassal','xDaftarMassal2','xdaftarMassal2perKelas','xdaftarMassal2perKelas','upload'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new pendaftaran;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['pendaftaran']))
{
$model->attributes=$_POST['pendaftaran'];
if($model->save())
$this->redirect(array('view','id'=>$model->idDataSiswa));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['pendaftaran']))
{
$model->attributes=$_POST['pendaftaran'];
if($model->save())
$this->redirect(array('view','id'=>$model->idDataSiswa));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('pendaftaran');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new pendaftaran('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['pendaftaran']))
$model->attributes=$_GET['pendaftaran'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=pendaftaran::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='pendaftaran-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
public function actionxDaftarMassal2() {
//error_reporting(E_ALL | E_STRICT);
//ini_set('display_errors', 1);
/*Server-side PHP file upload code for HTML5 File Drag & Drop demonstration
Featured on SitePoint.com
Developed by <NAME> (@craigbuckler) of OptimalWorks.net
*/ //$idLevelkelas dr proses POST xdaftarMassal2perKelasUpload belum berhasil ditangkap parse nya, sebab : enctype=multipart form data
//$idLevelkelas=var_dump();//$_POST['idLevelkelas'];
if(isset($_FILES['fileToUpload'])){
$error = "";
$msg = "";
$fileElementName = 'fileToUpload';
if(!empty($_FILES[$fileElementName]['error']))
{
switch($_FILES[$fileElementName]['error'])
{
case '0':
$error = 'no Error';
break;
case '1':
$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case '2':
$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case '3':
$error = 'The uploaded file was only partially uploaded';
break;
case '4':
$error = 'No file was uploaded.';
break;
case '6':
$error = 'Missing a temporary folder';
break;
case '7':
$error = 'Failed to write file to disk';
break;
case '8':
$error = 'File upload stopped by extension';
break;
case '999':$error = 'No error code avaiable';break;
default:
$error = 'No error code avaiable';
}
}elseif(empty($_FILES['fileToUpload']['tmp_name']) || $_FILES['fileToUpload']['tmp_name'] == 'none')
{
$error = 'No file was uploaded..';
}else
{
$path = Yii::app()->getBasePath()."/tmp/";
$fileExtension= pathinfo($_FILES['fileToUpload']['name'],PATHINFO_EXTENSION);
$newFileName=date('YmdHis').'.'.$fileExtension;
$location = $path . $newFileName;
move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $location);
$msg =Yii::app()->createAbsoluteUrl("/uploads/").'/'.$newFileName;
//for security reason, we force to remove all uploaded file
$physicalLoc=json_encode(Yii::app()->BasePath."\\tmp\\".$newFileName);
$var=$this->actionConvertExcel(Yii::app()->BasePath."\\tmp\\".$newFileName);
//@unlink(Yii::app()->BasePath."\\tmp\\".$newFileName);
}
echo "{";
echo "error: '" . $error . "',";
echo "msg: '" . $physicalLoc . "',";
echo "statusKonversi: '" . $var . "'";
//echo "statusKonversi: '" . $idLevelkelas . "'";
echo "}";
}else{
$model=new pendaftaran;
$this->render('xdaftarMassal2',array(
'model'=>$model,
));
}
}
public function actionxdaftarMassal2perKelas(){
if(isset($_FILES['fileToUpload'])){
$error = "";
$msg = "";
$fileElementName = 'fileToUpload';
if(!empty($_FILES[$fileElementName]['error']))
{
switch($_FILES[$fileElementName]['error'])
{
case '0':
Yii::app()->request->cookies['error'] = new CHttpCookie('error','no Error');
break;
case '1':
Yii::app()->request->cookies['error'] = new CHttpCookie('error','The uploaded file exceeds the upload_max_filesize directive in php.ini');
break;
case '2':
Yii::app()->request->cookies['error'] = new CHttpCookie('error','The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form');
break;
case '3':
Yii::app()->request->cookies['error'] = new CHttpCookie('error','The uploaded file was only partially uploaded');
break;
case '4':
Yii::app()->request->cookies['error'] = new CHttpCookie('error','No file was uploaded.');
break;
case '6':
Yii::app()->request->cookies['error'] = new CHttpCookie('error','Missing a temporary folder');
break;
case '7':
Yii::app()->request->cookies['error'] = new CHttpCookie('error','Failed to write file to disk');
break;
case '8':
Yii::app()->request->cookies['error'] = new CHttpCookie('error','File upload stopped by extension');
break;
case '999':Yii::app()->request->cookies['error'] = new CHttpCookie('error','No error code avaiable');break;
default:
Yii::app()->request->cookies['error'] = new CHttpCookie('error','No error code avaiable');
}
}elseif(empty($_FILES['fileToUpload']['tmp_name']) || $_FILES['fileToUpload']['tmp_name'] == 'none')
{
Yii::app()->request->cookies['error'] = new CHttpCookie('error','No file was uploaded..');
}else
{
$path = Yii::app()->getBasePath()."/tmp/";
$fileExtension= pathinfo($_FILES['fileToUpload']['name'],PATHINFO_EXTENSION);
$newFileName=date('YmdHis').'.'.$fileExtension;
$location = $path . $newFileName;
//$this->tempfilename=$newFileName;
Yii::app()->request->cookies['namaFile'] = new CHttpCookie('namaFile', $newFileName);
move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $location);
//$msg=Yii::app()->createAbsoluteUrl("/uploads/").'/'.$newFileName;
//for security reason, we force to remove all uploaded file
Yii::app()->request->cookies['physicalLoc'] = new CHttpCookie('physicalLoc', json_encode(Yii::app()->BasePath."\\tmp\\".$newFileName));
Yii::app()->request->cookies['error'] = new CHttpCookie('error','No Error, all Procedure is executed');
$model=new pendaftaran;
}
}else if(isset($_POST['idLevelkelas'])){
$var=$this->actionConvertExcel(Yii::app()->BasePath."\\tmp\\".Yii::app()->request->cookies['namaFile']->value);
echo "{";
echo "error: '" . Yii::app()->request->cookies['error']->value . "',";
echo "msg: '" . Yii::app()->request->cookies['physicalLoc']->value . "',";
echo "statusKonversi: '" . $var . "'";
//echo "statusKonversi: '" . $idLevelkelas . "'";
echo "}";
//prosedur penghapusan data cookies dan file temporary
@unlink(Yii::app()->BasePath."\\tmp\\".Yii::app()->request->cookies['namaFile']->value);
unset(Yii::app()->request->cookies['error']);
unset(Yii::app()->request->cookies['namaFile']);
unset(Yii::app()->request->cookies['physicalLoc']);
//unset(Yii::app()->request->cookies['cookie_name']);
//prosedur penghapusan data cookies dan file temporary
}else{
$model=new pendaftaran;
$this->render('xdaftarMassal2perKelasUpload',array('model'=>$model));
}
}
public function actionUpload(){
Yii::import( "xupload.models.XUploadForm" );
//Here we define the paths where the files will be stored temporarily
$path = realpath( Yii::app( )->getBasePath( )."/../uploads/" )."/";
$publicPath = Yii::app( )->getBaseUrl( )."/uploads/";
//This is for IE which doens't handle 'Content-type: application/json' correctly
header( 'Vary: Accept' );
if( isset( $_SERVER['HTTP_ACCEPT'] )
&& (strpos( $_SERVER['HTTP_ACCEPT'], 'application/json' ) !== false) ) {
header( 'Content-type: application/json' );
} else {
header( 'Content-type: text/plain' );
}
//Here we check if we are deleting and uploaded file
if( isset( $_GET["_method"] ) ) {
if( $_GET["_method"] == "delete" ) {
if( $_GET["file"][0] !== '.' ) {
$file = $path.$_GET["file"];
if( is_file( $file ) ) {
unlink( $file );
}
}
echo json_encode( true );
}
} else {
$model = new XUploadForm;
$model->file = CUploadedFile::getInstance( $model, 'file' );
//We check that the file was successfully uploaded
if( $model->file !== null ) {
//Grab some data
$model->mime_type = $model->file->getType( );
$model->size = $model->file->getSize( );
$model->name = $model->file->getName( );
//(optional) Generate a random name for our file
$filename = md5( Yii::app( )->user->id.microtime( ).$model->name);
$filename .= ".".$model->file->getExtensionName( );
if( $model->validate( ) ) {
//Move our file to our temporary dir
$model->file->saveAs( $path.$filename );
chmod( $path.$filename, 0777 );
//here you can also generate the image versions you need
//using something like PHPThumb
//Now we need to save this path to the user's session
if( Yii::app( )->user->hasState( 'images' ) ) {
$userImages = Yii::app( )->user->getState( 'images' );
} else {
$userImages = array();
}
$userImages[] = array(
"path" => $path.$filename,
//the same file or a thumb version that you generated
"thumb" => $path.$filename,
"filename" => $filename,
'size' => $model->size,
'mime' => $model->mime_type,
'name' => $model->name,
);
Yii::app( )->user->setState( 'images', $userImages );
//Now we need to tell our widget that the upload was succesfull
//We do so, using the json structure defined in
// https://github.com/blueimp/jQuery-File-Upload/wiki/Setup
echo json_encode( array( array(
"name" => $model->name,
"type" => $model->mime_type,
"size" => $model->size,
"url" => $publicPath.$filename,
"thumbnail_url" => $publicPath."thumbs/$filename",
"delete_url" => $this->createUrl( "upload", array(
"_method" => "delete",
"file" => $filename
) ),
"delete_type" => "POST"
) ) );
} else {
//If the upload failed for some reason we log some data and let the widget know
echo json_encode( array(
array( "error" => $model->getErrors( 'file' ),
) ) );
Yii::log( "XUploadAction: ".CVarDumper::dumpAsString( $model->getErrors( ) ),
CLogger::LEVEL_ERROR, "xupload.actions.XUploadAction"
);
}
} else {
throw new CHttpException( 500, "Could not upload file" );
}
}
}
public function actionConvertExcel($lokasiFile){
/*$model=new Pendaftaran;
$model->validate();*/
Yii::import('application.extensions.phpexcelreader.Spreadsheet_Excel_Reader');
//$model->attributes=$_POST['pendaftaran'];
//$itu=CUploadedFile::getInstance($model,'filee');
//$path=Yii::app()->BasePath.'/tmp/temp_file.xls'; //perlu dilihat
//$itu->saveAs($path);
$data = new Spreadsheet_Excel_Reader($lokasiFile);
//$id=array();
$NoIndukSiswa=array();
$NamaSiswa=array();
$namaOrtuAyah=array();
$namaOrtuIbu=array();
$alamatTinggal=array();
$tempatLahir=array();
$tanggalLahir=array();
$kotaAsal=array();
$tahunAjaranMasuk=array();
$nomorHP=array();
$contactDarurat=array();
$idlevelKelas=array();
if(isset($_POST['idLevelkelas'])){
$setLevelKelas=$_POST['idLevelkelas'];
}
for ($j = 2; $j <= $data->sheets[0]['numRows']; $j++)
{
//$id[$j]=$data->sheets[0]['cells'][$j][1];
//$nama[$j]=$data->sheets[0]['cells'][$j][2];
if (isset($data->sheets[0]['cells'][$j][1])) {
$NoIndukSiswa[$j] = $data->sheets[0]['cells'][$j][1];
} else {
$NoIndukSiswa[$j] = '';
}
if (isset($data->sheets[0]['cells'][$j][2])) {
$NamaSiswa[$j] = $data->sheets[0]['cells'][$j][2];
} else {
$NamaSiswa[$j] = '';
}
if (isset($data->sheets[0]['cells'][$j][3])) {
$namaOrtuAyah[$j] = $data->sheets[0]['cells'][$j][3];
} else {
$namaOrtuAyah[$j] = '';
}
if (isset($data->sheets[0]['cells'][$j][4])) {
$namaOrtuIbu[$j] = $data->sheets[0]['cells'][$j][4];
} else {
$namaOrtuIbu[$j] = '';
}
if (isset($data->sheets[0]['cells'][$j][5])) {
$alamatTinggal[$j] = $data->sheets[0]['cells'][$j][5];
} else {
$alamatTinggal[$j] = '';
}
if (isset($data->sheets[0]['cells'][$j][6])) {
$tempatLahir[$j] = $data->sheets[0]['cells'][$j][6];
} else {
$tempatLahir[$j] = '';
}
if (isset($data->sheets[0]['cells'][$j][7])) {
$tanggalLahir[$j] = $data->sheets[0]['cells'][$j][7];
} else {
$tanggalLahir[$j] = '';
}
if (isset($data->sheets[0]['cells'][$j][9])) {
$kotaAsal[$j] = $data->sheets[0]['cells'][$j][9];
} else {
$kotaAsal[$j] = '';
}
if (isset($data->sheets[0]['cells'][$j][10])) {
$tahunAjaranMasuk[$j] = $data->sheets[0]['cells'][$j][10];
} else {
$tahunAjaranMasuk[$j] = '';
}
if (isset($data->sheets[0]['cells'][$j][11])) {
$nomorHP[$j] = $data->sheets[0]['cells'][$j][11];
} else {
$nomorHP[$j] = '';
}
if (isset($data->sheets[0]['cells'][$j][12])) {
$contactDarurat[$j] = $data->sheets[0]['cells'][$j][12];
} else {
$contactDarurat[$j] = '';
}
if(isset($_POST['idLevelkelas'])){
$idlevelKelas[$j]=$setLevelKelas;
}
}
//tanggal 19 April 2013 : dibawah ini belum dicek, dan prosedur ini belum selesai , prosedur ini direferensikan dari link : http://www.yiiframework.com/forum/index.php/topic/23536-upload-data-excel-to-mysql/
//tanggal 22 April 2013 : upload dan conversi sudah berhasil, tinggal penyesuaian kolom, next step : upload data + konversi Per Kelas dan Per Unit
/*
* yang dirubah :
* 1. nama file di extension - phpexcelreader, dr 'excel_reader2.php' jadi Spreadsheet_Excel_Reader
*/
//$model=$this->loadModel();
for($i=0;$i<count($NoIndukSiswa);$i++)
{
$model=new Pendaftaran;
$model->validate();
//$model->id=$id[$i];
$model->NoIndukSiswa=$NoIndukSiswa[$i+2];
$model->NamaSiswa=$NamaSiswa[$i+2];
$model->namaOrtuAyah=$namaOrtuAyah[$i+2];
$model->namaOrtuIbu=$namaOrtuIbu[$i+2];
$model->alamatTinggal=$alamatTinggal[$i+2];
$model->tempatLahir=$alamatTinggal[$i+2];
$model->tanggalLahir=$alamatTinggal[$i+2];
$model->kotaAsal=$kotaAsal[$i+2];
$model->tahunAjaranMasuk=$tahunAjaranMasuk[$i+2];
$model->nomorHp=$nomorHP[$i+2];
$model->contactDarurat=$contactDarurat[$i+2];
if(isset($_POST['idLevelkelas'])){
$model->idlevelKelas=$idlevelKelas[$i+2];
}
$model->save(false); //jika didalam tanda kurung $model->save() harus diberi boolean FALSE, maka
if(isset($_POST['idLe'])){
$status=$NamaSiswa[$i+2].$_POST['idLevelkelas'];
}else{
$status=$NamaSiswa[$i+2];
}
}
//$this->render('daftarMassal',array('model'=>$model));
return $status;
}
public function actionPilihanPendaftaran(){
/*$procedureGroup='<div><p>Input Pendaftaran Siswa berikut keterangannya :
<ol>
<li>[Daftar Baru] : Pendaftaran Siswa Baru satu persatu, pendaftaran ini untuk pendaftaran di awal tahun</li>
<li>[Siswa Pindahan] : Pendaftaran Bagi Siswa Baru dari sekolah lain yang masuk di tengah jalannya tahun ajaran</li>
<li>[Import File] : import File Microsoft Excel 2003, yang berisi data siswa - siswa baru yang sudah fix untuk tahun ajaran baru.</li>
</ol>
</p><br>';*/
$procedureGroup='';
$procedureGroup.=CHtml::link('Daftar Baru',Yii::app()->createUrl('pendaftaran/create'),array('class'=>'btn btn-blue','href'=>'datasiswa/create'));
$procedureGroup.=' ';
$procedureGroup.=CHtml::link('Siswa Pindahan',Yii::app()->createUrl('pendaftaran/create'),array('id'=>'inline','class'=>'btn btn-blue','href'=>'datasiswa/create'));
$procedureGroup.=' ';
$procedureGroup.=CHtml::link('Import File',Yii::app()->createUrl('pendaftaran/xdaftarMassal2'),array('id'=>'fittedFrame','data-fancybox-type'=>'iframe','class'=>'btn btn-blue','href'=>'datasiswa/create')); //sementara default menggunakan submit form //upload dengan ajax belum support
$procedureGroup.=' ';
$procedureGroup.=CHtml::link('Import Per Unit',Yii::app()->createUrl('pendaftaran/xdaftarMassal2perKelas'),array('id'=>'fittedFrame','data-fancybox-type'=>'iframe','class'=>'btn btn-blue','href'=>'datasiswa/create')); //sementara default menggunakan submit form //upload dengan ajax belum support
//$procedureGroup.='</div>';
echo $procedureGroup;
/*$commandid = $_GET['commandid'];$iddata=$_GET['sid'];*/
/*switch ($commandid) {
case '1': echo GetUnpaidMonth::cekBulanPembayaran($iddata); //lihat component/GetUnpaidMonth
break;
case '2': echo "display detail";
break;
case '3': echo "display nilai";
break;
default:
break;
}*/
}
public function actionpilihKelas() {
$model=new Levelkelas;
$criteria = new CDbCriteria;
$criteria->select = 'idLevelkelas,namaKelas';
//$items = Levelkelas::model()->findAll($criteria);
//$optionslist=array();
//foreach ($items as $item)
$this->render('xdaftarMassal2perKelas',array('model'=>$model,'criteria'=>$criteria));
}
}
<file_sep><?php
/**
* This is the model class for table "profile".
*
* The followings are the available columns in table 'profile':
* @property integer $id
* @property string $ug_id
* @property string $hobbies
* @property string $avatar
*/
class Profile extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @return Profile the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'profile';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('ug_id', 'length', 'max'=>20),
array('hobbies', 'length', 'max'=>120),
array('hobbies', 'required', 'on' => array('updateProfile', 'registration')),
array('avatar', 'file', 'types'=>'jpg, gif, png', 'allowEmpty' => true),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, ug_id, hobbies', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'ug_id' => 'Ug',
'hobbies' => 'Hobbies',
'avatar' => 'Avatar',
);
}
/**
* returns an array that contains the views name to be loaded
* @return array
*/
public function profileViews()
{
return array(
UserGroupsUser::VIEW => 'index',
UserGroupsUser::EDIT => 'update',
UserGroupsUser::REGISTRATION => 'register'
);
}
/**
* returns an array that contains the name of the attributes that will
* be stored in session
* @return array
*/
public function profileSessionData()
{
return array(
'hobbies',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('ug_id',$this->ug_id,true);
$criteria->compare('hobbies',$this->hobbies,true);
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$criteria,
));
}
}<file_sep><?php
/* @var $this SystemTahunajaranController */
/* @var $data SystemTahunajaran */
?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('thnAjaran')); ?>:</b>
<?php echo CHtml::encode($data->thnAjaran); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('semester')); ?>:</b>
<?php echo CHtml::encode($data->semester); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('Keterangan')); ?>:</b>
<?php echo CHtml::encode($data->Keterangan); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('status_aktif')); ?>:</b>
<?php echo CHtml::encode($data->status_aktif); ?>
<br />
</div><file_sep><?php
/* @var $this PendaftaranController */
/* @var $model pendaftaran */
/* @var $form CActiveForm */
?>
<div class="wide form">
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
)); ?>
<div class="row">
<?php echo $form->label($model,'idDataSiswa'); ?>
<?php echo $form->textField($model,'idDataSiswa'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'NoIndukSiswa'); ?>
<?php echo $form->textField($model,'NoIndukSiswa'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'NamaSiswa'); ?>
<?php echo $form->textField($model,'NamaSiswa',array('size'=>60,'maxlength'=>70)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'namaOrtuAyah'); ?>
<?php echo $form->textField($model,'namaOrtuAyah',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'namaOrtuIbu'); ?>
<?php echo $form->textField($model,'namaOrtuIbu',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'alamatTinggal'); ?>
<?php echo $form->textField($model,'alamatTinggal',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'tempatLahir'); ?>
<?php echo $form->textField($model,'tempatLahir',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'tanggalLahir'); ?>
<?php echo $form->textField($model,'tanggalLahir',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'poinValue'); ?>
<?php echo $form->textField($model,'poinValue',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'kotaAsal'); ?>
<?php echo $form->textField($model,'kotaAsal',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'tahunAjaranMasuk'); ?>
<?php echo $form->textField($model,'tahunAjaranMasuk'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'nomorHp'); ?>
<?php echo $form->textField($model,'nomorHp',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'contactDarurat'); ?>
<?php echo $form->textField($model,'contactDarurat',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'NominalSPP'); ?>
<?php echo $form->textField($model,'NominalSPP'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'eksKur'); ?>
<?php echo $form->textField($model,'eksKur'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'uangUjian'); ?>
<?php echo $form->textField($model,'uangUjian'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'uangCambridge'); ?>
<?php echo $form->textField($model,'uangCambridge'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'idlevelKelas'); ?>
<?php echo $form->textField($model,'idlevelKelas'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'penilaianpsikis'); ?>
<?php echo $form->textArea($model,'penilaianpsikis',array('rows'=>6, 'cols'=>50)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'imgPath'); ?>
<?php echo $form->textArea($model,'imgPath',array('rows'=>6, 'cols'=>50)); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form --><file_sep><?php
/* @var $this LevelkelasController */
/* @var $data Levelkelas */
?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('idLevelkelas')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->idLevelkelas), array('view', 'id'=>$data->idLevelkelas)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('namaKelas')); ?>:</b>
<?php echo CHtml::encode($data->namaKelas); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('levelKelasName')); ?>:</b>
<?php echo CHtml::encode($data->levelKelasName); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('waliKelasID')); ?>:</b>
<?php echo CHtml::encode($data->waliKelasID); ?>
<br />
</div><file_sep><?php
/* @var $this TuitiondataController */
/* @var $model Tuitiondata */
/* @var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
)); ?>
<table class="form">
<!--<div class="row">
<?php echo $form->label($model,'idtuitionData'); ?>
<?php echo $form->textField($model,'idtuitionData'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'nominalDibayarkan'); ?>
<?php echo $form->textField($model,'nominalDibayarkan'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'nomerKuitansiPembayaran'); ?>
<?php echo $form->textField($model,'nomerKuitansiPembayaran',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'tahunAjaran_idtahunAjaran'); ?>
<?php echo $form->textField($model,'tahunAjaran_idtahunAjaran'); ?>
</div>-->
<tr>
<td>
<?php echo $form->label($model,'keyWordNama'); ?>
<?php echo $form->textField($model,'keyWordNama',array(
'size'=>60,'maxlength'=>70,
)); ?>
</td>
</tr>
<!--<div class="row">
<?php echo $form->label($model,'BulanTagihan'); ?>
<?php echo $form->textField($model,'BulanTagihan'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'statusTagihan'); ?>
<?php echo $form->textField($model,'statusTagihan',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'SPP'); ?>
<?php echo $form->textField($model,'SPP'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'billCategoryData'); ?>
<?php echo $form->textField($model,'billCategoryData',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'totalTagihan'); ?>
<?php echo $form->textField($model,'totalTagihan'); ?>
</div>-->
<tr>
<td>
<?php echo CHtml::submitButton('Search'); ?>
</td>
</tr>
</table>
<?php $this->endWidget(); ?>
</div><!-- search-form -->
<?php
/*
* proses mencari data dengan referensi keyword dari table yang lain
* Here is the process
1 - create a public variable say $keyword
2 - assign it to search function in rules as safe
3 - In search function, call the related data using with keyword
$criteria = new CDbCriteria;
$criteria->with = array('relation name');
4 - Then you need to set the data for compare as
$criteria->compare('relation.field', $this->keyword, true);
5 - If you want to sort it too, then create a new object of CSort and set it there as
$sort = new CSort();
$sort->attributes = array(
'keyword'=>array(
'asc'=>'relation.field',
'desc'=>'relation.field desc',
),
);
Hope this will help you.
*/
?><file_sep><?php
/* @var $this CatatankelakuanController */
/* @var $data Catatankelakuan */
?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('iddatasiswa')); ?>:</b>
<?php echo CHtml::encode($data->iddatasiswa); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('tanggalinput')); ?>:</b>
<?php echo CHtml::encode($data->tanggalinput); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('userpenginput')); ?>:</b>
<?php echo CHtml::encode($data->userpenginput); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('keterangan')); ?>:</b>
<?php echo CHtml::encode($data->keterangan); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('tanggaledit')); ?>:</b>
<?php echo CHtml::encode($data->tanggaledit); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('userpengedit')); ?>:</b>
<?php echo CHtml::encode($data->userpengedit); ?>
<br />
</div><file_sep><?php
/*
*
* and open the template in the editor.
*
*/
?>
<div class="form">
<div class="block">
<?php
$form=$this->beginWidget('CActiveForm',array( //htmlOptions dan yg lainnya.
'id'=>'global-search',
//'action'=>Yii::app()->createURL($this->route),
//'method'=>'get',
'htmlOptions'=>array(
'onsubmit'=>"return false;",/* Disable normal form submit */
'onkeypress'=>" if(event.keyCode == 13){ send(); } " /* Do ajax call when user presses enter key */
),
)
);
?>
<table class="form">
<tr>
<td>
<h8>Silahkan masukkan (bagian) nama siswa yang akan dicari</h8>
</td>
</tr>
<tr>
<td>
<?php echo $form->textField($model,'NamaSiswa',array('size'=>90,'maxlength'=>150,'class'=>'warning')); ?>
</td>
</tr>
<tr>
<td>
<?php echo CHtml::Button('Lakukan Pencarian',array('onclick'=>'send();','class'=>'btn btn-blue'));?>
</td>
</tr>
</table>
</div>
</div>
<script type="text/javascript">
function send()
{
var data=$("#global-search").serialize();
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("Pencarian/AjaxSearch?Datasiswa[NamaSiswa]=data&yt0=Search"); ?>',//Pencarian/admin?Datasiswa[NamaSiswa]=data&yt0=Search
data:data,
success:function(data){
document.getElementById('search-result').innerHTML=data;
//alert(data);
},
error: function(data) { // if error occured
alert("Error occured.please try again");
//alert(data);
},
dataType:'html'
});
}
</script>
<?php $this->endWidget(); ?>
<div id="search-result">
</div><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of printMaster
*
* @author <NAME>
*
*/
//$classId=$idClass;
echo CHtml::button('PRINT!',array('class'=>'btn btn-grey','style'=>'margin-right:10px','onClick'=>'window.print();'));
?>
<h1>MASTER UANG SEKOLAH</h1>
<?php
$connection=Yii::app()->db;
$command=$connection->createCommand("SELECT l.namaKelas FROM bellarminusjakarta.levelkelas l where l.idLevelKelas=$classId;");
$commandLevel=$connection->createCommand("SELECT l.levelkelasName FROM bellarminusjakarta.levelkelas l where l.idLevelKelas=$classId;");
$levelKelas=$commandLevel->queryScalar();
$command2=$connection->createCommand("SELECT lk.unit FROM bellarminusjakarta.levelkelaskategori lk where lk.id_ClassLevellowerScope<=$levelKelas and lk.id_ClassLevelmaxScope>=$levelKelas;");
$kelas =$command->queryScalar();
$unit=$command2->queryScalar();
echo("<h1>KELAS : $kelas</h1>");
echo("<h1>UNIT : $unit</h1>");
?>
<?php
$this->layout='forPrint';
$this->widget('application.components.CGridViewWithTotals', array(
'id'=>'data-sppsiswa-grid',
'dataProvider'=>$model->masterKelas($classId),
//'filter'=>$model,
'columns'=>array(
//'idDataSiswa',
//'NoIndukSiswa',
array(
'header'=>'No Induk',
'value'=>'$data->NoIndukSiswa',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:center;',
),
//'footer'=>'test',
//'hasFooter'=>'true',
),
array(
'header'=>'Nama',
'value'=>'$data->NamaSiswa',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'600px',
'style'=>'text-align:left; font-size:12px;',
),
'footer'=>'TOTAL',
//'hasFooter'=>'true',
),
array(
'header'=>'US',
'value'=>'number_format($data->NominalSPP,"0",",",".");',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
'footer'=>number_format($model->getTotalsSPP($model->masterKelas($classId)->getKeys()),"0",",","."),
//'hasFooter'=>'true',
),
array(
'header'=>'Eks-Kur', //column header
'value'=> 'number_format($data->biayaekskul->nominal,"0",",",".");',//column name, php expression
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
'footer'=>number_format($model->getTotalsEksKur($model->masterKelas($classId)->getKeys()),"0",",","."),
//'hasFooter'=>'true',
),
array(
'header'=>'Ujian', //column header
'value'=> 'number_format($data->biayaujian->nominal,"0",",",".");',//column name, php expression
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
'footer'=>number_format($model->getTotalsUjian($model->masterKelas($classId)->getKeys()),"0",",","."),
//'hasFooter'=>'true',
),
array(
'header'=>'Cambridge', //column header
'value'=> 'number_format($data->biayacambridge->nominal,"0",",",".");',//column name, php expression
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
'footer'=>number_format($model->getTotalsCambridge($model->masterKelas($classId)->getKeys()),"0",",","."),
//'hasFooter'=>'true',
),
array(
'header'=>'TOTAL', //column header
'value'=>'number_format(($data->NominalSPP+$data->biayaekskul->nominal+$data->biayaujian->nominal+$data->biayacambridge->nominal),"0",",",".");;
',//column name, php expression
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
'footer'=>number_format(($model->getTotalsSPP($model->masterKelas($classId)->getKeys())+$model->getTotalsEksKur($model->masterKelas($classId)->getKeys())+$model->getTotalsUjian($model->masterKelas($classId)->getKeys())+$model->getTotalsCambridge($model->masterKelas($classId)->getKeys())),"0",",","."),
//'hasFooter'=>'true',
),
/*array(
'header'=>'Uang Ujian', //column header
'value'=> '$data->tuitionbillcategory->nominal',//column name, php expression
'type'=>'raw',
),*/
/*array(
'class'=>'CButtonColumn',
'template'=>'{view}{update}',
),*/
),
'summaryText' => 'Menampilkan {count} data yang ditemukan.',
'template'=>' {items} {summary} ',
'emptyText'=>'Maaf Belum Ada Data yang diGenerate'
//'hasFooter'=>true,
));
?>
<file_sep><?php
Yii::import('zii.widgets.CMenu', true);
class ClassesMenuActive extends CMenu
{
public function init()
{
echo '<ul class="section menu">';
echo'<li><a class="menuitem"> Unit SD </a>';$this->widget('application.components.MenuSDActive',array('htmlOptions'=>array('class'=>'submenu')));echo '</li>';
echo'<li><a class="menuitem"> Unit SMP </a>';$this->widget('application.components.MenuSMPActive',array('htmlOptions'=>array('class'=>'submenu')));echo '</li>';
echo'<li><a class="menuitem"> Unit SMA </a>';$this->widget('application.components.MenuSMAActive',array('htmlOptions'=>array('class'=>'submenu')));echo '</li>';
echo'</ul>';
}
}
?>
<file_sep><?php
/* @var $this TuitionbillcategoryController */
/* @var $data Tuitionbillcategory */
?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('idtuitionbillcategory')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->idtuitionbillcategory), array('view', 'id'=>$data->idtuitionbillcategory)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('billCategoryName')); ?>:</b>
<?php echo CHtml::encode($data->billCategoryName); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('nominal')); ?>:</b>
<?php echo CHtml::encode($data->nominal); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('catatan')); ?>:</b>
<?php echo CHtml::encode($data->catatan); ?>
<br />
</div><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*
*/
$this->pageTitle=Yii::app()->name.'Administrasi Keuangan';
$this->breadcrumbs=array(
'Administrasi Keuangan Akademik',
);
/*$this->menu=array(
//array('label'=>'Create Datasiswa', 'url'=>array('tuitiondata/create')),
//array('label'=>'Manage Datasiswa', 'url'=>array('tuitiondata/admin')),
array('label'=>'Manage SPP','url'=>array('tuitiondata/admin')),
array('label'=>'Master SD','url'=>Yii::app()->createUrl('tuitiondata/rekapMasterUnit',array('idUnit'=>'1'))),
array('label'=>'Master SMP','url'=>Yii::app()->createUrl('tuitiondata/rekapMasterUnit',array('idUnit'=>'2'))),
array('label'=>'Master SMA','url'=>Yii::app()->createUrl('tuitiondata/rekapMasterUnit',array('idUnit'=>'3'))),
);*/
$this->layout="layoutKeuangan";
?>
<p><b>Notifikasi Pesan :</b></p>
<p>Menu :</p>
<div class="iconMenu"><a href="<?php echo $this->createUrl('tuitiondata/admin')?>" ><img src="<?php echo Yii::app()->theme->baseUrl?>/img/custom-btn/TagihanSPP.png"><br>Tagihan SPP</a></div>
<div class="iconMenu"><?php echo CHtml::link('<img src='.Yii::app()->theme->baseUrl.'/img/custom-btn/elemenTagihan.png><br>Elemen Tagihan',array('tuitionbillcategory/popupAdmin'),array(
'id'=>'inline',
'data-fancybox-type'=>'iframe'
//'class'=>'iframe',
));
?></div>
<div class="iconMenu"><?php echo CHtml::link('<img src='.Yii::app()->theme->baseUrl.'/img/custom-btn/detailTagihanSiswa.png><br>Detail Tagihan',array('datasppsiswa/admin'),array(
//'id'=>'inline',
//'data-fancybox-type'=>'iframe'
//'class'=>'iframe',
));
?></div><file_sep><div class="view">
<b>Hobbies: </b>
<?php
echo $model->hobbies;
echo CHtml::image('avatars/'.Yii::app()->user->name.'.jpg');
?>
</div><file_sep><?php
/* @var $this TuitiondataController */
/* @var $dataProvider CActiveDataProvider */
$this->breadcrumbs=array(
'Data Tagihan SPP',
);
$this->menu=array(
//array('label'=>'Create Tuitiondata', 'url'=>array('create')),
array('label'=>'Data Tagihan SPP', 'url'=>array('admin')),
);
?>
<p><b>Hal berikut perlu diperhatikan sebelum generate data tagihan SPP </b>:
<ol>
<li>Siswa baru harus sudah diinput terlebih dahulu.</li>
<li>Siswa yang naik sudah naik kelas, maka data siswa sudah harus diubah terlebih dahulu (proses naik).</li>
</ol>
</p>
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'emptyText' => '<div class="message info" id="ProsesdataSPP">
<center>
<h5> INFORMASI TAGIHAN SPP </h5>
<p>Maaf, Data Tagihan Belum Di - GENERATE,
Generate data hanya dapat dilakukan pada bulan Juni, atau setiap awal tahun ajaran baru <br>
</p>
'.
/*CHtml::ajaxButton('Generate Tagihan SPP',Yii::app()->createUrl('Tuitiondatacontroller/actionRunSQL'),array(
'success'=>"alert('success')",
'update'=>"alert('success')",
'replace'=>"alert('success')"
),array(
'class'=>'btn',
'style'=>'margin:10px;',
))*/
CHtml::Button('Generate Tagihan SPP',array(
'class'=>'btn',
'style'=>'margin:10px;',
'onclick'=>"doGeneration();",
))
.'
</center>
</div>',
'summaryText' => 'Menampilkan {start}-{end} dari {count} data.',
)); ?>
<div id='AjFlash' class="flash-success" style="display:none"></div>
<script type="text/javascript">
function doGeneration()
{
var data=$("#ProsesdataSPP").serialize();
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("Tuitiondata/RunSQL"); ?>',//Pencarian/admin?Datasiswa[NamaSiswa]=data&yt0=Search
data:data,
success:function(data){
//document.getElementById('search-result').innerHTML=data;
alert(data);
},
error: function(data) { // if error occured
alert("Error occured.please try again");
//alert(data);
},
dataType:'html'
});
}
</script><file_sep><?php
/* @var $this PendaftaranController */
/* @var $data pendaftaran */
?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('idDataSiswa')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->idDataSiswa), array('view', 'id'=>$data->idDataSiswa)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('NoIndukSiswa')); ?>:</b>
<?php echo CHtml::encode($data->NoIndukSiswa); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('NamaSiswa')); ?>:</b>
<?php echo CHtml::encode($data->NamaSiswa); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('namaOrtuAyah')); ?>:</b>
<?php echo CHtml::encode($data->namaOrtuAyah); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('namaOrtuIbu')); ?>:</b>
<?php echo CHtml::encode($data->namaOrtuIbu); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('alamatTinggal')); ?>:</b>
<?php echo CHtml::encode($data->alamatTinggal); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('tempatLahir')); ?>:</b>
<?php echo CHtml::encode($data->tempatLahir); ?>
<br />
<?php /*
<b><?php echo CHtml::encode($data->getAttributeLabel('tanggalLahir')); ?>:</b>
<?php echo CHtml::encode($data->tanggalLahir); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('poinValue')); ?>:</b>
<?php echo CHtml::encode($data->poinValue); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('kotaAsal')); ?>:</b>
<?php echo CHtml::encode($data->kotaAsal); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('tahunAjaranMasuk')); ?>:</b>
<?php echo CHtml::encode($data->tahunAjaranMasuk); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('nomorHp')); ?>:</b>
<?php echo CHtml::encode($data->nomorHp); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('contactDarurat')); ?>:</b>
<?php echo CHtml::encode($data->contactDarurat); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('NominalSPP')); ?>:</b>
<?php echo CHtml::encode($data->NominalSPP); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('eksKur')); ?>:</b>
<?php echo CHtml::encode($data->eksKur); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('uangUjian')); ?>:</b>
<?php echo CHtml::encode($data->uangUjian); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('uangCambridge')); ?>:</b>
<?php echo CHtml::encode($data->uangCambridge); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('idlevelKelas')); ?>:</b>
<?php echo CHtml::encode($data->idlevelKelas); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('penilaianpsikis')); ?>:</b>
<?php echo CHtml::encode($data->penilaianpsikis); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('imgPath')); ?>:</b>
<?php echo CHtml::encode($data->imgPath); ?>
<br />
*/ ?>
</div><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of pencarianController
*
* @author <NAME>
*/
class PencarianController extends Controller
{
public $layout='//layouts/column1';
public function filters()
{
return array(
'userGroupsAccessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array(),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('admin','popupview','popupupdate','create','update','delete','doQuery','AjaxSearch','ChoosenProcedure'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','popupview','popupupdate','create','update','delete','doQuery','AjaxSearch','ChoosenProcedure'),
'users'=>array('server'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('updatewithajax'),
'users'=>array('server'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
public function loadModel($id)
{
$model=Datasiswa::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Datasiswa');
$model=new Datasiswa;
$this->render('index',array(
'dataProvider'=>$dataProvider,
//'model'=>$dataProvider,
'model'=> $model,// -> 'model'~> adalah variable yang akan digunakan oleh
//'Datasiswa'=>$model,
));
}
public function actionAjaxSearch()
{
//$model=new Pencarian;
//$model->unsetAttributes(); // clear any default values
$model=new Pencarian('search');
$model->unsetAttributes(); // clear any default values
if(isset($_POST['Datasiswa']))
$model->attributes=$_POST['Datasiswa'];
$this->render('admin',array(
'model'=>$model,
));
//return $this->renderPartial('admin',array('model'=>$model));
//$texttorender = "this is from pencarian controller";
//return $this->render('test',array('text'=>$texttorender));
}
public function actionChoosenProcedure($commandid){
$commandid = $_GET['commandid'];$iddata=$_GET['sid'];
switch ($commandid) {
case '1': echo GetUnpaidMonth::cekBulanPembayaran($iddata); //lihat component/GetUnpaidMonth
break;
case '2': echo "display detail";
break;
case '3': echo "display nilai";
break;
default:
break;
}
}
//put your code here
}
?>
<file_sep><?php
/**
* This is the model class for table "archivedtuitiondata".
*
* The followings are the available columns in table 'archivedtuitiondata':
* @property integer $id
* @property integer $idtuitionData
* @property string $nominalPembayaran
* @property integer $nominalDibayarkan
* @property string $nomerKuitansiPembayaran
* @property integer $tahunAjaran_idtahunAjaran
* @property integer $DataSiswa_idDataSiswa
* @property integer $BulanTagihan
* @property string $statusTagihan
* @property integer $SPP
* @property string $billCategoryData
* @property integer $totalTagihan
* @property string $januari
* @property string $februari
* @property string $maret
* @property string $april
* @property string $mei
* @property string $juni
* @property string $juli
* @property string $agustus
* @property string $september
* @property string $oktober
* @property string $november
* @property string $desember
* @property integer $idLevelKelas
*/
class Archivedtuitiondata extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Archivedtuitiondata the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'archivedtuitiondata';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('idtuitionData, nominalDibayarkan, tahunAjaran_idtahunAjaran, DataSiswa_idDataSiswa, BulanTagihan, SPP, totalTagihan, idLevelKelas', 'numerical', 'integerOnly'=>true),
array('nomerKuitansiPembayaran, statusTagihan, billCategoryData', 'length', 'max'=>45),
array('nominalPembayaran, januari, februari, maret, april, mei, juni, juli, agustus, september, oktober, november, desember', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, idtuitionData, nominalPembayaran, nominalDibayarkan, nomerKuitansiPembayaran, tahunAjaran_idtahunAjaran, DataSiswa_idDataSiswa, BulanTagihan, statusTagihan, SPP, billCategoryData, totalTagihan, januari, februari, maret, april, mei, juni, juli, agustus, september, oktober, november, desember, idLevelKelas', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'idtuitionData' => 'Idtuition Data',
'nominalPembayaran' => 'Nominal Pembayaran',
'nominalDibayarkan' => 'Nominal Dibayarkan',
'nomerKuitansiPembayaran' => 'Nomer Kuitansi Pembayaran',
'tahunAjaran_idtahunAjaran' => 'Tahun Ajaran Idtahun Ajaran',
'DataSiswa_idDataSiswa' => 'Data Siswa Id Data Siswa',
'BulanTagihan' => 'Bulan Tagihan',
'statusTagihan' => 'Status Tagihan',
'SPP' => 'Spp',
'billCategoryData' => 'Bill Category Data',
'totalTagihan' => 'Total Tagihan',
'januari' => 'Januari',
'februari' => 'Februari',
'maret' => 'Maret',
'april' => 'April',
'mei' => 'Mei',
'juni' => 'Juni',
'juli' => 'Juli',
'agustus' => 'Agustus',
'september' => 'September',
'oktober' => 'Oktober',
'november' => 'November',
'desember' => 'Desember',
'idLevelKelas' => 'Id Level Kelas',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('idtuitionData',$this->idtuitionData);
$criteria->compare('nominalPembayaran',$this->nominalPembayaran,true);
$criteria->compare('nominalDibayarkan',$this->nominalDibayarkan);
$criteria->compare('nomerKuitansiPembayaran',$this->nomerKuitansiPembayaran,true);
$criteria->compare('tahunAjaran_idtahunAjaran',$this->tahunAjaran_idtahunAjaran);
$criteria->compare('DataSiswa_idDataSiswa',$this->DataSiswa_idDataSiswa);
$criteria->compare('BulanTagihan',$this->BulanTagihan);
$criteria->compare('statusTagihan',$this->statusTagihan,true);
$criteria->compare('SPP',$this->SPP);
$criteria->compare('billCategoryData',$this->billCategoryData,true);
$criteria->compare('totalTagihan',$this->totalTagihan);
$criteria->compare('januari',$this->januari,true);
$criteria->compare('februari',$this->februari,true);
$criteria->compare('maret',$this->maret,true);
$criteria->compare('april',$this->april,true);
$criteria->compare('mei',$this->mei,true);
$criteria->compare('juni',$this->juni,true);
$criteria->compare('juli',$this->juli,true);
$criteria->compare('agustus',$this->agustus,true);
$criteria->compare('september',$this->september,true);
$criteria->compare('oktober',$this->oktober,true);
$criteria->compare('november',$this->november,true);
$criteria->compare('desember',$this->desember,true);
$criteria->compare('idLevelKelas',$this->idLevelKelas);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}<file_sep><?php
/* @var $this PencarianController */
/* @var $model Pencarian */
$this->layout='forRenderPartial';
//$model = new Pencarian;
?>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'pencarian-grid',
//'itemsCssClass'=>'data display datatable',
'dataProvider'=>$model->search(),
//'filter'=>$model,
//'pager'=>'#',
'emptyText'=>'MAAF DATA TIDAK DITEMUKAN',
'blankDisplay'=>'MAAF DATA TIDAK DITEMUKAN',
'columns'=>array(
//'idDataSiswa',
array(
'header'=>'No Induk',
'value'=>'$data->NoIndukSiswa',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'70px',
'style'=>'text-align:left; font-size:12px; white-space: nowrap !important;',
//'padding'=>'0px'
),
),
array(
'header'=>'Nama',
'value'=>'$data->NamaSiswa',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'300px',
'style'=>'text-align:left; font-size:12px; white-space: nowrap !important;',
//'padding'=>'0px'
),
),
array(
'header'=>'Kelas',
'value'=>'$data->kelas->namaKelas',
//'filter'=>'<input name="Datasiswa[namaKelas]" type="text" maxlength="70">',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px; white-space: nowrap !important;',
//'padding'=>'0px'
),
),
//'NoIndukSiswa',
//'NamaSiswa',
//'namaOrtuAyah',
//'namaOrtuIbu',
//'alamatTinggal',
/*
'tempatLahir',
'tanggalLahir',
'poinValue',
'kotaAsal',
'tahunAjaranMasuk',
'nomorHp',
'contactDarurat',
'NominalSPP',
*/
//kolom untuk membuat tombol prosedur perintah
array(
'class'=>'CButtonColumn',
'header'=>'Pilih salah satu prosedur',
'template'=>'{bayarspp}{lihatdata}{lihatnilai}',
//'evaluateID'=>true,
'buttons'=>array(
'bayarspp'=>array(
//'id'=>'fancybox-trigger',
'label'=>'BAYAR SPP',
'url'=>'Yii::app()->createUrl("pencarian/ChoosenProcedure",array("commandid"=>"1","sid"=>$data->idDataSiswa));',
//'url'=>'',
//'imageUrl'=> "".Yii::app()->theme->baseUrl."/img/custom-btn/btn_spp.png",
'options'=>array(
'id'=>'ajaxed',
//'data-fancybox-type'=>'data-fancybox-type',
'class'=>'btn btn-blue',
//'id'=>'fancybox-trigger',
//'href'=>Yii::app()->controller->createUrl('pencarian/ChoosenProcedure',array('commandid'=>'1','id'=>'$id')),
//'valign'=>'middle',
'style'=>'padding-top: 0px !important;margin:5px 0 !important;',
),
),
'lihatdata'=>array(
'label'=>'LIHAT DATA',
'url'=>'Yii::app()->createUrl("datasiswa/profile", array("id"=>$data->idDataSiswa))',
//'imageUrl'=>"".Yii::app()->theme->baseUrl."/img/custom-btn/btn_lihat.png",
'options'=>array(
'class'=>'btn btn-green',
//'id'=>'fancybox-trigger',
//'valign'=>'middle',
'style'=>'padding-top: 0px !important;margin:5px !important;',
),
),
'lihatnilai'=>array(
'label'=>'LIHAT NILAI',
//'url'=>'Yii::app()->createUrl("datasiswa/popupupdate", array("id"=>$data->idDataSiswa))',
//'imageUrl'=>"".Yii::app()->theme->baseUrl."/img/custom-btn/btn_nilai.png",
'options'=>array(
'class'=>'btn btn-red',
//'id'=>'fancybox-trigger',
//'valign'=>'middle',
'style'=>'padding-top: 0px !important;margin:5px 0 !important;',
),
),
),
'htmlOptions'=>array(
'class'=>'button-column',
//'padding'=>'3.59375px',
//'width'=>'200px;',
'style'=>'width: auto !important; white-space: nowrap !important; height: 37px !important; margin-top:10px !important;',
//'height'=>'37px',
),
),
/*array(
'class'=>'CButtonColumn',
'template'=>'{view}{update}',
//'evaluateID'=>true,
'buttons'=>array(
'view'=>array(
//'id'=>'fancybox-trigger',
'label'=>'lihat data siswa ini',
'url'=>'Yii::app()->createUrl("datasiswa/popupview", array("id"=>$data->idDataSiswa))',
'options'=>array(
'id'=>'fancybox-trigger',
//'href'=>Yii::app()->controller->createUrl('datasiswa/popupview',array('id'=>'$id')),
),
),
'update'=>array(
'label'=>'update data siswa ini',
//'url'=>'Yii::app()->createUrl("datasiswa/popupupdate", array("id"=>$data->idDataSiswa))',
'options'=>array(
//'id'=>'fancybox-trigger',
),
),
),
),*/
),
'summaryText' => 'Menampilkan {count} data yang ditemukan.'
));
/*$this->widget('application.widgets.SimplaPager', array(
'pages'=>$pagination,
));
*
*/
?>
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of CustomCGridView
*
* @author <NAME>
*/
Yii::import('zii.widgets.grid.CGridView');
class CGridViewWithTotals extends CGridView
{
/**
* Renders the table header. Adds a 'totals' row.
*/
public function renderTableFooter()
{
//$hasFilter=$this->filter!==null && $this->filterPosition===self::FILTER_POS_FOOTER;
$hasFooter=$this->getHasFooter();
if($hasFooter)
{
echo "<tfoot>\n";
if($hasFooter)
{
echo "<tr>\n";
foreach($this->columns as $column)
$column->renderFooterCell();
echo "</tr>\n";
}
/*if($hasFilter)
$this->renderFilter();*/
echo "</tfoot>\n";
}
}
public function renderTableHeader()
{
if(!$this->hideHeader)
{
echo "<thead>\n";
if($this->filterPosition===self::FILTER_POS_HEADER)
$this->renderFilter();
echo '<tr class="' . $this->headerCssClass . ' ">' . "\n";
foreach($this->columns as $column)
$column->renderHeaderCell();
echo "</tr>\n";
if($this->filterPosition===self::FILTER_POS_BODY)
$this->renderFilter();
echo "</thead>\n";
}
else if($this->filter!==null && ($this->filterPosition===self::FILTER_POS_HEADER || $this->filterPosition===self::FILTER_POS_BODY))
{
echo "<thead>\n";
$this->renderFilter();
echo "</thead>\n";
}
}
}
?>
<file_sep><?php
/* milik db tuitiondata
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
//$this->layout="layout2";
$this->breadcrumbs=array(
'Pencarian Data Tagihan SPP'=>array('index'),
);
Yii::app()->clientScript->registerScript('search', "
$('.search-form form').submit(function(){
$.fn.yiiGridView.update('tuitiondata-grid', {
data: $(this).serialize()
});
$('.search-result').toggle();
return false;
});
");
?>
<p>
Untuk mempermudah pencarian data tagihan SPP siswa dan status pembayarannya gunakan fasilitas dibawah ini<br>
<a id="fancybox-trigger" class="iframe" href="popUpPay">ELEMEN TAGIHAN</a>
</p>
<div class="search-form">
<?php $this->renderPartial('_search_custom',array(
'model'=>$model,
'model2'=>$model2,
'model3'=>$model3,
)); ?>
</div>
<div id="search-result">
</div><file_sep><?php
/* @var $this SystemTahunajaranController */
/* @var $model SystemTahunajaran */
$this->breadcrumbs=array(
'System Tahunajarans'=>array('index'),
'Create',
);
$this->menu=array(
array('label'=>'List SystemTahunajaran', 'url'=>array('index')),
array('label'=>'Manage SystemTahunajaran', 'url'=>array('admin')),
);
?>
<h1>Create SystemTahunajaran</h1>
<?php echo $this->renderPartial('_form', array('model'=>$model)); ?><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
Yii::import('zii.widgets.CMenu', true);
class Mainmenu extends CMenu{
public function init(){
switch (Yii::app()->user->name) {
case 'server':
$this->widget('zii.widgets.CMenu', array(
'htmlOptions'=>array('class'=>'nav main'),
'items'=>array(
// Important: you need to specify url as 'controller/action',
// not just as 'controller' even if default acion is used.
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'Keuangan','url'=>array('/site/page','view'=>'administrasiKeuangan')),
array('label'=>'Perpustakaan','url'=>array('#')),
array('label'=>'Rumah Tangga','url'=>array('#')),
array('label'=>'IT','url'=>array('#')),
array('label'=>'SD','url'=>array('#')),
array('label'=>'SMP','url'=>array('#')),
array('label'=>'SMA','url'=>array('#')),
array('label'=>'Administrasi Umum','url'=>array('/site/page','view'=>'administrasiUmum')),
array('label'=>'About', 'url'=>array('/site/page','view'=>'about')),
array('label'=>'Contact', 'url'=>array('/site/contact')),
array('label'=>'User Manager','url'=>array('/userGroups'),'linkOptions'=>array('id'=>'printpreview','data-fancybox-type'=>'iframe')),
array('label'=>'Login', 'url'=>array('/userGroups'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/userGroups/user/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
));
break;
case 'keuangan':
$this->widget('zii.widgets.CMenu', array(
'htmlOptions'=>array('class'=>'nav main'),
'items'=>array(
// Important: you need to specify url as 'controller/action',
// not just as 'controller' even if default acion is used.
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'Keuangan','url'=>array('/site/page','view'=>'administrasiKeuangan')),
//array('label'=>'Perpustakaan','url'=>array('#')),
//array('label'=>'Rumah Tangga','url'=>array('#')),
//array('label'=>'IT','url'=>array('#')),
//array('label'=>'SD','url'=>array('#')),
//array('label'=>'SMP','url'=>array('#')),
//array('label'=>'SMA','url'=>array('#')),
array('label'=>'Administrasi Umum','url'=>array('/site/page','view'=>'administrasiUmum')),
//array('label'=>'About', 'url'=>array('/site/page','view'=>'about')),
//array('label'=>'Contact', 'url'=>array('/site/contact')),
//array('label'=>'User Manager','url'=>array('/userGroups')),
array('label'=>'Login', 'url'=>array('/userGroups'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/userGroups/user/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
));
break;
case 'Guest': $this->widget('zii.widgets.CMenu', array(
'htmlOptions'=>array('class'=>'nav main'),
'items'=>array(
// Important: you need to specify url as 'controller/action',
// not just as 'controller' even if default acion is used.
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'Login', 'url'=>array('/userGroups'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/userGroups/user/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
));
break;
default:
break;
}
/*if(Yii::app()->user->name=='server'){
}
if(Yii::app()->user->name=='keuangan'){
$this->widget('zii.widgets.CMenu', array(
'htmlOptions'=>array('class'=>'nav main'),
'items'=>array(
// Important: you need to specify url as 'controller/action',
// not just as 'controller' even if default acion is used.
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'Keuangan','url'=>array('/site/page','view'=>'administrasiKeuangan')),
//array('label'=>'Perpustakaan','url'=>array('#')),
//array('label'=>'Rumah Tangga','url'=>array('#')),
//array('label'=>'IT','url'=>array('#')),
//array('label'=>'SD','url'=>array('#')),
//array('label'=>'SMP','url'=>array('#')),
//array('label'=>'SMA','url'=>array('#')),
array('label'=>'Administrasi Umum','url'=>array('/site/page','view'=>'administrasiUmum')),
//array('label'=>'About', 'url'=>array('/site/page','view'=>'about')),
//array('label'=>'Contact', 'url'=>array('/site/contact')),
//array('label'=>'User Manager','url'=>array('/userGroups')),
array('label'=>'Login', 'url'=>array('/userGroups'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/userGroups/user/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
));
}else{
$this->widget('zii.widgets.CMenu', array(
'htmlOptions'=>array('class'=>'nav main'),
'items'=>array(
// Important: you need to specify url as 'controller/action',
// not just as 'controller' even if default acion is used.
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'Login', 'url'=>array('/userGroups'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/userGroups/user/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
));
}*/
}
}
?>
<file_sep><?php
/* @var $this SiteController */
$this->layout='column1';
$this->pageTitle=Yii::app()->name . ' - Control Panel ';
$this->breadcrumbs=array(
'Control Panel',
);
?>
<div class="iconMenu"><?php echo CHtml::link('<img src='.Yii::app()->theme->baseUrl.'/img/custom-btn/TahunAjaran.png><br>Setting Thn Ajaran',array('systemTahunajaran/TahunAjaranProcedure'),array('data-fancybox-type'=>'iframe','id'=>'fitwindow'));?><br></div>
<div class="iconMenu"><?php echo CHtml::link('<img src='.Yii::app()->theme->baseUrl.'/img/custom-btn/MatPel.png><br>Mata Pelajaran',array('pendaftaran/PilihanPendaftaran'),array('id'=>'ajaxed'));?><br></div>
<div class="iconMenu"><?php echo CHtml::link('<img src='.Yii::app()->theme->baseUrl.'/img/custom-btn/guruPengampu.png><br>Guru Pengampu',array('pendaftaran/PilihanPendaftaran'),array('id'=>'ajaxed'));?><br></div>
<file_sep><?php
/* @var $this DatasiswaController */
/* @var $model Datasiswa */
$this->breadcrumbs=array(
'Datasiswa'=>array('index'),
'Manage',
);
$this->menu=array(
array('label'=>'List Datasiswa', 'url'=>array('admin')),
array('label'=>'Create Datasiswa', 'url'=>array('create')),
);
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$.fn.yiiGridView.update('datasiswa-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<!--<p>
You may optionally enter a comparison operator (<b><</b>, <b><=</b>, <b>></b>, <b>>=</b>, <b><></b>
or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done.
</p>-->
<p><?php echo "Klik Disini Untuk Mencari : ".CHtml::link('[Klik Disini]','#',array('class'=>'search-button')); ?></p>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'datasiswa-grid',
'dataProvider'=>$model->viewKelas($id),
//'filter'=>$model,
'columns'=>array(
//'idDataSiswa',
'NoIndukSiswa',
'NamaSiswa',
array(
'header'=>'Kelas',
'value'=>'$data->kelas->namaKelas',
//'filter'=>'<input name="Datasiswa[namaKelas]" type="text" maxlength="70">',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
),
'namaOrtuAyah',
'namaOrtuIbu',
'alamatTinggal',
/*
'tempatLahir',
'tanggalLahir',
'poinValue',
'kotaAsal',
'tahunAjaranMasuk',
'nomorHp',
'contactDarurat',
'NominalSPP',
*/
array(
'class'=>'CButtonColumn',
'template'=>'{view}{update}',
//'evaluateID'=>true,
'buttons'=>array(
'view'=>array(
//'id'=>'fancybox-trigger',
'label'=>'lihat data siswa ini',
'url'=>'Yii::app()->createUrl("datasiswa/popupview", array("id"=>$data->idDataSiswa))',
'options'=>array(
'id'=>'fancybox-trigger',
//'href'=>Yii::app()->controller->createUrl('datasiswa/popupview',array('id'=>'$id')),
),
),
'update'=>array(
'label'=>'update data siswa ini',
//'url'=>'Yii::app()->createUrl("datasiswa/popupupdate", array("id"=>$data->idDataSiswa))',
'options'=>array(
//'id'=>'fancybox-trigger',
),
),
),
//'prevPageLabel'=>'Sebelumnya',
//'nextPageLabel'=>'Berikutnya',
),
),
));
?>
<file_sep><<<<<<< HEAD
myAppTest
=========
JustTestApp
=======
bellarminusIS
=============
bellarminus management software
>>>>>>> branch 'master' of https://github.com/ajimatahari/bellarminusIS.git
<file_sep><?php
/* @var $this TuitionbillcategoryController */
/* @var $model Tuitionbillcategory */
$homeUrl= Yii::app()->theme->baseUrl.'/css/layout.css';
$this->layout='flatLayout';
//Yii::app()->getClientScript()->registerCssFile(array($homeUrl, '/css/reset.css'));
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'tuitionbillcategory-grid',
'dataProvider'=>$model->search(),
//'filter'=>$model,
'columns'=>array(
/*array(
'header'=>'Id',
'headerHtmlOptions'=>array(
'class'=>'sorting',
),
'value'=>'$data->idtuitionbillcategory',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'15px',
'style'=>'text-align:left; background-color:white;font-size:12px;',
'class'=>'gradeA'
),
//'footer'=>'test',
//'hasFooter'=>'true',
),*/
array(
'header'=>'Bill Category',
'headerHtmlOptions'=>array(
'class'=>'sorting',
),
'value'=>'$data->billCategoryName',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:left;background-color:white;font-size:12px; border-right:solid 1px #e6e6e6;padding-right:5px;',
'class'=>'gradeA'
),
//'footer'=>'test',
//'hasFooter'=>'true',
),
array(
'header'=>'Nominal',
'headerHtmlOptions'=>array(
'class'=>'sorting',
),
'value'=>'$data->nominal',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'70px',
'style'=>'text-align:right; background-color:white;font-size:12px;border-right:solid 1px #e6e6e6;padding-right:5px;',
'class'=>'gradeA'
),
//'footer'=>'test',
//'hasFooter'=>'true',
),
array(
'header'=>'Catatan',
'headerHtmlOptions'=>array(
'class'=>'sorting',
),
'value'=>'$data->catatan',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'170px',
'style'=>'text-align:left;background-color:white;font-size:12px;border-right:solid 1px #e6e6e6;padding-right:5px;',
'class'=>'gradeA'
),
//'footer'=>'test',
//'hasFooter'=>'true',
),
array(
'class'=>'CButtonColumn',
'headerHtmlOptions'=>array(
'class'=>'sorting',
),
'template'=>'{update}',
//'evaluateID'=>true,
'htmlOptions'=>array(
'width'=>'20px',
'style'=>'text-align:center; background-color:white;font-size:12px;',
'class'=>'gradeA'
),
//'prevPageLabel'=>'Sebelumnya',
//'nextPageLabel'=>'Berikutnya',
),
),
'template'=>'{items}',
'cssFile'=>$homeUrl,
'itemsCssClass'=>'data display datatable',
'htmlOptions'=>array(
'style'=>'background-color:white;font-size:12px;',
),
)); ?>
<file_sep><?php
/**
* UserIdentity represents the data needed to identity a user.
* It contains the authentication method that checks if the provided
* data can identity the user.
*/
class UserIdentity extends CUserIdentity
{
/**
* Authenticates a user.
* The example implementation makes sure if the username and password
* are both '<PASSWORD>'.
* In practical applications, this should be changed to authenticate
* against some persistent user identity storage (e.g. database).
* @return boolean whether authentication succeeds.
<<<<<<< HEAD
* link tutorial : http://danaluther.blogspot.com/2010/03/yii-authentication-via-database.html
*/
private $_id;
public function authenticate()
{
/*$users=array(
// username => password
'demo'=>'<PASSWORD>',
'admin'=>'admin',
);
if(!isset($users[$this->username]))
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($users[$this->username]!==$this->password)
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
$this->errorCode=self::ERROR_NONE;
return !$this->errorCode;*/
//cek autentikasi kustom
$record= Users::model()->findByAttributes(array('username'=>$this->username)); //"Users::model()" bisa dibaca sebagai : untuk file model "users", yang notabene, model "users" merupakan representasi dr table Users
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($record->password!==md5($this-><PASSWORD>))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$record->id;
//$this->setState('title', $record->username); //<- belum tau fungsinya untuk apa
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
=======
*/
public function authenticate()
{
$users=array(
// username => password
'demo'=>'demo',
'admin'=>'admin',
);
if(!isset($users[$this->username]))
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($users[$this->username]!==$this->password)
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
$this->errorCode=self::ERROR_NONE;
return !$this->errorCode;
}
>>>>>>> branch 'master' of https://github.com/ajimatahari/myAppTest.git
}
<file_sep><?php
/**
* This is the model class for table "tuitionbillcategory".
*
* The followings are the available columns in table 'tuitionbillcategory':
* @property integer $idtuitionbillcategory
* @property string $billCategoryName
* @property integer $nominal
* @property string $catatan
* @property integer $tuitionbillcodeid
*/
class Tuitionbillcategory extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Tuitionbillcategory the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'tuitionbillcategory';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('billCategoryName, nominal, tuitionbillcodeid', 'required'),
array('nominal, tuitionbillcodeid', 'numerical', 'integerOnly'=>true),
array('billCategoryName', 'length', 'max'=>45),
array('catatan', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('idtuitionbillcategory, billCategoryName, nominal, catatan, tuitionbillcodeid', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'idtuitionbillcategory' => 'Idtuitionbillcategory',
'billCategoryName' => 'Bill Category Name',
'nominal' => 'Nominal',
'catatan' => 'Catatan',
'tuitionbillcodeid' => 'Tuitionbillcodeid',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('idtuitionbillcategory',$this->idtuitionbillcategory);
$criteria->compare('billCategoryName',$this->billCategoryName,true);
$criteria->compare('nominal',$this->nominal);
$criteria->compare('catatan',$this->catatan,true);
$criteria->compare('tuitionbillcodeid',$this->tuitionbillcodeid);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}<file_sep><?php
/* @var $this PendaftaranController */
/* @var $model pendaftaran */
$this->breadcrumbs=array(
'Pendaftarans'=>array('index'),
$model->idDataSiswa,
);
$this->menu=array(
array('label'=>'List pendaftaran', 'url'=>array('index')),
array('label'=>'Create pendaftaran', 'url'=>array('create')),
array('label'=>'Update pendaftaran', 'url'=>array('update', 'id'=>$model->idDataSiswa)),
array('label'=>'Delete pendaftaran', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->idDataSiswa),'confirm'=>'Are you sure you want to delete this item?')),
array('label'=>'Manage pendaftaran', 'url'=>array('admin')),
);
?>
<h1>View pendaftaran #<?php echo $model->idDataSiswa; ?></h1>
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'idDataSiswa',
'NoIndukSiswa',
'NamaSiswa',
'namaOrtuAyah',
'namaOrtuIbu',
'alamatTinggal',
'tempatLahir',
'tanggalLahir',
'poinValue',
'kotaAsal',
'tahunAjaranMasuk',
'nomorHp',
'contactDarurat',
'NominalSPP',
'eksKur',
'uangUjian',
'uangCambridge',
'idlevelKelas',
'penilaianpsikis',
'imgPath',
),
)); ?>
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
//Mulai javascript
jQuery(function($) {
jQuery('body').undelegate('input[id="createteam"]','click').delegate('input[id="createteam"]','click',function(){
jQuery.ajax({
'type':'POST',
'url':'/index.php?r=controller/action¶m=value',
'cache':false,
'data':jQuery(this).parents("form").serialize(),
'success':
function(html){
}});
return false;});
});
//akhir javascript 1<file_sep><?php $bulan=$_GET['bulan'];
Yii::app()->getClientScript()->registerCssFile(Yii::app()->theme->baseUrl.'/css/userProfile.css',CClientScript::POS_HEAD);
?>
<div class="form" style="background-color: white;">
<?php
$this->layout="forFancyloadedForm";
$timestamp = time();
$todayTime = date("sYimHd",$timestamp);
$form=$this->beginWidget('CActiveForm', array(
'id'=>'tuitiondata-form',
'action'=>Yii::app()->createUrl('tuitiondata/bayar',array('id'=>$model->idtuitionData)),
'enableAjaxValidation'=>false,
)); ?>
<table class="form" style="margin-bottom: 0 !important;">
<p class="sorting" style="margin-top: 0 !important; margin-bottom: 0 !important;">Pembayaran SPP atas nama <?php echo $model3->NamaSiswa ;?> Bulan <?php echo $bulan;?></p><hr class="user spacer">
<h6>kolom dengan tanda <span class="required">*</span> wajib diisi.<h6>
<tr>
<td class="col1"><?php echo CHtml::label('Token',false); ?></td>
<td class="col2"><?php echo CHtml::label($todayTime,false); ?><span class="success"> Angka ini adalah id unik referensi pencatatan transaksi di database, angka berbeda setiap detik</span></td>
</tr>
<tr>
<td class="col1"><?php echo $form->labelEx($model,'totalTagihan'); ?></td>
<td class="col2"> <?php echo CHtml::activeTextField($model,'totalTagihan',array(
'value'=>$model->totalTagihan,
'readonly'=>'true',
)) ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model2,'keterangan'); ?></td>
<td><?php echo CHtml::activeTextArea($model2,'keterangan',array('cols'=>'60','rows'=>'10')) ?></td>
</tr>
<tr class="row buttons">
<td colspan="2"><?php echo CHtml::activeHiddenField($model,'idtuitionData');
echo CHtml::hiddenField('token',$todayTime);
echo CHtml::hiddenField('bulan',$bulan);
echo CHtml::activeHiddenField($model,'DataSiswa_idDataSiswa');
echo CHtml::activeHiddenField($model2,'idReferensiTuition',array('value'=>$todayTime));
?>
<?php echo CHtml::htmlButton('<span></span>SIMPAN & PRINT',array('class'=>'btn-icon btn-grey btn-print','onclick'=>'submit();')); ?> <?php echo CHtml::htmlButton('<span></span>BATAL',array('class'=>'btn-icon btn-red btn-refresh','onclick'=>'parent.jQmin.fancybox.close();')); ?></td>
<td></td>
</td>
</table>
<?php $this->endWidget(); ?>
</div><!-- form --><file_sep><?php
/**
* This is the model class for table "datasiswa".
*
* The followings are the available columns in table 'datasiswa':
* @property integer $idDataSiswa
* @property integer $NoIndukSiswa
* @property string $NamaSiswa
* @property string $namaOrtuAyah
* @property string $namaOrtuIbu
* @property string $alamatTinggal
* @property string $tempatLahir
* @property string $tanggalLahir
* @property string $poinValue
* @property string $kotaAsal
* @property string $tahunAjaranMasuk
* @property string $nomorHp
* @property string $contactDarurat
* @property integer $NominalSPP
* @property integer $eksKur
* @property integer $uangUjian
* @property integer $uangCambridge
*
* The followings are the available model relations:
* @property Dataraportsemesteran[] $dataraportsemesterans
* @property Detailnilaisiswa[] $detailnilaisiswas
*/
class Datasiswa extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Datasiswa the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'datasiswa';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('NamaSiswa', 'required'),
array('NoIndukSiswa, NominalSPP, eksKur, uangUjian, uangCambridge,idlevelKelas', 'numerical', 'integerOnly'=>true),
array('NamaSiswa', 'length', 'max'=>70),
array('namaOrtuAyah, namaOrtuIbu, alamatTinggal, tempatLahir, tanggalLahir, poinValue, kotaAsal, nomorHp, contactDarurat', 'length', 'max'=>45),
array('tahunAjaranMasuk, penilaianpsikis, imgPath', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('idDataSiswa, NoIndukSiswa, NamaSiswa, namaOrtuAyah, namaOrtuIbu, alamatTinggal, tempatLahir, tanggalLahir, poinValue, kotaAsal, tahunAjaranMasuk, nomorHp, contactDarurat, NominalSPP, eksKur, uangUjian, uangCambridge, idlevelKelas', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'dataraportsemesterans' => array(self::HAS_MANY, 'Dataraportsemesteran', 'DataSiswa_idDataSiswa'),
'detailnilaisiswas' => array(self::HAS_MANY, 'Detailnilaisiswa', 'DataSiswa_idDataSiswa'),
'kelas'=>array(self::BELONGS_TO,'Levelkelas','idlevelKelas'),
'transaksiSPP'=>array(self::HAS_MANY,'Datatransaksispp','idDatasiswa'),
'kelakuan'=>array(self::HAS_MANY,'Catatankelakuan','idDatasiswa'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'idDataSiswa' => 'Id Data Siswa',
'NoIndukSiswa' => 'No Induk Siswa',
'NamaSiswa' => 'Nama Siswa',
'namaOrtuAyah' => 'Nama <NAME>',
'namaOrtuIbu' => 'Nama O<NAME>',
'alamatTinggal' => 'Alamat Tinggal',
'tempatLahir' => 'Tempat Lahir',
'tanggalLahir' => 'Tanggal Lahir',
'poinValue' => 'Poin Value',
'kotaAsal' => 'Kota Asal',
'tahunAjaranMasuk' => 'Tahun Ajaran Masuk',
'idlevelKelas' =>'Kelas',
'nomorHp' => 'Nomor Hp',
'contactDarurat' => 'Contact Darurat',
'NominalSPP' => 'Nominal Spp',
'penilaianpsikis'=>'catatan perilaku',
'imgPath'=>'Foto',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
//$count=Datasiswa::model()->count($criteria);
//$pages=new CPagination($count);
//$pages->pageSize=10;
//$pages->applyLimit($criteria);
$criteria->compare('idDataSiswa',$this->idDataSiswa);
$criteria->compare('NoIndukSiswa',$this->NoIndukSiswa);
$criteria->compare('NamaSiswa',$this->NamaSiswa,true);
$criteria->compare('namaOrtuAyah',$this->namaOrtuAyah,true);
$criteria->compare('namaOrtuIbu',$this->namaOrtuIbu,true);
$criteria->compare('alamatTinggal',$this->alamatTinggal,true);
$criteria->compare('tempatLahir',$this->tempatLahir,true);
$criteria->compare('tanggalLahir',$this->tanggalLahir,true);
$criteria->compare('poinValue',$this->poinValue,true);
$criteria->compare('kotaAsal',$this->kotaAsal,true);
$criteria->compare('tahunAjaranMasuk',$this->tahunAjaranMasuk,true);
$criteria->compare('idlevelKelas', $this->idlevelKelas);
$criteria->compare('nomorHp',$this->nomorHp,true);
$criteria->compare('contactDarurat',$this->contactDarurat,true);
$criteria->compare('NominalSPP',$this->NominalSPP);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
//'class'=>'CLinkPager',
'pageSize'=>'8',
//'route'=>'#',
),
//'pagination'=>'CLinkPager',
//'itemCount'=>'6',
));
}
public function viewKelas($id){
$criteria = new CDbCriteria;
$criteria->condition='`idlevelKelas`='.$id.'';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}<file_sep><?php
/* @var $this TuitiondataController */
/* @var $model Tuitiondata */
/* @var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
//'action'=>Yii::app()->createUrl($this->route),
//'method'=>'get',
'id'=>'advance-search',
//'action'=>Yii::app()->createURL($this->route),
//'method'=>'get',
'htmlOptions'=>array(
'onsubmit'=>"return false;",/* Disable normal form submit */
'onkeypress'=>" if(event.keyCode == 13){ send(); } " /* Do ajax call when user presses enter key */
),
)); ?>
<table class="form">
<tr>
<td>
<?php echo $form->label($model,'keyWordNama'); ?>
<?php echo $form->textField($model,'keyWordNama',array(
'size'=>60,'maxlength'=>70,
)); ?>
</td>
<!--</tr>-->
<td>
<?php echo $form->label($model,'keyWordBulan'); ?>
<?php echo $form->dropDownlist($model,'keyWordBulan',array(
''=>'',
'januari'=>'januari',
'februari'=>'februari',
'maret'=>'maret',
'april'=>'april',
'mei'=>'mei',
'juni'=>'juni',
'juli'=>'juli',
'agustus'=>'agustus',
'september'=>'september',
'november'=>'november',
'desember'=>'desember',
),array(
'onChange'=>'checkFieldDependenceDropDownlist();'
)); ?>
</td>
<td>
<?php echo $form->label($model,'keyWordStatusTagihan'); ?>
<?php echo $form->dropDownlist($model,'keyWordStatusTagihan',array(
''=>'',
'NULL'=>'Belum dibayar',
'NOT NULL'=>'Terbayar',
),array(
'disabled'=>'true'
)); ?>
</td>
<tr>
<td>
<?php echo CHtml::Button('Lakukan Pencarian',array('onclick'=>'send();','class'=>'btn btn-blue')); ?>
</td>
</tr>
</table>
<?php $this->endWidget(); ?>
</div><!-- search-form -->
<script type="text/javascript">
function send()
{
var data=$("#advance-search").serialize();
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("tuitiondata/AjaxSearch"); ?>',//Pencarian/admin?Datasiswa[NamaSiswa]=data&yt0=Search
data:data,
success:function(data){
document.getElementById('search-result').innerHTML=data;
//alert(data);
},
error: function(data) { // if error occured
alert("Error occured.please try again");
//alert(data);
},
dataType:'html'
});
}
function checkFieldDependenceDropDownlist()
{
var mForm = document.getElementById('advance-search');
BulanDropDownlist=document.getElementById('Tuitiondata_keyWordBulan');
BulanDropDownlistValue=BulanDropDownlist.options[BulanDropDownlist.selectedIndex].value;
TagihanDropDownlist=document.getElementById('Tuitiondata_keyWordStatusTagihan');
//TagihanDropDownlistValue=
if((BulanDropDownlistValue==='')){
TagihanDropDownlist.options[BulanDropDownlist.selectedIndex=0].selected=true;
TagihanDropDownlist.disabled=true;
}
else{
TagihanDropDownlist.disabled=false;
}
}
</script>
<?php
/*
* proses mencari data dengan referensi keyword dari table yang lain
* Here is the process
1 - create a public variable say $keyword
2 - assign it to search function in rules as safe
3 - In search function, call the related data using with keyword
$criteria = new CDbCriteria;
$criteria->with = array('relation name');
4 - Then you need to set the data for compare as
$criteria->compare('relation.field', $this->keyword, true);
5 - If you want to sort it too, then create a new object of CSort and set it there as
$sort = new CSort();
$sort->attributes = array(
'keyword'=>array(
'asc'=>'relation.field',
'desc'=>'relation.field desc',
),
);
Hope this will help you.
*/
?><file_sep><?php
/* @var $this PendaftaranController */
/* @var $model Pendaftaran */
/* @var $form CActiveForm */
//$this->layout="forFancyloadedForm";
?>
<div class="form">
<div class="block">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'pendaftaran-form',
'enableAjaxValidation'=>false,
//'action'=> $this->actionAjaxUpdate($id),
//'enableClientValidation'=>true,
/*'clientOptions' => array(
'validateOnSubmit'=>true,
'validateOnChange'=>true,
'validateOnType'=>false,
), */
'htmlOptions'=>array(
//'onsubmit'=>'return false', //menonaktifkan submisi data secara normal oleh form
//'onkeypress'=>'if(event.keyCode == 13){ send(); } ',
),
)); ?>
<p class="note">text box dengan tanda <span class="required">*</span> wajib terisi.</p>
<table class="form">
<?php echo $form->errorSummary($model); ?>
<tr>
<td class="col1"><?php echo $form->labelEx($model,'NoIndukSiswa'); ?></td>
<td class="col2"><?php echo $form->textField($model,'NoIndukSiswa'); ?></td>
<td class="col3"><?php echo $form->error($model,'NoIndukSiswa'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'NamaSiswa'); ?></td>
<td><?php echo $form->textField($model,'NamaSiswa',array('size'=>60,'maxlength'=>70)); ?></td>
<td><?php echo $form->error($model,'NamaSiswa'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'namaOrtuAyah'); ?></td>
<td><?php echo $form->textField($model,'namaOrtuAyah',array('size'=>45,'maxlength'=>45)); ?></td>
<td><?php echo $form->error($model,'namaOrtuAyah'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'namaOrtuIbu'); ?></td>
<td><?php echo $form->textField($model,'namaOrtuIbu',array('size'=>45,'maxlength'=>45)); ?></td>
<td><?php echo $form->error($model,'namaOrtuIbu'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'alamatTinggal'); ?></td>
<td><?php echo $form->textField($model,'alamatTinggal',array('size'=>45,'maxlength'=>45)); ?></td>
<td><?php echo $form->error($model,'alamatTinggal'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'tempatLahir'); ?></td>
<td><?php echo $form->textField($model,'tempatLahir',array('size'=>45,'maxlength'=>45)); ?></td>
<td><?php echo $form->error($model,'tempatLahir'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'tanggalLahir'); ?></td>
<td><?php echo CHtml::activeDateField($model,'tanggalLahir',array('size'=>45,'maxlength'=>45)); ?></td>
<td><?php echo $form->error($model,'tanggalLahir'); ?></td>
</tr>
<!--<tr>
<td><?php echo $form->labelEx($model,'poinValue'); ?></td>
<td><?php echo $form->textField($model,'poinValue',array('size'=>45,'maxlength'=>45)); ?></td>
<td><?php echo $form->error($model,'poinValue'); ?></td>
</tr>-->
<tr>
<td><?php echo $form->labelEx($model,'kotaAsal'); ?></td>
<td><?php echo $form->textField($model,'kotaAsal',array('size'=>45,'maxlength'=>45)); ?></td>
<td><?php echo $form->error($model,'kotaAsal'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'tahunAjaranMasuk'); ?></td>
<td><?php echo CHtml::activeDateField($model,'tahunAjaranMasuk'); ?></td>
<td><?php echo $form->error($model,'tahunAjaranMasuk'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'Kelas '); ?></td>
<td><?php
echo $form->dropDownList($model,'idlevelKelas'/*id kelas yang berhubungan didatabase datasiswa*/, CHtml::listData(Levelkelas::model()->findAll(), 'idLevelkelas', 'namaKelas'), array('empty'=>'Pilih Kelas'));
?></td>
<td><?php echo $form->error($model,'tahunAjaranMasuk'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'nomorHp'); ?></td>
<td><?php echo $form->textField($model,'nomorHp',array('size'=>45,'maxlength'=>45)); ?></td>
<td><?php echo $form->error($model,'nomorHp'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'contactDarurat'); ?></td>
<td><?php echo $form->textField($model,'contactDarurat',array('size'=>45,'maxlength'=>45)); ?></td>
<td><?php echo $form->error($model,'contactDarurat'); ?></td>
</tr>
<tr>
<td colspan=2><?php echo CHtml::htmlButton($model->isNewRecord ? 'Daftar' : 'Simpan',array('class'=>'btn btn-blue', 'onclick'=>'submit();'));?> <?php echo CHtml::htmlButton('Daftar & Input lagi',array('class'=>'btn btn-blue', 'onclick'=>'submit();'));?> <?php echo CHtml::htmlButton('Batal',array('class'=>'btn btn-red', 'onclick'=>''));?></td> <!-- Submit button yang biasanya-->
<!--<td colspan=2><?php /*echo CHtml::htmlButton($model->isNewRecord ? 'Create' : '<span></span>Simpan', array(
'id'=>'update',
'onclick'=>'send();',
'class'=>'btn-icon btn-grey btn-check',
'value'=>'save',
));*/?></td>-->
<!--<td colspan="2">
<?php
/*echo CHtml::ajaxButton('Save',
array('Datasiswa/UpdateWithAjax'),
array('data'=>'js:jQuery(this).parents("datasiswa-form").serialize()',
'type'=>'POST',
),
array('update'=>'#ajaxUpdateSelector')
//this is the updateselector of yours $('#update_selector').load(url);
);*/
?>
</td> -->
</tr>
</table>
<?php $this->endWidget(); ?>
</div>
<!--<div id="ajaxUpdateSelector"></div>-->
<!-- fungsi javascript untuk mengirim data dari form ini ke controller/action-->
<!--<script type="text/javascript">
function send()
{
var data=$("#datasiswa-form").serialize();
$.ajax({
type: 'POST',
url:'<?php echo Yii::app()->createAbsoluteUrl("datasiswa/updatewithajax"); ?>',
data:data,
success:function(data){
alert(data);
},
error: function(data) { // if error occured
alert("Error occured.please try again "+data);
//alert(data);
},
dataType:'html'
});
}
</script>-->
<!-- fungsi javascript untuk mengirim data dari form ini ke controller/action-->
</div><!-- form -->
<file_sep><?php
/* @var $this TuitionbillcategoryController */
/* @var $model Tuitionbillcategory */
?>
<h5>Update Detail data tagihan Siswa <?php echo $model->idtuitionbillcategory; ?></h5>
<?php echo $this->render('_form', array('model'=>$model)); ?><file_sep><?php
Yii::import('zii.widgets.CMenu', true);
class menuKeuangan extends CMenu
{
public function init()
{
$checkEmtpyness=Yii::app()->db->createCommand()
->select('*')
->from('tuitiondata')
->queryRow(); //queryrow return false kalo table yang diquery kosong / tidak ada recordnya
if($checkEmtpyness===false){
$this->widget('zii.widgets.CMenu', array(
'htmlOptions'=>array('class'=>'section menu'),
'items'=>array(
array('label'=>'Data Tagihan US', 'url'=>Yii::app()->createUrl('tuitiondata/admin')),
array('label'=>'Pencarian', 'url'=>Yii::app()->createUrl('tuitiondata/advancesearch')),
array('label'=>'Detail Master SPP','url'=>Yii::app()->createUrl('datasppsiswa/admin')),
array('label'=>'Master Uang Sekolah','url'=>Yii::app()->createUrl('tuitiondata/admin')),
),
));
}else{
$this->widget('zii.widgets.CMenu', array(
'htmlOptions'=>array('class'=>'section menu'),
'items'=>array(
array('label'=>'Data Tagihan US', 'url'=>Yii::app()->createUrl('tuitiondata/admin')),
array('label'=>'Pencarian', 'url'=>Yii::app()->createUrl('tuitiondata/advancesearch')),
array('label'=>'Detail Master SPP','url'=>Yii::app()->createUrl('datasppsiswa/admin')),
array('label'=>'Master Uang Sekolah','url'=>Yii::app()->createUrl('tuitiondata/admin')),
array('label'=>'Master SD','url'=>Yii::app()->createUrl('tuitiondata/rekapMasterUnit',array('idUnit'=>'1'))),
array('label'=>'Master SMP','url'=>Yii::app()->createUrl('tuitiondata/rekapMasterUnit',array('idUnit'=>'2'))),
array('label'=>'Master SMA','url'=>Yii::app()->createUrl('tuitiondata/rekapMasterUnit',array('idUnit'=>'3'))),
),
));
}
}
}
?>
<file_sep><?php
/* @var $this CatatankelakuanController */
/* @var $model Catatankelakuan */
/* @var $form CActiveForm */
?>
<div class="wide form">
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
)); ?>
<div class="row">
<?php echo $form->label($model,'id'); ?>
<?php echo $form->textField($model,'id'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'iddatasiswa'); ?>
<?php echo $form->textField($model,'iddatasiswa'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'tanggalinput'); ?>
<?php echo $form->textField($model,'tanggalinput'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'userpenginput'); ?>
<?php echo $form->textField($model,'userpenginput'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'keterangan'); ?>
<?php echo $form->textArea($model,'keterangan',array('rows'=>6, 'cols'=>50)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'tanggaledit'); ?>
<?php echo $form->textField($model,'tanggaledit'); ?>
</div>
<div class="row">
<?php echo $form->label($model,'userpengedit'); ?>
<?php echo $form->textField($model,'userpengedit'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form --><file_sep><?php
/* @var $this TahunajaranController */
/* @var $data Tahunajaran */
?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('idtahunAjaran')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->idtahunAjaran), array('view', 'id'=>$data->idtahunAjaran)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('tahunajaran')); ?>:</b>
<?php echo CHtml::encode($data->tahunajaran); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('semester')); ?>:</b>
<?php echo CHtml::encode($data->semester); ?>
<br />
</div><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*
*/
$this->layout="userProfile";
$this->menu=array(
array('label'=>'Manage Datasiswa', 'url'=>array('admin')),
);
Yii::app()->clientScript->registerCssFile(Yii::app()->theme->baseUrl.'/css/userProfile.css');
?>
<div class="grid_10">
<div class="box round first">
<!--<div class="user-name"><h2><?php echo $model->NamaSiswa;?></h2></div>--><h2>DATA DIRI</h2>
<div class="user">
<div class="user image"><img src="<?php
$varImg=$model->imgPath;
if(($varImg)==NULL){echo Yii::app()->theme->BaseUrl."/img/user_pic.png";}
?>"></div>
<div class="user grouper" style="width: 940px !important;">
<!--<hr class="user spacer">--><hr class="user spacer"><p class="sectionhead">DATA PRIBADI</p><hr class="user spacer">
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'nullDisplay'=>'Belum Diisi',
'attributes'=>array(
array(
'label'=>'Nomor Induk Siswa',
'name'=>'NoIndukSiswa',
),
array(
'label'=>'Nama Lengkap',
'name'=>'NamaSiswa',
),
array(
'label'=>'Nama Ayah',
'name'=>'namaOrtuAyah',
),
array(
'label'=>'Nama Ibu',
'name'=>'namaOrtuIbu',
),
array(
'label'=>'Tempat,Tanggal Lahir',
'value'=>$model->tempatLahir.', '.date("d M Y",strtotime($model->tanggalLahir)),
),
'alamatTinggal',
array(
'label'=>'Tanggal Masuk Tahun Ajaran',
'value'=>date("d M Y",strtotime($model->tahunAjaranMasuk)),
),
'nomorHp',
'contactDarurat',
array(
'label'=>'Nominal Pembayaran SPP',
//'type'=>'number',
'value'=> 'Rp. '.number_format((double)$model->NominalSPP,'2',',','.'),
),
),
'cssFile'=>'Yii::app()->theme->baseUrl."/css/userProfile.css"',
));?>
</div>
<div class="user grouper"><hr class="user spacer"><p class="sectionhead">DATA KELUARGA</p><hr class="user spacer">
<!--
disini untuk CATATAN PEMBAYARAN SPP
-->
</div>
<div class="user grouper"><hr class="user spacer"><p class="sectionhead">CATATAN PEMBAYARAN SPP</p><hr class="user spacer">
<!--
disini untuk CATATAN PEMBAYARAN SPP
-->
</div>
</div>
<!--<h2>DATA NILAI</h2>-->
</div>
</div><file_sep><?php
/* @var $this SystemTahunajaranController */
/* @var $model SystemTahunajaran */
$this->layout="forFancyloadedForm";
$this->breadcrumbs=array(
'System Tahunajarans'=>array('index'),
'Manage',
);
$this->menu=array(
array('label'=>'List SystemTahunajaran', 'url'=>array('index')),
array('label'=>'Create SystemTahunajaran', 'url'=>array('create')),
);
?>
<center><h5>Pengaturan Tahun Ajaran</h5></center>
<div id="loaderPosition" style="width:100%; text-align: center;"></div>
<div id="setingContainer" style="text-align: justify;">
<p style="margin:0;" id="removeThisText">Tahun Ajaran yang sedang aktif pada saat ini adalah :
<b><?php $drDb = Yii::app()->db->createCommand()
->select('thnAjaran')
->from('system_tahunajaran')
->where('status_aktif = 1')
->queryScalar();
$drDbPiece=explode(':',$drDb);
$thnAjaran=implode('/', $drDbPiece);
echo $thnAjaran;
?>
</b><?php
echo CHtml::ajaxLink(' [edit]',Yii::app()->createUrl('SystemTahunAjaran/CreateThnAjaran'),
array(
'beforeSend' => 'function(){
$("#removeThisText").hide();
$("#loaderPosition").addClass("ajaxloading");}',
'update'=>'#setingContainer',
'complete' => 'function(){
$("#loaderPosition").removeClass("ajaxloading");
$("#removeThisText").remove();
var current_height = document.body.offsetHeight;
var current_width = document.body.offsetWidth;
parent.$(".fancybox-skin").height(current_height + 30);
parent.$(".fancybox-skin").width(current_width + 30);
parent.$(".fancybox-inner").height(current_height + 30);
parent.$("#fancybox-outer").width(current_width + 30);
parent.$("#fancybox-wrap").width(current_width + 30);
parent.$("#fancybox-content").width(current_width + 30);
parent.$(".fancybox-inner").width(current_width + 30);
//parent.$.fancybox.reposition();
}',
),
array('style'=>'color: blue;')
);
?>
</p></div>
<file_sep><?php
/* @var $this TuitionbillcategoryController */
/* @var $dataProvider CActiveDataProvider */
$this->breadcrumbs=array(
'Tuitionbillcategories',
);
$this->menu=array(
array('label'=>'Create Tuitionbillcategory', 'url'=>array('create')),
array('label'=>'Manage Tuitionbillcategory', 'url'=>array('admin')),
);
?>
<h1>Tuitionbillcategories</h1>
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); ?>
<file_sep><?php /* @var $this Controller */ ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/reset.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/text.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/grid.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/layout.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/nav.css" media="screen" />
<!--[if IE 6]><link rel="stylesheet" type="text/css" href="css/ie6.css" media="screen" /><![endif]-->
<!--[if IE 7]><link rel="stylesheet" type="text/css" href="css/ie.css" media="screen" /><![endif]-->
<!-- BEGIN: load jquery -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.core.min.js"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.widget.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.accordion.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.effects.core.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.effects.slide.min.js" type="text/javascript"></script>
<!-- END: load jquery -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/popup/jquery.facebox.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/quick-sand/jquery.quicksand.js" type="text/javascript"></script>
<!-- BEGIN: load jquery2 -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.core.min.js"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.widget.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.accordion.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.effects.core.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.effects.slide.min.js" type="text/javascript"></script>
<!-- END: load jquery2 -->
<!-- BEGIN: load jqplot -->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/jquery.jqplot.min.css" />
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="js/jqPlot/excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jqPlot/jquery.jqplot.min.js"></script>
<script language="javascript" type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jqPlot/plugins/jqplot.barRenderer.min.js"></script>
<script language="javascript" type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jqPlot/plugins/jqplot.pieRenderer.min.js"></script>
<script language="javascript" type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jqPlot/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script language="javascript" type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jqPlot/plugins/jqplot.highlighter.min.js"></script>
<script language="javascript" type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jqPlot/plugins/jqplot.pointLabels.min.js"></script>
<!-- END: load jqplot -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/setup.js" type="text/javascript"></script>
<script type="text/javascript">
//untuk mencegah versi yang saling berkonflik gunakan jQuery.noConflict
var jQ164 = jQuery.noConflict();
jQ164(document).ready(function () {
setupLeftMenu();
setSidebarHeight();
});
</script>
<!-- BEGIN: load Fancybox -->
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox/jquery.easing-1.3.pack.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
<link rel="stylesheet" href="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />
<!-- END: load fancybox -->
<script type="text/javascript">
//javascript yg digunakan adalah yg untuk fancybox
//fancybox javacript function
var jQmin = jQuery.noConflict();
jQmin(document).ready(function() {
/* This is basic - uses default settings */
jQmin("a#fancybox-trigger").fancybox();
/* Using custom settings */
jQmin("a#inline").fancybox({
'hideOnContentClick': true
});
/* Apply fancybox to multiple items */
jQmin("a.group").fancybox({
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : false
});
});
//fancybox javascript function
//fancybox ajax function
/*jQmin("#datasiswa-form").bind("submit", function() {
if (jQmin("#login_name").val().length < 1 || jQmin("#login_pass").val().length < 1) {
jQmin("#login_error").show();
jQmin.fancybox.resize();
return false;
}
jQmin.fancybox.showActivity();
jQmin.ajax({
type : "POST",
cache : false,
url : "datasiswa/updateUsingAjax",
data : jQmin(this).serializeArray(),
success: function(data) {
jQmin.fancybox(data);
}
});
return false;
});*/
</script>
</head>
<body>
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*
*/
echo $content;
?>
</body></html><file_sep><?php /* @var $this Controller */ ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/printCSS.css" media="print" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/printCSS.css" media="screen" />
<!--[if IE 6]><link rel="stylesheet" type="text/css" href="css/ie6.css" media="screen" /><![endif]-->
<!--[if IE 7]><link rel="stylesheet" type="text/css" href="css/ie.css" media="screen" /><![endif]-->
<!-- BEGIN: load jquery -->
</head>
<body id="F4">
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*
*/
echo $content;
?>
</body></html><file_sep><?php
/* @var $this SystemTahunajaranController */
/* @var $model SystemTahunajaran */
/* @var $form CActiveForm */
?>
<div id="set-semester-container" class="form">
<center><p style="margin:5px;">Tahun ajaran yang aktif saat ini adalah :<?php echo Yii::app()->session['thnAjaran']; ?> semester <?php $thnAjaran=Yii::app()->session['semester']; echo $thnAjaran;?></p></center>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'set-semester-form',
'enableAjaxValidation'=>false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<table class="form"" style="border:solid 1px black;">
<tr style="border:solid 1px black; background-color: #2E5E79; color: white;">
<td style="text-align:center;"><?php echo CHtml::label('SEMESTER :',false); echo CHtml::hiddenField('thnAjaran',$thnAjaran);?></td>
<td style="text-align:center;">1</td>
<td style="text-align:center;">2</td>
</tr>
</tr>
<td style="text-align:center;">Pilih salah satu</td>
<td style="text-align:center;">
<?php
echo CHtml::RadioButton('semesterGroup',false,
array('value'=>'1'));?>
</td>
<td style="text-align:center;">
<?php
echo CHtml::RadioButton('semesterGroup',false,
array('value'=>'2'));?>
</td>
</tr>
<tr style="background-color: #E6F0F3;">
<td colspan="3" style="text-align:center;"><?php echo CHtml::AjaxSubmitButton('Simpan',Yii::app()->createUrl('systemTahunajaran/SubmitTahunAjaranBaru'),
array(
'beforeSend' => 'function(){
$("#set-semester-container").hide();}',
'update'=>'#setingContainer',
'complete' => 'function(){
$("#set-semester-container").remove();
var current_height = document.body.offsetHeight;
var current_width = document.body.offsetWidth;
parent.$(".fancybox-skin").height(current_height + 30);
parent.$(".fancybox-skin").width(current_width + 30);
parent.$(".fancybox-inner").height(current_height + 30);
parent.$("#fancybox-outer").width(current_width + 30);
parent.$("#fancybox-wrap").width(current_width + 30);
parent.$("#fancybox-content").width(current_width + 30);
parent.$(".fancybox-inner").width(current_width + 30);
//parent.$.fancybox.reposition();
}',
),
array('class'=>'btn-custom')
);?></td>
</tr>
</table>
<?php $this->endWidget(); ?>
</div><!-- form --><file_sep><?php
/* @var $this TuitiondataController */
/* @var $model Tuitiondata */
/* @var $model2 Archiveddatatransaksi */
/* @var $model3 Datasiswa */
/**/
$bulan=$_GET['bulan'];
$this->breadcrumbs=array(
'Pembayaran SPP'=>array('index'),
$bulan,
);
$this->menu=array(
//array('label'=>'List Tuitiondata', 'url'=>array('index')),
array('label'=>'Manage Tuitiondata', 'url'=>array('admin')),
);
Yii::app()->getClientScript()->registerCssFile(Yii::app()->theme->baseUrl.'/css/userProfile.css',CClientScript::POS_HEAD);
?>
<br>
<hr class="user spacer"><p class="sectionhead">Pembayaran SPP atas Nama <?php echo $model3->NamaSiswa ;?> Bulan <?php echo $bulan;?></p><hr class="user spacer">
<hr class="user spacer"><p class="sectionhead">Keterangan</p><hr class="user spacer">
<?php echo $this->renderPartial('_form_pembayaran', array('model'=>$model,'model2'=>$model2,'bulan'=>$bulan)); ?><file_sep>include.path=${php.global.include.path}
<<<<<<< HEAD
php.version=PHP_54
=======
php.version=PHP_53
>>>>>>> branch 'master' of https://github.com/ajimatahari/myAppTest.git
source.encoding=UTF-8
src.dir=.
tags.asp=false
tags.short=true
web.root=.
<file_sep><h2><?php echo Yii::t('userGroupsModule.general', 'External Profile'); ?></h2>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'user-groups-profile-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model,'hobbies'); ?>
<?php echo $form->textField($model,'hobbies',array('size'=>60,'maxlength'=>120)); ?>
<?php echo $form->error($model,'hobbies'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::ajaxSubmitButton(Yii::t('userGroupsModule.general','Update External Profile'), Yii::app()->baseUrl . '/userGroups/user/update/id/'.$user_id, array('update' => '#userGroups-container'), array('id' => 'submit-profile-'.$model->id.rand()) ); ?>
</div>
<?php $this->endWidget(); ?>
</div>
<h2><?php echo Yii::t('userGroupsModule.general', 'Avatar'); ?></h2>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'user-groups-avatar-form',
'action'=>array('/profile/load'),
'htmlOptions'=> array(
'enctype'=>'multipart/form-data',
)
)); ?>
<div class="row">
<?php echo $form->labelEx($model,'avatar'); ?>
<?php echo CHtml::activeFileField($model,'avatar'); ?>
<?php echo $form->error($model,'avatar'); ?>
</div>
<div class="row">
<p>you can just upload images.</p>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton(Yii::t('userGroupsModule.general','load avatar')); ?>
</div>
<?php $this->endWidget(); ?>
</div><file_sep><?php
/* @var $this TahunajaranController */
/* @var $model Tahunajaran */
$this->breadcrumbs=array(
'Tahunajarans'=>array('index'),
$model->idtahunAjaran,
);
$this->menu=array(
array('label'=>'List Tahunajaran', 'url'=>array('index')),
array('label'=>'Create Tahunajaran', 'url'=>array('create')),
array('label'=>'Update Tahunajaran', 'url'=>array('update', 'id'=>$model->idtahunAjaran)),
array('label'=>'Delete Tahunajaran', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->idtahunAjaran),'confirm'=>'Are you sure you want to delete this item?')),
array('label'=>'Manage Tahunajaran', 'url'=>array('admin')),
);
?>
<h1>View Tahunajaran #<?php echo $model->idtahunAjaran; ?></h1>
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'idtahunAjaran',
'tahunajaran',
'semester',
),
)); ?>
<file_sep><?php
/* @var $this SystemTahunajaranController */
/* @var $model SystemTahunajaran */
$this->breadcrumbs=array(
'System Tahunajarans'=>array('index'),
$model->id=>array('view','id'=>$model->id),
'Update',
);
$this->menu=array(
array('label'=>'List SystemTahunajaran', 'url'=>array('index')),
array('label'=>'Create SystemTahunajaran', 'url'=>array('create')),
array('label'=>'View SystemTahunajaran', 'url'=>array('view', 'id'=>$model->id)),
array('label'=>'Manage SystemTahunajaran', 'url'=>array('admin')),
);
?>
<h1>Update SystemTahunajaran <?php echo $model->id; ?></h1>
<?php echo $this->renderPartial('_form', array('model'=>$model)); ?><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of PembayaranController
*
* @author <NAME>
*/
class PembayaranController extends Controller{
public $layout='//layouts/Layout2';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('admin','create','update','delete','pembayaran'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','create','update','delete'),
'users'=>array('server'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
public function prosesBayar(){
$modelDatasiswa = new Datasiswa;
$modelDatatransaksipp = new Datatransaksispp;
$modelDataSPPsiswa = new DataSPPsiswa;
//ubah kode dibawah ini
if(isset($_POST['A'], $_POST['B']))
{
// populate input data to $a and $b
$a->attributes=$_POST['A'];
$b->attributes=$_POST['B'];
// validate BOTH $a and $b
$valid=$a->validate();
$valid=$b->validate() && $valid;
if($valid)
{
// use false parameter to disable validation
$a->save(false);
$b->save(false);
// ...redirect to another page
}
}
$this->render('create', array(
'a'=>$a,
'b'=>$b,
));
}
//put your code here
}
?>
<file_sep><?php
/* @var $this TuitiondataController */
/* @var $model Tuitiondata */
$this->breadcrumbs=array(
'Tuitiondatas'=>array('index'),
$model->idtuitionData,
);
$this->menu=array(
//array('label'=>'List Tuitiondata', 'url'=>array('index')),
//array('label'=>'Create Tuitiondata', 'url'=>array('create')),
//array('label'=>'Update Tuitiondata', 'url'=>array('update', 'id'=>$model->idtuitionData)),
//array('label'=>'Delete Tuitiondata', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->idtuitionData),'confirm'=>'Are you sure you want to delete this item?')),
array('label'=>'Manage Tuitiondata', 'url'=>array('admin')),
);
?>
<h1> View Tuitiondata #<?php echo $model->idtuitionData; ?></h1>
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'idtuitionData',
'nominalDibayarkan',
'nomerKuitansiPembayaran',
'tahunAjaran_idtahunAjaran',
'DataSiswa_idDataSiswa',
'BulanTagihan',
'statusTagihan',
'SPP',
'billCategoryData',
'totalTagihan',
'januari',
'februari',
'maret',
'april',
'mei',
'juni',
'juli',
'agustus',
'september',
'oktober',
'november',
'desember',
),
)); ?>
<file_sep><?php
/* @var $this TuitiondataController */
/* @var $model Tuitiondata */
/* @var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'tuitiondata-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'idtuitionData'); ?>
<?php echo $form->textField($model,'idtuitionData'); ?>
<?php echo $form->error($model,'idtuitionData'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nominalDibayarkan'); ?>
<?php echo $form->textField($model,'nominalDibayarkan'); ?>
<?php echo $form->error($model,'nominalDibayarkan'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nomerKuitansiPembayaran'); ?>
<?php echo $form->textField($model,'nomerKuitansiPembayaran',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'nomerKuitansiPembayaran'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'tahunAjaran_idtahunAjaran'); ?>
<?php echo $form->textField($model,'tahunAjaran_idtahunAjaran'); ?>
<?php echo $form->error($model,'tahunAjaran_idtahunAjaran'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'DataSiswa_idDataSiswa'); ?>
<?php echo $form->textField($model,'DataSiswa_idDataSiswa'); ?>
<?php echo $form->error($model,'DataSiswa_idDataSiswa'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'BulanTagihan'); ?>
<?php echo $form->textField($model,'BulanTagihan'); ?>
<?php echo $form->error($model,'BulanTagihan'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'statusTagihan'); ?>
<?php echo $form->textField($model,'statusTagihan',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'statusTagihan'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'SPP'); ?>
<?php echo $form->textField($model,'SPP'); ?>
<?php echo $form->error($model,'SPP'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'billCategoryData'); ?>
<?php echo $form->textField($model,'billCategoryData',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'billCategoryData'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'totalTagihan'); ?>
<?php echo $form->textField($model,'totalTagihan'); ?>
<?php echo $form->error($model,'totalTagihan'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form --><file_sep><?php /* @var $this Controller */ ?>
<?php $this->beginContent('//layouts/main'); ?>
<div class="grid_12">
<?php
$this->widget('application.components.Mainmenu');
?>
</div>
<!-- mainmenu -->
<!-- navigasi end -->
<!--<div class="grid_12">
<div class="box round first">
</div>
</div>-->
<div class="grid_2">
<div class="box sidemenu">
<div class="block" id="section-menu">
<?php
/*$this->beginWidget('zii.widgets.CPortlet', array(
'title'=>'Operations',
));*/
$this->beginWidget('zii.widgets.CMenu', array(
'items'=>$this->menu,
'htmlOptions'=>array('class'=>'section menu'),
));
$this->endWidget();
//$this->widget('application.components.ClassesMenuActive');
?>
</div><!-- sidebar -->
</div>
</div>
<div class="grid_10">
<div class="box round first">
<?php if(isset($this->breadcrumbs)):?>
<?php $this->widget('zii.widgets.CBreadcrumbs', array(
'links'=>$this->breadcrumbs,
'tagName'=>'h2', //mengubah tag yang sudah ada.
'activeLinkTemplate'=>'{label}</a>', // will generate the clickable breadcrumb links
'separator'=>' - ',
'inactiveLinkTemplate'=>'{label}', // will generate the current page url : <li>News</li>
'homeLink'=>'<a id="breadcrumbsonly" href="'.Yii::app()->homeUrl.'">Home</a>' // will generate your homeurl item : <li><a href="/dr/dr/public_html/">Home</a></li>
)); ?><!-- breadcrumbs -->
<?php endif?>
<?php echo $content; ?>
</div>
</div>
<div id="footer">
Copyright © <?php echo date('Y'); ?> Bellarminus IS by <EMAIL><br/>
</div><!-- footer -->
<?php $this->endContent(); ?><file_sep><?php
class TuitiondataController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/layoutKeuangan';
/**
* @return array action filters
*/
public function filters()
{
return array(
'userGroupsAccessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('admin','create','update','runSQL','advanceSearch','AjaxSearch','bayar','rekapMasterUnit','rekapAllBulanan','rekapKelasBulanan','rekapKelasTahunan','rekapAllTahunan','rekapSD','rekapSMP','rekapSMA','PrintReportMaster'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','create','update','delete','runSQL','advanceSearch','AjaxSearch','bayar','rekapMasterUnit','rekapAllBulanan','rekapKelasBulanan','rekapKelasTahunan','rekapAllTahunan','rekapSD','rekapSMP','rekapSMA','PrintReportMaster'),
'users'=>array('server'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Tuitiondata;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Tuitiondata']))
{
$model->attributes=$_POST['Tuitiondata'];
if($model->save())
$this->redirect(array('view','id'=>$model->idtuitionData));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Tuitiondata']))
{
$model->attributes=$_POST['Tuitiondata'];
if($model->save())
$this->redirect(array('view','id'=>$model->idtuitionData));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Tuitiondata');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Tuitiondata('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Tuitiondata']))
$model->attributes=$_GET['Tuitiondata'];
$this->render('admin',array(
'model'=>$model,
));
}
public function actionAjaxSearch()
{
//$keywordBulan=$_POST[''];
$model=new Tuitiondata('search');
$model3=new Datasiswa('search');
$model->unsetAttributes(); // clear any default values
if(isset($_POST['Tuitiondata']))
$model->attributes=$_POST['Tuitiondata'];
$this->render('advancesearchresult',array(
'model'=>$model,
'model3'=>$model3,
));
}
public function actionadvanceSearch()
{
$model=new Tuitiondata('search');
$model2=new Archiveddatatransaksi;
$modelDataSiswa=new Datasiswa('search');
$model->unsetAttributes(); // clear any default values
if(isset($_POST['Tuitiondata']))
$model->attributes=$_POST['Tuitiondata'];
$this->render('advancesearch',array(
'model'=>$model,
'model2'=>$model2,
'model3'=>$modelDataSiswa,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=Tuitiondata::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='tuitiondata-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
public function actionrekapMasterUnit($idUnit){
//Master Tagihan di Ambil dari DataSPPSiswa
$idUnit=$_GET['idUnit'];
$LevelKelasModel=new Levelkelas('search');
$LevelKelasKategoriModel=new Levelkelaskategori('search');
//$model->unsetAttributes(); // clear any default values
if(isset($_GET['Tuitiondata'])){
$model->attributes=$_GET['Tuitiondata'];
}
$tab_list=ComponentTabsTuitionData::gettabs($idUnit); //return value nya berupa array model //cek perbandingan nya dengan MenuSDActive/MenuSMPActive/MenuSMAActive model alur data mirip,
//print_r($tab_list)
$tabarray=array();
$i=1;
foreach ($tab_list as $tab_name){
$classTag=$tab_name->kelas->namaKelas;
$idClass=$tab_name->kelas->idLevelkelas;
$TuitionDataModel=new Tuitiondata('search');
$DataSppSiswa=new DataSPPsiswa('search');
//$DataSppSiswa=$DataSppSiswa->masterKelas($tab_name->kelas->idLevelkelas);
//$DataSPPSiswa->unsetAttributes();
$tabarray[$classTag]=array('id'=>$tab_name->kelas->namaKelas,
'content'=>$this->renderPartial('lapRekapContentWithTotal',array('model'=>$DataSppSiswa,'classId'=>$idClass,'pagination'=>false),TRUE,TRUE),//$tab_name->kelas->namaKelas
//$this->renderPartial('lapRekapContent',array('model'=>$DataSppSiswa),TRUE),
);
$i++;
}
$this->render('lapRekap',array(
//'model'=>$model,
'tabarray'=>$tabarray,
));
}
/*public function actionrekapSD($idBulan){
$model=new Tuitiondata('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Tuitiondata']))
$model->attributes=$_GET['Tuitiondata'];
$this->render('lapRekap',array(
'model'=>$model,
));
}
public function actionrekapSMP($idBulan){
$model=new Tuitiondata('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Tuitiondata']))
$model->attributes=$_GET['Tuitiondata'];
$this->render('lapRekap',array(
'model'=>$model,
));
}
public function actionrekapSMA($idBulan){
$model=new Tuitiondata('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Tuitiondata']))
$model->attributes=$_GET['Tuitiondata'];
$this->render('lapRekap',array(
'model'=>$model,
));
}
public function actionrekapAllBulanan(){
$model=new Tuitiondata('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Tuitiondata']))
$model->attributes=$_GET['Tuitiondata'];
$this->render('lapRekap',array(
//'model'=>$model,
));
}
public function actionrekapKelasBulanan($idBulan,$idKelas){
$model=new Tuitiondata('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Tuitiondata']))
$model->attributes=$_GET['Tuitiondata'];
$this->render('lapRekap',array(
'model'=>$model,
));
}
public function actionrekapKelasTahunan(){
$model=new Tuitiondata('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Tuitiondata']))
$model->attributes=$_GET['Tuitiondata'];
$this->render('lapRekap',array(
'model'=>$model,
));
}
public function actionrekapAllTahunan(){
$model=new Tuitiondata('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Tuitiondata']))
$model->attributes=$_GET['Tuitiondata'];
$this->render('lapRekap',array(
'model'=>$model,
));
}*/
/*action untuk menjalankan query SQL dan menggenerate data SPP*/
public function actionRunSQL()
{
/*lakukan generate data SQL,
* generate data hanya dapat dilakukan pertahun / persemester
*/
//if($id==='1'){
//$datasiswa = new Datasiswa;
//$dataSPPsiswa = new DataSPPsiswa;
//$tuitionbillcategory = new Tuitionbillcategory;
$thisYearLimit=date('Y'); //batas waktu generate
$MonthLimit='02'; //untuk production state diset ke Bulan juni atau bulan '06'
$generateLimitTime=$MonthLimit.'-'.$thisYearLimit;
if(date('m-Y')<$generateLimitTime){
$theString = "BATAS WAKTU!";
echo $theString;
}else{
$criteriaDatasiswa = new CDbCriteria;
$criteriaDatasiswa->select='*';
//$query1='';//untuk tahun pertama,
//$query2='';//untuk tahun kedua,
//$query3='';//untuk tahun ketiga,
$items = DataSPPsiswa::model()->findAll($criteriaDatasiswa); //mengambil model dan relasi dari dataSPPsiswa
foreach ($items as $item){
$spp=$item->NominalSPP;
$ekskul=$item->biayaekskul->nominal;
$ujian=$item->biayaujian->nominal;
$cambridge=$item->biayacambridge->nominal;
$totalTagihan=$spp+$ekskul+$ujian+$cambridge;
Yii::app()->db->createCommand() //proses ini sudah berhasil, hanya iterasi nya yang belum berjalan
->insert('tuitiondata',array(
'Datasiswa_idDatasiswa'=>$item->idDataSiswa,
'totalTagihan'=>$totalTagihan,
'idLevelKelas'=>$item->idlevelKelas
));
}
$theString = "BERHASIL!";
echo $theString;
}
//lakukan Operasi SQL untuk Generate Data disini, dan jangan lupa berikan return value;
//}
}
public function actionbayar($id)
{
if(isset($_GET['idDataSiswa'])){
$bulan=$_GET['bulan'];
$model=new Tuitiondata('search');
$model2=new Archiveddatatransaksi;
$modelDataSiswa=new Datasiswa('search');
//$model->unsetAttributes(); // clear any default values
//$modelDataSiswa->attributes=$_GET['datasiswa'];
$model=$this->loadModel($id);
$idDS=$_GET['idDataSiswa'];
$modelDataSiswa=Datasiswa::model()->findByPk($idDS);
$this->render('_form_pembayaran',array(
'model'=>$model,
'model2'=>$model2,
'model3'=>$modelDataSiswa,
'bulan'=>$bulan,
//'model'
//'layout'=>'layout2'
));
}if(isset($_POST['Archiveddatatransaksi'])){
$bulan=$_POST['bulan'];
$token=$_POST['token'];
$model=new Tuitiondata;
//$model=$model->findAllByPk($id);
$model=$this->loadModel($id);
//$model->
$model->attributes=$_POST['Tuitiondata'];
$model->setAttributes(array($bulan=>$token),true);
$model->save(false);
$model2=new Archiveddatatransaksi;
$model2->attributes=$_POST['Archiveddatatransaksi'];
$model2->setAttributes(array('idDataSiswa'=>'$model->DataSiswa_idDataSiswa'),true);
$model2->save(false); //seandainya database masih kosong maka dalam save() harus diberi bolean false karena berati validasinya gagal
$model->unsetAttributes();
$this->redirect(Yii::app()->createUrl('tuitiondata/admin'));
/*$this->render('admin',array(
'model'=>$model,
'model2'=>$model2,
//'model'
//'layout'=>'layout2'
));*/
}
}
/*Print related method*/
public function actionPrintReportMaster($idUnit,$classId){
$idUnit=$_GET['idUnit'];$classId=$_GET['classId'];
$TuitionDataModel=new Tuitiondata('search');
$DataSPPsiswa=new DataSPPsiswa;
//
//$model=new Datasiswa;
//$criteria = new CDbCriteria;
//$criteria->select = '*';
//$criteria->with='levelkelas';
//$criteria->distinct = TRUE;
//1-6 scope UNIT SD
//$criteria->condition = '`idlevelKelas` = '.$classId.'';
//$criteria->group='`namaKelas`'; //menggroup murid yang ada di dalam database berdasarkan kelasnya..
//$criteria->order='levelKelasName';
//$criteria->order = '`position` ASC';
//$DataSPPsiswa=$DataSPPsiswa->masterKelas($classId);
//$TuitionDataModel=$TuitionDataModel->with('datasiswa')->findByAttributes(array('DataSiswa_idDataSiswa')=>idDataSiswa);
//
$this->render('printMaster',array('model'=>$DataSPPsiswa,'classId'=>$classId,'pagination'=>false));
}
}
<file_sep><?php
/* @var $this TuitionbillcategoryController */
/* @var $model Tuitionbillcategory */
/* @var $form CActiveForm */
//$this->layout='flatLayout';
?>
<!--<div class="box round first">-->
<h5 style="padding-left:5px !important; padding-top:5px !important; padding-bottom:5px !important; margin-bottom: 0 !important; background-color: #8f8f8f; color: white;">Edit Kategori tagihan : <?php echo $model->billCategoryName; ?></h5>
<div class="form" style="padding:10px; background-color:white;">
<div class="block">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'tuitionbillcategory-form',
'enableAjaxValidation'=>false,
)); ?>
<h6>kolom dengan tanda <span class="required">*</span> wajib diisi.<h6>
<?php echo $form->errorSummary($model); ?>
<table class="form" style="">
<tr>
<td class="col1"><?php echo $form->labelEx($model,'billCategoryName'); ?></td>
<td class="col2"style="padding-bottom:0 !important;"><?php echo $form->textField($model,'billCategoryName',array('class'=>'mini','size'=>45,'maxlength'=>45)); ?></td>
<td class="col3"style="padding-bottom:0 !important;"><?php echo $form->error($model,'billCategoryName'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'nominal'); ?></td>
<td><?php echo $form->textField($model,'nominal',array('class'=>'mini')); ?></td>
<td><?php echo $form->error($model,'nominal'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'catatan'); ?></td>
<td><?php echo $form->textArea($model,'catatan',array('rows'=>6, 'cols'=>40)); ?></td>
<td><?php echo $form->error($model,'catatan'); ?></td>
</tr
<tr>
<td colspan="2">
<?php //echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save',array('class'=>'btn btn-blue')); ?>
<?php echo CHtml::htmlButton($model->isNewRecord ? 'Create' : 'Save',array('class'=>'btn btn-grey','style'=>'margin-right:10px','onClick'=>'submit();')); ?>
<?php echo CHtml::htmlButton('BATAL',array('class'=>'btn btn-red','style'=>'margin-right:10px','onClick'=>'window.location="'.$this->createUrl('popupAdmin').'";')); ?>
</td>
</tr>
</table>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<!--</div>--><file_sep><?php
$this->layout='forRenderPartial';
$idClass=$classId;
$this->widget('application.components.CGridViewWithTotals', array(
'id'=>'data-sppsiswa-grid',
'dataProvider'=>$model->masterKelas($classId),
//'filter'=>$model,
'columns'=>array(
//'idDataSiswa',
//'NoIndukSiswa',
array(
'header'=>'No Induk',
'value'=>'$data->NoIndukSiswa',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:center;',
),
//'footer'=>'test',
//'hasFooter'=>'true',
),
array(
'header'=>'Nama',
'value'=>'$data->NamaSiswa',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'600px',
'style'=>'text-align:left; font-size:12px;',
),
'footer'=>'TOTAL',
//'hasFooter'=>'true',
),
array(
'header'=>'US',
'value'=>'number_format($data->NominalSPP,"0",",",".");',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
'footer'=>number_format($model->getTotalsSPP($model->masterKelas($classId)->getKeys()),"0",",","."),
//'hasFooter'=>'true',
),
array(
'header'=>'Eks-Kur', //column header
'value'=> 'number_format($data->biayaekskul->nominal,"0",",",".");',//column name, php expression
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
'footer'=>number_format($model->getTotalsEksKur($model->masterKelas($classId)->getKeys()),"0",",","."),
//'hasFooter'=>'true',
),
array(
'header'=>'Ujian', //column header
'value'=> 'number_format($data->biayaujian->nominal,"0",",",".");',//column name, php expression
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
'footer'=>number_format($model->getTotalsUjian($model->masterKelas($classId)->getKeys()),"0",",","."),
//'hasFooter'=>'true',
),
array(
'header'=>'Cambridge', //column header
'value'=> 'number_format($data->biayacambridge->nominal,"0",",",".");',//column name, php expression
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
'footer'=>number_format($model->getTotalsCambridge($model->masterKelas($classId)->getKeys()),"0",",","."),
//'hasFooter'=>'true',
),
array(
'header'=>'TOTAL', //column header
'value'=>'number_format(($data->NominalSPP+$data->biayaekskul->nominal+$data->biayaujian->nominal+$data->biayacambridge->nominal),"0",",",".");;
',//column name, php expression
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
'footer'=>number_format(($model->getTotalsSPP($model->masterKelas($classId)->getKeys())+$model->getTotalsEksKur($model->masterKelas($classId)->getKeys())+$model->getTotalsUjian($model->masterKelas($classId)->getKeys())+$model->getTotalsCambridge($model->masterKelas($classId)->getKeys())),"0",",","."),
//'hasFooter'=>'true',
),
/*array(
'header'=>'Uang Ujian', //column header
'value'=> '$data->tuitionbillcategory->nominal',//column name, php expression
'type'=>'raw',
),*/
/*array(
'class'=>'CButtonColumn',
'template'=>'{view}{update}',
),*/
),
'summaryText' => 'Menampilkan {count} data yang ditemukan.',
'template'=>' {items} {summary} {pager}',
'emptyText'=>'Maaf Belum Ada Data yang diGenerate'
//'hasFooter'=>true,
));
echo CHtml::button('PRINT PREVIEW!',array('id'=>'printpreview','class'=>'btn btn-grey','data-fancybox-type'=>'iframe','style'=>'margin-right:10px','href'=>Yii::app()->createUrl('tuitiondata/PrintReportMaster',array('idUnit'=>'1','classId'=>$classId))));
?>
<file_sep><?php
/**
* This is the model class for table "levelkelas".
*
* The followings are the available columns in table 'levelkelas':
* @property integer $idLevelkelas
* @property string $namaKelas
* @property string $levelKelasName
* @property string $waliKelasID
*
* The followings are the available model relations:
* @property Matapelajaran[] $matapelajarans
*/
class Levelkelas extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Levelkelas the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'levelkelas';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('idLevelkelas, namaKelas', 'required'),
array('idLevelkelas', 'numerical', 'integerOnly'=>true),
array('namaKelas, levelKelasName, waliKelasID', 'length', 'max'=>45),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('idLevelkelas, namaKelas, levelKelasName, waliKelasID', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'matapelajarans' => array(self::HAS_MANY, 'Matapelajaran', 'levelKelas_idkelas'),
//'kelasUnit'=>array(self::BELONGS_TO,'Levelkelaskategori','idlevelKelas'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'idLevelkelas' => 'Id Levelkelas',
'namaKelas' => 'Nama Kelas',
'levelKelasName' => 'Level Kelas Name',
'waliKelasID' => 'Wali Kelas',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('idLevelkelas',$this->idLevelkelas);
$criteria->compare('namaKelas',$this->namaKelas,true);
$criteria->compare('levelKelasName',$this->levelKelasName,true);
$criteria->compare('waliKelasID',$this->waliKelasID,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}<file_sep><?php
/* @var $this PencarianController */
/* @var $model Pencarian */
$this->layout='layoutKeuangan';
//$model = new Pencarian;
?>
<?php
/*
* ini untuk dynamic tabs content
*/
//
$this->widget('zii.widgets.jui.CJuiTabs',array(
/*'tabs'=>array(
'StaticTab 1'=>'Content for tab 1',
'StaticTab 2'=>array('content'=>'Content for tab 2', 'id'=>'tab2'),
// panel 3 contains the content rendered by a partial view
'AjaxTab'=>array('ajax'=>Yii::app()->createUrl('tuitiondata/admin')),
),*/
'tabs'=>$tabarray,
// additional javascript options for the tabs plugin
'options'=>array(
'collapsible'=>true,
),
));
?>
<file_sep>var jQmin = jQuery.noConflict();
jQmin(document).ready(
function() {
/* This is basic - uses default settings */
jQmin("a#fancybox-trigger").fancybox();
/* Using custom settings */
jQmin("a#inline").fancybox({
//minWidth : 800,
//minHeight : 400,
//fitToView : true,
autoSize : true,
closeClick : true,
closeBtn : false,
openEffect : 'none',
closeEffect : 'none',
padding : 5
//margin : 5,
//wrapCSS : 'body{background-color:white;}table{margin:0 !important;}'
//overflow : 'hidden',
// scrolling : 'no'
});
jQmin("#printpreview").fancybox({
//minWidth : 800,
minHeight : 500,
fitToView : true,
width : 842,
height : 600,
//autoSize : true,
closeClick : true,
closeBtn : false,
openEffect : 'none',
closeEffect : 'none',
padding : 5,
wrapCSS : 'bgWhite'
//scrolling :
});
jQmin("#ajaxed").fancybox({
//minWidth : 800,
//minHeight : 500,
fitToView : true,
//width : 842,
//height : 'auto',
//autoHeight : true,
autoSize : true,
//closeClick : true,
closeBtn : false,
openEffect : 'none',
closeEffect : 'none',
padding : 5,
type : 'ajax',
dataType : 'html',
headers : { 'X-fancyBox': true },
tpl: {wrap : '<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>'},
//wrapCSS : '.element.style{height:auto !important;}'
//scrolling :
beforeShow: function() {
$('.fancybox-image')
.width($(window).width())
.height($(window).height());
},
onUpdate: function() {
$('.fancybox-image')
.width($(window).width())
.height($(window).height());
}
});
jQmin("#fittedFrame").fancybox({
minWidth : 400,
minHeight : 100,
fitToView : false,
width : 'auto',
height : 'auto',
//autoHeight : true,
autoSize : true,
autoResize : true,
scrolling : 'no',
//closeClick : true,
closeBtn : false,
openEffect : 'none',
closeEffect : 'none',
padding : 10,
helpers : {
overlay : {
css : { 'overlay' : 'hidden' }
}
}
});
jQmin("#fitwindow").fancybox({
minHeight : 150,
autoSize : true,
//closeClick : true,
//fitToView : true,
closeBtn : false,
openEffect : 'none',
closeEffect : 'none',
scrolling : 'no'
/*beforeShow: function() {
$('.fancybox-image')
.width($(window).width())
.height($(window).height());
},
onUpdate: function() {
$('.fancybox-image')
.width($(window).width())
.height($(window).height());
}*/
});
/* Apply fancybox to multiple items */
jQmin("a.group").fancybox({
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : false,
'showCloseButton' : false
});
});
function closeFancy(){
JQmin.fancybox.close();
}
//fancybox javascript function
//fancybox ajax function
//jQmin("#datasiswa-form").bind("submit", function() {
/*if (jQmin("#login_name").val().length < 1 || jQmin("#login_pass").val().length < 1) {
jQmin("#login_error").show();
jQmin.fancybox.resize();
return false;
}*/
/*jQmin.fancybox.showActivity();
jQmin.ajax({
type : "POST",
cache : false,
url : "datasiswa/updatewithajax",
data : jQmin(this).serializeArray(),//var data=$("#datasiswa-form").serialize();
error: function(data) { // if error occured
jQmin.fancybox('Error'+data);
//alert(data);
},
success: function(data) {
jQmin.fancybox(data);
}
});*/
//return false;
//});<file_sep><?php
/* @var $this DatasiswaController */
/* @var $model Datasiswa */
/*$this->breadcrumbs=array(
'Datasiswas'=>array('index'),
$model->idDataSiswa=>array('view','id'=>$model->NamaSiswa),
'Update',
);*/
$this->layout='flatLayout'; //nnt diganti flatLayout
/*$this->menu=array(
array('label'=>'List Datasiswa', 'url'=>array('index')),
array('label'=>'Create Datasiswa', 'url'=>array('create')),
array('label'=>'View Datasiswa', 'url'=>array('view', 'id'=>$model->idDataSiswa)),
array('label'=>'Manage Datasiswa', 'url'=>array('admin')),
);*/
?>
<p><b>Update Datasiswa <?php echo $model->NamaSiswa; ?></b></p>
<div id="ajaxAlert">this is popupupdate</div>
<!--<img src="<?php //echo Yii::app()->theme->baseUrl; ?>/blue/../img/btn-icons.png">-->
<?php echo $this->renderPartial('_form', array('model'=>$model)); ?><file_sep><?php
/*
* file daftar massal untuk prosedur pendaftaran
*
*/
$this->layout="forFancyloadedForm";
?>
<center><h6>Pilih Kelas dari file yang baru saja diupload</h6></center>
<center><img id="loading" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/ajaxfileupload/ajax-loader.gif" style="display:none; float: none !important;"></center>
<div class="form">
<div class="block">
<table class="form" >
<tr style='text-align:center;'><td>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'pilihKelas-form',
'enableAjaxValidation'=>false,
//'action'=>Yii::app()->createUrl('pendaftaran/xdaftarMassal2perKelas'),
'action'=>Yii::app()->createUrl('pendaftaran/xdaftarMassal2perKelas'),
'htmlOptions'=>array(
//'enctype'=>'multipart/form-data',
'style'=>'display:inline;',
//'onsubmit'=>"return false;",/* Disable normal form submit */
//'onkeypress'=>" if(event.keyCode == 13){ send(); } " /* Do ajax call when user presses enter key */
),
)
);
//echo CHtml::dropDownList('kelas','',$items);
?><h6>KELAS :</h6>
<?php
$criteria = new CDbCriteria;
$criteria->select = 'idLevelkelas,namaKelas';
echo CHtml::dropDownList('idLevelkelas','',CHtml::listData(Levelkelas::model()->findAll($criteria),'idLevelkelas','namaKelas'),array('id'=>'select'));?>
<?php echo CHtml::htmlButton('Convert',array('id'=>'iframe','data-fancybox-type'=>'iframe','class'=>'btn btn-blue','onclick'=>'send();'));
$this->endWidget(); ?>
</td></tr>
</table>
</div>
</div>
<script type="text/javascript">
/*CATATAN PENTING : SETIAP SCRIPT INCLUDE PADA JAVASCRIPT HARUS DIBERTI TAG CDATA! FORMAT SEPERTI DIBAWAH*/
//<![CDATA[
var $ = jQuery.noConflict();
function send()
{
var data=$("#pilihKelas-form").serialize();
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("Pendaftaran/xdaftarMassal2perKelas"); ?>',//Pencarian/admin?Datasiswa[NamaSiswa]=data&yt0=Search
data:data,
beforeSend:function(){
$('.form').hide();
$('#loading').show();
},
success:function(data){
$('#loading').hide();
document.getElementById('post-result').innerHTML=data;
//alert(data);
},
error: function(data) { // if error occured
//alert("msg");
//alert(data);
},
dataType:'html'
});
}
//]]>
</script>
<div id="post-result">
</div><file_sep><?php
/*properti ini milik tuition data
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
//Yii::app()->getClientScript()->registerScriptFile(Yii::app()->theme->baseUrl.'/blue/js/fancybox/jquery.fancybox-1.3.4.pack.js',CClientScript::POS_HEAD);
//Yii::app()->getClientScript()->registerCssFile(Yii::app()->theme->baseUrl.'/blue/js/fancybox/jquery.fancybox-1.3.4.css',CClientScript::POS_HEAD);
$this->layout='forFancyloadedForm';
?>
<script type="text/javascript">
$(document).ready(function(){$('#fancybox-grid-trigger').fancybox();});
</script>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'tuitiondata-grid',
'dataProvider'=>$model->search(),
//'afterAjaxUpdate'=>"function(id,data){ $('a#fancybox-trigger').fancybox(); }",
//'filter'=>$model,
'columns'=>array(
//'idtuitionData',
array(
'header'=>'NamaSiswa',
'value'=>'$data->datasiswa->NamaSiswa',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'170px',
'style'=>'text-align:left; font-size:12px;',
),
),
array(
'header'=>'Tagihan Total',
'value'=>'number_format($data->totalTagihan,"0",",",".");',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
),
array(
'header'=>'Jan',
'value'=>'(!empty($data->januari))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=januari&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
//'linkHtmlOptions'=>array('id'=>'fancybox-trigger','class'=>'iframe','style'=>'color:red;'),
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'feb',
'value'=>'(!empty($data->februari))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=februari&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'mar',
'value'=>'(!empty($data->maret))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=maret&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'apr',
'value'=>'(!empty($data->april))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=april&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'mei',
'value'=>'(!empty($data->mei))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=mei&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'jun',
'value'=>'(!empty($data->juni))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=juni&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'jul',
'value'=>'(!empty($data->juli))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=juli&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'agu',
'value'=>'(!empty($data->agustus))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=agustus&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'sep',
'value'=>'(!empty($data->september))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=september&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'okt',
'value'=>'(!empty($data->oktober))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=oktober&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'nov',
'value'=>'(!empty($data->november))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=november&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'des',
'value'=>'(!empty($data->desember))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=desember&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'class'=>'CButtonColumn',
),
),
'emptyText' => '<div class="message info" id="ProsesdataSPP">
<center>
<h5> DATA TIDAK DITEMUKAN </h5>
</center>
</div>',
'summaryText' => 'Menampilkan {start}-{end} dari {count} data.'
)); ?>
<file_sep><?php
/* @var $this TuitiondataController */
/* @var $model Tuitiondata */
$this->breadcrumbs=array(
'Data Tagihan SPP bulanan Siswa'=>array('index'),
);
$this->menu=array(
//array('label'=>'List Tuitiondata', 'url'=>array('index')),
//array('label'=>'Create Tuitiondata', 'url'=>array('create')),
//array('label'=>'Create Tuitiondata', 'url'=>array('create')),
array('label'=>'Generate Tagihan SPP', 'url'=>array('admin')),
array('label'=>'Pencarian', 'url'=>array('advancesearch')),
);
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$.fn.yiiGridView.update('tuitiondata-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<p><b>Daftar Tagihan Siswa</b></p>
<p>
berikut daftar tagihan semua siswa dan semua bulan yang belum terbayar. untuk melakukan pencarian custom atas siswa, data siswa,
tagihan siswa silahkan gunakan fasilitas menu di samping.<br>
<b>Hal berikut perlu diperhatikan sebelum generate data tagihan SPP </b>:
<ol>
<li>Siswa baru harus sudah diinput terlebih dahulu.</li>
<li>Siswa yang naik sudah naik kelas, maka data siswa sudah harus diubah terlebih dahulu (proses naik).</li>
<li>Generate Data hanya dapat dilakukan dibulan Juni setiap tahun ajaran baru, dengan melihat faktor no.1 dan 2.</li>
</ol>
</p>
<!--<p>
Gunakan Tombol dibawah untuk me-generate laporan rekapan :<br><br>
<?php
echo CHtml::button('MASTER REKAP BULANAN',array('class'=>'btn btn-grey','style'=>'margin-right:10px','onClick'=>'location.href="'.Yii::app()->createUrl('tuitiondata/rekapAllBulanan').'"'));
echo CHtml::button('MASTER REKAP SD',array('class'=>'btn btn-grey','style'=>'margin-right:10px','onClick'=>'location.href="'.Yii::app()->createUrl('tuitiondata/rekapMasterUnit',array('idUnit'=>'1')).'"'));
echo CHtml::button('MASTER REKAP TAHUNAN',array('class'=>'btn btn-grey','style'=>'margin-right:10px'));
echo CHtml::button('MASTER REKAP SMP',array('class'=>'btn btn-grey','style'=>'margin-right:10px'));
echo CHtml::button('MASTER REKAP SMA',array('class'=>'btn btn-grey','style'=>'margin-right:10px'));
echo CHtml::button('REKAP PERKELAS',array('class'=>'btn btn-grey','style'=>'margin-right:10px'));
?>
</p>-->
<p><?php echo "Klik Disini Untuk Mencari : ".CHtml::link('[Klik Disini]','#',array('class'=>'search-button')); ?></p>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'tuitiondata-grid',
'dataProvider'=>$model->search(),
//'filter'=>$model,
'columns'=>array(
//'idtuitionData',
array(
'header'=>'NamaSiswa',
'value'=>'$data->datasiswa->NamaSiswa',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'170px',
'style'=>'text-align:left; font-size:12px;',
),
),
array(
'header'=>'Total Uang Sekolah',
'value'=>'number_format($data->totalTagihan,"0",",",".");',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
),
array(
'header'=>'Jan',
'value'=>'(!empty($data->januari))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=januari&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'id'=>'inline',
'data-fancybox-type'=>'iframe',
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'feb',
'value'=>'(!empty($data->februari))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=februari&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'mar',
'value'=>'(!empty($data->maret))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=maret&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'apr',
'value'=>'(!empty($data->april))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=april&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:right; font-size:12px;',
),
),
array(
'header'=>'mei',
'value'=>'(!empty($data->mei))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=mei&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'jun',
'value'=>'(!empty($data->juni))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=juni&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'jul',
'value'=>'(!empty($data->juli))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=juli&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'agu',
'value'=>'(!empty($data->agustus))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=agustus&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'sep',
'value'=>'(!empty($data->september))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=september&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'okt',
'value'=>'(!empty($data->oktober))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=oktober&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'nov',
'value'=>'(!empty($data->november))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=november&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
array(
'header'=>'des',
'value'=>'(!empty($data->desember))? "<a href=# style=color:blue !important;>[lunas]</a>" : "<a id=inline data-fancybox-type=iframe href=bayar/$data->idtuitionData?idDataSiswa=$data->DataSiswa_idDataSiswa&bulan=desember&bayar=formulir style=color:red !important;>[bayar]</a>";',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'50px',
'style'=>'text-align:center; font-size:12px;',
),
),
/*array(
'class'=>'CButtonColumn',
),*/
),
'emptyText' => '<div class="message info" id="ProsesdataSPP">
<center>
<h5> INFORMASI TAGIHAN SPP </h5>
<p>Maaf, Data Tagihan Belum Di - GENERATE,
Generate data hanya dapat dilakukan pada bulan Juni, atau setiap awal tahun ajaran baru <br>
</p>
'.
/*CHtml::ajaxButton('Generate Tagihan SPP',Yii::app()->createUrl('Tuitiondatacontroller/actionRunSQL'),array(
'success'=>"alert('success')",
'update'=>"alert('success')",
'replace'=>"alert('success')"
),array(
'class'=>'btn',
'style'=>'margin:10px;',
))*/
CHtml::Button('Generate Tagihan SPP',array(
'class'=>'btn',
'style'=>'margin:10px;',
'onclick'=>"doGeneration();",
))
.'
</center>
</div>',
'summaryText' => 'Menampilkan {start}-{end} dari {count} data. <br>',
'template'=>' {items} {summary} {pager}'
)); ?>
<script type="text/javascript">
function doGeneration()
{
var data=$("#ProsesdataSPP").serialize();
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("Tuitiondata/RunSQL"); ?>',//Pencarian/admin?Datasiswa[NamaSiswa]=data&yt0=Search
data:data,
success:function(data){
//document.getElementById('search-result').innerHTML=data;
alert(data);
location.reload();
},
error: function(data) { // if error occured
alert("Error occured.please try again");
//alert(data);
},
dataType:'html'
});
}
</script><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class RequireLogin extends CBehavior
{
public function attach($owner)
{
$owner->attachEventHandler('onBeginRequest', array($this, 'handleBeginRequest'));
}
public function handleBeginRequest($event)
{
//jika ingin menambahkan link yang boleh dibuka tanpa login tinggal menambahkannya di dalam arraynya
if (Yii::app()->user->isGuest && isset($_GET['r']) && !in_array($_GET['r'],array('site/login','site/contact','site/index','site/captcha'))) {
Yii::app()->user->loginRequired();
}/*else{
Yii::app()->user->logout();
}*/
}
}
?>
<file_sep><?php
/*
* file daftar massal untuk prosedur pendaftaran
*
*/
$this->layout="forFancyloadedForm";
?>
<div class="form">
<div class="block">
<center><h6>silahkan upload file microsoft excel yang berisi data siswa baru</h6></center>
<table class="form">
<tr style='text-align:center;'>
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'excelPendaftaran-form',
'enableAjaxValidation'=>false,
'htmlOptions'=>array(
'enctype'=>'multipart/form-data',
'style'=>'display:inline;',
//'onsubmit'=>"return false;",/* Disable normal form submit */
//'onkeypress'=>" if(event.keyCode == 13){ send(); } " /* Do ajax call when user presses enter key */
),
)
);
?>
<td><b>Pilih File :</b></td>
<td><?php echo $form->fileField($model,'filee',array('size'=>60,'maxlength'=>200)); ?>
<?php echo CHtml::htmlButton('Masukkan!',array('class'=>'btn btn-blue','onclick'=>'submit();'));
?></td>
</tr>
</table>
</div>
</div>
<script type="text/javascript">
function send()
{
var data=$("#excelPendaftaran-form").serialize();
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("Pendaftaran/daftarMassal"); ?>',//Pencarian/admin?Datasiswa[NamaSiswa]=data&yt0=Search
data:data,
contentType:attr( "enctype", "multipart/form-data" ),
success:function(data){
//document.getElementById('search-result').innerHTML=data;
alert('its using ajax');
},
error: function(data) { // if error occured
alert("Error occured.please try again");
//alert(data);
},
dataType:'html'
});
}
</script>
<?php $this->endWidget(); ?><file_sep><?php /* @var $this Controller */ ?>
<?php $this->beginContent('//layouts/main'); ?>
<div class="grid_12">
<?php
$this->widget('zii.widgets.CMenu', array(
'htmlOptions'=>array('class'=>'nav main'),
'items'=>array(
// Important: you need to specify url as 'controller/action',
// not just as 'controller' even if default acion is used.
array('label'=>'Home', 'url'=>array('site/index')),
array('label'=>'Keuangan','url'=>array('site/page','view'=>'administrasiKeuangan')),
array('label'=>'Perpustakaan','url'=>array('#')),
array('label'=>'Rumah Tangga','url'=>array('#')),
array('label'=>'IT','url'=>array('#')),
array('label'=>'SD','url'=>array('#')),
array('label'=>'SMP','url'=>array('#')),
array('label'=>'SMA','url'=>array('#')),
array('label'=>'Administrasi Umum','url'=>array('site/page','view'=>'administrasiUmum')),
array('label'=>'About', 'url'=>array('site/page','view'=>'about')),
array('label'=>'Contact', 'url'=>array('site/contact')),
array('label'=>'User Manager','url'=>array('/userGroups')),
array('label'=>'Login', 'url'=>array('/userGroups'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/userGroups/user/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
));
?>
</div>
<!-- mainmenu -->
<!-- navigasi end -->
<!--<div class="grid_12">
<div class="box round first">
</div>
</div>-->
<div class="grid_2">
<div class="box sidemenu">
<div class="block" id="section-menu">
<?php
/*$this->beginWidget('zii.widgets.CPortlet', array(
'title'=>'Operations',
));*/
$this->beginWidget('zii.widgets.CMenu', array(
'items'=>$this->menu,
'htmlOptions'=>array('class'=>'section menu'),
));
$this->endWidget();
$this->widget('application.components.ClassesMenuActive');
?>
</div><!-- sidebar -->
</div>
</div>
<?php echo $content; ?>
<div id="footer">
Copyright © <?php echo date('Y'); ?> Bellarminus IS by <EMAIL><br/>
</div><!-- footer -->
<?php $this->endContent(); ?><file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class FilebrowserController extends Controller{
public $layout='//layouts/fileBrowserMain';
/**
* @return array action filters
*/
//public $tempfilename;
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
//'postOnly + delete', // we only allow deletion via POST request
//'indexConnector' => "application.extensions.ezzeelfinder.ElFinderConnectorAction",
);
}
public function accessRules()
{
return array(
/*array('deny', // deny all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('admin','delete','create','update','elfinderC'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete','create','update','elfinderC'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),*/
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('ElfinderC','ElfinderCConnector'),
'users'=>array('@'),
//'expression'=> "Yii::app()->user->isAdmin === true",
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
public function actions()
{
return array(
'ElfinderCConnector' => "application.extensions.ezzeelfinder.ElFinderConnectorAction",
);
}
public function actionElfinderC(){
$this->render('fileUploader');
}
}
/*23 Mei 2013
* masalah terletak pada penamaan file dari index.php, seharusnya bukan index.php, supaya bisa diatur melalui accessRule PBAC
*/
?>
<file_sep><?php
//index untuk view
?>
<div class="grid-center">
<h5 class="welcome-word">Selamat datang di sistem informasi sekolah <NAME></h5>
<div class="wrapper">
<?php echo $this->renderPartial('_search',array('model'=>$model),array('class'=>'GlobalsearchField')); ?>
</div>
</div>
<file_sep><?php
/*
* file daftar massal untuk prosedur pendaftaran
*
*/
$this->layout="forFancyloadedForm";
?>
<center><h6>silahkan upload file microsoft excel yang berisi data siswa baru</h6></center>
<center><img id="loading" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/ajaxfileupload/ajax-loader.gif" style="display:none; float: none !important;"></center>
<center><h6><?php echo CHtml::link('untuk membuka klik tulisan ini',Yii::app()->createUrl('datasiswa/admin'),array('id'=>'finishState','style'=>'display:none;'));?></h6></center>
<div class="form">
<div class="block">
<table class="form" >
<tr style='text-align:center;'>
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'excelPendaftaran-form',
'enableAjaxValidation'=>false,
//'action'=>Yii::app()->createUrl('pendaftaran/xDaftarMassal2'),
'htmlOptions'=>array(
'enctype'=>'multipart/form-data',
'style'=>'display:inline;',
//'onsubmit'=>"return false;",/* Disable normal form submit */
//'onkeypress'=>" if(event.keyCode == 13){ send(); } " /* Do ajax call when user presses enter key */
),
)
);
?>
<td><b>Pilih File :</b></td></tr>
<tr style="text-align: center;"><td>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" /><?php echo $form->fileField($model,'',array('id'=>'fileToUpload','class'=>'input','name'=>'fileToUpload','style'=>'margin:5px;')); ?>
<div id="submitbutton"><?php echo CHtml::htmlButton('Masukkan!',array('class'=>'btn btn-blue','onclick'=>'return ajaxFileUpload();'));
?></div></td>
<?php $this->endWidget(); ?>
</tr>
</table>
</div>
</div>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/ajaxfileupload/jquery.js"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/ajaxfileupload/ajaxfileupload.js"></script>
<script type="text/javascript">
/*CATATAN PENTING : SETIAP SCRIPT INCLUDE PADA JAVASCRIPT HARUS DIBERTI TAG CDATA! FORMAT SEPERTI DIBAWAH*/
//<![CDATA[
var afu = jQuery.noConflict();
function ajaxFileUpload() {
afu("#loading")
.ajaxStart(function(){
afu('.form').hide();
afu(this).show();
})
.ajaxComplete(function(){
afu(this).hide();
afu('.form').show();
});
//can perform client side field required checking for "fileToUpload" field
afu.ajaxFileUpload(
{
url:'<?php echo Yii::app()->createAbsoluteUrl('pendaftaran/xdaftarMassal2');?>',
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json',
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
//alert(data.error);
}else
{
//alert(data.msg); // returns location of uploaded file
}
}
},
error: function (data, status, e)
{
alert(e);
}
}
)
return false;
}
//]]>
</script><file_sep><?php
/**
* This is the model class for table "datasiswa".
*
* The followings are the available columns in table 'datasiswa':
* @property integer $idDataSiswa
* @property integer $NoIndukSiswa
* @property string $NamaSiswa
* @property string $namaOrtuAyah
* @property string $namaOrtuIbu
* @property string $alamatTinggal
* @property string $tempatLahir
* @property string $tanggalLahir
* @property string $poinValue
* @property string $kotaAsal
* @property string $tahunAjaranMasuk
* @property string $nomorHp
* @property string $contactDarurat
* @property integer $NominalSPP
* @property integer $eksKur
* @property integer $uangUjian
* @property integer $uangCambridge
*
* The followings are the available model relations:
* @property Dataraportsemesteran[] $dataraportsemesterans
* @property Detailnilaisiswa[] $detailnilaisiswas
*/
class DataSPPsiswa extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return DataSPPsiswa the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'datasiswa';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('NamaSiswa', 'required'),
array('NoIndukSiswa, NominalSPP, eksKur, uangUjian, uangCambridge', 'numerical', 'integerOnly'=>true),
array('NamaSiswa', 'length', 'max'=>70),
array('namaOrtuAyah, namaOrtuIbu, alamatTinggal, tempatLahir, tanggalLahir, poinValue, kotaAsal, nomorHp, contactDarurat', 'length', 'max'=>45),
array('tahunAjaranMasuk', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('idDataSiswa, NoIndukSiswa, NamaSiswa, namaOrtuAyah, namaOrtuIbu, alamatTinggal, tempatLahir, tanggalLahir, poinValue, kotaAsal, tahunAjaranMasuk, nomorHp, contactDarurat, NominalSPP, eksKur, uangUjian, uangCambridge', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'dataraportsemesterans' => array(self::HAS_MANY, 'Dataraportsemesteran', 'DataSiswa_idDataSiswa'),
'detailnilaisiswas' => array(self::HAS_MANY, 'Detailnilaisiswa', 'DataSiswa_idDataSiswa'),
'biayaekskul'=>array(self::BELONGS_TO,'Tuitionbillcategory','eksKur'),
'biayaujian'=>array(self::BELONGS_TO,'Tuitionbillcategory','uangUjian'),
'biayacambridge'=>array(self::BELONGS_TO,'Tuitionbillcategory','uangCambridge'),
'kelas'=>array(self::BELONGS_TO,'Levelkelas','idlevelKelas'),
//'uangUjian'=>array(self::BELONGS_TO,'Tuitionbillcategory','tuitionbillcodeid'),
//'uangCambridge'=>array(self::BELONGS_TO,'Tuitionbillcategory','tuitionbillcodeid'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
//'idDataSiswa' => 'Id Data Siswa',
'NoIndukSiswa' => 'No Induk Siswa',
'NamaSiswa' => 'Nama Siswa',
//'namaOrtuAyah' => 'Nama Ortu Ayah',
//'namaOrtuIbu' => 'Nama Ortu Ibu',
//'alamatTinggal' => 'Alamat Tinggal',
//'tempatLahir' => 'Tempat Lahir',
//'tanggalLahir' => 'Tanggal Lahir',
//'poinValue' => 'Poin Value',
//'kotaAsal' => 'Kota Asal',
'tahunAjaranMasuk' => 'Tahun Ajaran Masuk',
//'nomorHp' => 'Nomor Hp',
//'contactDarurat' => 'Contact Darurat',
'NominalSPP' => 'Nominal Spp',
'eksKur' => 'Eks Kur',
'uangUjian' => 'Uang Ujian',
'uangCambridge' => 'Uang Cambridge',
'nominal' => 'nominal',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('idDataSiswa',$this->idDataSiswa);
$criteria->compare('NoIndukSiswa',$this->NoIndukSiswa);
$criteria->compare('NamaSiswa',$this->NamaSiswa,true);
$criteria->compare('namaOrtuAyah',$this->namaOrtuAyah,true);
$criteria->compare('namaOrtuIbu',$this->namaOrtuIbu,true);
$criteria->compare('alamatTinggal',$this->alamatTinggal,true);
$criteria->compare('tempatLahir',$this->tempatLahir,true);
$criteria->compare('tanggalLahir',$this->tanggalLahir,true);
$criteria->compare('poinValue',$this->poinValue,true);
$criteria->compare('kotaAsal',$this->kotaAsal,true);
$criteria->compare('tahunAjaranMasuk',$this->tahunAjaranMasuk,true);
$criteria->compare('nomorHp',$this->nomorHp,true);
$criteria->compare('contactDarurat',$this->contactDarurat,true);
$criteria->compare('NominalSPP',$this->NominalSPP);
$criteria->compare('eksKur',$this->eksKur);
$criteria->compare('uangUjian',$this->uangUjian);
$criteria->compare('uangCambridge',$this->uangCambridge);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public function joinViewTables(){
$criteria=new CDbCriteria;
$criteria->alias = 'jtb';
//$criteria->together('');
//$criteria->condition
$criteria->compare('idDataSiswa',$this->idDataSiswa);
$criteria->compare('NoIndukSiswa',$this->NoIndukSiswa);
$criteria->compare('NamaSiswa',$this->NamaSiswa,true);
$criteria->compare('NominalSPP',$this->NominalSPP);
$criteria->compare('eksKur',$this->eksKur);
$criteria->compare('uangUjian',$this->uangUjian);
$criteria->compare('uangCambridge',$this->uangCambridge);
//$criteria->compare('nominal', Tuitionbillcategory::model()->nominal);
//$criteria->join= 'INNER JOIN tuitionbillcategory AS tbc ON jtb.ekskur=tbc.Tuitionbillcodeid';
/*$criteria2=new $criteria;
//$criteria2->alias = 'jtb2';
//$criteria2->compare('idDataSiswa',$this->idDataSiswa);
//$criteria2->compare('NoIndukSiswa',$this->NoIndukSiswa);
//$criteria2->compare('NamaSiswa',$this->NamaSiswa,true);
//$criteria2->compare('NominalSPP',$this->NominalSPP);
//$criteria2->compare('eksKur',$this->eksKur);
//$criteria2->compare('uangUjian',$this->uangUjian);
//$criteria2->compare('uangCambridge',$this->uangCambridge);
//$criteria2->compare('nominal', Tuitionbillcategory::model()->nominal);
//$criteria2->join= 'INNER JOIN tuitionbillcategory AS tbc ON jtb2.uangUjian=tbc.Tuitionbillcodeid';*/
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public static function jumlahTotalBiaya()
{
$totalBiaya = $this->getRelated('tuitionbillcategory'); // fetches array of ProjectCost models, which you can iterate over
$nominalTotal = 0;
foreach($totalBiaya as $tuitionbillcategory)
{
$nominalTotal += $tuitionbillcategory->Percent * $tuitionbillcategory->getRelated('eksKur')->nominal;
}
return $nominalTotal;
}
public function masterKelas($id){
$criteria = new CDbCriteria;
$criteria->condition='`idlevelKelas`='.$id.'';
$criteria->compare('idDataSiswa',$this->idDataSiswa);
//$criteria->compare('NoIndukSiswa',$this->NoIndukSiswa);
//$criteria->compare('NamaSiswa',$this->NamaSiswa,true);
//$criteria->compare('namaOrtuAyah',$this->namaOrtuAyah,true);
//$criteria->compare('namaOrtuIbu',$this->namaOrtuIbu,true);
//$criteria->compare('alamatTinggal',$this->alamatTinggal,true);
//$criteria->compare('tempatLahir',$this->tempatLahir,true);
//$criteria->compare('tanggalLahir',$this->tanggalLahir,true);
//$criteria->compare('poinValue',$this->poinValue,true);
//$criteria->compare('kotaAsal',$this->kotaAsal,true);
//$criteria->compare('tahunAjaranMasuk',$this->tahunAjaranMasuk,true);
//$criteria->compare('nomorHp',$this->nomorHp,true);
//$criteria->compare('contactDarurat',$this->contactDarurat,true);
//$criteria->compare('NominalSPP',$this->NominalSPP);
//$criteria->compare('eksKur',$this->eksKur);
//$criteria->compare('uangUjian',$this->uangUjian);
//$criteria->compare('uangCambridge',$this->uangCambridge);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>false,
'keys'=>$this->idDataSiswa,
));
}
public function getTotalsSPP($ids)
{
$ids2 = implode(',',$ids);
$connection=Yii::app()->db;
$command=$connection->createCommand("SELECT SUM(d.nominalSPP)FROM `datasiswa` d where d.idDataSiswa in ($ids2)");
$amount = $command->queryScalar();
return $amount;
//$ids2=serialize($ids);
//return $ids2;
}
public function getTotalsEksKur($ids)
{
$ids2 = implode(',',$ids);
$connection=Yii::app()->db;
$command=$connection->createCommand("SELECT SUM(t.nominal)FROM `tuitionbillcategory` t, `datasiswa` d where d.idDataSiswa in ($ids2) and d.eksKur=t.tuitionbillcodeid");
$amount = $command->queryScalar();
return $amount;
//$ids2=serialize($ids);
//return $ids2;
}
public function getTotalsUjian($ids)
{
$ids2 = implode(',',$ids);
$connection=Yii::app()->db;
$command=$connection->createCommand("SELECT SUM(t.nominal)FROM `tuitionbillcategory` t, `datasiswa` d where d.idDataSiswa in ($ids2) and d.uangUjian=t.tuitionbillcodeid");
$amount = $command->queryScalar();
return $amount;
//$ids2=serialize($ids);
//return $ids2;
}
public function getTotalsCambridge($ids)
{
$ids2 = implode(',',$ids);
$connection=Yii::app()->db;
$command=$connection->createCommand("SELECT SUM(t.nominal)FROM `tuitionbillcategory` t, `datasiswa` d where d.idDataSiswa in ($ids2) and d.uangCambridge=t.tuitionbillcodeid");
$amount = $command->queryScalar();
return $amount;
//$ids2=serialize($ids);
//return $ids2;
}
}<file_sep><?php
/**
* This is the model class for table "datatransaksispp".
*
* The followings are the available columns in table 'datatransaksispp':
* @property integer $id
* @property integer $idDatasiswa
* @property integer $nominalpembayaran
* @property string $tokentransaksi
* @property string $tanggal
*/
class Datatransaksispp extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Datatransaksispp the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'datatransaksispp';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('id', 'required'),
array('id, idDatasiswa, nominalpembayaran', 'numerical', 'integerOnly'=>true),
array('tokentransaksi, tanggal', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, idDatasiswa, nominalpembayaran, tokentransaksi, tanggal', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'idDatasiswa' => 'Id Datasiswa',
'nominalpembayaran' => 'Nominalpembayaran',
'tokentransaksi' => 'Tokentransaksi',
'tanggal' => 'Tanggal',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('idDatasiswa',$this->idDatasiswa);
$criteria->compare('nominalpembayaran',$this->nominalpembayaran);
$criteria->compare('tokentransaksi',$this->tokentransaksi,true);
$criteria->compare('tanggal',$this->tanggal,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}<file_sep><?php
class SystemTahunajaranController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='forFancyloadedForm';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('admin','delete','create','update','UpdateSemesterActive','CreateThnAjaran','TahunAjaranProcedure','SubmitTahunAjaranBaru'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete','create','update','UpdateSemesterActive','CreateThnAjaran','TahunAjaranProcedure','SubmitTahunAjaranBaru'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new SystemTahunajaran;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['SystemTahunajaran']))
{
$model->attributes=$_POST['SystemTahunajaran'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
public function actionCreateThnAjaran(){
$model=new SystemTahunajaran;
$CurSms=$this->checkCurrentSemesterIn();
switch ($CurSms) {
case '2':$this->render('_formAddThnAjar',array(
'model'=>$model,
));
break; //1 = untuk bulan Juni/Juli, apabila tombol Edit diTekan
case '1':$this->render('_formSetSemester',array(
'model'=>$model,
));
break; //1 = untuk bulan Des/Januari, apabila tombol Edit diTekan
default:$drDb = Yii::app()->db->createCommand()
->select('thnAjaran')
->from('system_tahunajaran')
->where('status_aktif = 1')
->queryScalar();
$drDbPiece=explode(':',$drDb);
$thnAjaran=implode('/', $drDbPiece);
echo "<div id=\"loaderPosition\" style=\"width:100%; text-align: center;\"></div>
<div id=\"setingContainer\" style=\"text-align: justify;\">
<p style=\"margin:0;\" id=\"removeThisText\">Tahun Ajaran yang sedang aktif pada saat ini adalah :
<b>".$thnAjaran."</b></p></div>";
echo "Maaf penggantian Semester hanya dapat dilakukan pada bulan Des/Jan, Sedangkan set Tahun Ajaran Baru pada bulan Juni/Juli";
break;
}
}
public function actionTahunAjaranProcedure(){
//$Perintah=$_POST['perintah'];
/*
* $Perintah = adalah perintah dari user yang diminta oleh user;
* $PerintahTerautentikasi = adalah perintah yang sudah dicek validitas Bulan yang sedang berjalan,
* untuk menentukan apakah perintah yang akan dijalankan, boleh dilaksanakan pada bulan itu
*/
$model=new SystemTahunajaran;
$CurSms=$this->checkCurrentSemesterIn();
if(!isset($_POST['perintah'])&&$CurSms===1){
$PerintahTerautentikasi=4;//default view
}elseif(!isset($_POST['perintah'])&&$CurSms===2){
$PerintahTerautentikasi=3;
}elseif(($_POST['perintah']=='edit')&&($CurSms===2)){
$PerintahTerautentikasi=2; //value 1 = ada di semester 2 masuk tahun ajaran baru -> render formAddThnAjar
}elseif(($_POST['perintah']=='edit')&&($CurSms===1)){
$PerintahTerautentikasi=1; //value 2 = ada di semester satu masuk ke semester dua -> render formsetsemester
}
switch ($PerintahTerautentikasi) {
case '1':$this->render('_formAddThnAjar',array(
'model'=>$model,
));//edit -> Create tahun ajaran baru
break;
case '2':$this->render('_formSetSemester',array(
'model'=>$model,
));//edit Tahun Ajaran -> Set Semester
break;
case '3':$this->renderText('<h5><p style="text-align:center;">Tahun Ajaran Aktif : '.Yii::app()->session['thnAjaran'].', Maaf penggantian Semester hanya dapat dilakukan pada bulan Des/Jan, Sedangkan set Tahun Ajaran Baru pada bulan Juni/Juli <br>'.
CHtml::AjaxSubmitButton('edit',Yii::app()->createUrl('systemTahunajaran/TahunAjaranProcedure'),
array(
'type'=>'POST',
'dataType'=>'html',
'data'=>'perintah=edit',//this one
'beforeSend' => 'function(){
$("#setingContainer").hide();}',
'update'=>'#iframe-insider',
'complete' => 'function(){
$("#setingContainer").remove();
var current_height = document.body.offsetHeight;
var current_width = document.body.offsetWidth;
parent.$(".fancybox-skin").height(current_height + 30);
parent.$(".fancybox-skin").width(current_width + 30);
parent.$(".fancybox-inner").height(current_height + 30);
parent.$("#fancybox-outer").width(current_width + 30);
parent.$("#fancybox-wrap").width(current_width + 30);
parent.$("#fancybox-content").width(current_width + 30);
parent.$(".fancybox-inner").width(current_width + 30);
//parent.$.fancybox.reposition();
}',
),
array('id'=>'perintah','class'=>'btn-custom','name'=>'perintah')
).'</p></h5>');
break;
case '4':$this->renderText('<div id=\"setingContainer\" style=\"text-align: justify;\"><h5><p style="text-align:center;">Tahun Ajaran Aktif : '.$thnAjaran.', Maaf penggantian Semester hanya dapat dilakukan pada bulan Des/Jan, Sedangkan set Tahun Ajaran Baru pada bulan Juni/Juli <br> <a href=#>EDIT Perintah : 2 _formSetSemester</a></p></h5></div>');
break;
default:$this->renderText("<div id=\"loaderPosition\" style=\"width:100%; text-align: center;\"></div>
<div id=\"setingContainer\" style=\"text-align: justify;\">
<p style=\"margin:0;\" id=\"removeThisText\">Tahun Ajaran yang sedang aktif pada saat ini adalah :
<b>".$thnAjaran."</b></p></div>");
break;
}
}
public function actionSubmitTahunAjaranBaru(){
$model=new SystemTahunajaran;
$thnAwal=$_POST['tahunAwal'];$thnPenutup=$_POST['tahunPenutup'];
$thnAjaran= $thnAwal.':'.$thnPenutup;
$semester=1;
for ($semester = 1; $semester <= 2 ; $semester++) {
$user = Yii::app()->db->createCommand()
->insert('system_tahunajaran',array('thnAjaran'=>$thnAjaran,'semester'=>$semester));
}
$this->render('_formSetSemester',array(
'model'=>$model,
'thnAjaran'=>$thnAjaran,
));
//return $user;
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['SystemTahunajaran']))
{
$model->attributes=$_POST['SystemTahunajaran'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
public function actionUpdateSemesterActive(){
$model=new SystemTahunajaran;
$semesterTerpilih=$_POST['semesterGroup'];
if(isset($semesterTerpilih)){
}
$this->renderPartial('_form',array(
'model'=>$model,
));
} //load form secara ajax
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('SystemTahunajaran');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new SystemTahunajaran('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['SystemTahunajaran']))
$model->attributes=$_GET['SystemTahunajaran'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=SystemTahunajaran::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='system-tahunajaran-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
public function checkCurrentSemesterIn() {
$month=date('m');
if(1<=$month&&$month<=2){
$CurrentSemester=1; //ada di semester satu masuk ke semester dua -> render formsetsemester
}
if(6<=$month&&$month<=7){
$CurrentSemester=2; //ada di semester 2 masuk tahun ajaran baru -> render formAddThnAjar
}
else{
$CurrentSemester=3;
}
return $CurrentSemester;
}
}
<file_sep><?php /* @var $this Controller */ ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/reset.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/text.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/grid.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/layout.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/nav.css" media="screen" />
<!--[if IE 6]><link rel="stylesheet" type="text/css" href="css/ie6.css" media="screen" /><![endif]-->
<!--[if IE 7]><link rel="stylesheet" type="text/css" href="css/ie.css" media="screen" /><![endif]-->
</head>
<body>
<?php Yii::app()->clientscript->registerCss('btn-icon','.btn-icon span{ background-image: url("'.Yii::app()->theme->baseUrl.'/img/btn-icons.png") !important;
background-repeat: no-repeat;
background-position: 0 0;
width: 16px;
height: 16px;
position: absolute;
left: 6px;
top: 6px;}','screen')?>
<div class="container_12" id="page">
<!-- ending headernya -->
<div class="clear">
</div>
<!-- navigasi -->
<?php echo Yii::app()->user->profile('MODEL_CLASS_NAME', 'ATTRIBUTE_NAME');?>
<?php echo $content; ?>
<div class="clear"></div>
<div id="footer">
Copyright © <?php echo date('Y'); ?> Bellarminus IS by <EMAIL> <?php //echo Yii::app()->user->name;?><br/>
</div><!-- footer -->
</div><!-- page -->
</body></html><file_sep><?php
/* @var $this DatatransaksisppController */
/* @var $data Datatransaksispp */
?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('idDatasiswa')); ?>:</b>
<?php echo CHtml::encode($data->idDatasiswa); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('nominalpembayaran')); ?>:</b>
<?php echo CHtml::encode($data->nominalpembayaran); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('tokentransaksi')); ?>:</b>
<?php echo CHtml::encode($data->tokentransaksi); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('tanggal')); ?>:</b>
<?php echo CHtml::encode($data->tanggal); ?>
<br />
</div><file_sep><?php
/* @var $this DataSPPsiswaController */
/* @var $model DataSPPsiswa */
$this->breadcrumbs=array(
'Data Sppsiswas'=>array('index'),
$model->idDataSiswa=>array('view','id'=>$model->idDataSiswa),
'Update',
);
$this->menu=array(
//array('label'=>'List DataSPPsiswa', 'url'=>array('index')),
//array('label'=>'Create DataSPPsiswa', 'url'=>array('create')),
//array('label'=>'View DataSPPsiswa', 'url'=>array('view', 'id'=>$model->idDataSiswa)),
array('label'=>'List Data SPP siswa', 'url'=>array('admin')),
);
?>
<p><b>Update DataSPPsiswa <?php echo $model->NamaSiswa; ?></b></p>
<?php echo $this->renderPartial('_form', array('model'=>$model)); ?><file_sep><?php
$this->layout='forRenderPartial';
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'data-sppsiswa-grid',
'dataProvider'=>$model->masterKelas($classId),
//'filter'=>$model,
'columns'=>array(
'idDataSiswa',
//'NoIndukSiswa',
array(
'header'=>'No Induk',
'value'=>'$data->NoIndukSiswa',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:center;',
),
//'footer'=>'test',
//'hasFooter'=>'true',
),
array(
'header'=>'Nama',
'value'=>'$data->NamaSiswa',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'600px',
'style'=>'text-align:left; font-size:12px;',
),
//'footer'=>'test',
//'hasFooter'=>'true',
),
array(
'header'=>'SPP Pokok',
'value'=>'number_format($data->NominalSPP,"0",",",".");',
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
//'footer'=>'test',
//'hasFooter'=>'true',
),
array(
'header'=>'Eks-Kur', //column header
'value'=> 'number_format($data->biayaekskul->nominal,"0",",",".");',//column name, php expression
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
'footer'=>$model->getTotalsEksKur($model->search()->getData()),
//'hasFooter'=>'true',
),
array(
'header'=>'Ujian', //column header
'value'=> 'number_format($data->biayaujian->nominal,"0",",",".");',//column name, php expression
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
//'footer'=>$subtotalUjian,
//'hasFooter'=>'true',
),
array(
'header'=>'Cambridge', //column header
'value'=> 'number_format($data->biayacambridge->nominal,"0",",",".");',//column name, php expression
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
//'footer'=>$subtotalCambridge,
//'hasFooter'=>'true',
),
array(
'header'=>'Tertagih', //column header
'value'=>'number_format(($data->NominalSPP+$data->biayaekskul->nominal+$data->biayaujian->nominal+$data->biayacambridge->nominal),"0",",",".");;
',//column name, php expression
'type'=>'raw',
'htmlOptions'=>array(
'width'=>'100px',
'style'=>'text-align:right; font-size:12px;',
),
'footer'=>'Total',
//'hasFooter'=>'true',
),
/*array(
'header'=>'Uang Ujian', //column header
'value'=> '$data->tuitionbillcategory->nominal',//column name, php expression
'type'=>'raw',
),*/
/*array(
'class'=>'CButtonColumn',
'template'=>'{view}{update}',
),*/
),
'summaryText' => 'Menampilkan {count} data yang ditemukan.',
'template'=>' {items} {summary} {pager}'
//'hasFooter'=>true,
));
echo CHtml::button('CETAK!',array('class'=>'btn btn-grey','style'=>'margin-right:10px'));
?>
<file_sep><?php
/* @var $this DataSPPsiswaController */
/* @var $model DataSPPsiswa */
/* @var $form CActiveForm */
?>
<div class="form">
<div class="block">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'data-sppsiswa-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<table class='form'>
<tr>
<td class='col1'><?php echo $form->labelEx($model,'NoIndukSiswa'); ?></td>
<td class='col2'><?php echo $form->textField($model,'NoIndukSiswa'); ?></td>
<td class='col3'><?php echo $form->error($model,'NoIndukSiswa'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'NamaSiswa'); ?></td>
<td><?php echo $form->textField($model,'NamaSiswa',array('size'=>60,'maxlength'=>70)); ?></td>
<td><?php echo $form->error($model,'NamaSiswa'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'NominalSPP'); ?></td>
<td><?php echo $form->textField($model,'NominalSPP'); ?></td>
<td><?php echo $form->error($model,'NominalSPP'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'eksKur'); ?></td>
<td><?php echo $form->checkBox($model,'eksKur'); ?></td>
<td><?php echo $form->error($model,'eksKur'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'uangUjian'); ?></td>
<td><?php echo $form->checkBox($model,'uangUjian'); ?></td>
<td><?php echo $form->error($model,'uangUjian'); ?></td>
</tr>
<tr>
<td><?php echo $form->labelEx($model,'uangCambridge'); ?></td>
<td><?php echo $form->checkBox($model,'uangCambridge'); ?></td>
<td><?php echo $form->error($model,'uangCambridge'); ?></td>
</tr>
<tr>
<td colspan='3'><?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save',array('class'=>'btn')); ?></td>
</tr>
</table>
<?php $this->endWidget(); ?>
</div></div><!-- form --><file_sep><?php /* @var $this Controller */ ?>
<<<<<<< HEAD
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/reset.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/text.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/grid.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/layout.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/nav.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/style.css" media="screen" />
<!--[if IE 6]><link rel="stylesheet" type="text/css" href="css/ie6.css" media="screen" /><![endif]-->
<!--[if IE 7]><link rel="stylesheet" type="text/css" href="css/ie.css" media="screen" /><![endif]-->
<!--Jquery UI CSS-->
<link href="<?php echo Yii::app()->theme->baseUrl; ?>/css/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
<!-- BEGIN: load jquery -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.core.min.js"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.widget.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.accordion.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.effects.core.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.effects.slide.min.js" type="text/javascript"></script>
<!-- END: load jquery -->
<!--jQuery Date Picker-->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.widget.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.datepicker.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.progressbar.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/popup/jquery.facebox.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/quick-sand/jquery.quicksand.js" type="text/javascript"></script>
<!-- Load TinyMCE -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/tiny-mce/jquery.tinymce.js" type="text/javascript"></script>
<!-- BEGIN: load jquery2 -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.core.min.js"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.widget.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.ui.accordion.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.effects.core.min.js" type="text/javascript"></script>
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jquery-ui/jquery.effects.slide.min.js" type="text/javascript"></script>
<!-- END: load jquery2 -->
<!-- BEGIN: load jqplot -->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/jquery.jqplot.min.css" />
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="js/jqPlot/excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jqPlot/jquery.jqplot.min.js"></script>
<script language="javascript" type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jqPlot/plugins/jqplot.barRenderer.min.js"></script>
<script language="javascript" type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jqPlot/plugins/jqplot.pieRenderer.min.js"></script>
<script language="javascript" type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jqPlot/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script language="javascript" type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jqPlot/plugins/jqplot.highlighter.min.js"></script>
<script language="javascript" type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/jqPlot/plugins/jqplot.pointLabels.min.js"></script>
<!-- END: load jqplot -->
<script src="<?php echo Yii::app()->theme->baseUrl; ?>/js/setup.js" type="text/javascript"></script>
<script type="text/javascript">
//untuk mencegah versi yang saling berkonflik gunakan jQuery.noConflict
var jQ164 = jQuery.noConflict();
jQ164(document).ready(function () {
setSidebarHeight();
setupLeftMenu();
setupTinyMCE();
setupProgressbar('progress-bar');
setDatePicker('date-picker');
setupDialogBox('dialog', 'opener');
//jQ164('input[type="checkbox"]').fancybutton();
//jQ164('input[type="radio"]').fancybutton();
});
</script>
<!-- BEGIN: load Fancybox -->
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/lib/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<link rel="stylesheet" href="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/jquery.fancybox.css?v=2.1.4" type="text/css" media="screen" />
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/jquery.fancybox.pack.js?v=2.1.4"></script>
<link rel="stylesheet" href="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" />
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-media.js?v=1.0.5"></script>
<link rel="stylesheet" href="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" />
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-buttons.css?v=2.1.4" />
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-buttons.js?v=2.1.4"></script>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-thumbs.css?v=2.1.4" />
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-thumbs.js?v=2.1.4"></script>
<!-- END: load fancybox -->
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/customfancyapps.js">//javascript yg digunakan adalah yg untuk fancybox//fancybox javacript function</script>
</head>
<body>
<?php Yii::app()->clientscript->registerCss('btn-icon','.btn-icon span{ background-image: url("'.Yii::app()->theme->baseUrl.'/img/btn-icons.png") !important;
background-repeat: no-repeat;
background-position: 0 0;
width: 16px;
height: 16px;
position: absolute;
left: 6px;
top: 6px;}','screen')?>
<div class="container_12" id="page">
<!-- starting headernya -->
<div class="grid_12 header-repeat">
<div id="branding">
<div class="floatleft fontwhite">
<h1><img src="<?php echo Yii::app()->theme->baseUrl; ?>/img/custom-btn/logo-kecil.png"><b><?php echo CHtml::encode(Yii::app()->name); ?></b></h1>
</div>
<div class="floatright">
<!-- <!-- untuk pengembangan selanjutnya
<div class="floatleft marginleft10">
<img src="<?php echo Yii::app()->theme->baseUrl; ?>/img/img-profile.jpg" alt="Profile Pic" /></div>
<div class="floatleft marginleft10">
<ul class="inline-ul floatleft">
<li>Hello Admin</li>
<li><a href="#">Config</a></li>
<li><a href="#">Logout</a></li>
</ul>
<br />
<span class="small grey">Last Login: 3 hours ago</span>
</div>
-->
</div>
</div>
</div>
<!-- ending headernya -->
<div class="clear">
</div>
<!-- navigasi -->
<?php echo Yii::app()->user->profile('MODEL_CLASS_NAME', 'ATTRIBUTE_NAME');?>
<?php echo $content; ?>
<div class="clear"></div>
<div id="footer">
Copyright © <?php echo date('Y'); ?> Bellarminus IS by <EMAIL> <?php //echo Yii::app()->user->name;?><br/>
=======
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="language" content="en" />
<!-- blueprint CSS framework -->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/screen.css" media="screen, projection" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/print.css" media="print" />
<!--[if lt IE 8]>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/ie.css" media="screen, projection" />
<![endif]-->
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/main.css" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/form.css" />
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
</head>
<body>
<div class="container" id="page">
<div id="header">
<div id="logo"><?php echo CHtml::encode(Yii::app()->name); ?></div>
</div><!-- header -->
<div id="mainmenu">
<?php $this->widget('zii.widgets.CMenu',array(
'items'=>array(
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
array('label'=>'Contact', 'url'=>array('/site/contact')),
array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
)); ?>
</div><!-- mainmenu -->
<?php if(isset($this->breadcrumbs)):?>
<?php $this->widget('zii.widgets.CBreadcrumbs', array(
'links'=>$this->breadcrumbs,
)); ?><!-- breadcrumbs -->
<?php endif?>
<?php echo $content; ?>
<div class="clear"></div>
<div id="footer">
Copyright © <?php echo date('Y'); ?> by My Company.<br/>
All Rights Reserved.<br/>
<?php echo Yii::powered(); ?>
>>>>>>> branch 'master' of https://github.com/ajimatahari/myAppTest.git
</div><!-- footer -->
</div><!-- page -->
</body>
</html>
<file_sep><?php
/* @var $this SystemTahunajaranController */
/* @var $model SystemTahunajaran */
/* @var $form CActiveForm */
?>
<div id="system-tahunajaran-container" class="form">
<p style="margin:5px;">Isikan awal mulai tahun ajaran baru dan tahun penutup tahun ajaran</p>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'system-tahunajaran-form',
'enableAjaxValidation'=>false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<table class="form"" style="border:solid 1px black;">
<tr style="border:solid 1px black; background-color: #2E5E79; color: white;">
<td style="text-align:center;"><?php echo CHtml::label('Tahun Awal',false); ?></td>
<td style="text-align:center;"><?php echo CHtml::label('Tahun Penutup',false);?></td>
</tr>
<tr style="border:solid 1px black; background-color: #E6F0F3;">
<td style="text-align:center;"><?php echo CHtml::textField('tahunAwal',false); ?></td>
<td style="text-align:center;"><?php echo CHtml::textField('tahunPenutup',false);?></td>
</tr>
<tr style="background-color: #E6F0F3;">
<td colspan="2" style="text-align:center;"><?php echo CHtml::AjaxSubmitButton('Simpan',Yii::app()->createUrl('systemTahunajaran/SubmitTahunAjaranBaru'),
array(
'beforeSend' => 'function(){
$("#system-tahunajaran-container").hide();}',
'update'=>'#setingContainer',
'beforUpdate'=>'function(){
$("#system-tahunajaran-container").remove();
$("#system-tahunajaran-form").remove();}',
'complete' => 'function(){
var current_height = document.body.offsetHeight;
var current_width = document.body.offsetWidth;
$("#system-tahunajaran-form").remove();
parent.$(".fancybox-skin").height(current_height + 30);
parent.$(".fancybox-skin").width(current_width + 30);
parent.$(".fancybox-inner").height(current_height + 30);
parent.$("#fancybox-outer").width(current_width + 30);
parent.$("#fancybox-wrap").width(current_width + 30);
parent.$("#fancybox-content").width(current_width + 30);
parent.$(".fancybox-inner").width(current_width + 30);
//parent.$.fancybox.reposition();
}',
),
array('class'=>'btn-custom')
);?></td>
</tr>
</table>
<?php $this->endWidget(); ?>
</div><!-- form --><file_sep><?php
/* @var $this DatasiswaController */
/* @var $model Datasiswa */
$this->breadcrumbs=array(
'Datasiswas'=>array('index'),
$model->idDataSiswa,
);
$this->menu=array(
//array('label'=>'List Datasiswa', 'url'=>array('index')),
//array('label'=>'Create Datasiswa', 'url'=>array('create')),
//array('label'=>'Update Datasiswa', 'url'=>array('update', 'id'=>$model->idDataSiswa)),
//array('label'=>'Delete Datasiswa', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->idDataSiswa),'confirm'=>'Are you sure you want to delete this item?')),
array('label'=>'Manage Datasiswa', 'url'=>array('admin')),
);
?>
<h4><?php echo $model->NamaSiswa; ?></h4>
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'idDataSiswa',
'NoIndukSiswa',
'NamaSiswa',
'namaOrtuAyah',
'namaOrtuIbu',
'alamatTinggal',
'tempatLahir',
'tanggalLahir',
'poinValue',
'kotaAsal',
'tahunAjaranMasuk',
'nomorHp',
'contactDarurat',
'NominalSPP',
),
)); ?>
<file_sep>this profile extension shows both how to implement a normal field without the need af a proper controller and both how to implement some particular field (i.e. a file upload field) using a custom controller.
to make this work put the Profile.php file inside your application models directory, store the ProfileController.php file inside your Controllers directory and then put the profile folder inside your views directory.
remember that you need to create the needed database table to make this profile extension work.
You can find the query to create the database table inside the userExtension.sql file.
### DISCLAIMER ###
this user extension is provided just to show you how to create your own.
In particular the file upload part of this user extension is not at all optimized, and therefore should not be used in your own application.
<file_sep><?php
/* @var $this SiteController */
$this->pageTitle=Yii::app()->name;
<<<<<<< HEAD
$this->layout='column1';
?>
<h2>Selamat Datang di <?php echo CHtml::encode(Yii::app()->name); ?></h2>
<p>Selamat datang di Bellarminus Managemen Software, username dan aktivitas anda akan direkam dalam penggunaan software ini.</p>
<p>Anda diberikan hak untuk mengubah data dan mengoperasikan menu sesuai dengan privilege user yang telah diberikan kepada anda</p>
<!--<ul>
<li>View file: <code><?php echo __FILE__; ?></code></li>
<li>Layout file: <code><?php echo $this->getLayoutFile('main'); ?></code></li>
</ul>-->
<?echo Yii::app()->basePath;?>
<p>jika anda memiliki beberapa pertanyaan dan keluhan silahkan hubungi bagian IT pada pesawat 119.<?php echo Yii::app()->basePath;?></p>
=======
?>
<h1>Welcome to <i><?php echo CHtml::encode(Yii::app()->name); ?></i></h1>
<p>Congratulations! You have successfully created your Yii application.</p>
<p>You may change the content of this page by modifying the following two files:</p>
<ul>
<li>View file: <code><?php echo __FILE__; ?></code></li>
<li>Layout file: <code><?php echo $this->getLayoutFile('main'); ?></code></li>
</ul>
<p>For more details on how to further develop this application, please read
the <a href="http://www.yiiframework.com/doc/">documentation</a>.
Feel free to ask in the <a href="http://www.yiiframework.com/forum/">forum</a>,
should you have any questions.</p>
>>>>>>> branch 'master' of https://github.com/ajimatahari/myAppTest.git
<file_sep><?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of GetUnpaidMonth
*
* @author <NAME>
*/
class GetUnpaidMonth extends CApplicationComponent{
public static function cekBulanPembayaran($iddata){
$monthArray=array('januari','februari','maret','april','mei','juni','juli','agustus','september','oktober','november','desember');
$idtuitionData = Yii::app()->db->createCommand()
->select('idtuitionData')
->from('tuitiondata')
->where('DataSiswa_idDataSiswa = '.$iddata)
->queryScalar();
$buttongroup='';
foreach($monthArray as $items){
$checkEmpty = Yii::app()->db->createCommand()
->select($items)
->from('tuitiondata')
->where('DataSiswa_idDataSiswa = '.$iddata)
->queryScalar();
if($checkEmpty==''){
$buttongroup.=CHtml::link($items,Yii::app()->createUrl("tuitiondata/bayar",array('id'=>$idtuitionData,'idDataSiswa'=>$iddata,'bulan'=>$items,'bayar'=>'formulir')),array('id'=>'inline','data-fancybox-type'=>'iframe','class'=>'btn btn-blue'));
$buttongroup.=' ';
}/*else{
$buttongroup.='dancuks';
}*/
}
/*$model=new Tuitiondata;
$criteria = new CDbCriteria;
$criteria->condition=$iddata;
//$criteria->condition;*/
return $buttongroup;
}
//put your code here
}
?>
<file_sep><?php
/* @var $this LevelkelasController */
/* @var $model Levelkelas */
/* @var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'levelkelas-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'idLevelkelas'); ?>
<?php echo $form->textField($model,'idLevelkelas'); ?>
<?php echo $form->error($model,'idLevelkelas'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'namaKelas'); ?>
<?php echo $form->textField($model,'namaKelas',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'namaKelas'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'levelKelasName'); ?>
<?php echo $form->textField($model,'levelKelasName',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'levelKelasName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'waliKelasID'); ?>
<?php echo $form->textField($model,'waliKelasID',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'waliKelasID'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form --><file_sep><?php
Yii::import('zii.widgets.CMenu', true);
class MenuSDActive extends CMenu
{
//public $itemCssClass='section menu';
public function init()
{
// Here we define query conditions.
$criteria = new CDbCriteria;
$criteria->select = '*';
//$criteria->with=
//$criteria->distinct = TRUE;
$criteria->condition = '`levelKelasName` BETWEEN 1 AND 6'; //1-6 scope UNIT SD
$criteria->group='`namaKelas`'; //menggroup murid yang ada di dalam database berdasarkan kelasnya..
//$criteria->order = '`position` ASC';
$items = Datasiswa::model()->with('kelas')->findAll($criteria);
ini_set('memory_limit', '-1');
//print_r($items);
foreach ($items as $item)
$this->items[] = array('label'=>"ACOT ".$item->kelas->namaKelas, 'url'=>'admin?Datasiswa[idlevelKelas]='.$item->kelas->idLevelkelas.'&yt0=Search');
parent::init();
}
}
?>
<file_sep><?php
/* @var $this PendaftaranController */
/* @var $model pendaftaran */
$this->breadcrumbs=array(
'Pendaftaran Siswa Baru'
);
$this->menu=array(
//array('label'=>'List pendaftaran', 'url'=>array('index')),
//array('label'=>'Manage pendaftaran', 'url'=>array('admin')),
);
?>
<p>Pada halaman ini, anda diminta untuk memasukkan data personal siswa satu persatu.<br> di akhir formulir ini
akan ada 3 tombol :
<ol>
<li><b>[Daftar]</b> : menyimpan data siswa dan langsung menavigasi pada halaman view data siswa yang telah dimasukkan</li>
<li><b>[Daftar & Input Lagi]</b> : menyimpan data siswa dan melakukan input data siswa lainnya yang akan disimpan</li>
<li><b>[Batal ]</b> : untuk membatalkan prosedur dan menavigasi menuju halaman administrasi Umum.</li>
</ol>
</p>
<?php echo $this->renderPartial('_form', array('model'=>$model)); ?><file_sep><?php
/* @var $this TuitiondataController */
/* @var $data Tuitiondata */
?>
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('idtuitionData')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->idtuitionData), array('view', 'id'=>$data->idtuitionData)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('nominalDibayarkan')); ?>:</b>
<?php echo CHtml::encode($data->nominalDibayarkan); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('nomerKuitansiPembayaran')); ?>:</b>
<?php echo CHtml::encode($data->nomerKuitansiPembayaran); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('tahunAjaran_idtahunAjaran')); ?>:</b>
<?php echo CHtml::encode($data->tahunAjaran_idtahunAjaran); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('DataSiswa_idDataSiswa')); ?>:</b>
<?php echo CHtml::encode($data->DataSiswa_idDataSiswa); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('BulanTagihan')); ?>:</b>
<?php echo CHtml::encode($data->BulanTagihan); ?>
<br />
<?php /*
<b><?php echo CHtml::encode($data->getAttributeLabel('statusTagihan')); ?>:</b>
<?php echo CHtml::encode($data->statusTagihan); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('SPP')); ?>:</b>
<?php echo CHtml::encode($data->SPP); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('billCategoryData')); ?>:</b>
<?php echo CHtml::encode($data->billCategoryData); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('totalTagihan')); ?>:</b>
<?php echo CHtml::encode($data->totalTagihan); ?>
<br />
*/ ?>
</div><file_sep><?php /* @var $this Controller */ ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/reset.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/text.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/grid.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/layout.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/nav.css" media="screen" />
<!--[if IE 6]><link rel="stylesheet" type="text/css" href="css/ie6.css" media="screen" /><![endif]-->
<!--[if IE 7]><link rel="stylesheet" type="text/css" href="css/ie.css" media="screen" /><![endif]-->
<!-- BEGIN: load Fancybox -->
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/lib/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/lib/jquery.mousewheel-3.0.6.pack.js"></script>
<link rel="stylesheet" href="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/jquery.fancybox.css?v=2.1.4" type="text/css" media="screen" />
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/jquery.fancybox.pack.js?v=2.1.4"></script>
<link rel="stylesheet" href="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-buttons.css?v=1.0.5" type="text/css" media="screen" />
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-buttons.js?v=1.0.5"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-media.js?v=1.0.5"></script>
<link rel="stylesheet" href="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7" type="text/css" media="screen" />
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-buttons.css?v=2.1.4" />
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-buttons.js?v=2.1.4"></script>
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-thumbs.css?v=2.1.4" />
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/helpers/jquery.fancybox-thumbs.js?v=2.1.4"></script>
<!-- END: load fancybox -->
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/fancybox2/source/customfancyapps.js">//javascript yg digunakan adalah yg untuk fancybox//fancybox javacript function</script>
</head>
<body style="background-color: white;">
<div id="iframe-insider">
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*
*/
echo $content;
?></div>
</body></html>
|
b309ffbf71d0f84ddcbbf911a7064d05ec10f6b6
|
[
"Markdown",
"JavaScript",
"INI",
"Text",
"PHP"
] | 92 |
PHP
|
ajimatahari/bellarminusIS
|
59f09ac7a4e8ca0b6fe7f03bf531d8da6549a6b0
|
51900341b4a52467e4dca05689363dab6d67689c
|
refs/heads/master
|
<file_sep># k8s-helm-practice
This repo was primarily created following the steps outlined by Bitnami's
article ["How to Create Your First Helm Chart"][bitnami article]. Check the
commit history for how the steps were followed.
[bitnami article]: https://docs.bitnami.com/kubernetes/how-to/create-your-first-helm-chart/
## Prerequisites
### Docker
* **MacOS / Windows**: Install Docker for Mac / Windows.
* **Others**: Install Docker.
### Kubernetes
* **MacOS / Windows**: Use Docker for Mac / Windows and enable Kubernetes in
the settings.
* **Others**: Install Kubernetes.
### Helm
* **MacOS**:
```bash
brew install kubernetes-helm
```
* **Others**:
```bash
curl -sL https://raw.githubusercontent.com/kubernetes/helm/master/scripts/get | bash -
```
> Do not forget to run `helm init` after installing Helm.
## Using Docker
### Building the Docker image
```bash
docker build -t k8s-helm-practice .
```
* `k8s-helm-practice` can be replaced with whatever you would like to tag your
image as.
### Running the Docker image
```bash
docker run -e PORT=3000 -p 3000:3000 -it k8s-helm-practice
```
* `PORT` can be any port you would like to run the server on within the
container
* `-p` is used to expose and connect a port from the container to your host
machine. This should be set to the same value as `PORT`
* `k8s-helm-practice` can be replaced with whatever you would like to tag your
image as.
## Using Helm and Kubernetes
### Configuration
* To change the port you can configure the `service.port` value in
`node-server/values.yaml`.
* To configure the Docker image name, change `image.repository` in
`node-server/values.yaml`.
### Running
The Docker image will need to be built using the tag specified as
`image.repository` in `node-server/values.yaml` before proceeding. See above for
how to build the Docker image.
* To run, connect to the service on the port specified, locally:
```bash
helm install --name example ./node-server --set service.type=NodePort | tail -4 | bash -
```
This will start the service on the local cluster using Helm, take the'
commands from the `NOTES` section using `tail`, and run the commands to
get the local URL to hit the service started.
> You may need to replace the IP in the URL with `localhost`.
* To stop and remove the application:
```bash
helm del --purge example
```
In the above commands `example` can be replaced with whatever you would like to
name your service.
<file_sep># Use node:10, the current stable release, for the build stage
FROM node:10 as builder
# Copy application source code to /opt/k8s-helm-practice directory of your
# container
COPY . /opt/k8s-helm-practice
# Change directory to where the application source code was copied
WORKDIR /opt/k8s-helm-practice
# Install dependencies of your app, defined into package.json
RUN \
set -e; \
npm ci; \
npm run build;
# Use node:10-alpine for the target image
FROM node:10-alpine
# Copy the application and installed modules from the previous build stage
COPY --from=builder /opt/k8s-helm-practice /opt/k8s-helm-practice
# Change directory to where the application is
WORKDIR /opt/k8s-helm-practice
# Add environmental variable for the server port
ENV PORT=3000
# Expose the server port that is specified
EXPOSE $PORT
# Run the app!
CMD ["npm", "start"]
<file_sep>import babel from 'rollup-plugin-babel';
import { dependencies } from './package.json';
export default {
input: './src/index.ts',
output: {
file: './dist/server.js',
format: 'cjs',
},
plugins: [
babel({
extensions: ['.ts'],
}),
],
external: [...Object.keys(dependencies)],
};
|
63b203b040ee9fbe034dd90d1883474f7915fb00
|
[
"Markdown",
"JavaScript",
"Dockerfile"
] | 3 |
Markdown
|
dfrankland/k8s-helm-practice
|
2d5e1b426c952e1c973d51ddc50e64a2941fadcb
|
c4531fd95510d61b705adfb8ceb070f9d5ddc635
|
refs/heads/master
|
<file_sep>// time: O(logN^2) solution
class Solution
{
public:
int hash(int N)
{
int result = 0;
while (N)
{
result += pow(10, N % 10);
N /= 10;
}
return result;
}
bool reorderedPowerOf2(int N)
{
int H = hash(N);
for (int i = 0; i < 32; ++i)
if (hash(1 << i) == H)
return true;
return false;
}
};<file_sep>class Solution
{
public:
bool isOpening(char c)
{
return (c == '(' || c == '{' || c == '[');
}
char getOp(char c)
{
if (c == ')')
return '(';
if (c == '}')
return '{';
if (c == ']')
return '[';
return '-';
}
bool isValid(string s)
{
if (s.length() == 0)
return true;
int n = s.length();
if (n & 1)
return false;
if (s[0] == ')' || s[0] == '}' || s[0] == ']')
return false;
if (s[n - 1] == '(' || s[n - 1] == '{' || s[n - 1] == '[')
return false;
stack<char> ST;
for (int i = 0; i < n; ++i)
{
if (isOpening(s[i]))
ST.push(s[i]);
else
{
if (ST.empty())
return false;
if (getOp(s[i]) != ST.top())
return false;
else
ST.pop();
}
}
return ST.empty();
}
};<file_sep>class Solution
{
public:
bool isAnagram(string s, string t)
{
if (s.size() != t.size())
return false;
vector<int> Counts(26, 0);
for (char c : s)
++Counts[c - 'a'];
for (char c : t)
--Counts[c - 'a'];
for (int c : Counts)
if (c != 0)
return false;
return true;
}
};<file_sep>class Solution
{
public:
bool containsDuplicate(vector<int> &nums)
{
unordered_set<int> distinct(nums.begin(), nums.end());
return nums.size() != distinct.size();
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// bfs solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
vector<double> averageOfLevels(TreeNode *root)
{
if (!root)
return {};
vector<double> result;
queue<TreeNode *> Q;
TreeNode *cur = NULL;
int q_size = 0;
double sum = 0;
Q.push(root);
while (!Q.empty())
{
q_size = Q.size();
sum = 0;
for (int i = 0; i < q_size; ++i)
{
cur = Q.front();
Q.pop();
sum += cur->val;
if (cur->left)
Q.push(cur->left);
if (cur->right)
Q.push(cur->right);
}
result.emplace_back(sum / q_size);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// dfs solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void averageOfLevelsUtil(TreeNode *root, vector<double> &result, vector<int> &count, int level = 0)
{
if (!root)
return;
if (result.size() <= level)
{
result.emplace_back(0);
count.emplace_back(0);
}
averageOfLevelsUtil(root->left, result, count, level + 1);
averageOfLevelsUtil(root->right, result, count, level + 1);
result[level] += root->val;
++count[level];
}
vector<double> averageOfLevels(TreeNode *root)
{
vector<double> result;
vector<int> count;
averageOfLevelsUtil(root, result, count);
for (int i = 0; i < result.size(); ++i)
result[i] /= count[i];
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
unordered_map<int, unordered_map<int, int>> T = {
{0, {{-1, 0}, {1, 0}, {-2, 0}, {2, 0}}},
{1, {{-1, 1}, {1, 0}, {-2, 1}, {2, 1}}},
{2, {{-1, 0}, {1, 0}, {-2, 2}, {2, -2}}},
{3, {{-1, 1}, {1, 0}, {-2, 0}, {2, 0}}},
{4, {{-1, -2}, {1, 0}, {-2, 0}, {2, 1}}},
{5, {{-1, 2}, {1, 0}, {-2, 1}, {2, 0}}},
{6, {{-1, 0}, {1, 0}, {-2, 2}, {2, -2}}},
{7, {{-1, 1}, {1, 0}, {-2, 0}, {2, 1}}},
{8, {{-1, 0}, {1, 0}, {-2, 1}, {2, 1}}},
{9, {{-1, 1}, {1, 0}, {-2, 1}, {2, 0}}},
{10, {{-1, -2}, {1, 0}, {-2, 0}, {2, 0}}},
{11, {{-1, 2}, {1, 0}, {-2, 0}, {2, 0}}},
{12, {{-1, 0}, {1, 0}, {-2, 0}, {2, 1}}},
{13, {{-1, 0}, {1, 0}, {-2, 1}, {2, 0}}},
};
int W; // number of columns.
int H; // number of rows.
cin >> W >> H;
cin.ignore();
vector<vector<int>> g(H);
for (int i = 0; i < H; i++)
{
g[i] = vector<int>(W, 0);
for (int j = 0; j < W; ++j)
cin >> g[i][j];
}
int EX; // the coordinate along the X axis of the exit (not useful for this first mission, but must be read).
cin >> EX;
cin.ignore();
int prev = -1;
// game loop
while (1)
{
int XI;
int YI;
string POS;
cin >> XI >> YI >> POS;
cin.ignore();
if (POS == "TOP")
prev = -1;
if (POS == "LEFT")
prev = -2;
if (POS == "RIGHT")
prev = 2;
int type = g[YI][XI];
int next = T[type][prev];
if (next == 2)
{ // to the right
prev = -2;
++XI;
}
else if (next == -2)
{ // to the left
prev = 2;
--XI;
}
else if (next == 1)
{ // down
prev = -1;
++YI;
}
// One line containing the X Y coordinates of the room in which you believe Indy will be on the next turn.
cout << XI << " " << YI << endl;
}
}<file_sep>from fractions import Fraction
def solution(m):
# the matrix can be treated as a absorbing markov chain
# ref: https://en.wikipedia.org/wiki/Absorbing_Markov_chain
# we wish to find the limiting matrix of the given input
# ref: https://www.youtube.com/watch?v=BsOkOaB8SFk
# standardize the matrix
def processMatrix(m):
row_sum = [sum(m[i]) for i in range(len(m))] # sum of each row of given matrix
bool_terminal = [x == 0 for x in row_sum] # bool_terminal[i] represents if ith row is terminal or not
terminal_rows = set([i for i, x in enumerate(bool_terminal) if x]) # indices of terminal rows in m
# add fractions of probability => row_element/row_sum
tmp_m = []
for i in range(len(m)):
tmp_m.append(list(map(lambda x : Fraction(0, 1) if(row_sum[i] == 0) else Fraction(x, row_sum[i]), m[i])))
# seperate the terminal and non-terminal states
non_term_mat = []
zero_mat = []
for i in range(len(tmp_m)):
if i in terminal_rows:
zero_mat.append(tmp_m[i])
else:
non_term_mat.append(tmp_m[i])
# zero_mat.extend(non_term_mat)
non_term_mat.extend(zero_mat)
# final processing (shifting columns to match with terminal & non-terminal rows)
processedMatrix = []
for i in range(len(non_term_mat)):
processedMatrix.append([])
tmp = []
for j in range(len(non_term_mat)):
if j in terminal_rows:
tmp.append(non_term_mat[i][j])
else:
processedMatrix[i].append(non_term_mat[i][j])
processedMatrix[i].extend(tmp)
# the zero_mat length helps in easier split and early stopping
return processedMatrix, len(zero_mat)
def splitIntoQR(m, zero_len):
"""
--------------
| q | r |
--------------
| | |
| 0 | I |
| | |
--------------
"""
q_len = len(m) - zero_len # size of side of q matrix
q_mat = []
r_mat = []
for i in range(q_len):
q_mat.append([int(i==j) - m[i][j] for j in range(q_len)]) # performing the (I-Q) step in-place
r_mat.append(m[i][q_len:])
return q_mat, r_mat
# create a copy of the matrix
def copyMat(m):
copy_mat = []
for i in range(len(m)):
copy_mat.append([])
for j in range(len(m[i])):
# copy_mat[i].append(Fraction(m[i][j].numerator, m[i][j].denominator))
copy_mat[i].append(m[i][j])
return copy_mat
# ref: https://elonen.iki.fi/code/misc-notes/python-gaussj/
def gaussJordanElmination(m, i_row):
mat = copyMat(m)
for i in range(len(mat)):
idx = -1
for j in range(i, len(mat)):
if mat[j][i].numerator != 0:
idx = j
break
if idx == -1:
raise ValueError('error: Gauss elimination failed!')
mat[i], mat[idx] = mat[idx], mat[j]
i_row[i], i_row[idx] = i_row[idx], i_row[i]
for j in range(i+1, len(mat)):
if mat[j][i].numerator == 0:
continue
ratio = -mat[j][i]/mat[i][i]
for k in range(i, len(mat)):
mat[j][k] += ratio * mat[i][k]
i_row[j] += ratio * i_row[i]
result = [0 for i in range(len(mat))]
for i in range(len(mat)):
idx = len(mat) - 1 - i
end = len(mat) - 1
while end > idx:
i_row[idx] -= mat[idx][end] * result[end]
end -= 1
result[idx] = i_row[idx]/mat[idx][idx]
return result
# create transpose of matrix
def transposeMat(m):
result = []
for i in range(len(m)):
for j in range(len(m)):
if i == 0:
result.append([])
result[j].append(m[i][j])
return result
# find inverse of the matrix
def inverseMat(m):
trans_m = transposeMat(m)
inverse_m = []
for i in range(len(trans_m)):
identity_mat_row = [Fraction(int(i==j), 1) for j in range(len(trans_m))]
inverse_m.append(gaussJordanElmination(trans_m, identity_mat_row))
return inverse_m
# multiply matrix m1 with matrix m2
def multiplyMat(m1, m2):
result = []
for i in range(len(m1)):
result.append([])
for j in range(len(m2[0])):
result[i].append(Fraction(0, 1))
for k in range(len(m1[0])):
result[i][j] += m1[i][k] * m2[k][j]
return result
# greatest common divisor of x and y
def gcd(x, y):
def _gcd(x, y):
if y == 0:
return x
return _gcd(y, x%y)
# return _gcd(x, y)
return _gcd(abs(x), abs(y))
# calculate lowest common multiple of x & y
def lcm(x, y):
# return int((x*y)/gcd(abss(x),abs(y)))
return int((x*y)/gcd(x,y))
## solution begins hers
m, zero_len = processMatrix(m)
# if all rows are terminal
if zero_len == len(m):
return [1,1]
# get (i-q) & r matrix
q_mat, r_mat = splitIntoQR(m, zero_len)
# get inv(i-q)
inv_q_mat = inverseMat(q_mat)
# get the limiting matrix
limiting_mat = multiplyMat(inv_q_mat, r_mat)
sol = limiting_mat[0]
# solve each fraction for common denominator as per the readme.txt
common_denominator = 1
for item in sol:
common_denominator = lcm(common_denominator, item.denominator)
result = list(map(lambda x : int((x.numerator*common_denominator)/x.denominator), sol))
result.append(common_denominator)
return result<file_sep>class Solution
{
public:
void combinationSum3Util(int k, int n, vector<vector<int>> &result, vector<int> &res, int start = 1)
{
if (n < 0 || k < 0)
return;
if (n == 0 && k == 0)
{
result.emplace_back(res);
return;
}
for (int i = start; i <= 9; ++i)
{
res.emplace_back(i);
combinationSum3Util(k - 1, n - i, result, res, i + 1);
res.pop_back();
}
}
vector<vector<int>> combinationSum3(int k, int n)
{
vector<vector<int>> result;
vector<int> res;
combinationSum3Util(k, n, result, res);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int t = 0, q = 0, x = 0, pos = 0;
cin >> t;
vector<long long int> transactions(t, 0);
cin >> transactions[0];
for (int i = 1; i < t; ++i)
{
cin >> x;
transactions[i] = x + transactions[i - 1];
}
cin >> q;
while (q--)
{
cin >> x;
pos = (lower_bound(transactions.begin(), transactions.end(), x) - transactions.begin());
if (pos == t)
cout << "-1\n";
else
cout << (pos + 1) << "\n";
}
return 0;
}<file_sep>class Solution
{
public:
vector<vector<bool>> vis;
vector<pair<int, int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
bool existUtil(vector<vector<char>> &board, string &word, int r, int c, int idx = 0)
{
if (idx == word.length())
return true;
if (board[r][c] != word[idx] || vis[r][c])
return false;
if (idx == word.length() - 1)
return true;
vis[r][c] = true;
int x = 0, y = 0;
for (auto d : dirs)
{
x = r + d.first;
y = c + d.second;
if (x >= 0 && x < board.size() && y >= 0 && y < board[x].size() && !vis[x][y])
if (existUtil(board, word, x, y, idx + 1))
return true;
}
vis[r][c] = false; // the backtracking step
return false;
}
bool exist(vector<vector<char>> &board, string word)
{
vis = vector<vector<bool>>(board.size(), vector<bool>(board[0].size(), false));
for (int i = 0; i < board.size(); ++i)
{
for (int j = 0; j < board[i].size(); ++j)
{
if (existUtil(board, word, i, j))
return true;
}
}
return false;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// efficient recursive solution with memoization
class Solution
{
public:
vector<vector<vector<int>>> MEM;
bool isScrambleUtil(string &s1, string &s2, int i1, int i2, int len)
{
if (len == 1)
return s1[i1] == s2[i2];
if (MEM[i1][i2][len] != -1)
return MEM[i1][i2][len];
for (int i = 1; i < len; ++i)
{
if (isScrambleUtil(s1, s2, i1, i2, i) && isScrambleUtil(s1, s2, i1 + i, i2 + i, len - i))
{
MEM[i1][i2][len] = 1;
return true;
}
if (isScrambleUtil(s1, s2, i1, i2 + len - i, i) && isScrambleUtil(s1, s2, i1 + i, i2, len - i))
{
MEM[i1][i2][len] = 1;
return true;
}
}
MEM[i1][i2][len] = 0;
return false;
}
bool isScramble(string s1, string s2)
{
if (s1.length() != s2.length())
return false;
MEM = vector<vector<vector<int>>>(s1.length(), vector<vector<int>>(s1.length(), vector<int>(s1.length() + 1, -1)));
return isScrambleUtil(s1, s2, 0, 0, s1.length());
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// recursive solution with memoization
class Solution
{
public:
bool isScrambleUtil(string s1, string s2, unordered_map<string, bool> &MEM)
{
if (s1.length() == 0)
return true;
if (s1.length() == 1)
return s1 == s2;
if (s1 == s2)
return true;
int len = s1.length();
if (MEM.count(s1 + s2))
return MEM[s1 + s2];
for (int i = 1; i < len; ++i)
{
if (isScrambleUtil(s1.substr(0, i), s2.substr(0, i), MEM) && isScrambleUtil(s1.substr(i), s2.substr(i), MEM))
{
MEM[s1 + s2] = true;
return true;
}
if (isScrambleUtil(s1.substr(0, i), s2.substr(len - i), MEM) && isScrambleUtil(s1.substr(i), s2.substr(0, len - i), MEM))
{
MEM[s1 + s2] = true;
return true;
}
}
MEM[s1 + s2] = false;
return false;
}
bool isScramble(string s1, string s2)
{
if (s1.length() != s2.length())
return false;
unordered_map<string, bool> MEM;
return isScrambleUtil(s1, s2, MEM);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// dp solution
class Solution
{
public:
bool isScramble(string s1, string s2)
{
if (s1.length() != s2.length())
return false;
int len = s1.length();
vector<vector<vector<bool>>> MEM(len, vector<vector<bool>>(len, vector<bool>(len + 1, false)));
for (int k = 1; k <= len; ++k)
{
for (int i = len - k; i >= 0; --i)
{
for (int j = len - k; j >= 0; --j)
{
if (k == 1)
{
MEM[i][j][k] = s1[i] == s2[j];
}
else
{
for (int q = 1; q < k; ++q)
{
if ((MEM[i][j][q] && MEM[i + q][j + q][k - q]) || (MEM[i][j + k - q][q] && MEM[i + q][j][k - q]))
{
MEM[i][j][k] = true;
break;
}
}
}
}
}
}
return MEM[0][0][len];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>class Solution
{
public:
bool isMatch(string s, string p)
{
int s_len = s.length(), p_len = p.length();
vector<vector<bool>> tab(s_len + 1, vector<bool>(p_len + 1, false));
tab[0][0] = true;
for (int i = 1; i <= p_len; ++i)
{
if (p[i - 1] == '*')
tab[0][i] = tab[0][i - 1];
}
for (int i = 1; i <= s_len; ++i)
{
for (int j = 1; j <= p_len; ++j)
{
if (s[i - 1] == p[j - 1] || p[j - 1] == '?')
tab[i][j] = tab[i - 1][j - 1];
if (p[j - 1] == '*')
tab[i][j] = tab[i - 1][j - 1] | tab[i - 1][j] | tab[i][j - 1];
}
}
return tab[s_len][p_len];
}
};<file_sep>class Solution
{
public:
int minCostToMoveChips(vector<int> &position)
{
int count_odd = 0, count_even = 0;
for (int &p : position)
{
if (p & 1)
++count_odd;
else
++count_even;
}
return min(count_odd, count_even);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>
# def solution(s):
# # since all employees move at similar speed
# # people moving in same direction will never salute each other
# # hence all we have to do is
# # for every '>' count '<' to its right
# # that count x2 is the result
# salute_count = 0
# left_arrow_count = 0
# # iterate the string from right to left
# for i in range(len(s)-1, -1, -1):
# if s[i] == '<':
# left_arrow_count += 1
# elif s[i] == '>':
# salute_count += 2*left_arrow_count
# return salute_count
# print(solution(">----<"))
# def solution(total_lambs):
# # if being stingy : follow a fibonacci sequence
# # if being generous : follow a geometric progression of power of 2
# # generous_count = int(round(math.log(total_lambs+1, 2))) # min possible
# generous_count = 1 # min possible
# stingy_count = 0 # max possible
# # calculate generous count
# while True:
# total = 2**generous_count-1
# if total <= total_lambs:
# generous_count += 1
# else:
# generous_count -= 1
# break
# # calculate stingy count
# f1 = 1
# f2 = 1
# total = 0
# while total + f1 <= total_lambs:
# total += f1
# f1, f2 = f2, f1 + f2
# stingy_count += 1
# return stingy_count - generous_count
# print(solution(143))
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
ll t = 0, n = 0, k = 0, p = 0, x = 0, smaller = 0;
cin >> t;
while (t--)
{
cin >> n >> k >> p;
smaller = 0;
for (int i = 0; i < k; ++i)
{
cin >> x;
if (x <= p + smaller)
++smaller;
}
if (n - k < p)
{
cout << "-1\n";
}
else
{
cout << p + smaller << "\n";
}
}
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
string printBalancedTernary(int n) {
if(n < 0) {
string response = printBalancedTernary(-n);
transform(response.begin(), response.end(), response.begin(), [](char c){
if(c == 'T') return '1';
else if(c == '1') return 'T';
return c;
});
return response;
}
if(n == 0) return "";
if(n%3 == 0) return printBalancedTernary(n/3)+"0";
else if(n%3 == 1) return printBalancedTernary(n/3)+"1";
else return printBalancedTernary((n/3)+1)+"T";
}
int main()
{
int N;
cin >> N; cin.ignore();
if(N == 0) {
cout<<"0\n";
return 0;
}
cout<<printBalancedTernary(N)<<"\n";
}<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long int
// returns sum of all numbers from 1-n that are multiples of 3 or 5
ll getSumofMultiples(ll n)
{
--n; // numbers in [1,n), i.e. excluding n
ll result = 0;
ll by_three = n / 3; // count of numbers which are multiple of 3
ll by_five = n / 5; // count of numbers which are multiple of 5
// numbers divisible by both must be divisible by their lcm -> lcm(3,5) = 5
// these numbers should only be counted once
ll by_fifteen = n / 15; // count of numbers which are multiple of 15
// clean solution (3 + 6 + 9) = 3(1 + 2 + 3) = 3*(sum of n terms) = 3*n*(n+1)/2
result = (3 * (by_three * (by_three + 1))) / 2;
result += (5 * (by_five * (by_five + 1))) / 2;
result -= (15 * (by_fifteen * (by_fifteen + 1))) / 2;
// // alternative solution: sum of AP = n/2(2*a+(n-1)*d)
// result = (by_three*(2*3+(by_three-1)*3))/2;
// result += (by_five*(2*5+(by_five-1)*5))/2;
// result -= (by_fifteen*(2*15+(by_fifteen-1)*15))/2;
return result;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
ll t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
cout << getSumofMultiples(n) << "\n";
}
return 0;
}
<file_sep>// time: O(n*m), space: O(min(n,m)) solution (longest commong subsequence)
class Solution
{
public:
int maxUncrossedLines(vector<int> &A, vector<int> &B)
{
int m = A.size(), n = B.size();
if (m > n)
return maxUncrossedLines(B, A);
vector<int> tab(m + 1, 0);
int cur = 0, prev = 0;
for (int j = 1; j <= n; ++j)
{
prev = 0;
for (int i = 1; i <= m; ++i)
{
cur = tab[i];
if (A[i - 1] == B[j - 1])
tab[i] = 1 + prev;
else
tab[i] = max(tab[i], tab[i - 1]);
prev = cur;
}
}
return tab[m];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// time: O(n*m), space: O(n*m) solution (longest commong subsequence)
class Solution
{
public:
int maxUncrossedLines(vector<int> &A, vector<int> &B)
{
int m = A.size(), n = B.size();
vector<vector<int>> tab(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; ++i)
{
for (int j = 1; j <= n; ++j)
{
if (A[i - 1] == B[j - 1])
tab[i][j] = 1 + tab[i - 1][j - 1];
else
tab[i][j] = max(tab[i - 1][j], tab[i][j - 1]);
}
}
return tab[m][n];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int threeSumClosest(vector<int> &nums, int target)
{
int ret = 0, min_diff = 999999;
sort(nums.begin(), nums.end());
int n = nums.size(), tx = 0, diff;
for (int i = 0; i < nums.size(); ++i)
{
int l = i + 1, r = n - 1;
while (l < r)
{
tx = nums[i] + nums[l] + nums[r];
if (tx == target)
return target;
diff = abs(tx - target);
if (min_diff > diff)
{
min_diff = diff;
ret = tx;
}
if (tx < target)
{
++l;
while (l < r && nums[l] == nums[l - 1])
++l;
}
else
{
--r;
while (r > l && nums[r] == nums[r + 1])
--r;
}
}
}
return ret;
}
};<file_sep>/*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Uber.
* Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
* For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
* Follow-up: what if you can't use division?
*
* Online Judge: https://leetcode.com/problems/product-of-array-except-self/
*/
class Solution
{
public:
vector<int> productExceptSelf(vector<int> &nums)
{
int tmp = 1;
vector<int> res(nums.size(), 1);
for (int i = 1; i < nums.size(); ++i)
res[i] = res[i - 1] * nums[i - 1];
for (int i = nums.size() - 2; i >= 0; --i)
{
tmp *= nums[i + 1];
res[i] = res[i] * tmp;
}
return res;
}
};<file_sep>class Solution
{
public:
int smallestRangeI(vector<int> &A, int K)
{
int max_ele = INT_MIN, min_ele = INT_MAX;
for (int &a : A)
{
max_ele = max(max_ele, a);
min_ele = min(min_ele, a);
}
return max(max_ele - min_ele - 2 * K, 0);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *mergeTwoSortedLists(ListNode *l1, ListNode *l2)
{
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
if (l1->val <= l2->val)
{
l1->next = mergeTwoSortedLists(l1->next, l2);
return l1;
}
else
{
l2->next = mergeTwoSortedLists(l1, l2->next);
return l2;
}
}
ListNode *divideAndMerge(vector<ListNode *> &lists, int start, int end)
{
if (start == end)
return lists[start];
if (end - start == 1)
return mergeTwoSortedLists(lists[start], lists[end]);
int mid = start + ((end - start) >> 1);
ListNode *left = divideAndMerge(lists, start, mid);
ListNode *right = divideAndMerge(lists, mid + 1, end);
return mergeTwoSortedLists(left, right);
}
ListNode *mergeKLists(vector<ListNode *> &lists)
{
if (lists.size() == 0)
return NULL;
if (lists.size() == 1)
return lists[0];
return divideAndMerge(lists, 0, lists.size() - 1);
}
};
// --------------------------------------------------------------------------------------------------------
// /**
// * Definition for singly-linked list.
// * struct ListNode {
// * int val;
// * ListNode *next;
// * ListNode(int x) : val(x), next(NULL) {}
// * };
// */
// class Solution
// {
// public:
// class MyComp
// {
// public:
// bool operator()(const pair<int, ListNode *> &o1, const pair<int, ListNode *> &o2)
// {
// return o1.first > o2.first;
// }
// };
// ListNode *mergeKLists(vector<ListNode *> &lists)
// {
// if (lists.size() == 0)
// return NULL;
// if (lists.size() == 1)
// return lists[0];
// priority_queue<pair<int, ListNode *>, vector<pair<int, ListNode *>>, MyComp> PQ;
// for (int i = 0; i < lists.size(); ++i)
// if (lists[i])
// PQ.push({lists[i]->val, lists[i]});
// if (PQ.size() == 0)
// return NULL;
// ListNode *head = PQ.top().second;
// PQ.pop();
// ListNode *t = head;
// if (t->next != NULL)
// PQ.push({t->next->val, t->next});
// while (!PQ.empty())
// {
// t->next = PQ.top().second;
// t = t->next;
// PQ.pop();
// if (t->next != NULL)
// PQ.push({t->next->val, t->next});
// }
// return head;
// }
// };<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <stack>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
string sequence;
getline(cin, sequence);
unordered_map<char, double> res;
int depth = 0;
for(int i=0; i<sequence.length(); ++i) {
if(sequence[i] == '-') {
res[sequence[++i]] += 1.0/(depth--);
}
else {
++depth;
}
}
auto it = *max_element(res.begin(), res.end(), [](const pair<char, double> &x, const pair<char, double> &y){
return x.second < y.second;
});
cout<<it.first<<"\n";
}<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long int
#define SIEVE_SIZE 2000000
ll primeSumSieve[SIEVE_SIZE];
void generateSieve()
{
/*
generates the sieve
also,
stores the sum of primes upton n in primeSumSieve[n]
(for better efficiency in multiple testcases)
*/
for (int i = 0; i < SIEVE_SIZE; ++i)
primeSumSieve[i] = 1;
primeSumSieve[0] = primeSumSieve[1] = 0;
for (size_t i = 2; i * i <= SIEVE_SIZE; ++i)
{
if (primeSumSieve[i])
{
for (size_t j = i * i; j <= SIEVE_SIZE; j += i)
primeSumSieve[j] = 0;
}
}
ll p_sum = 0;
for (size_t i = 2; i <= SIEVE_SIZE; ++i)
{
if (primeSumSieve[i])
p_sum += i;
primeSumSieve[i] = p_sum;
}
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t = 0, n = 0;
cin >> t;
generateSieve();
while (t--)
{
cin >> n;
cout << primeSumSieve[n] << "\n";
}
return 0;
}
<file_sep>class NumArray
{
vector<int> preSum;
public:
NumArray(vector<int> &nums)
{
preSum = vector<int>(nums.size() + 1, 0);
for (int i = 0; i < nums.size(); ++i)
preSum[i + 1] = nums[i] + preSum[i];
}
int sumRange(int i, int j)
{
return preSum[j + 1] - preSum[i];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
int diameterOfBinaryTreeUtil(TreeNode *root, int &diameter)
{
if (root == NULL)
return 0;
int left = diameterOfBinaryTreeUtil(root->left, diameter);
int right = diameterOfBinaryTreeUtil(root->right, diameter);
// update diameter with sum of left & right subtree heights if smaller
diameter = max(diameter, left + right);
// return the height of the current node
return 1 + max(left, right);
}
int diameterOfBinaryTree(TreeNode *root)
{
int diameter = 0;
diameterOfBinaryTreeUtil(root, diameter);
return diameter;
}
};<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Dropbox.
* Given the root to a binary search tree, find the second largest node in the tree.
*
*
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
TreeNode *getLargest(TreeNode *node)
{
if (node->right != NULL)
return getLargest(node->right);
return node;
}
TreeNode *getSecondLargest(TreeNode *root)
{
// root is pointing to the largest element in bst with a left child
if (root->right == NULL && root->left != NULL)
return getLargest(root->left);
// root is pointing at the parent of the larget element in bst with no children
if (root->right != NULL && root->right->right == NULL && root->right->left == NULL)
return root;
return getSecondLargest(root->right);
}
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <cmath>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int R;
cin >> R; cin.ignore();
int V;
cin >> V; cin.ignore();
vector<pair<int, int> > vaults;
for (int i = 0; i < V; i++) {
int C;
int N;
cin >> C >> N; cin.ignore();
vaults.push_back({N, C-N});
}
int digit_ct = 10, vowel_ct = 5;
int res = 0;
int idx = R <= V ? R : V;
int real_time = 0;
priority_queue<int, vector<int>, greater<int> > pq;
for(int i=0; i<idx; ++i) {
pq.push(pow(digit_ct, vaults[i].first) * pow(vowel_ct, vaults[i].second));
--V;
}
while(V) {
if(idx >= vaults.size()) break;
int tmp = pq.top();
pq.pop();
tmp += pow(digit_ct, vaults[idx].first) * pow(vowel_ct, vaults[idx].second);
pq.push(tmp);
--V;
++idx;
}
while(!pq.empty()) {
res = pq.top();
pq.pop();
}
cout << res << endl;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
unordered_map<string, int> weekdays = {
{"Sunday", 0},
{"Monday", 1},
{"Tuesday", 2},
{"Wednesday", 3},
{"Thursday", 4},
{"Friday", 5},
{"Saturday", 6}};
vector<string> toPrint = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
unordered_map<string, pair<int, int>> months = {
{"Jan", {0, 31}},
{"Feb", {1, 28}},
{"Mar", {2, 31}},
{"Apr", {3, 30}},
{"May", {4, 31}},
{"Jun", {5, 30}},
{"Jul", {6, 31}},
{"Aug", {7, 31}},
{"Sep", {8, 30}},
{"Oct", {9, 31}},
{"Nov", {10, 30}},
{"Dec", {11, 31}},
};
vector<string> toIterate = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
class Date
{
public:
string moy;
int dom;
Date(string moy, int dom)
{
this->moy = moy;
this->dom = dom;
}
int operator-(const Date &obj) const
{
int ret = 0;
int moy_num_src = months[this->moy].first;
int moy_num_des = months[obj.moy].first;
if (moy_num_src < moy_num_des)
{ // month(s) ahead
for (int i = moy_num_src + 1; i < moy_num_des; ++i)
{
ret += months[toIterate[i]].second;
}
ret += (months[this->moy].second - this->dom) + obj.dom;
return ret;
}
else if (moy_num_src > moy_num_des)
{ // month(s) behind
for (int i = moy_num_des + 1; i < moy_num_src; ++i)
{
ret += months[toIterate[i]].second;
}
ret += (months[obj.moy].second - obj.dom) + this->dom;
return -ret;
}
else
{ // same month
ret = obj.dom - this->dom;
return ret;
}
return ret;
}
};
int main()
{
int leapYear;
cin >> leapYear;
cin.ignore();
string sourceDayOfWeek;
string sourceMonth;
int sourceDayOfMonth;
cin >> sourceDayOfWeek >> sourceMonth >> sourceDayOfMonth;
cin.ignore();
string targetMonth;
int targetDayOfMonth;
cin >> targetMonth >> targetDayOfMonth;
cin.ignore();
if (leapYear)
months["Feb"].second = 29;
Date src(sourceMonth, sourceDayOfMonth);
Date tar(targetMonth, targetDayOfMonth);
int dayDiff = src - tar;
if (dayDiff > 0)
cout << toPrint[(weekdays[sourceDayOfWeek] + dayDiff) % 7] << "\n";
else
cout << toPrint[(weekdays[sourceDayOfWeek] + dayDiff + 364) % 7] << "\n";
}<file_sep>// permutation based solution
class Solution
{
public:
void permute(vector<int> &perm, int &result, int idx = 0)
{
if (idx == perm.size())
++result;
else
{
for (int i = idx; i < perm.size(); ++i)
{
if (perm[i] % (idx + 1) == 0 || (idx + 1) % perm[i] == 0)
{
swap(perm[i], perm[idx]);
permute(perm, result, idx + 1);
swap(perm[i], perm[idx]);
}
}
}
}
int countArrangement(int n)
{
int result = 0;
vector<int> perm(n, 0);
for (int i = 0; i < n; ++i)
perm[i] = i + 1;
permute(perm, result);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>from collections import deque
def get_best_path(grid_map):
rows = len(grid_map)
cols = len(grid_map[0])
class Node:
def __init__(self, x, y, can_break):
self.x = x
self.y = y
self.can_break = can_break # a boolean to specify whether or not we can break a wall (should a path be traced from this node)
def __hash__(self):
return self.x ^ self.y
def __eq__(self, other):
return self.x == other.x and self.y == other.y and self.can_break == other.can_break
def get_neighbour_nodes(self):
neighbours = []
if self.x > 0: # can go up
# can go to next node (no wall)
if grid_map[self.x-1][self.y] == 0:
neighbours.append(Node(self.x-1, self.y, self.can_break))
elif self.can_break: # (wall present and) can break a wall
neighbours.append(Node(self.x-1, self.y, False))
if self.x < rows-1: # can go down
# can go to next node (no wall)
if grid_map[self.x+1][self.y] == 0:
neighbours.append(Node(self.x+1, self.y, self.can_break))
elif self.can_break: # (wall present and) can break a wall
neighbours.append(Node(self.x+1, self.y, False))
if self.y > 0: # can go left
# can go to next node (no wall)
if grid_map[self.x][self.y-1] == 0:
neighbours.append(Node(self.x, self.y-1, self.can_break))
elif self.can_break: # (wall present and) can break a wall
neighbours.append(Node(self.x, self.y-1, False))
if self.y < cols-1: # can go right
# can go to next node (no wall)
if grid_map[self.x][self.y+1] == 0:
neighbours.append(Node(self.x, self.y+1, self.can_break))
elif self.can_break: # (wall present and) can break a wall
neighbours.append(Node(self.x, self.y+1, False))
return neighbours
# start from top-left
start = Node(0, 0, True)
queue = deque([start])
distances = {start: 1}
# perform breadth-first-traversal
while len(queue):
cur_node = queue.popleft()
# if we reached the escape pod
if cur_node.x == rows-1 and cur_node.y == cols-1:
return distances[cur_node]
# iterate over the possible neighbours from the current node
for next_node in cur_node.get_neighbour_nodes():
if next_node not in distances.keys():
distances[next_node] = distances[cur_node] + 1
queue.append(next_node)
# no possible path found
return -1
res = get_best_path([[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]])
print(res)
<file_sep>// efficient bit-mask approach
class Solution
{
public:
int bitwiseComplement(int N)
{
if (N == 0)
return 1;
int mask = N;
mask |= (mask >> 1);
mask |= (mask >> 2);
mask |= (mask >> 4);
mask |= (mask >> 8);
mask |= (mask >> 16);
return N ^ mask;
}
};
// simple bitwise flipping approach
class Solution
{
public:
int bitwiseComplement(int N)
{
if (N == 0)
return 1;
int result = 0, i = 0;
while (N)
{
if (N % 2 == 0)
result += pow(2, i);
N >>= 1;
++i;
}
return result;
}
};
// bit mask approach
class Solution
{
public:
int bitwiseComplement(int N)
{
int mask = 1;
while (mask < N)
{
mask = (mask << 1) + 1;
}
return N ^ mask;
}
};<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Google.
* An XOR linked list is a more memory efficient doubly linked list.
* Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at index.
* If using a language that has no pointers (such as Python), you can assume you have access to get_pointer and dereference_pointer functions that converts between nodes and memory addresses.
*
*
*/
#include <bits/stdc++.h>
#include <inttypes.h>
using namespace std;
struct Node
{
int data; // to store data
Node *both; // common pointer for previous and next node
};
class DLL
{
int size;
Node *head; // points to head (start)
Node *tail; // point to tail (end)
public:
DLL()
{
this->size = 0; // initialize with a size of 0
this->head = NULL;
this->tail = NULL;
}
Node *XOR(Node *a, Node *b)
{
// uintptr_t is an unsigned integer pointer data type
// which is generally used when we intend to perform integeral operation on a pointer
// (like in this case XOR operation)
return (Node *)((uintptr_t)a ^ (uintptr_t)b);
}
// insert data at end
void push_back(int data)
{
Node *new_node = new Node();
new_node->data = data;
new_node->both = XOR(this->tail, NULL);
if (this->tail) // if a tail already exists, its "both" must be updated
this->tail->both = XOR(XOR(this->tail->both, NULL), new_node);
if (this->head == NULL) // if this is the first node head must also be updated
this->head = new_node;
this->tail = new_node;
++this->size; // increment size of list
}
//insert data at the begining
void push_front(int data)
{
Node *new_node = new Node();
new_node->data = data;
new_node->both = XOR(NULL, this->head);
if (this->head) // if a head already exists, its "both" must be updated
this->head->both = XOR(new_node, XOR(NULL, this->head->both));
if (this->tail == NULL) // if this is the first node tail must also be updated
this->tail = new_node;
this->head = new_node;
++this->size; // increment size of list
}
// fetch the data at given index [0, this->size-1]
int get(int idx)
{
if (idx + 1 > this->size || idx < 0) // check for invalid index
{
cout << "index out of bounds!!!";
return 0;
}
Node *it = this->head;
Node *prev = NULL;
Node *next = NULL;
while (idx--) // iterate over list
{
next = XOR(it->both, prev);
prev = it;
it = next;
}
return it->data;
}
// delete the node at given index [0, this->size-1]
void delete_node(int idx)
{
if (idx + 1 > this->size || idx < 0) // check for invalid index
{
cout << "index out of bounds!!!";
return;
}
Node *it = this->head;
Node *prev = NULL;
Node *next = NULL;
while (idx--) // iterate over list
{
next = XOR(it->both, prev);
prev = it;
it = next;
}
next = XOR(it->both, prev);
if (prev) // node has a previous node which needs to be updated
prev->both = XOR(XOR(prev->both, it), next);
else // node has no previous node, i.e. head node is being deleted
this->head = next;
if (next) // node has a next node which needs to be updated
next->both = XOR(XOR(next->both, it), prev);
else // node has no next node, i.e. tail node is being deleted
this->tail = prev;
delete (it); // remove the node
}
// print the list
void print()
{
if (this->head == NULL) // check if empty
return;
Node *it = this->head;
Node *prev = NULL;
Node *next = NULL;
while (true) // iterate till end
{
cout << it->data << " ";
if (it == this->tail)
break;
next = XOR(it->both, prev);
prev = it;
it = next;
}
return;
}
};
int main()
{
DLL dll;
dll.push_back(78);
dll.push_front(7);
dll.push_front(2);
dll.push_front(3);
dll.push_back(15);
dll.push_front(1);
dll.push_back(17);
dll.print();
cout << "\n****** getting the element at first index *******\n";
cout << dll.get(1);
cout << "\n****** deleting node at 3rd index *******\n";
dll.delete_node(3);
dll.print();
cout << "\n****** deleting node at 5th index *******\n";
dll.delete_node(5);
dll.print();
cout << "\n****** deleting node at 0th index *******\n";
dll.delete_node(0);
dll.print();
cout << "\n****** deleting node at 1st index *******\n";
dll.delete_node(1);
dll.print();
return 0;
}
<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
int getHeight(TreeNode *root)
{
if (!root)
return 0;
int l_height = getHeight(root->left);
if (l_height == -1)
return -1;
int r_height = getHeight(root->right);
if (r_height == -1)
return -1;
if (abs(l_height - r_height) > 1)
return -1;
return 1 + max(l_height, r_height);
}
bool isBalanced(TreeNode *root)
{
return getHeight(root) != -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int fourSumCount(vector<int> &A, vector<int> &B, vector<int> &C, vector<int> &D)
{
int result = 0;
unordered_map<int, int> mem;
for (int &a : A)
for (int &b : B)
++mem[a + b];
for (int &c : C)
for (int &d : D)
result += mem[-(c + d)];
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// constant space solution
class Solution
{
public:
int largestOverlapUtil(int x_shift, int y_shift, vector<vector<int>> &A, vector<vector<int>> &B)
{
int row = 0, col = 0, n = A.size(), count = 0;
for (int shift_row = x_shift; shift_row < n; ++shift_row)
{
col = 0;
for (int shift_col = y_shift; shift_col < n; ++shift_col)
{
if (A[shift_row][shift_col] == 1 && A[shift_row][shift_col] == B[row][col])
++count;
++col;
}
++row;
}
return count;
}
int largestOverlap(vector<vector<int>> &A, vector<vector<int>> &B)
{
int result = INT_MIN, n = A.size();
for (int x_shift = 0; x_shift < n; ++x_shift)
{
for (int y_shift = 0; y_shift < n; ++y_shift)
{
result = max(result, largestOverlapUtil(x_shift, y_shift, A, B));
result = max(result, largestOverlapUtil(x_shift, y_shift, B, A));
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// efficient for sparse matrices
class Solution
{
public:
int largestOverlap(vector<vector<int>> &A, vector<vector<int>> &B)
{
int n = A.size(), result = 0;
vector<int> t_a, t_b;
unordered_map<int, int> mem;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (A[i][j] == 1)
t_a.emplace_back(i * 100 + j);
if (B[i][j] == 1)
t_b.emplace_back(i * 100 + j);
}
}
for (int &e : t_a)
{
for (int &f : t_b)
{
++mem[e - f];
}
}
for (auto element : mem)
result = max(result, element.second);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long int
// ll gcd(ll a, ll b) {
// // returns the gcd of two numbers
// if(b == 0) return a;
// return gcd(b, a%b);
// }
// ll lcm(ll a, ll b) {
// // returns the lcm of two numbers, lcm(x,y) = (x*y)/gcd(x,y)
// return (a*b)/gcd(a, b);
// }
// ll getSmallestMultiple(ll n) {
// // returns the smallest multiple divisible by all numbers in [1, n]
// // lcm(x,y,z) lcm(lcm(x,y),z)
// ll result = 1;
// for(int i=2; i<=n; ++i)
// result = lcm(result, i);
// return result;
// }
bool sieve[50];
void generateSieve()
{
for (int i = 0; i < 50; ++i)
sieve[i] = true;
sieve[0] = sieve[1] = false;
for (int i = 2; i * i < 50; ++i)
{
if (sieve[i])
{
for (int j = i * i; j < 50; j += i)
{
sieve[j] = false;
}
}
}
}
ll getSmallestMultipleOptimal(ll n)
{
/*
refer this : https://projecteuler.net/overview=005
we need all prime numbers upto n (n <= 40, given)
*/
ll result = 1;
vector<int> primes;
for (int i = 2; i <= n; ++i)
{
if (sieve[i])
primes.push_back(i);
}
bool flag = true;
for (int i = 0; i < primes.size(); ++i)
{
if (primes[i] * primes[i] > n)
flag = false;
if (flag)
{
result *= pow(primes[i], floor(log(n) / log(primes[i])));
}
else
{
result *= primes[i];
}
}
return result;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
ll t = 0, n = 0;
cin >> t;
generateSieve();
while (t--)
{
cin >> n;
cout << getSmallestMultipleOptimal(n) << "\n";
}
return 0;
}
<file_sep>class Solution
{
public:
int reverse(int x)
{
long long int ret = 0;
while (x)
{
if (abs((long)10 * ret) > INT_MAX)
return 0;
ret = 10 * ret + x % 10;
x /= 10;
}
return ret;
}
};<file_sep>/**
*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Google.
* You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall. Each False boolean represents a tile you can walk on.
* Given this matrix, a start coordinate, and an end coordinate, return the minimum number of steps required to reach the end coordinate from the start. If there is no possible path, then return null. You can move up, left, down, and right. You cannot move through walls. You cannot wrap around the edges of the board.
* For example, given the following board:
[[f, f, f, f],
[t, t, f, t],
[f, f, f, f],
[f, f, f, f]]
* and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum number of steps required to reach the end is 7, since we would need to go through (1, 2) because there is a wall everywhere else on the second row.
*
*/
<file_sep>class Solution
{
public:
int minAddToMakeValid(string S)
{
int result = 0, count = 0;
for (char &c : S)
{
if (c == '(')
++count;
else
{
if (count == 0)
++result;
else
--count;
}
}
return result + count;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int removeCoveredIntervals(vector<vector<int>> &intervals)
{
if (intervals.size() == 0)
return 0;
int result = 1;
sort(intervals.begin(), intervals.end(), [](const vector<int> &a, const vector<int> &b) {
if (a[0] == b[0])
return a[1] > b[1];
return a[0] < b[0];
});
int start = intervals[0][0], end = intervals[0][1];
for (int i = 1; i < intervals.size(); ++i)
{
if (start > intervals[i][0] || intervals[i][1] > end)
{
++result;
start = intervals[i][0];
end = intervals[i][1];
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// BIT based solution
class NumArray
{
vector<int> f, nums;
void update_tree(int idx, int val)
{
while (idx < f.size())
{
f[idx] += val;
idx += (idx & -idx);
}
}
int get_from_tree(int idx)
{
int res = 0;
while (idx > 0)
{
res += f[idx];
idx -= (idx & -idx);
}
return res;
}
public:
NumArray(vector<int> &nums)
{
this->nums = nums;
this->f = vector<int>(nums.size() + 1, 0);
for (int i = 0; i < nums.size(); ++i)
update_tree(i + 1, nums[i]);
}
void update(int index, int val)
{
update_tree(index + 1, val - nums[index]);
nums[index] = val;
}
int sumRange(int left, int right)
{
return get_from_tree(right + 1) - get_from_tree(left);
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* obj->update(index,val);
* int param_2 = obj->sumRange(left,right);
*/
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Point{
public:
int x;
int y;
Point(int x, int y) {
this->x = x;
this->y = y;
}
};
double getDistance(Point a, Point b) {
return sqrt(pow((b.x - a.x), 2) + pow((b.y - a.y), 2));
}
double isRightAngle(Point a, Point b, Point c) {
return (b.x - a.x)*(c.x - b.x) + (b.y - a.y)*(c.y - b.y) == 0;
}
string whichQuad(Point a, Point b, Point c, Point d) {
if(getDistance(a,b) == getDistance(c,d) && getDistance(b,c) == getDistance(d,a)) {
if(isRightAngle(a, b, c)) { // not parallelogram/rhombus
if(getDistance(a,b) == getDistance(b,c)) return "square";
return "rectangle";
}
else {
if(getDistance(a,b) == getDistance(b,c)) return "rhombus";
return "parallelogram";
}
}
return "quadrilateral";
}
int main()
{
int n;
cin >> n; cin.ignore();
for (int i = 0; i < n; i++) {
string A;
int xA;
int yA;
string B;
int xB;
int yB;
string C;
int xC;
int yC;
string D;
int xD;
int yD;
cin >> A >> xA >> yA >> B >> xB >> yB >> C >> xC >> yC >> D >> xD >> yD; cin.ignore();
Point a(xA, yA);
Point b(xB, yB);
Point c(xC, yC);
Point d(xD, yD);
cout<<A<<B<<C<<D<<" is a "<<whichQuad(a,b,c,d)<<".\n";
}
}<file_sep>class Solution
{
public:
int maxDepth(string s)
{
int result = 0, depth = 0;
for (char &c : s)
{
depth += (c == '(') ? 1 : ((c == ')') ? -1 : 0);
result = max(result, depth);
}
return result;
}
};<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
int t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
vector<ll> A(n, 0);
vector<ll> B(n, 0);
for (int i = 0; i < n; ++i)
cin >> A[i];
for (int i = 0; i < n; ++i)
cin >> B[i];
reverse(B.begin(), B.end());
int j = 0;
ll ans = LONG_MIN;
for (int i = 0; i < n; ++i)
{
if (A[i] > B[0])
{
ans = max(ans, (ll)0);
}
j = lower_bound(B.begin(), B.end(), A[i]) - B.begin();
j = n - j - 1;
if (j >= i)
ans = max(ans, (ll)(j - i));
else
ans = max(ans, (ll)0);
}
cout << ans << "\n";
}
return 0;
}<file_sep>// dfs approach
class Solution
{
public:
bool canReach(vector<int> &arr, int start)
{
if (start >= 0 && start < arr.size() && arr[start] >= 0)
{
if (arr[start] == 0)
return true;
arr[start] = -arr[start];
return canReach(arr, start + arr[start]) || canReach(arr, start - arr[start]);
}
return false;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// bfs approach
class Solution
{
public:
bool canReach(vector<int> &arr, int start)
{
int cur_idx = 0, left_idx = 0, right_idx = 0;
queue<int> Q;
Q.push(start);
while (Q.size())
{
cur_idx = Q.front();
Q.pop();
if (arr[cur_idx] == 0)
return true;
if (arr[cur_idx] < 0)
continue;
left_idx = cur_idx - arr[cur_idx];
right_idx = cur_idx + arr[cur_idx];
if (left_idx >= 0)
Q.push(left_idx);
if (right_idx < arr.size())
Q.push(right_idx);
arr[cur_idx] = -arr[cur_idx];
}
return false;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
vector<int> relativeSortArray(vector<int> &arr1, vector<int> &arr2)
{
vector<int> HashMap(1001, 0);
int idx = 0;
for (int &a : arr1)
++HashMap[a];
for (int &b : arr2)
{
while (HashMap[b] > 0)
{
arr1[idx++] = b;
--HashMap[b];
}
}
for (int i = 0; i < 1001; ++i)
{
while (HashMap[i] > 0)
{
arr1[idx++] = i;
--HashMap[i];
}
}
return arr1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
bool isPunct(char c)
{
return !isalnum(c) && c != ' ';
}
string removeExtraSpaces(string s)
{
string ret;
int n = s.length();
int i = 0;
while (i < n)
{
if (s[i] == ' ')
{
while (i < n && s[i] == ' ')
++i;
if (!isPunct(s[i]))
ret += " ";
}
if (i < n)
ret += s[i];
++i;
}
return ret;
}
string putSpaces(string s)
{
string ret;
int n = s.length();
int i = 0;
while (i < n)
{
if (isPunct(s[i]))
{
ret += s[i];
if (i + 1 < n && s[i + 1] != ' ')
ret += " ";
++i;
}
if (i < n)
ret += s[i];
++i;
}
return ret;
}
string removeExtraPuncts(string s)
{
string ret;
int n = s.length();
int i = 0;
while (i < n)
{
if (isPunct(s[i]))
{
ret += s[i];
while (i < n && isPunct(s[i]))
++i;
}
if (i < n)
ret += s[i];
++i;
}
return ret;
}
string capitalize(string s)
{
string ret;
int n = s.length();
int i = 0;
for (int j = 0; j < n; ++j)
s[j] = tolower(s[j]);
while (i < n)
{
if (s[i] == '.')
{
if (i + 2 < n)
s[i + 2] = toupper(s[i + 2]);
}
ret += s[i];
++i;
}
ret[0] = toupper(ret[0]);
return ret;
}
int main()
{
string intext;
getline(cin, intext);
string result = removeExtraSpaces(intext);
result = removeExtraPuncts(result);
result = putSpaces(result);
result = capitalize(result);
cout << result << "\n";
}<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
int main()
{
int n = 0;
ll max_ele = INT_MIN;
long double x = 0, prod = 0;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> x;
prod += log(x);
max_ele = max(max_ele, (ll)x);
}
if (max_ele == 1)
{
cout << "2";
return 0;
}
ll l = 1, r = max_ele, mid = 0, ans = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
if ((long double)n * log((long double)mid) > prod)
{
ans = mid;
r = mid - 1;
}
else
l = mid + 1;
}
cout << ans;
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
vector<int> bowls(14, 0);
for (int i = 0; i < 14; ++i)
{
cin >> bowls[i];
}
int num;
cin >> num;
cin.ignore();
num += 8;
int grains = bowls[num - 1];
bowls[num - 1] = 0;
while (grains)
{
if (num == 6)
++num;
++bowls[num];
num = (num + 1) % 14;
--grains;
}
for (int i = 0; i < 14; ++i)
{
if (i == 6 || i == 13)
cout << "[" << bowls[i] << "]\n";
else
cout << bowls[i] << " ";
}
if (num == 0)
cout << "REPLAY";
}<file_sep>class Solution
{
public:
int calculateMinimumHP(vector<vector<int>> &dungeon)
{
int rows = dungeon.size();
int cols = dungeon[0].size();
vector<vector<int>> tab(rows, vector<int>(cols, 0));
for (int i = rows - 1; i >= 0; --i)
{
for (int j = cols - 1; j >= 0; --j)
{
if (i == rows - 1 && j == cols - 1)
tab[i][j] = max(1, 1 - dungeon[i][j]);
else if (i == rows - 1)
{
tab[i][j] = max(1, tab[i][j + 1] - dungeon[i][j]);
}
else if (j == cols - 1)
{
tab[i][j] = max(1, tab[i + 1][j] - dungeon[i][j]);
}
else
{
tab[i][j] = max(1, min(tab[i + 1][j], tab[i][j + 1]) - dungeon[i][j]);
}
}
}
return tab[0][0];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, max_ele = INT_MIN, min_ele = INT_MAX, sum = 0, x = 0;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> x;
sum += x;
max_ele = max(max_ele, x);
min_ele = min(min_ele, x);
}
cout << (sum - max_ele) << " " << (sum - min_ele);
return 0;
}<file_sep>// iterative solution
class Solution
{
public:
int rangeBitwiseAnd(int m, int n)
{
if (m == 0 || m == n)
return m;
if ((n / m) >= 2)
return 0;
int i = 0;
while (m != n)
{
m >>= 1;
n >>= 1;
++i;
}
return (m << i);
}
};
// recursive solution
class Solution
{
public:
int rangeBitwiseAnd(int m, int n)
{
return m != n ? (rangeBitwiseAnd(m >> 1, n >> 1) << 1) : m;
}
};<file_sep>// a better approach
// (find a number with all bits as 1 untill the left most set bit of num,
// xor it with num to get the result, eg: num = 5(101) ^ (111) = 2(010))
class Solution
{
public:
int findComplement(int num)
{
int bitmask = 1;
while (bitmask < num)
bitmask = (bitmask << 1) + 1;
return bitmask ^ num;
}
};
// normal approach
class Solution
{
public:
int findComplement(int num)
{
if (num == 0)
return 1;
int result = 0, rem = 0, power = 0;
while (num)
{
rem = num % 2;
if (rem == 0)
result += pow(2, power);
num /= 2;
++power;
}
return result;
}
};<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
long long int t = 0, n = 0, a = 0, b = 0, cost1 = 0, cost2 = 0, x = 0, y = 0;
cin >> t;
while (t--)
{
cin >> n >> a >> b;
x = n * b / (a + b);
y = n - x;
cost1 = a * x * x + b * y * y;
++x;
--y;
cost2 = a * x * x + b * y * y;
cout << min(cost1, cost2) << "\n";
}
return 0;
}<file_sep>class Solution {
public:
void markRegions(vector<vector<char>>& board, int r, int c) {
static vector<pair<int, int>> dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
board[r][c] = '?';
int x = 0, y = 0;
for(auto d : dirs) {
x = r + d.first;
y = c + d.second;
if(x >= 0 && x < board.size() && y >= 0 && y < board[x].size() && board[x][y] == 'O')
markRegions(board, x, y);
}
}
void solve(vector<vector<char>>& board) {
if(board.size() <= 2) return;
int m = board.size(), n = board[0].size();
if(n <= 2) return;
for(int i=0; i<m; ++i) {
if(board[i][0] == 'O') markRegions(board, i, 0);
if(board[i][n-1] == 'O') markRegions(board, i, n-1);
}
for(int i=0; i<n; ++i) {
if(board[0][i] == 'O') markRegions(board, 0, i);
if(board[m-1][i] == 'O') markRegions(board, m-1, i);
}
for(int i=0; i<m; ++i) {
for(int j=0; j<n; ++j) {
if(board[i][j] == 'O') board[i][j] = 'X';
else if(board[i][j] == '?') board[i][j] = 'O';
}
}
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// better solution
class Solution
{
public:
int findNumbers(vector<int> &nums)
{
int result = 0;
for (int &n : nums)
{
result += ((n >= 10 && n <= 99) || (n >= 1000 && n <= 9999) || (n == 100000)) ? 1 : 0;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// simple solution
class Solution
{
public:
int getDigitCount(int n)
{
int count = 0;
while (n)
{
n /= 10;
++count;
}
return count;
}
int findNumbers(vector<int> &nums)
{
int result = 0;
for (int &n : nums)
result += (getDigitCount(n) % 2 ? 0 : 1);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *reverseBetween(ListNode *head, int m, int n)
{
if (m == n)
return head;
int count = 1;
ListNode *cur = head;
ListNode *prev = NULL;
ListNode *next = head->next;
ListNode *start_a = NULL;
ListNode *start_b = NULL;
while (count <= n)
{
if (count == m)
{
start_a = prev;
start_b = cur;
}
else if (count > m)
{
cur->next = prev;
}
prev = cur;
cur = next;
if (cur)
next = cur->next;
++count;
}
if (start_a)
start_a->next = prev;
if (start_b)
start_b->next = cur;
// if m == 1 start_a is always null hence last prev is the new head
if (m == 1)
return prev;
return head;
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int speed;
cin >> speed;
cin.ignore();
int lightCount;
cin >> lightCount;
cin.ignore();
vector<pair<int, int>> lights;
for (int i = 0; i < lightCount; i++)
{
int distance;
int duration;
cin >> distance >> duration;
cin.ignore();
lights.push_back({distance, duration});
}
bool flag = true;
for (int i = speed; i >= 1; --i)
{
flag = true;
for (int j = 0; j < lights.size(); ++j)
{
int tm = (lights[j].first * 18) / (i * 5);
if (tm % (2 * lights[j].second) >= lights[j].second)
{
flag = false;
break;
}
}
if (flag)
{
cout << i << "\n";
return 0;
}
}
cout << "0" << endl;
}<file_sep>// O(logn) solution
class Solution
{
public:
int hIndex(vector<int> &citations)
{
int n = citations.size();
int l = 0, r = n - 1, mid = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
if (citations[mid] >= n - mid)
r = mid - 1;
else
l = mid + 1;
}
return n - l;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(n) solution
class Solution
{
public:
int hIndex(vector<int> &citations)
{
int n = citations.size();
for (int i = 0; i < n; ++i)
{
if (citations[i] >= n - i)
return n - i;
}
return 0;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
long long int n = 0, x = 0, count = 0, max_sum = 0, max_ele = INT_MIN;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> x;
max_ele = max(max_ele, x);
if (x >= 0)
{
++count;
max_sum += x;
}
}
if (max_ele < 0)
{
cout << max_ele << " 1";
return 0;
}
cout << max_sum << " " << count;
return 0;
}<file_sep>"""
#
# Good morning! Here's your coding interview problem for today.
# This problem was asked by Facebook.
# Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability.
#
#
# reference:
# https://en.wikipedia.org/wiki/Reservoir_sampling
# https://www.dailycodingproblem.com/blog/how-to-pick-a-random-element-from-an-infinite-stream/
# https://galaiko.rocks/posts/probability/
#
# """
import random
def pick(stream):
random_element = 0
for i, e in enumerate(stream):
if random.randint(1, i+1) == 1:
random_element = e
return random_element
print(pick([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
"""
# Online Judge: https://leetcode.com/problems/random-pick-index/
#
# language: C++
#
#
#
#
#
class Solution {
vector<int> nums;
public:
Solution(vector<int>& nums) {
this->nums = nums;
}
int pick(int target) {
int count = 0, idx = -1;
for(int i=0; i<this->nums.size(); ++i) {
if(this->nums[i] == target) {
++count;
if(1+(rand()%count) == 1) idx = i;
}
}
return idx;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(nums);
* int param_1 = obj->pick(target);
*/
"""
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
ll n = 0, total_xor = 0, xor_1 = 0, xor_2 = 0;
cin >> n;
vector<ll> a(n, 0);
for (int i = 0; i < n; ++i)
{
cin >> a[i];
total_xor ^= a[i];
}
total_xor = total_xor ^ (total_xor & (total_xor - 1));
for (ll &e : a)
{
if ((e & total_xor) == 0)
xor_1 ^= e;
else
xor_2 ^= e;
}
cout << min(xor_1, xor_2) << " " << max(xor_1, xor_2);
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
string b;
getline(cin, b);
int prev_zero = 0, prev_prev_zero = -1, max_so_far = -999999;
for(int i=0; i<b.length(); ++i) {
if(b[i] == '0') {
prev_zero = i;
break;
}
}
int i = 0;
for(i=prev_zero+1; i<b.length(); ++i) {
if(b[i] == '0') {
max_so_far = max(max_so_far, ((i - prev_zero - 1) + (prev_zero - prev_prev_zero)));
prev_prev_zero = prev_zero;
prev_zero = i;
}
}
max_so_far = max(max_so_far, ((i - prev_zero - 1) + (prev_zero - prev_prev_zero)));
cout<<max_so_far<<"\n";
}<file_sep>#include <bits/stdc++.h>
using namespace std;
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
int main()
{
int n = 0, c = 0, p = 0;
cin >> n;
vector<int> a;
while (n--)
{
cin >> c;
if (c == 1)
{
cin >> p;
a.insert(upper_bound(a.begin(), a.end(), p), p);
}
else
{
if (a.size() < 3)
cout << "Not enough enemies\n";
else
{
cout << a[a.size() - (a.size() / 3)] << "\n";
}
}
}
return 0;
}
// #include <bits/stdc++.h>
// using namespace std;
// auto speedup = []() {
// std::ios::sync_with_stdio(false);
// cin.tie(nullptr);
// cout.tie(nullptr);
// return nullptr;
// }();
// int main()
// {
// int n = 0, c = 0, p = 0;
// cin >> n;
// vector<int> a;
// while (n--)
// {
// cin >> c;
// if (c == 1)
// {
// cin >> p;
// a.push_back(p);
// }
// else
// {
// if (a.size() < 3)
// cout << "Not enough enemies\n";
// else
// {
// nth_element(a.begin(), a.begin() + ((a.size() / 3) - 1), a.end(), greater<int>());
// cout << a[(a.size() / 3) - 1] << "\n";
// }
// }
// }
// return 0;
// }<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ull long long int
#define SIEVE_SIZE 1000001
bool sieve[SIEVE_SIZE];
vector<int> primes;
void generateSieve()
{
for (int i = 0; i < SIEVE_SIZE; ++i)
{
sieve[i] = true;
}
sieve[0] = sieve[1] = false;
for (int i = 2; i * i <= SIEVE_SIZE; ++i)
{
for (int j = i * i; j < SIEVE_SIZE; j += i)
{
sieve[j] = false;
}
}
for (int i = 0; i < SIEVE_SIZE; ++i)
if (sieve[i])
primes.push_back(i);
}
int main()
{
generateSieve();
ull n = 0, val = 0;
cin >> n;
for (int &c : primes)
{
val = n - 9 - powl(c, 3);
if (powl((ull)(cbrtl(val)), 3) != val)
continue;
val = cbrtl(val);
if (sieve[val])
{
cout << "1 2 " << c << " " << val;
return 0;
}
}
cout << "-1";
return 0;
}<file_sep>// mathematical solution, constant space & time (n+4)C4
class Solution
{
public:
int countVowelStrings(int n)
{
return ((n + 1) * (n + 2) * (n + 3) * (n + 4)) / 24;
}
};
// space efficient dp solution
class Solution
{
public:
int countVowelStrings(int n)
{
int a = 1, e = 1, i = 1, o = 1, u = 1;
while (n > 1)
{
a = (a + e + i + o + u);
e = (e + i + o + u);
i = (i + o + u);
o = (o + u);
--n;
}
return a + e + i + o + u;
}
};
// dp solution
class Solution
{
public:
int countVowelStrings(int n)
{
vector<vector<int>> tab(n + 1, vector<int>(6, 0));
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= 5; ++j)
tab[i][j] = tab[i][j - 1] + (i > 1 ? tab[i - 1][j] : 1);
return tab[n][5];
}
};
// recursive solution (inefficient)
class Solution
{
public:
void countVowelStringsUtil(int &n, int &result, int cur = 0, int sz = 0)
{
if (sz == n)
++result;
else
for (int i = cur; i < 5; ++i)
countVowelStringsUtil(n, result, i, sz + 1);
}
int countVowelStrings(int n)
{
int result = 0;
countVowelStringsUtil(n, result);
return result;
}
};<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
using namespace std;
int calculate_score(string &name, int rank)
{
int score = 0;
for (char c : name)
{
score += (int(c) - int('A') + 1);
}
return score * rank;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n = 0, q = 0;
cin >> n;
vector<string> names;
unordered_map<string, int> scores;
string input;
for (int i = 0; i < n; ++i)
{
cin >> input;
names.emplace_back(input);
}
sort(names.begin(), names.end());
for (int i = 0; i < n; ++i)
{
scores[names[i]] = calculate_score(names[i], i + 1);
}
cin >> q;
while (q--)
{
cin >> input;
cout << scores[input] << "\n";
}
return 0;
}
<file_sep>// stack solution
class StockSpanner
{
public:
stack<pair<int, int>> stocks;
StockSpanner()
{
}
int next(int price)
{
int count = 1;
while (!stocks.empty() && stocks.top().first <= price)
{
count += stocks.top().second;
stocks.pop();
}
stocks.push({price, count});
return count;
}
};
/**
* Your StockSpanner object will be instantiated and called as such:
* StockSpanner* obj = new StockSpanner();
* int param_1 = obj->next(price);
*/
// dp solution
class StockSpanner
{
public:
vector<int> stocks;
vector<int> tab;
StockSpanner()
{
}
int next(int price)
{
this->stocks.emplace_back(price);
int count = 1, idx = this->stocks.size() - 2;
while (idx >= 0 && this->stocks[idx] <= price)
{
count += tab[idx];
idx -= tab[idx];
}
tab.emplace_back(count);
return count;
}
};
/**
* Your StockSpanner object will be instantiated and called as such:
* StockSpanner* obj = new StockSpanner();
* int param_1 = obj->next(price);
*/<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Google.
* Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
* For example, given the following Node class
-------------------------------------------------------------------------
|class Node: |
|def __init__(self, val, left=None, right=None): |
| self.val = val |
| self.left = left |
| self.right = right |
-------------------------------------------------------------------------
* The following test should pass:
-------------------------------------------------------------------------
|node = Node('root', Node('left', Node('left.left')), Node('right')) |
|assert deserialize(serialize(node)).left.left.val == 'left.left' |
-------------------------------------------------------------------------
*
* Online Judge: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
*
*/
// ************************************** my approach **************************************
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// class Codec {
// public:
// // Encodes a tree to a single string.
// string serialize(TreeNode* root) {
// if(root == NULL) return "x,";
// queue<TreeNode*> Q;
// Q.push(root);
// TreeNode* tmp = NULL;
// string ret;
// while(!Q.empty()) {
// tmp = Q.front();
// Q.pop();
// if(tmp) {
// ret += to_string(tmp->val) + ",";
// Q.push(tmp->left);
// Q.push(tmp->right);
// }
// else ret += "x,";
// }
// int ind = ret.length()-2;
// while(ret[ind] == 'x') ind -= 2;
// return ret.substr(0, ind+2);
// }
// vector<TreeNode*> getValues(string data) {
// vector<TreeNode*> ret;
// size_t cur_pos = 0, pos = 0;
// pos = data.find(",", cur_pos);
// string tmp;
// while(pos != string::npos) {
// tmp = data.substr(cur_pos, pos-cur_pos);
// if(tmp == "x") ret.push_back(NULL);
// else ret.emplace_back(new TreeNode(stoi(tmp)));
// cur_pos = pos+1;
// pos = data.find(",", cur_pos);
// }
// return ret;
// }
// // Decodes your encoded data to tree.
// TreeNode* deserialize(string data) {
// vector<TreeNode*> tree = getValues(data);
// int ind = 1;
// for(int i=0; i<tree.size(); ++i) {
// if(tree[i]) {
// if(ind < tree.size()) tree[i]->left = tree[ind];
// if(ind+1 < tree.size()) tree[i]->right = tree[ind+1];
// ind +=2;
// }
// }
// return tree[0];
// }
// };
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
// ************************************** General approach (using preorder traversal) **************************************
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec
{
public:
void serializeUtil(TreeNode *root, ostringstream &out)
{
if (root == NULL)
out << "x ";
else
{
out << root->val << " ";
serializeUtil(root->left, out);
serializeUtil(root->right, out);
}
}
// Encodes a tree to a single string.
string serialize(TreeNode *root)
{
ostringstream out;
serializeUtil(root, out);
return out.str();
}
TreeNode *deserializeUtil(istringstream &in)
{
string val;
in >> val;
if (val == "x")
return NULL;
TreeNode *root = new TreeNode(stoi(val));
root->left = deserializeUtil(in);
root->right = deserializeUtil(in);
return root;
}
// Decodes your encoded data to tree.
TreeNode *deserialize(string data)
{
istringstream in(data);
return deserializeUtil(in);
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
<file_sep>// without stack solution
class Solution
{
public:
bool checkValidString(string s)
{
int l = 0, h = 0;
for (char &c : s)
{
if (c == '(')
{
++l;
++h;
}
else if (c == ')')
{
--l;
--h;
}
else
{
--l;
++h;
}
if (h < 0)
return false;
if (l < 0)
l = 0;
}
return l == 0;
}
};
// two stack solution
class Solution
{
public:
bool checkValidString(string s)
{
stack<int> paren, aster;
for (int i = 0; i < s.length(); ++i)
{
if (s[i] == '(')
paren.push(i);
else if (s[i] == '*')
aster.push(i);
else
{
if (paren.empty())
{
if (aster.empty())
return false;
aster.pop();
}
else
{
paren.pop();
}
}
}
while (!paren.empty() && !aster.empty() && paren.top() < aster.top())
{
aster.pop();
paren.pop();
}
if (!paren.empty())
return false;
return true;
}
};<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
{
stack<int> s1, s2;
ListNode *cur = l1;
while (cur)
{
s1.push(cur->val);
cur = cur->next;
}
cur = l2;
while (cur)
{
s2.push(cur->val);
cur = cur->next;
}
int sum_c = 0;
if (s1.size())
sum_c += s1.top(), s1.pop();
if (s2.size())
sum_c += s2.top(), s2.pop();
ListNode *prev = new ListNode(sum_c % 10);
sum_c /= 10;
while (s1.size() || s2.size() || sum_c)
{
if (s1.size())
sum_c += s1.top(), s1.pop();
if (s2.size())
sum_c += s2.top(), s2.pop();
cur = new ListNode(sum_c % 10);
sum_c /= 10;
cur->next = prev;
prev = cur;
}
return prev;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
bool isRobotBounded(string instructions)
{
int dir = 0, x = 0, y = 0;
vector<pair<int, int>> delta = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
for (char &c : instructions)
{
if (c == 'R')
dir = (dir + 1) % 4;
else if (c == 'L')
dir = (4 + dir - 1) % 4;
else
{
x += delta[dir].first;
y += delta[dir].second;
}
}
return (x == 0 && y == 0) || (dir != 0);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
vector<vector<int>> ret;
vector<vector<int>> fourSum(vector<int> &nums, int target)
{
if (nums.size() == 0)
return ret;
int n = nums.size();
sort(nums.begin(), nums.end());
if (nums[n - 1] * 4 < target)
return ret;
for (int i = 0; i < nums.size(); ++i)
{
threeSum(nums, i + 1, target - nums[i]);
while (i < n - 1 && nums[i] == nums[i + 1])
++i;
}
return ret;
}
void threeSum(vector<int> &nums, int ind, int target)
{
int n = nums.size();
if (nums[n - 1] * 3 < target)
return;
for (int i = ind; i < n; ++i)
{
if (nums[n - 1] * 2 < target - nums[i])
continue;
int l = i + 1, r = n - 1;
while (l < r)
{
int x = nums[i] + nums[l] + nums[r];
if (x == target)
{
ret.push_back({nums[ind - 1], nums[i], nums[l], nums[r]});
++l;
--r;
while (l < r && nums[l] == nums[l - 1])
++l;
while (r > l && nums[r] == nums[r + 1])
--r;
}
else if (x < target)
{
++l;
while (l < r && nums[l] == nums[l - 1])
++l;
}
else
{
--r;
while (r > l && nums[r] == nums[r + 1])
--r;
}
}
while (i < n - 1 && nums[i] == nums[i + 1])
++i;
}
}
};<file_sep>// count sort
class Solution
{
public:
vector<int> sortArray(vector<int> &nums)
{
int count[100001];
memset(count, 0, sizeof(count));
for (int &n : nums)
++count[n + 50000];
int idx = 0;
for (int i = 0; i < 100001; ++i)
{
if (count[i])
for (int j = 0; j < count[i]; ++j)
nums[idx++] = i - 50000;
}
return nums;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void maxAncestorDiffUtil(TreeNode *root, int &result, int min_so_far = INT_MAX, int max_so_far = INT_MIN)
{
if (!root)
return;
min_so_far = min(min_so_far, root->val);
max_so_far = max(max_so_far, root->val);
result = max(result, max_so_far - min_so_far);
maxAncestorDiffUtil(root->left, result, min_so_far, max_so_far);
maxAncestorDiffUtil(root->right, result, min_so_far, max_so_far);
}
int maxAncestorDiff(TreeNode *root)
{
int result = INT_MIN;
maxAncestorDiffUtil(root, result);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
void makeLPS(vector<int> &lps, string s)
{
int i = 1, len = 0, n = s.length();
lps[0] = 0;
while (i < n)
{
if (s[i] == s[len])
{
++len;
lps[i] = len;
++i;
}
else
{
if (len > 0)
len = lps[len - 1];
else
{
lps[i] = 0;
++i;
}
}
}
}
int strStr(string haystack, string needle)
{
if (haystack.length() == 0)
return needle.length() == 0 ? 0 : -1;
if (needle.length() == 0)
return 0;
int h_len = haystack.length();
int n_len = needle.length();
vector<int> lps(n_len, 0);
makeLPS(lps, needle);
int i = 0, j = 0;
while (i < h_len)
{
if (haystack[i] == needle[j])
{
++i;
++j;
}
if (j == n_len)
return i - j;
if (haystack[i] != needle[j])
{
if (j > 0)
j = lps[j - 1];
else
++i;
}
}
return -1;
}
};<file_sep>// bfs solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
vector<vector<int>> levelOrderBottom(TreeNode *root)
{
if (!root)
return {};
vector<vector<int>> result;
vector<int> res;
queue<TreeNode *> Q;
TreeNode *cur = NULL;
int q_size = 0;
Q.push(root);
while (!Q.empty())
{
res.clear();
q_size = Q.size();
while (q_size--)
{
cur = Q.front();
Q.pop();
res.emplace_back(cur->val);
if (cur->left)
Q.push(cur->left);
if (cur->right)
Q.push(cur->right);
}
result.emplace_back(res);
}
reverse(result.begin(), result.end());
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// dfs solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void dfs(TreeNode *root, vector<vector<int>> &result, int level = 1)
{
if (!root)
return;
if (result.size() < level)
{
result.push_back({});
}
dfs(root->left, result, level + 1);
dfs(root->right, result, level + 1);
result[level - 1].emplace_back(root->val);
}
vector<vector<int>> levelOrderBottom(TreeNode *root)
{
if (!root)
return {};
vector<vector<int>> result;
dfs(root, result);
reverse(result.begin(), result.end());
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
vector<vector<int>> ret;
void permuteUtil(vector<int> &nums, int ind)
{
if (ind == nums.size())
{
ret.push_back(nums);
return;
}
for (int i = ind; i < nums.size(); ++i)
{
swap(nums[i], nums[ind]);
permuteUtil(nums, ind + 1);
swap(nums[i], nums[ind]);
}
}
vector<vector<int>> permute(vector<int> &nums)
{
permuteUtil(nums, 0);
return ret;
}
};<file_sep>// iterative solution (using queue)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
TreeNode *invertTree(TreeNode *root)
{
if (!root)
return NULL;
TreeNode *cur = NULL;
TreeNode *tmp = NULL;
queue<TreeNode *> Q;
Q.push(root);
while (!Q.empty())
{
cur = Q.front();
Q.pop();
tmp = cur->left;
cur->left = cur->right;
cur->right = tmp;
if (cur->left)
Q.push(cur->left);
if (cur->right)
Q.push(cur->right);
}
return root;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// iterative solution (using stack)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
TreeNode *invertTree(TreeNode *root)
{
if (!root)
return NULL;
TreeNode *cur = root;
TreeNode *tmp = NULL;
stack<TreeNode *> S;
while (cur || !S.empty())
{
while (cur)
{
if (cur->right)
S.push(cur->right);
tmp = cur->right;
cur->right = cur->left;
cur->left = tmp;
cur = cur->right;
}
if (S.size())
{
cur = S.top();
S.pop();
}
}
return root;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// recursive solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
TreeNode *invertTree(TreeNode *root)
{
if (!root)
return NULL;
TreeNode *left = invertTree(root->left);
TreeNode *right = invertTree(root->right);
root->left = right;
root->right = left;
return root;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode *head) {
if (!head || !head->next)
return true;
ListNode *slow = head;
ListNode *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *tmp = head;
ListNode *nxt = head->next;
ListNode *prev = NULL;
while (tmp != slow) {
tmp->next = prev;
prev = tmp;
tmp = nxt;
nxt = nxt->next;
}
if (fast)
slow = slow->next;
while (prev) {
if (prev->val != slow->val)
return false;
prev = prev->next;
slow = slow->next;
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>// queue based solution
class RecentCounter
{
public:
queue<int> Q;
RecentCounter()
{
}
int ping(int t)
{
Q.push(t);
while (Q.front() < t - 3000)
Q.pop();
return Q.size();
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter* obj = new RecentCounter();
* int param_1 = obj->ping(t);
*/
// binary search based solution
class RecentCounter
{
public:
vector<int> calls;
RecentCounter()
{
}
int ping(int t)
{
int result = lower_bound(calls.begin(), calls.end(), t - 3000) - calls.begin();
calls.emplace_back(t);
return calls.size() - result;
}
};
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter* obj = new RecentCounter();
* int param_1 = obj->ping(t);
*/<file_sep>// iterative dp solution
class Solution
{
public:
bool isPossible(string &s, unordered_set<string> &wDict)
{
vector<bool> tab(s.length() + 1, false);
tab[0] = true;
string subWord;
for (int i = 0; i < s.length(); ++i)
{
for (int j = i; j >= 0; --j)
{
if (tab[j])
{
subWord = s.substr(j, i - j + 1);
if (wDict.count(subWord))
{
tab[i + 1] = true;
break;
}
}
}
}
return tab[s.length()];
}
vector<string> wordBreak(string s, vector<string> &wordDict)
{
unordered_set<string> wDict(wordDict.begin(), wordDict.end());
vector<vector<string>> tab(s.length() + 1, vector<string>(0));
tab[0] = {""};
string subWord;
if (!isPossible(s, wDict))
return {};
for (int i = 0; i < s.length(); ++i)
{
for (int j = i; j >= 0; --j)
{
if (tab[j].size())
{
subWord = s.substr(j, i - j + 1);
if (wDict.count(subWord))
{
for (string &s : tab[j])
tab[i + 1].emplace_back(s + (s.length() ? " " : "") + subWord);
}
}
}
}
return tab[s.length()];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// recursive solution with memoization
class Solution
{
public:
unordered_map<string, vector<string>> MEM;
vector<string> wordBreakUtil(const string s, unordered_set<string> &wDict)
{
if (s.length() == 0)
return {};
if (MEM.count(s) > 0)
return MEM[s];
vector<string> result;
string subWord;
for (int i = 1; i <= s.size(); ++i)
{
subWord = s.substr(0, i);
if (wDict.count(subWord) > 0)
{
if (i < s.length())
{
vector<string> response = wordBreakUtil(s.substr(i, s.length() - i), wDict);
for (string res : response)
{
result.emplace_back(subWord + " " + res);
}
}
else
{
result.emplace_back(subWord);
}
}
}
MEM[s] = result;
return result;
}
vector<string> wordBreak(string s, vector<string> &wordDict)
{
unordered_set<string> wDict(wordDict.begin(), wordDict.end());
return wordBreakUtil(s, wDict);
}
};<file_sep>class Solution {
public:
vector<int> shortestToChar(string s, char c) {
int n = s.length(), idx = -1e5;
vector<int> result(n, -1);
for (int i = 0; i < s.length(); ++i) {
if (s[i] == c)
idx = i;
result[i] = i - idx;
}
idx = 1e5;
for (int i = s.length() - 1; i >= 0; --i) {
if (s[i] == c)
idx = i;
result[i] = min(result[i], idx - i);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 0;
cin >> n;
int sum = 1, cur = 2;
unordered_set<int> MEM;
MEM.insert(sum);
while (sum < n)
{
if (MEM.count(n - sum))
{
cout << "YES";
return 0;
}
sum += cur;
++cur;
MEM.insert(sum);
}
cout << "NO";
return 0;
}<file_sep>// solved on: https://www.lintcode.com/problem/the-maze-iii/description
// bfs solution
class Solution
{
public:
/**
* @param maze: the maze
* @param ball: the ball position
* @param hole: the hole position
* @return: the lexicographically smallest way
*/
string findShortestWay(vector<vector<int>> &maze, vector<int> &ball, vector<int> &hole)
{
// write your code here
vector<pair<string, int>> result;
vector<vector<bool>> vis(maze.size(), vector<bool>(maze[0].size(), false));
vector<tuple<int, int, string>> dirs = {
make_tuple(-1, 0, "u"), make_tuple(0, 1, "r"), make_tuple(1, 0, "d"), make_tuple(0, -1, "l")};
queue<tuple<int, int, int, string>> Q;
tuple<int, int, int, string> tmp;
string tmp_res, res;
int x = 0, y = 0, tmp_dist = 0, r = 0, c = 0, distance = 0;
Q.push(make_tuple(ball[0], ball[1], 0, ""));
while (!Q.empty())
{
tmp = Q.front();
Q.pop();
tie(r, c, distance, res) = tmp;
vis[r][c] = true;
for (auto d : dirs)
{
x = r + get<0>(d);
y = c + get<1>(d);
tmp_dist = distance;
tmp_res = res + get<2>(d);
while (x >= 0 && x < maze.size() && y >= 0 && y < maze[x].size() && maze[x][y] == 0)
{
if (x == hole[0] && y == hole[1])
{
result.push_back({tmp_res, tmp_dist});
}
x += get<0>(d);
y += get<1>(d);
++tmp_dist;
}
x -= get<0>(d);
y -= get<1>(d);
if (!vis[x][y])
Q.push(make_tuple(x, y, tmp_dist, tmp_res));
}
}
if (result.size() == 0)
return "impossible";
sort(result.begin(), result.end(), [](const pair<string, int> &o1, const pair<string, int> &o2) {
if (o1.second == o2.second)
{
return o1.first < o2.first;
}
return o1.second < o2.second;
});
return result[0].first;
}
};<file_sep>class Solution {
public:
int shortestPathBinaryMatrix(vector<vector<int>> &grid) {
int n = grid.size(), r = 0, c = 0, x = 0, y = 0, dist = 0, q_size = 0;
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1)
return -1;
vector<pair<int, int>> dirs = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1},
{1, 0}, {1, -1}, {0, -1}, {-1, -1}};
queue<pair<int, int>> Q;
pair<int, int> cur;
Q.push({0, 0});
grid[0][0] = 1;
while (Q.size()) {
q_size = Q.size();
++dist;
while (q_size--) {
cur = Q.front();
Q.pop();
r = cur.first;
c = cur.second;
if (r == n - 1 && c == n - 1)
return dist;
for (auto &dir : dirs) {
x = r + dir.first;
y = c + dir.second;
if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 0) {
Q.push({x, y});
grid[x][y] = 1; // marking as visited here reduces redundant
// additions to the queue which prevents TLE
}
}
}
}
return -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int getRotorIdx(char c) {
return c - 'A';
}
string applyCaesarShift(string m, int s) {
int ct = 0;
for(int i=0; i<m.length(); ++i) {
m[i] = ((m[i] - 'A' + s + ct)%26 + 'A');
++ct;
}
return m;
}
string unapplyCaesarShift(string m, int s) {
int ct = 0;
int shift_adj = 26;
while(shift_adj < (s + m.length())) shift_adj += shift_adj;
for(int i=0; i<m.length(); ++i) {
m[i] = ((m[i] - 'A' - s - ct + shift_adj)%26 + 'A');
++ct;
}
return m;
}
int main()
{
string Operation;
getline(cin, Operation);
int pseudoRandomNumber;
cin >> pseudoRandomNumber; cin.ignore();
string rotors[3];
for (int i = 0; i < 3; i++) {
getline(cin, rotors[i]);
}
string message;
getline(cin, message);
if(Operation == "ENCODE") {
string im = applyCaesarShift(message, pseudoRandomNumber);
for(int i=0; i<3; ++i) {
for(int j=0; j<im.length(); ++j) {
im[j] = rotors[i][getRotorIdx(im[j])];
}
}
cout << im << endl;
}
else {
unordered_map<char, char> rotor_map[3];
for (int i = 0; i < 3; i++) {
for(int j=0; j<26; ++j) {
rotor_map[i][rotors[i][j]] = j + 'A';
}
}
for(int i=2; i>=0; --i) {
for(int j=0; j<message.length(); ++j) {
message[j] = rotor_map[i][message[j]];
}
}
string im = unapplyCaesarShift(message, pseudoRandomNumber);
cout << im << endl;
}
}<file_sep>// dfs solution
class Solution
{
public:
void markIslandDFS(vector<vector<char>> &grid, int i, int j)
{
// if invalid cell or cell is not a part of island
if (i < 0 || i >= grid.size() || j < 0 || j >= grid[i].size() || grid[i][j] != '1')
return;
// mark current cell as visited
grid[i][j] = '2';
// mark all neighbouring cells that are valid
markIslandDFS(grid, i + 1, j);
markIslandDFS(grid, i - 1, j);
markIslandDFS(grid, i, j + 1);
markIslandDFS(grid, i, j - 1);
}
int numIslands(vector<vector<char>> &grid)
{
int island_count = 0;
for (int i = 0; i < grid.size(); ++i)
{
for (int j = 0; j < grid[i].size(); ++j)
{
if (grid[i][j] == '1')
{
++island_count;
markIslandDFS(grid, i, j);
}
}
}
return island_count;
}
};
// bfs solution
class Solution
{
public:
void markIslandBFS(vector<vector<char>> &grid, int i, int j)
{
grid[i][j] = '2'; // mark the current land as visited
static vector<pair<int, int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
queue<pair<int, int>> Q;
pair<int, int> cur;
int x = 0, y = 0;
Q.push({i, j});
while (!Q.empty())
{
cur = Q.front();
Q.pop();
for (auto d : dirs)
{
x = cur.first + d.first;
y = cur.second + d.second;
if (x >= 0 && x < grid.size() && y >= 0 && y < grid[x].size() && grid[x][y] == '1')
{
grid[x][y] = '2'; // mark the current land as visited
Q.push({x, y});
}
}
}
}
int numIslands(vector<vector<char>> &grid)
{
int island_count = 0;
for (int i = 0; i < grid.size(); ++i)
{
for (int j = 0; j < grid[i].size(); ++j)
{
if (grid[i][j] == '1')
{
++island_count;
markIslandBFS(grid, i, j);
}
}
}
return island_count;
}
};<file_sep>class Solution
{
public:
bool containsNearbyDuplicate(vector<int> &nums, int k)
{
unordered_set<int> mem;
for (int i = 0; i < nums.size(); ++i)
{
if (mem.count(nums[i]))
return true;
mem.insert(nums[i]);
if (i >= k)
mem.erase(nums[i - k]);
}
return false;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// counting bit solution
// __builtin_clz returns number of leading zeros: so __builtin_clz(1) returns 31, hence we subtract it with 31 and not 32 since the last value of num , i.e. 1 will only require to be subtrcted
class Solution
{
public:
int numberOfSteps(int num)
{
return num ? __builtin_popcount(num) + 31 - __builtin_clz(num) : 0;
}
};
// simple approach
class Solution
{
public:
int numberOfSteps(int num)
{
int x = num, result = 0;
while (x)
{
x = x & 1 ? (x - 1) : (x >> 1);
++result;
}
return result;
}
};<file_sep>class Solution
{
public:
void merge(vector<int> &nums1, int m, vector<int> &nums2, int n)
{
if (n == 0)
return;
int i = m - 1, j = n - 1;
for (int idx = nums1.size() - 1; idx >= 0; --idx)
{
nums1[idx] = (i >= 0 ? nums1[i] : INT_MIN) > (j >= 0 ? nums2[j] : INT_MIN) ? nums1[i--] : nums2[j--];
}
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int L;
cin >> L; cin.ignore();
int H;
cin >> H; cin.ignore();
string T;
getline(cin, T);
for(int i=0; i<T.length(); ++i) {
if('a' <= T[i] && T[i] <= 'z' ) {
T[i] = T[i] - 32;
cerr<<"\n-*-";
}
else if(T[i] < 'A' || T[i] > 'Z') {
T[i] = char(91);
}
}
int idx = 0;
for (int i = 0; i < H; i++) {
string ROW;
getline(cin, ROW);
for(int j=0; j<T.length(); ++j) {
idx = L*(T[j]-65);
cout<< ROW.substr(idx, L);
}
cout<<endl;
}
// cout << "answer" << endl;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int *res;
string **operations;
int performOperation(string* );
int getArgument(string s) {
if(s == "_") return 0;
if(s[0] == '$') {
int ref = stoi(s.substr(1, s.length()-1));
if(res[ref] == -999)
res[ref] = performOperation(operations[ref]);
return res[ref];
}
return stoi(s);
}
int performOperation(string *op) {
int ret = 0, arg_1, arg_2;
arg_1 = getArgument(op[1]);
arg_2 = getArgument(op[2]);
if(op[0] == "VALUE") {
ret = arg_1;
}
else if(op[0] == "ADD") {
ret = arg_1 + arg_2;
}
else if(op[0] == "SUB") {
ret = arg_1 - arg_2;
}
else if(op[0] == "MULT") {
ret = arg_1 * arg_2;
}
return ret;
}
int main()
{
int N;
cin >> N; cin.ignore();
res = new int[N];
operations = new string*[N];
for (int i = 0; i < N; i++) {
operations[i] = new string[3];
res[i] = -999;
}
for (int i = 0; i < N; i++) {
cin >> operations[i][0] >> operations[i][1] >> operations[i][2]; cin.ignore();
}
for (int i = 0; i < N; i++) {
res[i] = performOperation(operations[i]);
}
for (int i = 0; i < N; i++) {
cout << res[i] << endl;
}
}<file_sep>class Solution
{
public:
vector<int> smallerNumbersThanCurrent(vector<int> &nums)
{
int n = nums.size(), cur = 0, count = 0;
vector<int> result(n, 0);
vector<int> idx(101, 0);
for (int i = 0; i < n; ++i)
++idx[nums[i]];
for (int i = 1; i < 101; ++i)
idx[i] += idx[i - 1];
for (int i = 0; i < n; ++i)
result[i] = nums[i] == 0 ? 0 : idx[nums[i] - 1];
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution {
public:
bool hasAllCodes(string s, int k) {
if (s.length() < k)
return false;
unordered_set<int> mem;
int num = 0;
for (int i = 0; i < s.length(); ++i) {
num <<= 1;
num |= (s[i] - '0');
if (i >= k - 1) {
mem.insert(num);
num &= ~(1 << (k - 1));
}
}
return mem.size() >= (1 << k);
}
P
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>// linear solution with pointers
class Solution
{
public:
int waysToSplit(vector<int> &nums)
{
int n = nums.size(), result = 0, j = 0, k = 0, MOD = 1e9 + 7;
vector<int> preSum(n, 0);
partial_sum(nums.begin(), nums.end(), preSum.begin());
for (int i = 0; i < n - 2; ++i)
{
while (j <= i || (j < n - 1 && preSum[i] > preSum[j] - preSum[i]))
++j;
while (k <= j || (k < n && preSum[k - 1] - preSum[i] <= preSum.back() - preSum[k - 1]))
++k;
result += max(k - j - 1, 0);
if (result >= MOD)
result -= MOD;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// binary search based solution
class Solution
{
public:
int waysToSplit(vector<int> &nums)
{
int n = nums.size(), result = 0, start = 0, end = 0, limit = 0, MOD = 1e9 + 7;
vector<int> preSum(n, 0);
partial_sum(nums.begin(), nums.end(), preSum.begin());
for (int i = 0; i < n - 2; ++i)
{
limit = (preSum.back() - preSum[i]) >> 1;
start = lower_bound(preSum.begin() + i + 1, preSum.end(), preSum[i] + preSum[i]) - preSum.begin();
end = (upper_bound(preSum.begin() + start, preSum.end() - 1, preSum[i] + limit) - preSum.begin()) - 1;
result += max(end - start + 1, 0);
if (result >= MOD)
result -= MOD;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
// vector<int> multiply(vector<int>& num1, vector<int>& num2) {
// // multiplies two vectors as numbers
// vector<int> res(num1.size()+num2.size(), 0);
// int prod = 0;
// for(int i=num1.size()-1; i>=0; --i) {
// for(int j=num2.size()-1; j>=0; --j) {
// prod = res[i+j+1] + num1[i]*num2[j];
// res[i+j+1] = prod%10;
// res[i+j] += prod/10;
// }
// }
// return res;
// }
// int getPowerDigitSum(int n) {
// // returns the sum of digits of 2^n
// if(n == 0) return 1;
// vector<int> res = {1};
// vector<int> res2 = {2};
// while(n) {
// if(~n&1) { // n is even
// res2 = multiply(res2, res2);
// n >>= 1;
// }
// else {
// res = multiply(res, res2);
// --n;
// }
// }
// int digitSum = 0;
// for(auto r : res) {
// digitSum += r;
// }
// return digitSum;
// }
#define MEM_SIZE 10001
int MEM[MEM_SIZE];
void multiplyByTwo(vector<int> &num)
{
int carry = 0;
for (int i = num.size() - 1; i >= 0; --i)
{
num[i] *= 2;
num[i] += carry;
carry = num[i] / 10;
num[i] %= 10;
}
if (carry)
num.insert(num.begin(), carry);
}
void preCompute()
{
for (int i = 0; i < MEM_SIZE; ++i)
MEM[i] = 0;
MEM[0] = 1;
MEM[1] = 2;
vector<int> pows = {2};
for (int i = 2; i < MEM_SIZE; ++i)
{
multiplyByTwo(pows);
MEM[i] = accumulate(pows.begin(), pows.end(), 0);
}
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t = 0, n = 0;
cin >> t;
preCompute();
while (t--)
{
cin >> n;
// cout<<getPowerDigitSum(n)<<"\n"; // this gives a TLE on a few cases
cout << MEM[n] << "\n";
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
int main()
{
int n = 0, q = 0, pos;
ll r = 0;
long double x = 0, y = 0;
cin >> n;
vector<ll> dist(n, 0);
for (int i = 0; i < n; ++i)
{
cin >> x >> y;
dist[i] = ceil(sqrt(x * x + y * y));
}
sort(dist.begin(), dist.end());
cin >> q;
while (q--)
{
cin >> r;
pos = upper_bound(dist.begin(), dist.end(), r) - dist.begin();
cout << pos << "\n";
}
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int W;
int H;
cin >> W >> H; cin.ignore();
int n_chars = W/3 + 1;
unordered_map<char, char> Hash;
string top, top_c, bot;
string *legs = new string[H-2];
for (int i = 0; i < H; i++) {
if(i == 0) {
getline(cin, top);
}
else if(i == H-1) {
getline(cin, bot);
}
else {
getline(cin, legs[i-1]);
}
}
for(int i=0; i<W; i+=3) {
Hash[top[i]] = bot[i];
}
top_c = top;
for (int i = 0; i < H-2; i++) {
int ind = 0;
ind = legs[i].find("--", ind);
while(ind != string::npos) {
char tmp = Hash[top_c[ind-1]];
Hash[top_c[ind-1]] = Hash[top_c[ind+2]];
Hash[top_c[ind+2]] = tmp;
swap(top_c[ind-1], top_c[ind+2]);
ind = legs[i].find("--", ind+1);
}
}
for(int i=0; i<W; i+=3) {
cout<<top[i]<<Hash[top[i]]<<"\n";
}
}<file_sep>/*
the idea is to get the closest to the half value of the total weight of the stones
we do it by using a modified 0/1 knapsack dp algorithm such that the weight is the value itself
*/
class Solution
{
public:
int lastStoneWeightII(vector<int> &stones)
{
int sum = accumulate(stones.begin(), stones.end(), 0);
int target = sum >> 1;
int closest = -1;
vector<vector<int>> tab(stones.size(), vector<int>(target + 1, -1));
tab[0][0] = 0;
tab[0][stones[0]] = stones[0];
for (int r = 1; r < stones.size(); ++r)
{
for (int w = 0; w <= target; ++w)
{
tab[r][w] = tab[r - 1][w];
if (stones[r] <= w && tab[r - 1][w - stones[r]] >= 0)
{
tab[r][w] = w;
}
closest = max(closest, tab[r][w]);
}
}
return abs(sum - 2 * closest);
}
};<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *partition(ListNode *head, int x)
{
if (!head)
return NULL;
ListNode *less = NULL, *less_cur = NULL;
ListNode *more = NULL, *more_cur = NULL;
ListNode *cur = head;
while (cur)
{
if (cur->val < x)
{
if (!less)
{
less = cur;
}
else
{
less_cur->next = cur;
}
less_cur = cur;
cur = cur->next;
less_cur->next = NULL;
}
else
{
if (!more)
{
more = cur;
}
else
{
more_cur->next = cur;
}
more_cur = cur;
cur = cur->next;
more_cur->next = NULL;
}
}
if (less)
less_cur->next = more;
else
return more;
return less;
}
};<file_sep>// O(n + m) solution
class Solution
{
public:
vector<vector<int>> intervalIntersection(vector<vector<int>> &A, vector<vector<int>> &B)
{
vector<vector<int>> result;
int i = 0, j = 0;
while (i < A.size() && j < B.size())
{
if (B[j][0] > A[i][1])
++i;
else if (A[i][0] > B[j][1])
++j;
else
{
result.push_back({max(A[i][0], B[j][0]), min(A[i][1], B[j][1])});
if (A[i][1] < B[j][1])
++i;
else
++j;
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(n*m) solution
class Solution
{
public:
vector<vector<int>> intervalIntersection(vector<vector<int>> &A, vector<vector<int>> &B)
{
vector<vector<int>> result;
for (auto &a : A)
{
for (auto &b : B)
{
if (b[0] > a[1])
break;
if ((b[0] >= a[0] && b[0] <= a[1]) || (b[1] >= a[0] && b[1] <= a[1]))
{
result.push_back({max(a[0], b[0]), min(a[1], b[1])});
}
else if ((a[0] >= b[0] && a[0] <= b[1]) || (a[1] >= b[0] && a[1] <= b[1]))
{
result.push_back({max(a[0], b[0]), min(a[1], b[1])});
}
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Airbnb.
* Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.
* For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.
* Follow-up: Can you do this in O(N) time and constant space?
*
*
* Online Judge: https://leetcode.com/problems/house-robber/
*
*/
class Solution
{
public:
int rob(vector<int> &nums)
{
if (nums.size() == 0)
return 0;
if (nums.size() == 1)
return nums[0];
if (nums.size() == 2)
return max(nums[0], nums[1]);
int incl = nums[0], excl = 0, tmp = 0;
for (int i = 1; i < nums.size(); ++i)
{
tmp = incl;
incl = max(incl, nums[i] + excl);
excl = tmp;
}
return max(incl, excl);
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int ROUNDS;
cin >> ROUNDS;
cin.ignore();
int CASH;
cin >> CASH;
cin.ignore();
double bet_cash, cash = CASH;
for (int i = 0; i < ROUNDS; i++)
{
bet_cash = ceil(cash / 4.0);
int res, bet;
string PLAY;
cin >> res >> PLAY;
if (PLAY == "PLAIN")
{
cin >> bet;
if (res == bet)
bet_cash = bet_cash * 35;
else
bet_cash = -1 * bet_cash;
}
else if (PLAY == "ODD")
{
if (res % 2 == 0)
bet_cash *= -1;
}
else
{
if (res % 2 != 0 || res == 0)
bet_cash *= -1;
}
cash += bet_cash;
}
cout << cash << "\n";
}<file_sep>#include <bits/stdc++.h>
using namespace std;
int countOccurrences(string s, string c, string next = "", bool checkNext = false)
{
int count = 0;
size_t pos = 0, cur = 0;
pos = s.find(c, cur);
while (pos != string::npos)
{
if (!checkNext || s.substr(pos + c.length(), next.length()) != next)
++count;
cur = pos + c.length();
pos = s.find(c, cur);
}
return count;
}
int main()
{
int t = 0;
string s;
cin >> t;
while (t--)
{
cin >> s;
cout << "SUVO = " << countOccurrences(s, "SUVO", "JIT", true) << ", SUVOJIT = " << countOccurrences(s, "SUVOJIT") << "\n";
}
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int t = 0;
string num;
cin >> t;
while (t--)
{
cin >> num;
if (stoi(num) % 21 == 0 || num.find("21") != string::npos)
cout << "The streak is broken!\n";
else
cout << "The streak lives still in our heart!\n";
}
return 0;
}<file_sep>class Solution
{
public:
bool isSubsequence(string s, string t)
{
if (s == t || s.length() == 0)
return true;
if (t.length() == 0)
return false;
int i = 0, j = 0;
while (j < t.length())
{
if (s[i] == t[j])
++i;
++j;
if (i == s.length())
return true;
}
return false;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
bool validateUtil(vector<vector<char>> &board, int i, int j)
{
int row_offset = (i / 3) * 3;
int col_offset = (j / 3) * 3;
for (int k = 0; k < 9; ++k)
{
if (k != j && board[i][k] == board[i][j])
return false;
if (k != i && board[k][j] == board[i][j])
return false;
if ((row_offset + k / 3 != i || col_offset + k % 3 != j) && board[row_offset + k / 3][col_offset + k % 3] == board[i][j])
return false;
}
return true;
}
bool isValidSudoku(vector<vector<char>> &board)
{
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
{
if (board[i][j] != '.')
{
if (!validateUtil(board, i, j))
return false;
}
}
}
return true;
}
};<file_sep>/**
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Google.
* The edit distance between two strings refers to the minimum number of character insertions, deletions, and substitutions required to change one string to the other. For example, the edit distance between “kitten” and “sitting” is three: substitute the “k” for “s”, substitute the “e” for “i”, and append a “g”.
* Given two strings, compute the edit distance between them.
*
*
* Online Judge: https://leetcode.com/problems/edit-distance/
*
*/
class Solution
{
public:
int minDistance(string word1, string word2)
{
int m = word1.length(), n = word2.length();
if (m == 0)
return n;
if (n == 0)
return m;
vector<vector<int>> tab(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; ++i)
tab[i][0] = i;
for (int i = 1; i <= n; ++i)
tab[0][i] = i;
for (int i = 1; i <= m; ++i)
{
for (int j = 1; j <= n; ++j)
{
if (word1[i - 1] == word2[j - 1])
tab[i][j] = tab[i - 1][j - 1];
else
tab[i][j] = 1 + min(tab[i - 1][j - 1], min(tab[i - 1][j], tab[i][j - 1]));
}
}
return tab[m][n];
}
};<file_sep>// best solution (single pass)
class Solution
{
public:
void rotate(vector<int> &nums, int k)
{
k %= nums.size();
int count = 0, idx = 0, prev = 0, next_idx = 0, tmp = 0;
for (int i = 0; count < nums.size(); ++i)
{
idx = i;
prev = nums[i];
do
{
next_idx = (idx + k) % nums.size();
tmp = nums[next_idx];
nums[next_idx] = prev;
prev = tmp;
idx = next_idx;
++count;
} while (idx != i);
}
}
};
// alternate solution
class Solution
{
public:
void rotate(vector<int> &nums, int k)
{
k = k % nums.size();
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin() + k);
reverse(nums.begin() + k, nums.end());
}
};
// alternate solution
class Solution
{
public:
void rotate(vector<int> &nums, int k)
{
std::rotate(nums.rbegin(), nums.rbegin() + (k % nums.size()), nums.rend());
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_set>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Move{
public:
int x;
int y;
int dir;
Move(int x, int y, int dir) {
this->x = x;
this->y = y;
this->dir = dir;
}
bool operator==(const Move& obj) const {
return (this->x == obj.x && this->y == obj.y && this->dir == obj.dir);
}
};
class MyHash{
public:
size_t operator()(const Move& obj) const {
return (hash<int>()(obj.x) ^ hash<int>()(obj.y) ^ hash<int>()(obj.dir));
}
};
int main()
{
int w;
int h;
cin >> w >> h; cin.ignore();
long long n;
cin >> n; cin.ignore();
string *grid = new string[h];
int x = 0, y = 0;
bool found = false;
for (int i = 0; i < h; i++) {
getline(cin, grid[i]);
if(!found) {
y = grid[i].find("O");
if(y != string::npos) {
x = i;
found = true;
}
}
}
int t_x = x, t_y = y;
int idx = 0;
int DIR_X[4] = {-1, 0, 1, 0};
int DIR_Y[4] = {0, 1, 0, -1};
unordered_set<Move, MyHash> moves;
vector<Move> move_list;
while(true) {
while(grid[t_x+DIR_X[idx]][t_y+DIR_Y[idx]] == '#') idx = (idx+1)%4;
t_x += DIR_X[idx];
t_y += DIR_Y[idx];
Move obj(t_x, t_y, idx);
if(moves.find(obj) != moves.end()) break;
moves.insert(obj);
move_list.push_back(obj);
}
n = n%move_list.size();
cout<<move_list[n-1].y<<" "<<move_list[n-1].x;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
double getWork(int level, int weight) {
return ((level-1)*6.5/100)*10*weight;
}
int main()
{
int X;
cin >> X; cin.ignore();
int N;
cin >> N; cin.ignore();
vector<int> bricks(N, 0);
for (int i = 0; i < N; i++) {
cin >> bricks[i]; cin.ignore();
}
sort(bricks.begin(), bricks.end(), greater<int>());
double work = 0;
int level = 1;
int ct = 0;
for(int i=0; i<N; ++i) {
work += getWork(level, bricks[i]);
++ct;
if(ct == X) {
ct = 0;
++level;
}
}
printf("%.3f", work);
}<file_sep>#include <bits/stdc++.h>
using namespace std;
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
int main()
{
long long int n = 0, q = 0, m = 0;
cin >> n >> q;
vector<long long int> preSum(n, 0);
for (int i = 0; i < n; ++i)
{
cin >> preSum[i];
if (i > 0)
preSum[i] += preSum[i - 1];
}
while (q--)
{
cin >> m;
cout << (lower_bound(preSum.begin(), preSum.end(), m) - preSum.begin() + 1) << "\n";
}
return 0;
}<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool sieve[1000000];
void generateSieve()
{
for (int i = 0; i < 1000000; ++i)
sieve[i] = true;
sieve[0] = sieve[1] = false;
for (int i = 2; i * i <= 1000000; ++i)
{
if (sieve[i])
{
for (int j = i * i; j <= 1000000; j += i)
sieve[j] = false;
}
}
}
vector<int> getPrimes()
{
generateSieve();
vector<int> res;
for (int i = 0; i < 1000000; ++i)
{
if (sieve[i])
res.push_back(i);
}
return res;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
vector<int> primes = getPrimes();
int t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
cout << primes[n - 1] << "\n";
}
return 0;
}
<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Google.
* Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k.
* For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since:
10 = max(10, 5, 2)
7 = max(5, 2, 7)
8 = max(2, 7, 8)
8 = max(7, 8, 7)
* Do this in O(n) time and O(k) space. You can modify the input array in-place and you do not need to store the results. You can simply print them out as you compute them.
*
*
* Online Judge: https://leetcode.com/problems/sliding-window-maximum/
*
*/
class Solution
{
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k)
{
vector<int> result;
deque<int> window;
for (int i = 0; i < nums.size(); ++i)
{
// add the new element meanwhile replacing all smaller elements
while (!window.empty() && nums[i] >= nums[window.back()])
window.pop_back();
window.emplace_back(i);
if (i >= k - 1)
result.emplace_back(nums[window.front()]);
// remove all indices outside the next window in left
while (!window.empty() && window.front() <= i - k + 1)
window.pop_front();
}
return result;
}
};<file_sep>/*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Google.
* Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
* For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.
* In this example, assume nodes with the same value are the exact same node objects.
* Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space.
*
*
* Online Judge: https://leetcode.com/problems/intersection-of-two-linked-lists/
*
*
*/
// a good, small & intuitive solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
ListNode *curA = headA, *curB = headB;
while (curA != curB)
{
curA = curA ? curA->next : headB;
curB = curB ? curB->next : headA;
}
return curA;
}
};
// my solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
int getLength(ListNode *head)
{
if (head == NULL)
return 0;
int ct = 0;
while (head)
{
++ct;
head = head->next;
}
return ct;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
if (!headA || !headB)
return NULL;
int lengthA = getLength(headA);
int lengthB = getLength(headB);
if (lengthA < lengthB)
{
swap(lengthA, lengthB);
ListNode *tmp = headA;
headA = headB;
headB = tmp;
}
int lenDiff = lengthA - lengthB;
while (lenDiff--)
headA = headA->next;
while (headA && headB)
{
if (headA == headB)
return headA;
headA = headA->next;
headB = headB->next;
}
return NULL;
}
};<file_sep>class Solution
{
public:
double getPow(double x, long n)
{
if (x == 0 || x == 1)
return x;
double ret = 1;
while (n)
{
if (n & 1)
ret *= x;
x *= x;
n >>= 1;
}
return ret;
}
double myPow(double x, long n)
{
if (n < 0)
return 1.0 / getPow(x, -n);
return getPow(x, n);
}
};<file_sep>// reference : https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/discuss/414804/A-Review%3A-Why-This-Problem-Is-a-Tip-of-the-Iceberg
// more efficient backtracking solution (uses 1d vector to store heights of squares and extra greedy method to prune the search space)
class Solution
{
public:
int getLargestSquare(vector<int> &heights, int &idx, int &n)
{
// find the height of largest square that can fit starting from idx
int len = 1;
while (idx + len < heights.size() && heights[idx] + len < n && heights[idx + len] == heights[idx])
++len;
return len;
}
void cover(vector<int> &heights, int &idx, int &len, bool cover)
{
// cover all heights from idx -> len with an increment in height of len
for (int i = idx; i < idx + len; ++i)
heights[i] += cover ? len : -len;
}
void backtrack(vector<int> &heights, int &n, int &result, int count = 0)
{
if (count >= result)
return;
int idx = 0;
// find top-left-most uncovered block
for (int i = 1; i < heights.size(); ++i)
{
if (heights[i] < heights[idx])
{
idx = i;
}
}
// if all blocks are covered
if (heights[idx] == n)
{
result = min(result, count);
return;
}
// find the largest possible square that fits
int len = getLargestSquare(heights, idx, n);
// backtrack for all possible lengths
for (int i = len; i >= 1; --i)
{
cover(heights, idx, i, true);
backtrack(heights, n, result, count + 1);
cover(heights, idx, i, false);
}
}
int getGeneralSolution(int n, int m)
{
int ct = 1;
while (m != n)
{
if (n < m)
m -= n;
else
n -= m;
++ct;
}
return ct;
}
int tilingRectangle(int n, int m)
{
if (m == n)
return 1;
if (n < m)
return tilingRectangle(m, n);
vector<int> heights(m, 0);
int result = getGeneralSolution(n, m);
backtrack(heights, n, result);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// simple backtracking solution (uses 2d matrix of nxm)
class Solution
{
public:
int getLargestSquare(vector<vector<int>> &grid, int x, int y)
{
// starting from (x, y) return the size of largest valid square possible
int len = 1;
while (x + len < grid.size() && y + len < grid[0].size())
{
for (int i = 0; i <= len; ++i)
{
if (grid[x + i][y + len] || grid[x + len][y + i])
return len;
}
++len;
}
return len;
}
void cover(vector<vector<int>> &grid, int x, int y, int len, int val)
{
// fill a square of size => len with value => val starting from position (x, y)
for (int i = x; i < x + len; ++i)
for (int j = y; j < y + len; ++j)
grid[i][j] = val;
}
void backtrack(vector<vector<int>> &grid, int &result, int count = 0)
{
if (count > result)
return;
int x = -1, y = -1;
// find top-left-most uncovered block
for (int i = 0; i < grid.size(); ++i)
{
for (int j = 0; j < grid[i].size(); ++j)
{
if (grid[i][j] == 0)
{
x = i;
y = j;
break;
}
}
if (x != -1 && y != -1)
break;
}
// if all blocks are covered
if (x == -1 && y == -1)
{
result = min(result, count);
return;
}
// find the largest possible square that fits
int len = getLargestSquare(grid, x, y);
// backtrack for all possible lengths
for (int i = len; i >= 1; --i)
{
cover(grid, x, y, i, 1);
backtrack(grid, result, count + 1);
cover(grid, x, y, i, 0);
}
}
int tilingRectangle(int n, int m)
{
vector<vector<int>> grid(n, vector<int>(m, 0));
int result = INT_MAX;
backtrack(grid, result);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Facebook.
* Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded.
* For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
* You can assume that the messages are decodable. For example, '001' is not allowed.
*
*
* Online Judge: https://leetcode.com/problems/decode-ways/
*
*/
// recursive approach with memoization
class Solution
{
public:
int numDecodingsUtil(string s, int idx, vector<int> &MEM)
{
if (idx >= s.length())
return 1;
if (MEM[idx] != -1)
return MEM[idx];
if (s[idx] == '0')
return 0;
int res = numDecodingsUtil(s, idx + 1, MEM);
if (idx + 1 < s.length() && (s[idx] == '1' || (s[idx] == '2' && s[idx + 1] < '7')))
{
res += numDecodingsUtil(s, idx + 2, MEM);
}
MEM[idx] = res;
return res;
}
int numDecodings(string s)
{
if (s.length() == 0)
return 0;
vector<int> MEM(s.length(), -1);
return numDecodingsUtil(s, 0, MEM);
}
};
// iterative approach using dynamic programming (more space efficient)
class Solution
{
public:
int numDecodings(string s)
{
if (s.length() == 0)
return 0;
int n = s.length();
vector<int> MEM(n + 1, 0);
MEM[n] = 1;
for (int i = n - 1; i >= 0; --i)
{
if (s[i] != '0')
{
MEM[i] = MEM[i + 1];
if (i + 1 < n && (s[i] == '1' || (s[i] == '2' && s[i + 1] < '7')))
MEM[i] += MEM[i + 2];
}
else
MEM[i] = 0;
}
return MEM[0];
}
};
<file_sep>// left-max, right-max based solution
class Solution
{
public:
int trap(vector<int> &height)
{
if (height.size() == 0)
return 0;
int n = height.size(), result = 0;
vector<int> leftMax(n, 0), rightMax(n, 0);
leftMax[0] = height[0];
rightMax[n - 1] = height[n - 1];
for (int i = 1; i < n; ++i)
leftMax[i] = max(height[i], leftMax[i - 1]);
for (int i = n - 2; i >= 0; --i)
rightMax[i] = max(height[i], rightMax[i + 1]);
for (int i = 0; i < n; ++i)
result += max(min(leftMax[i], rightMax[i]) - height[i], 0);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// stack based solution (not as fast than the one above)
class Solution
{
public:
int trap(vector<int> &height)
{
int n = height.size(), result = 0, cur = 0, len = 0;
stack<int> S;
for (int i = 0; i < n; ++i)
{
while (S.size() && height[i] > height[S.top()])
{
cur = S.top();
S.pop();
if (S.size() == 0)
break;
len = i - S.top() - 1;
result += max(min(height[i], height[S.top()]) - height[cur], 0) * len;
}
S.push(i);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// constant extra space solution
class Solution
{
public:
int trap(vector<int> &height)
{
int n = height.size(), result = 0;
int left = 0, right = n - 1;
int left_max = 0, right_max = 0;
while (left < right)
{
left_max = max(left_max, height[left]);
right_max = max(right_max, height[right]);
if (left_max <= right_max)
result += left_max - height[left++];
else
result += right_max - height[right--];
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2)
{
if (nums1.size() > nums2.size())
return findMedianSortedArrays(nums2, nums1);
int x = nums1.size(), y = nums2.size();
int l = 0, r = nums1.size(), mid1 = 0, mid2 = 0, x1 = 0, y1 = 0, x2 = 0, y2 = 0, left = 0, right = 0;
while (l <= r)
{
mid1 = l + ((r - l) >> 1);
mid2 = ((x + y) >> 1) - mid1;
x1 = mid1 > 0 ? nums1[mid1 - 1] : -999999;
y1 = mid1 < x ? nums1[mid1] : 999999;
x2 = mid2 > 0 ? nums2[mid2 - 1] : -999999;
y2 = mid2 < y ? nums2[mid2] : 999999;
if (y1 < x2)
l = mid1 + 1;
else if (x1 > y2)
r = mid1 - 1;
else
{
left = max(x1, x2);
right = min(y1, y2);
if ((x + y) & 1)
return right;
else
return (left + right) / 2.0;
}
}
return -1;
}
};<file_sep>#include <bits/stdc++.h>
using namespace std;
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
bool isValid(vector<int> &GR, vector<int> &PL, int time)
{
int count = 0;
for (int i = 0; i < PL.size(); ++i)
{
for (int j = 0; j < time && count < GR.size() && PL[i] >= GR[count]; j += 2)
++count;
}
return count == GR.size();
}
int main()
{
int n = 0, m = 0;
cin >> n >> m;
vector<int> groups(n, 0);
vector<int> planes(m, 0);
for (int i = 0; i < n; ++i)
cin >> groups[i];
for (int i = 0; i < m; ++i)
cin >> planes[i];
sort(groups.begin(), groups.end());
sort(planes.begin(), planes.end());
if (groups[groups.size() - 1] > planes[planes.size() - 1])
{
cout << "-1";
return 0;
}
int l = 1, r = 2 * (n - 1) + 1, mid = 0;
while (l < r)
{
mid = l + ((r - l) >> 1);
if (isValid(groups, planes, mid))
r = mid;
else
l = mid + 1;
}
cout << l;
return 0;
}<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Facebook.
* Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed).
* For example, given the string "([])[]({})", you should return true.
* Given the string "([)]" or "((()", you should return false.
*
*
* Online Judge: https://leetcode.com/problems/valid-parentheses/submissions/
*
*/
class Solution
{
public:
bool isValid(string s)
{
if (s.length() & 1)
return false;
stack<char> S;
unordered_map<char, char> map = {{'(', ')'}, {'[', ']'}, {'{', '}'}};
for (char &c : s)
{
if (map.count(c))
S.push(c);
else
{
if (S.empty() || map[S.top()] != c)
return false;
S.pop();
}
}
return S.size() == 0;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *removeNthFromEnd(ListNode *head, int n)
{
ListNode *B = head;
ListNode *F = head;
for (int i = 0; i < n; ++i)
F = F->next;
if (F == NULL)
return head->next;
while (F->next != NULL)
{
F = F->next;
B = B->next;
}
ListNode *rem = B->next;
B->next = rem->next;
delete (rem);
return head;
}
};<file_sep>class Solution
{
public:
bool isIsomorphic(string s, string t)
{
vector<int> m1(128, -1), m2(128, -1);
if (s.length() != t.length())
return false;
for (int i = 0; i < s.length(); ++i)
{
if (m1[s[i]] == -1)
m1[s[i]] = i;
if (m2[t[i]] == -1)
m2[t[i]] = i;
if (m1[s[i]] != m2[t[i]])
return false;
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// O(1) space, O(n) time, no modification of nums
class Solution
{
public:
int findDuplicate(vector<int> &nums)
{
int slow = nums[0];
int fast = nums[0];
while (true)
{
slow = nums[slow];
fast = nums[nums[fast]];
if (slow == fast)
break;
}
slow = nums[0];
while (slow != fast)
{
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// solved on : https://www.lintcode.com/problem/reverse-words-in-a-string-ii/description
class Solution
{
public:
/**
* @param str: a string
* @return: return a string
*/
string reverseWords(string &str)
{
reverse(str.begin(), str.end());
int l = 0, r = 0;
while (r <= str.length())
{
if (str[r] == ' ' || r == str.length())
{
reverse(str.begin() + l, str.begin() + r);
l = r + 1;
}
++r;
}
return str;
}
};<file_sep>"""
#
# Good morning! Here's your coding interview problem for today.
# This problem was asked by Apple.
# Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
#
#
"""
import threading
import time
THREAD_COUNT = 0
# in seconds (amount of time taken by a single job)
JOB_EXEC_TIME = 10
# in milli seconds (time interval between two job threads)
JOB_FREQ_TIME = 5000
def job():
id = THREAD_COUNT
print("Job #" + str(id) + " started at: " + str(time.time()))
time.sleep(JOB_EXEC_TIME)
print("Job #" + str(id) + " ended at: " + str(time.time()))
def scheduler(f, n):
global THREAD_COUNT
while True:
t = threading.Thread(target=f)
t.start()
time.sleep(n/1000)
THREAD_COUNT += 1
if __name__ == '__main__':
scheduler(job, JOB_FREQ_TIME)
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
bool isValidDir(int i, int j, int h, int w) {
if(i < 0 || j < 0 || i >= h || j >= w) return false;
return true;
}
int main()
{
int width;
int height;
cin >> width >> height; cin.ignore();
vector<pair<int, int> > dirs = {{1,0}, {0,1}, {-1,0}, {0,-1}};
string *grid = new string[height];
for (int i = 0; i < height; i++) {
cin >> grid[i]; cin.ignore();
}
int ct = 0, x = 0, y = 0;
for(int i=0; i<height; ++i) {
for(int j=0; j<width; ++j) {
if(grid[i][j] == '0') {
ct = 0;
for(auto d : dirs) {
x = i + d.first;
y = j + d.second;
if(isValidDir(x, y, height, width) && grid[x][y] != '#') ++ct;
}
grid[i][j] = ct + '0';
}
}
}
for (int i = 0; i < height; i++) {
cout << grid[i] << endl;
}
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Don't let the machines win. You are humanity's last hope...
**/
int main()
{
int width; // the number of cells on the X axis
cin >> width;
cin.ignore();
int height; // the number of cells on the Y axis
cin >> height;
cin.ignore();
vector<string> grid(height);
for (int i = 0; i < height; i++)
{
getline(cin, grid[i]); // width characters, each either 0 or .
cerr << "\n --- " << grid[i] << "\n";
}
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
if (grid[i][j] != '.')
{
cout << j << " " << i << " ";
int pos = grid[i].find('0', j + 1);
if (pos != string::npos)
cout << pos << " " << i << " ";
else
cout << "-1 -1 ";
int k = 0;
for (k = i + 1; k < height; ++k)
{
if (grid[k][j] == '0')
break;
}
if (k < height)
cout << j << " " << k << "\n";
else
cout << "-1 -1\n";
}
}
}
}<file_sep>class Solution
{
public:
string removeKdigits(string num, int k)
{
string res;
for (char &n : num)
{
while (k > 0 && res.length() && res.back() > n)
{
res.pop_back();
--k;
}
if (res.length() || n != '0')
res += n;
}
while (res.length() && k--)
res.pop_back();
return res.length() ? res : "0";
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
string preProcess(string s)
{
string ret = "$#";
for (auto c : s)
ret += string(1, c) + "#";
return ret + "@";
}
string postProcess(string s)
{
string ret;
for (auto c : s)
ret += c == '#' ? "" : string(1, c);
return ret;
}
string longestPalindrome(string s)
{
if (s.length() == 0)
return "";
s = preProcess(s);
int c = 0, r = 0, mir = 0, i = 1, n = s.length();
vector<int> lp(n, 0);
while (i < n)
{
mir = 2 * c - i;
if (i < r)
lp[i] = min(lp[mir], r - i);
while (s[i + (1 + lp[i])] == s[i - (1 + lp[i])])
++lp[i];
if (i + lp[i] > r)
{
c = i;
r = i + lp[i];
}
++i;
}
int max_ind = 0;
for (int i = 1; i < n; ++i)
if (lp[max_ind] < lp[i])
max_ind = i;
s = s.substr(max_ind - lp[max_ind], lp[max_ind] * 2 + 1);
return postProcess(s);
}
};<file_sep>// fast solution (using a double sized array to store -ve indices in an array)
class Solution
{
public:
int findMaxLength(vector<int> &nums)
{
int result = 0, cur_sum = 0, idx = 0;
int MEM_SIZE = 2 * nums.size() + 1;
vector<int> MEM(MEM_SIZE, -2); // to store -ve values
MEM[0] = -1;
for (int i = 0; i < nums.size(); ++i)
{
cur_sum += (nums[i] == 0) ? -1 : 1;
idx = (MEM_SIZE + cur_sum) % MEM_SIZE;
if (MEM[idx] != -2)
result = max(result, i - MEM[idx]);
else
MEM[idx] = i;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// my first solution using unordered_map
class Solution
{
public:
int findMaxLength(vector<int> &nums)
{
int result = 0, cur_sum = 0;
unordered_map<int, int> MEM = {{0, -1}};
for (int i = 0; i < nums.size(); ++i)
{
cur_sum = (nums[i] == 0) ? cur_sum - 1 : cur_sum + 1;
if (MEM.count(cur_sum))
result = max(result, i - MEM[cur_sum]);
else
MEM[cur_sum] = i;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// class Solution
// {
// public:
// int hammingWeight(uint32_t n)
// {
// return __builtin_popcount(n);
// }
// };
class Solution
{
public:
int hammingWeight(uint32_t n)
{
if (n == 0)
return 0;
int ct = 1;
while (n & (n - 1))
{
n = n & (n - 1);
++ct;
}
return ct;
}
};<file_sep>// randomized partition based solution
class Solution
{
public:
int partition(vector<int> &nums, int l, int r)
{
swap(nums[l], nums[l + (rand() % (r - l + 1))]);
int pivot = nums[l];
int j = l + 1;
for (int i = l + 1; i <= r; ++i)
{
if (nums[i] >= pivot)
swap(nums[i], nums[j++]);
}
swap(nums[l], nums[j - 1]);
return j - 1;
}
int findKthLargest(vector<int> &nums, int k)
{
int l = 0, r = nums.size() - 1, p = 0;
while (true)
{
p = partition(nums, l, r);
if (p == k - 1)
return nums[p];
else if (p > k - 1)
r = p - 1;
else
l = p + 1;
}
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// nth_element solution (can also use partial_sort)
class Solution
{
public:
int findKthLargest(vector<int> &nums, int k)
{
nth_element(nums.begin(), nums.begin() + k - 1, nums.end(), greater<int>());
return nums[k - 1];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// priority queue solution (can also use multiset)
class Solution
{
public:
int findKthLargest(vector<int> &nums, int k)
{
priority_queue<int, vector<int>, greater<int>> PQ;
for (int &n : nums)
{
if (PQ.size() < k)
PQ.push(n);
else if (n > PQ.top())
{
PQ.pop();
PQ.push(n);
}
}
return PQ.top();
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int monotoneIncreasingDigits(int N)
{
string num = to_string(N);
int start = num.length();
for (int i = num.length() - 1; i > 0; --i)
{
if (num[i - 1] > num[i])
{
start = i;
--num[i - 1];
}
}
for (int i = start; i < num.length(); ++i)
num[i] = '9';
return stoi(num);
}
};<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
string stringSum(string num1, string num2)
{
/*
adds two string numbers
*/
if (num1.length() < num2.length())
return stringSum(num2, num1);
// num1 is always larger or equal in size to num2
string result(num1.size() + 1, '0');
int i = num1.size() - 1, sum = 0;
for (int j = num2.size() - 1; j >= 0; --j)
{
sum = (num1[i] - '0') + (num2[j] - '0') + (result[i + 1] - '0');
result[i + 1] = sum % 10 + '0';
result[i] += sum / 10;
--i;
}
while (i >= 0)
{
sum = (result[i + 1] - '0') + (num1[i] - '0');
result[i + 1] = sum % 10 + '0';
result[i] += sum / 10;
--i;
}
return result[0] == '0' ? result.substr(1, result.length() - 1) : result;
}
string addStringNums(vector<string> &nums, int start, int end)
{
/*
recursively adds a list of string numbers
*/
if (start == end)
return nums[start];
if (end - start == 1)
return stringSum(nums[start], nums[end]);
int mid = start + ((end - start) >> 1);
string left = addStringNums(nums, start, mid);
string right = addStringNums(nums, mid + 1, end);
return stringSum(left, right);
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin >> n;
vector<string> nums;
string num;
while (n--)
{
cin >> num;
nums.emplace_back(num);
}
string sum = addStringNums(nums, 0, nums.size() - 1);
cout << sum.substr(0, 10);
return 0;
}
<file_sep>class Solution
{
public:
string getActualString(string s)
{
string result = "";
int backspace_count = 0;
for (int i = s.length() - 1; i >= 0; --i)
{
if (s[i] == '#')
{
++backspace_count;
}
else
{
if (backspace_count == 0)
{
result += s[i];
}
else
--backspace_count;
}
}
return result;
}
bool backspaceCompare(string S, string T)
{
return getActualString(S) == getActualString(T);
}
};<file_sep>// solved on: https://www.lintcode.com/problem/find-the-celebrity/description
// time: O(n), space: O(1) solution
// Forward declaration of the knows API.
bool knows(int a, int b);
class Solution
{
public:
/**
* @param n a party with n people
* @return the celebrity's label or -1
*/
int findCelebrity(int n)
{
// Write your code here
int l = 0, r = n - 1, deg = 0;
while (l < r)
{
if (knows(l, r))
++l;
else
--r;
}
for (int i = 0; i < n; ++i)
if (i != l && knows(i, l) && !knows(l, i))
++deg;
return deg == n - 1 ? l : -1;
}
};
// time: O(n), space: O(n) solution, recursive
// Forward declaration of the knows API.
bool knows(int a, int b);
class Solution
{
public:
/**
* @param n a party with n people
* @return the celebrity's label or -1
*/
int findCelebrityUtil(int id)
{
if (id == 1)
return 0;
int cel = findCelebrityUtil(id - 1);
if (cel == -1)
return id - 1;
if (knows(id - 1, cel))
return cel;
else if (cel, id - 1)
return id - 1;
return -1;
}
int findCelebrity(int n)
{
// Write your code here
int l = findCelebrityUtil(n), deg = 0;
if (l == -1)
return -1;
for (int i = 0; i < n; ++i)
if (i != l && knows(i, l) && !knows(l, i))
++deg;
return deg == n - 1 ? l : -1;
}
};
// time: O(n^2), space: O(n) solution
// Forward declaration of the knows API.
bool knows(int a, int b);
class Solution
{
public:
/**
* @param n a party with n people
* @return the celebrity's label or -1
*/
int findCelebrity(int n)
{
// Write your code here
vector<int> balance(n, 0);
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (j != i && knows(i, j))
{
--balance[i];
++balance[j];
}
}
}
for (int i = 0; i < n; ++i)
if (balance[i] == n - 1)
return i;
return -1;
}
};<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Twitter.
* Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix.
* For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal].
* Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries.
*
*
*/
// for the sake of simplicity I'm assuming that only lowercase characters are used
#include <bits/stdc++.h>
using namespace std;
class Trie
{
char data;
vector<Trie *> children;
bool isEnd;
public:
Trie()
{
this->data = '*'; // represents the root
this->children = vector<Trie *>(26, NULL); // 26 children to store all the possible lowercase characters [a-z]
this->isEnd = false; // signifies the end of a valid word
}
// initialize a new node with the given character data
Trie(char c)
{
this->data = c;
this->children = vector<Trie *>(26, NULL);
this->isEnd = false;
}
// insert a string s into the trie
void insert(string s, int idx = 0)
{
if (idx == s.length())
return;
if (!this->children[s[idx] - 'a']) // check if a node for current character does not exists
this->children[s[idx] - 'a'] = new Trie(s[idx]); // create a new one if true
if (idx == s.length() - 1) // if this is the last character of the word mark isEnd to be true
this->children[s[idx] - 'a']->isEnd = true; // signifies a valid end of word
this->children[s[idx] - 'a']->insert(s, idx + 1); // insert the next character to the children of the current character
}
// store all children of current node in words vector
void print(vector<string> &words, string s = "")
{
if (this->isEnd && s.length() > 0) // is a valid word
words.push_back(s);
// iterate over all children
for (int i = 0; i < 26; ++i)
{
if (this->children[i]) // if a valid node is present look down the next level
this->children[i]->print(words, s + string(1, this->children[i]->data));
}
}
// lookup for the given string and store all its children in words vector by using print() as a subroutine
void findpAndPrint(vector<string> &words, string s, int idx = 0)
{
if (idx == s.length()) // prefix match, now look at all the sub tries
{
this->print(words, s); // store all sub tries of the current node in words vector (all prefix matches)
return;
}
if (!this->children[s[idx] - 'a']) // character of given string not present, no prefix matches
return;
this->children[s[idx] - 'a']->findpAndPrint(words, s, idx + 1); // look at the next level for the next character
}
};
int main()
{
Trie t;
t.insert("dog");
t.insert("deer");
t.insert("deal");
t.insert("test");
t.insert("anuj");
t.insert("value");
t.insert("variable");
t.insert("apple");
vector<string> words;
cout << "****** Dictionary ******\n";
t.print(words);
if (words.size() > 0)
for (string w : words)
cout << w << "\n";
else
cout << "{Empty!!!}\n";
cout << "************************\n";
cout << "******** Lookup ********\n";
words.clear();
t.findpAndPrint(words, "de");
if (words.size() > 0)
for (string w : words)
cout << w << "\n";
else
cout << "{No matches!!!}\n";
cout << "************************\n";
return 0;
}
<file_sep>// recursive dfs + pruning
class Solution
{
public:
void coinChangeUtil(vector<int> &coins, int amount, int idx, int count, int &res)
{
if (idx < 0 || count > res)
return;
if (amount % coins[idx] == 0)
{
res = min(res, count + amount / coins[idx]);
return;
}
int div = amount / coins[idx];
for (int i = div; i >= 0; --i)
{
if (count + i > res)
return; // prioritize larger coins first, also prevents tle
coinChangeUtil(coins, amount - (coins[idx] * i), idx - 1, count + i, res);
}
}
int coinChange(vector<int> &coins, int amount)
{
sort(coins.begin(), coins.end());
int res = INT_MAX;
coinChangeUtil(coins, amount, coins.size() - 1, 0, res);
return res == INT_MAX ? -1 : res;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// recursive memoization
class Solution
{
public:
int coinChangeUtil(vector<int> &coins, int amount, vector<int> &mem)
{
if (mem[amount] != INT_MAX)
return mem[amount];
int res = 0, min_count = INT_MAX;
for (int &c : coins)
{
if (c <= amount)
{
res = coinChangeUtil(coins, amount - c, mem);
if (res >= 0 && res < min_count)
{
min_count = min(min_count, 1 + res);
}
}
}
mem[amount] = min_count == INT_MAX ? -1 : min_count;
return mem[amount];
}
int coinChange(vector<int> &coins, int amount)
{
vector<int> mem(amount + 1, INT_MAX);
mem[0] = 0;
return coinChangeUtil(coins, amount, mem);
}
};
// dp solution
class Solution
{
public:
int coinChange(vector<int> &coins, int amount)
{
vector<int> tab(amount + 1, amount + 1);
tab[0] = 0;
for (int &c : coins)
{
for (int i = c; i <= amount; ++i)
tab[i] = min(tab[i], 1 + tab[i - c]);
}
return tab[amount] == amount + 1 ? -1 : tab[amount];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// class Codec {
// public:
// // Encodes a tree to a single string.
// string serialize(TreeNode* root) {
// if(root == NULL) return "x,";
// queue<TreeNode*> Q;
// Q.push(root);
// TreeNode* tmp = NULL;
// string ret;
// while(!Q.empty()) {
// tmp = Q.front();
// Q.pop();
// if(tmp) {
// ret += to_string(tmp->val) + ",";
// Q.push(tmp->left);
// Q.push(tmp->right);
// }
// else ret += "x,";
// }
// int ind = ret.length()-2;
// while(ret[ind] == 'x') ind -= 2;
// return ret.substr(0, ind+2);
// }
// vector<TreeNode*> getValues(string data) {
// vector<TreeNode*> ret;
// size_t cur_pos = 0, pos = 0;
// pos = data.find(",", cur_pos);
// string tmp;
// while(pos != string::npos) {
// tmp = data.substr(cur_pos, pos-cur_pos);
// if(tmp == "x") ret.push_back(NULL);
// else ret.emplace_back(new TreeNode(stoi(tmp)));
// cur_pos = pos+1;
// pos = data.find(",", cur_pos);
// }
// return ret;
// }
// // Decodes your encoded data to tree.
// TreeNode* deserialize(string data) {
// vector<TreeNode*> tree = getValues(data);
// int ind = 1;
// for(int i=0; i<tree.size(); ++i) {
// if(tree[i]) {
// if(ind < tree.size()) tree[i]->left = tree[ind];
// if(ind+1 < tree.size()) tree[i]->right = tree[ind+1];
// ind +=2;
// }
// }
// return tree[0];
// }
// };
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec
{
public:
void serializeUtil(TreeNode *root, ostringstream &out)
{
if (root == NULL)
out << "x ";
else
{
out << root->val << " ";
serializeUtil(root->left, out);
serializeUtil(root->right, out);
}
}
// Encodes a tree to a single string.
string serialize(TreeNode *root)
{
ostringstream out;
serializeUtil(root, out);
return out.str();
}
TreeNode *deserializeUtil(istringstream &in)
{
string val;
in >> val;
if (val == "x")
return NULL;
TreeNode *root = new TreeNode(stoi(val));
root->left = deserializeUtil(in);
root->right = deserializeUtil(in);
return root;
}
// Decodes your encoded data to tree.
TreeNode *deserialize(string data)
{
istringstream in(data);
return deserializeUtil(in);
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Microsoft.
* You have an N by N board. Write a function that, given N, returns the number of possible arrangements of the board where N queens can be placed on the board without threatening each other, i.e. no two queens share the same row, column, or diagonal.
*
*
* Online Judge: https://leetcode.com/problems/n-queens-ii/
*
*/
class Solution
{
public:
int count;
bool isValid(vector<int> &board, int val, int limit)
{
for (int i = 0; i < limit; ++i)
{
if (board[i] == val || abs(val - board[i]) == abs(limit - i))
return false;
}
return true;
}
void totalNQueenUtil(vector<int> &board, int idx = 0)
{
if (idx == board.size())
{
++count;
return;
}
for (int i = 0; i < board.size(); ++i)
{
if (isValid(board, i, idx))
{
board[idx] = i;
totalNQueenUtil(board, idx + 1);
}
}
}
int totalNQueens(int n)
{
count = 0;
vector<int> board(n, -1);
totalNQueenUtil(board);
return count;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 0, m = 0, k = 0, count = 0, x = 0;
cin >> n >> m >> k;
set<int> rows;
vector<int> row_count(m, 0);
for (int i = 1; i <= m; ++i)
{
rows.insert(i);
}
for (int i = 0; i < n; ++i)
{
cin >> x;
if (!rows.empty())
{
auto it = rows.lower_bound(x);
if (it == rows.end())
it = rows.begin();
if (*it != x)
++count;
++row_count[*it];
if (row_count[*it] == k)
rows.erase(*it);
}
else
++count;
}
cout << count;
return 0;
}<file_sep>class Solution
{
public:
int subtractProductAndSum(int n)
{
int digit_sum = 0, product_sum = 1, x = n, rem = 0;
while (x)
{
rem = x % 10;
x /= 10;
digit_sum += rem;
product_sum *= rem;
}
return product_sum - digit_sum;
}
};<file_sep>class Solution
{
public:
int balancedStringSplit(string s)
{
int result = 0, count = 0;
for (char &c : s)
{
count += (c == 'L') ? 1 : -1;
if (count == 0)
++result;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
string getLine(vector<string> &words, int maxWidth, int l, int r, int len, int space_ct, bool last)
{
int spaces = maxWidth - len;
spaces += space_ct;
int same = (last || (space_ct == 0)) ? 0 : spaces / space_ct;
int extra = (last || (space_ct == 0)) ? space_ct : spaces % space_ct;
int trail = (last || (space_ct == 0)) ? maxWidth - len : 0;
string res;
for (int i = l; i <= r; ++i)
{
res += words[i];
if (i < r)
{
res.append(same, ' ');
if (extra)
{
res.append(1, ' ');
--extra;
}
}
}
if (trail)
res.append(trail, ' ');
return res;
}
vector<string> fullJustify(vector<string> &words, int maxWidth)
{
vector<string> result;
int l = 0, len = -1, space_ct = -1;
for (int i = 0; i < words.size(); ++i)
{
if (len + words[i].length() + 1 <= maxWidth)
{
len += words[i].length() + 1;
++space_ct;
}
else
{
result.emplace_back(getLine(words, maxWidth, l, i - 1, len, space_ct, false));
l = i;
--i;
len = -1;
space_ct = -1;
}
}
result.emplace_back(getLine(words, maxWidth, l, words.size() - 1, len, space_ct, true));
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <complex>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
double x, y;
cin >> x >> y;
cin.ignore();
int m;
cin >> m;
cin.ignore();
complex<double> c(x, y);
complex<double> f(0, 0);
int limit = 1;
while (limit < m)
{
f = f * f + c;
if (abs(f) > 2)
break;
++limit;
}
cout << min(limit, m) << "\n";
}<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Facebook.
* A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost while ensuring that no two neighboring houses are of the same color.
* Given an N by K matrix where the nth row and kth column represents the cost to build the nth house with kth color, return the minimum cost which achieves this goal.
*
*
* Online Judge: https://leetcode.com/problems/paint-house-ii/
* Online Judge used: https://www.lintcode.com/en/old/problem/paint-house-ii/
*
*
*/
// my solution
class Solution
{
public:
/**
* @param costs: n x k cost matrix
* @return: an integer, the minimum cost to paint all houses
*/
int minCostII(vector<vector<int>> &costs)
{
// write your code here
if (costs.size() == 0)
return 0;
if (costs.size() == 1)
return *min_element(costs[0].begin(), costs[0].end());
pair<int, int> minTab; // stores the minimum and second minimum of each preceeding row
int first_min = 0, second_min = 0;
for (int i = 0; i < costs.size(); ++i)
{
first_min = 0, second_min = 1;
for (int j = 0; j < costs[i].size(); ++j)
{
if (i > 0)
{
if (j == minTab.first)
{
costs[i][j] += costs[i - 1][minTab.second];
}
else
{
costs[i][j] += costs[i - 1][minTab.first];
}
}
if (costs[i][first_min] > costs[i][j])
{
second_min = first_min;
first_min = j;
}
else if (costs[i][second_min] > costs[i][j] && j != first_min)
{
second_min = j;
}
}
minTab = {first_min, second_min};
}
return *min_element(costs[costs.size() - 1].begin(), costs[costs.size() - 1].end());
}
};
<file_sep>class Solution
{
public:
int minOperations(vector<int> &nums, int x)
{
long target = -x, sum = 0;
int result = 0, l = 0, n = nums.size();
for (int &n : nums)
target += n;
for (int r = 0; r < n; ++r)
{
sum += nums[r];
while (l < r && sum > target)
sum -= nums[l++];
if (sum == target)
result = max(result, r - l + 1);
}
return result ? nums.size() - result : target ? -1 : nums.size();
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long int
ll getLargestPrimeFactor(ll n)
{
ll largest_prime_factor = 2;
// divide by two (prime factor) untill n becomes odd;
while (n % 2 == 0)
n >>= 1;
// 2 is the only prime factor
if (n == 1)
return 2;
// skip even numbers
for (size_t i = 3; i * i <= n; i += 2)
{
if (n % i == 0)
{
largest_prime_factor = i;
while (n % i == 0)
n = n / i;
}
}
// n itself is a prime now
if (n > 2)
return n;
return largest_prime_factor;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
ll t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
cout << getLargestPrimeFactor(n) << "\n";
}
return 0;
}
<file_sep>// O(nlogn) solution
class Solution
{
public:
int lengthOfLIS(vector<int> &nums)
{
if (nums.size() == 0)
return 0;
vector<int> tab(nums.size(), 0);
int len = 1, pos = 0;
tab[0] = nums[0];
for (int i = 1; i < nums.size(); ++i)
{
if (tab[len - 1] < nums[i])
{
tab[len++] = nums[i];
}
else
{
pos = lower_bound(tab.begin(), tab.begin() + len, nums[i]) - tab.begin();
tab[pos] = nums[i];
}
}
return len;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(n^2) solution
class Solution
{
public:
int lengthOfLIS(vector<int> &nums)
{
if (nums.size() == 0)
return 0;
int result = 1;
vector<int> tab(nums.size(), 1);
for (int i = 1; i < nums.size(); ++i)
{
for (int j = 0; j < i; ++j)
{
if (nums[j] < nums[i])
tab[i] = max(tab[i], tab[j] + 1);
}
result = max(result, tab[i]);
}
return result;
}
};<file_sep>class Solution
{
public:
vector<vector<int>> generateMatrix(int n)
{
if (n == 0)
return {};
if (n == 1)
return {{1}};
vector<vector<int>> ret(n, vector<int>(n, 0));
int h_start = 0, h_end = n - 1;
int v_start = 0, v_end = n - 1;
int val = 1;
while (true)
{
for (int i = h_start; i <= h_end; ++i)
ret[v_start][i] = val++;
++v_start;
if (v_start > v_end)
break;
for (int i = v_start; i <= v_end; ++i)
ret[i][h_end] = val++;
--h_end;
if (h_start > h_end)
break;
for (int i = h_end; i >= h_start; --i)
ret[v_end][i] = val++;
--v_end;
if (v_start > v_end)
break;
for (int i = v_end; i >= v_start; --i)
ret[i][h_start] = val++;
++h_start;
if (h_start > h_end)
break;
}
return ret;
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
ll N;
cin >> N;
cin.ignore();
ll C;
cin >> C;
cin.ignore();
vector<ll> B(N, 0);
ll sum = 0;
for (size_t i = 0; i < N; i++)
{
cin >> B[i];
cin.ignore();
sum += B[i];
}
if (sum < C)
{
cout << "IMPOSSIBLE" << endl;
return 0;
}
sort(B.begin(), B.end());
ll cur_rat = C / N;
ll tmp = 0, d = 0;
for (size_t i = 0; i < N; ++i)
{
if (i + 1 == N)
tmp = C;
else
tmp = min(B[i], cur_rat);
cout << tmp << "\n";
C -= tmp;
d = N - i - 1;
if (d)
cur_rat = C / d;
}
}<file_sep>#include <iostream>
#include <vector>
#define ll long long int
using namespace std;
bool isSpecial(ll n)
{
return n & (n << 1);
}
int main()
{
ll n = 0, q = 0, l = 0, r = 0, count = 0;
cin >> n >> q;
vector<int> a(n, 0);
for (int i = 0; i < n; ++i)
{
cin >> a[i];
}
while (q--)
{
cin >> l >> r;
count = 0;
for (int i = l - 1; i < r; ++i)
{
if (isSpecial(a[i]))
++count;
}
cout << count << "\n";
}
return 0;
}
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// heap solution
class MedianFinder
{
public:
/** initialize your data structure here. */
priority_queue<int> h_left;
priority_queue<int, vector<int>, greater<int>> h_right;
int count = 0;
MedianFinder()
{
}
void addNum(int num)
{
++count;
if (h_left.empty())
{
h_left.push(num);
return;
}
if (num <= h_left.top())
h_left.push(num);
else
h_right.push(num);
if (h_left.size() > h_right.size() + 1)
{
h_right.push(h_left.top());
h_left.pop();
}
else if (h_right.size() > h_left.size())
{
h_left.push(h_right.top());
h_right.pop();
}
}
double findMedian()
{
if (count & 1)
return h_left.top();
return double(h_left.top() + h_right.top()) / 2.0;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/
// multiset solution
class MedianFinder
{
public:
/** initialize your data structure here. */
multiset<int> nums;
multiset<int>::iterator mid;
MedianFinder()
{
mid = nums.end();
}
void addNum(int num)
{
int n = nums.size();
nums.emplace(num);
if (!n)
{
mid = nums.begin();
}
else if (num < *mid)
{
mid = ((n & 1) ? --mid : mid);
}
else
{
mid = ((n & 1) ? mid : ++mid);
}
}
double findMedian()
{
if (nums.size() & 1)
return *mid;
return (*mid + *next(mid)) * 0.5;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_set>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
// class Trie {
// public:
// char c;
// vector<Trie*> children;
// Trie(char c) {
// this->c = c;
// this->children = vector<Trie*>(10, NULL);
// }
// };
// Trie* getNode(char c) {
// Trie* ret = new Trie(c);
// return ret;
// }
// Trie* insert(Trie* head, string s) {
// Trie* t = head;
// int i=0;
// while(i < s.length() && t->children[s[i]-'0'] != NULL) {
// t = t->children[s[i]-'0'];
// ++i;
// }
// while(i<s.length()) {
// t->children[s[i]-'0'] = getNode(s[i]);
// t = t->children[s[i]-'0'];
// ++i;
// }
// return head;
// }
// int count(Trie* head) {
// int ret = 1;
// for(int i=0; i<10; ++i) {
// if(head->children[i] != NULL) {
// ret += count(head->children[i]);
// }
// }
// return ret;
// }
int main()
{
int N;
cin >> N;
cin.ignore();
unordered_set<string> NUM;
// Trie* head = getNode('*');
for (int i = 0; i < N; i++)
{
string telephone;
cin >> telephone;
cin.ignore();
for (int j = 1; j <= telephone.size(); ++j)
{
NUM.insert(telephone.substr(0, j));
}
// head = insert(head, telephone);
}
// The number of elements (referencing a number) stored in the structure.
// cout << count(head)-1 << endl;
cout << NUM.size() << endl;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int getPosition(string s, int start=0) {
return s.find(';', start);
}
int main()
{
int N;
cin >> N; cin.ignore();
string XthenCOMMANDS;
getline(cin, XthenCOMMANDS);
int cur_position = 0;
int next_position = getPosition(XthenCOMMANDS, cur_position);
int pos = stol(XthenCOMMANDS.substr(cur_position, next_position));
cur_position = next_position+1;
next_position = getPosition(XthenCOMMANDS, cur_position);
string cur_ins = XthenCOMMANDS.substr(cur_position, next_position-cur_position);
char dir = cur_ins[cur_ins.length()-1];
int dist = stol(cur_ins.substr(0, cur_ins.length()-1));
for (int i = 0; i < N; i++) {
string RthenROADPATTERN;
getline(cin, RthenROADPATTERN);
int t_pos = RthenROADPATTERN.find(';');
int R = stol(RthenROADPATTERN.substr(0, t_pos));
string road = RthenROADPATTERN.substr(t_pos+1, RthenROADPATTERN.length()-t_pos-1);
for(int k=0; k<R; ++k) {
if(dist == 0) {
cur_position = next_position+1;
next_position = getPosition(XthenCOMMANDS, cur_position);
string cur_ins = XthenCOMMANDS.substr(cur_position, next_position-cur_position);
dir = cur_ins[cur_ins.length()-1];
dist = stol(cur_ins.substr(0, cur_ins.length()-1));
}
if(dir == 'R') ++pos;
else if(dir == 'L') --pos;
for(int r=0; r<road.length(); ++r) {
if(r == pos-1) {
cout<<"#";
--dist;
}
else cout<<road[r];
}
cout<<"\n";
}
}
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
bool validateIsbnTen(string s)
{
int prod_sum = 0;
for (int i = 0; i < 9; ++i)
{
prod_sum += (s[i] - '0') * (10 - i);
}
int rem = prod_sum % 11;
rem = rem == 0 ? 0 : 11 - rem;
if (s[9] == rem + '0' || (rem == 10 && s[9] == 'X'))
return true;
return false;
}
bool validateIsbnThirteen(string s)
{
int prod_sum = 0;
for (int i = 0; i < 12; ++i)
{
prod_sum += (s[i] - '0') * ((i & 1) ? 3 : 1);
}
int rem = prod_sum % 10;
rem = rem == 0 ? 0 : 10 - rem;
return s[12] == rem + '0';
}
bool validate(string s)
{
if (s.length() == 10)
return validateIsbnTen(s);
else if (s.length() == 13)
return validateIsbnThirteen(s);
return false;
}
int main()
{
int N;
cin >> N;
cin.ignore();
vector<string> invalid;
for (int i = 0; i < N; i++)
{
string ISBN;
getline(cin, ISBN);
if (!validate(ISBN))
invalid.push_back(ISBN);
}
cout << invalid.size() << " invalid:\n";
for (auto i : invalid)
cout << i << "\n";
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
* ---
* Hint: You can use the debug stream to print initialTX and initialTY, if Thor seems not follow your orders.
**/
int getDir(int src, int dest) {
if(dest == src) return 0;
if(dest > src) return 1;
if(dest < src) return -1;
}
int main()
{
int lightX; // the X position of the light of power
int lightY; // the Y position of the light of power
int initialTX; // Thor's starting X position
int initialTY; // Thor's starting Y position
cin >> lightX >> lightY >> initialTX >> initialTY; cin.ignore();
// game loop
while (1) {
int remainingTurns; // The remaining amount of turns Thor can move. Do not remove this line.
cin >> remainingTurns; cin.ignore();
int x = getDir(initialTX, lightX);
int y = getDir(initialTY, lightY);
if(x == 0) {
if(y == 1) {
cout<<"S"<<endl;
++initialTY;
}
else if(y == -1) {
cout<<"N"<<endl;
--initialTY;
}
}
else if(y == 0) {
if(x == 1) {
cout<<"E"<<endl;
++initialTX;
}
else if(x == -1) {
cout<<"W"<<endl;
--initialTX;
}
}
else if(x == 1 && y == -1) {
cout<<"NE"<<endl;
--initialTY;
++initialTX;
}
else if(x == -1 && y == -1) {
cout<<"NW"<<endl;
--initialTY;
--initialTX;
}
else if(x == -1 && y == 1) {
cout<<"SW"<<endl;
++initialTY;
--initialTX;
}
else if(x == 1 && y == 1) {
cout<<"SE"<<endl;
++initialTY;
++initialTX;
}
// A single line providing the move to be made: N NE E SE S SW W or NW
// cout << "SE" << endl;
cerr<<initialTX<<" : "<<initialTY<<"\n";
}
}<file_sep>// O(n)
class Solution
{
public:
int majorityElement(vector<int> &nums)
{
int cur = 0, count = 0;
for (int &n : nums)
{
if (count == 0)
cur = n;
count += cur == n ? 1 : -1;
}
return cur;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(n)
class Solution
{
public:
int majorityElement(vector<int> &nums)
{
nth_element(nums.begin(), nums.begin() + (nums.size() >> 1), nums.end());
return nums[nums.size() >> 1];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(n)
class Solution
{
public:
int majorityElement(vector<int> &nums)
{
unordered_map<int, int> mem;
for (int &n : nums)
{
++mem[n];
if (mem[n] > floor(nums.size() >> 1))
return n;
}
return -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// solved on: https://www.lintcode.com/problem/the-maze-ii/description
// dijkstras priority queue solution
class Solution
{
public:
/**
* @param maze: the maze
* @param start: the start
* @param destination: the destination
* @return: the shortest distance for the ball to stop at the destination
*/
int shortestDistance(vector<vector<int>> &maze, vector<int> &start, vector<int> &destination)
{
// write your code here
vector<vector<int>> dist(maze.size(), vector<int>(maze[0].size(), INT_MAX));
dist[start[0]][start[1]] = 0;
auto compare = [&dist](const pair<int, int> o1, const pair<int, int> o2) {
return dist[o1.first][o1.second] > dist[o2.first][o2.second];
};
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(compare)> PQ(compare);
for (int i = 0; i < dist.size(); ++i)
{
for (int j = 0; j < dist[i].size(); ++j)
PQ.push({i, j});
}
vector<pair<int, int>> dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int x = 0, y = 0, distance = 0;
while (!PQ.empty())
{
auto cur = PQ.top();
PQ.pop();
if (dist[cur.first][cur.second] == INT_MAX)
continue;
if (cur.first == destination[0] && cur.second == destination[1])
break;
for (auto d : dirs)
{
x = cur.first + d.first;
y = cur.second + d.second;
distance = 0;
while (x >= 0 && x < maze.size() && y >= 0 && y < maze[x].size() && maze[x][y] == 0)
{
x += d.first;
y += d.second;
++distance;
}
x -= d.first;
y -= d.second;
if (dist[cur.first][cur.second] + distance < dist[x][y])
{
dist[x][y] = dist[cur.first][cur.second] + distance;
PQ.push({x, y});
}
}
}
return dist[destination[0]][destination[1]] == INT_MAX ? -1 : dist[destination[0]][destination[1]];
}
};
// better dfs solution
class Solution
{
public:
/**
* @param maze: the maze
* @param start: the start
* @param destination: the destination
* @return: the shortest distance for the ball to stop at the destination
*/
void shortestDistanceUtil(vector<vector<int>> &maze, vector<vector<int>> &dist, int row, int col, vector<int> &dest)
{
if (row == dest[0] && col == dest[1])
return;
static vector<pair<int, int>> dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int x = 0, y = 0, distance = 0;
for (auto d : dirs)
{
x = row + d.first;
y = col + d.second;
distance = 0;
while (x >= 0 && x < maze.size() && y >= 0 && y < maze[x].size() && maze[x][y] == 0)
{
x += d.first;
y += d.second;
++distance;
}
if (dist[row][col] + distance < dist[x - d.first][y - d.second])
{
dist[x - d.first][y - d.second] = dist[row][col] + distance;
shortestDistanceUtil(maze, dist, x - d.first, y - d.second, dest);
}
}
}
int shortestDistance(vector<vector<int>> &maze, vector<int> &start, vector<int> &destination)
{
// write your code here
vector<vector<int>> dist(maze.size(), vector<int>(maze[0].size(), INT_MAX));
dist[start[0]][start[1]] = 0;
shortestDistanceUtil(maze, dist, start[0], start[1], destination);
return dist[destination[0]][destination[1]] == INT_MAX ? -1 : dist[destination[0]][destination[1]];
}
};
// dfs solution
class Solution
{
public:
/**
* @param maze: the maze
* @param start: the start
* @param destination: the destination
* @return: the shortest distance for the ball to stop at the destination
*/
int shortestDistanceUtil(vector<vector<int>> &maze, vector<vector<bool>> &vis, int row, int col, vector<int> &dest, int dist = 0)
{
if (vis[row][col])
return -1;
if (row == dest[0] && col == dest[1])
return dist;
vis[row][col] = true;
static vector<pair<int, int>> dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int x = 0, y = 0, tmp_dist = dist, res = 0, result = INT_MAX;
for (auto d : dirs)
{
x = row + d.first;
y = col + d.second;
tmp_dist = dist + 1;
while (x >= 0 && x < maze.size() && y >= 0 && y < maze[x].size() && maze[x][y] == 0)
{
x += d.first;
y += d.second;
++tmp_dist;
}
res = shortestDistanceUtil(maze, vis, x - d.first, y - d.second, dest, tmp_dist - 1);
if (res != -1)
result = min(result, res);
}
vis[row][col] = false;
return result == INT_MAX ? -1 : result;
}
int shortestDistance(vector<vector<int>> &maze, vector<int> &start, vector<int> &destination)
{
// write your code here
vector<vector<bool>> vis(maze.size(), vector<bool>(maze[0].size(), false));
return shortestDistanceUtil(maze, vis, start[0], start[1], destination);
}
};
// bfs solution
class Solution
{
public:
/**
* @param maze: the maze
* @param start: the start
* @param destination: the destination
* @return: the shortest distance for the ball to stop at the destination
*/
int shortestDistance(vector<vector<int>> &maze, vector<int> &start, vector<int> &destination)
{
// write your code here
vector<vector<bool>> vis(maze.size(), vector<bool>(maze[0].size(), false));
vector<pair<int, int>> dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
queue<tuple<int, int, int>> Q;
tuple<int, int, int> tmp;
int x = 0, y = 0, r = 0, c = 0, dist = 0, tmp_dist = 0;
Q.push(make_tuple(start[0], start[1], 0));
while (!Q.empty())
{
tmp = Q.front();
Q.pop();
tie(r, c, dist) = tmp;
vis[r][c] = true;
tmp_dist = dist;
for (auto d : dirs)
{
x = r + d.first;
y = c + d.second;
++tmp_dist;
while (x >= 0 && x < maze.size() && y >= 0 && y < maze[x].size() && maze[x][y] == 0)
{
x += d.first;
y += d.second;
++tmp_dist;
}
x -= d.first;
y -= d.second;
--tmp_dist;
if (x == destination[0] && y == destination[1])
return tmp_dist;
if (!vis[x][y])
Q.push(make_tuple(x, y, tmp_dist));
tmp_dist = dist;
}
}
return -1;
}
};<file_sep>// O(sqrt(n)) solution
class Solution
{
public:
int kthFactor(int n, int k)
{
int res = 1;
for (; res * res <= n; ++res)
{
if (n % res == 0 && --k == 0)
return res;
}
while (res > 1)
{
--res;
if (res * res == n)
continue;
if (n % res == 0 && --k == 0)
return n / res;
}
return -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(n) solution
class Solution
{
public:
int kthFactor(int n, int k)
{
int res = 0;
while (res <= n && k)
{
++res;
if (n % res == 0)
--k;
}
return res <= n ? res : -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
string shiftingLetters(string S, vector<int> &shifts)
{
int n = shifts.size();
for (int i = n - 1; i >= 0; --i)
{
shifts[i] %= 26;
shifts[i] += (i + 1 < n) ? shifts[i + 1] : 0;
S[i] = ((S[i] - 'a' + shifts[i]) % 26) + 'a';
}
return S;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// O(n) time solution and O(logn) space
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
int result;
unordered_map<int, int> MEM;
void pathSumUtil(TreeNode *root, int pre_sum, int sum)
{
if (!root)
return;
pre_sum += root->val;
if (MEM.count(pre_sum - sum))
{
result += MEM[pre_sum - sum];
}
++MEM[pre_sum];
pathSumUtil(root->left, pre_sum, sum);
pathSumUtil(root->right, pre_sum, sum);
--MEM[pre_sum];
}
int pathSum(TreeNode *root, int sum)
{
result = 0;
int pre_sum = 0;
MEM[pre_sum] = 1;
pathSumUtil(root, pre_sum, sum);
return result;
}
};
// O(n^2) solution and O(logn) space (stack space of recursion)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
int result;
void pathSumUtil(TreeNode *root, int sum)
{
if (root == NULL)
return;
if (root->val == sum)
++result;
pathSumUtil(root->left, sum - root->val);
pathSumUtil(root->right, sum - root->val);
}
void traverse(TreeNode *root, int &sum)
{
if (root)
{
traverse(root->left, sum);
pathSumUtil(root, sum);
traverse(root->right, sum);
}
}
int pathSum(TreeNode *root, int sum)
{
result = 0;
traverse(root, sum);
return result;
}
};<file_sep>class Solution {
public:
int countPrimeSetBits(int L, int R) {
unordered_set<int> mem = {2, 3, 5, 7, 11,
13, 17, 19}; // since 1e6 can go as high as 2^20
int result = 0;
for (int i = L; i <= R; ++i)
result += mem.count(__builtin_popcount(i));
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
string getBinaryString(int x) {
string ret;
while(x) {
ret += x%2 + '0';
x /= 2;
}
int n = ret.length();
for(int i=0; i<n/2; ++i) {
char t = ret[i];
ret[i] = ret[n-i-1];
ret[n-i-1] = t;
}
if(n < 7) {
int ct = 7-n;
while(ct--) ret = "0" + ret;
}
return ret.substr(0, 7);
}
void printCN(string s) {
int ct = 0;
string op;
int i = 0;
while(i<s.length()) {
ct = 0;
if(s[i] == '1') {
op += "0 ";
while(i < s.length() && s[i] == '1') { ++ct; ++i;}
while(ct--) op += "0";
}
else {
op += "00 ";
while(i < s.length() && s[i] == '0') { ++ct; ++i;}
while(ct--) op += "0";
}
op += " ";
}
cout<<op.substr(0, op.length()-1);
}
int main()
{
string MESSAGE;
getline(cin, MESSAGE);
string op;
for(int i=0; i<MESSAGE.length(); ++i) {
op += getBinaryString(MESSAGE[i]);
}
cerr<<op<<"\n";
printCN(op);
cout << endl;
}<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long int
#define MEM_SIZE 5000001
#define CACHE_SIZE 5000001
int MEM[MEM_SIZE];
int CACHE[CACHE_SIZE];
int getCollatzSeq(ll n)
{
// returns the length of the collatz sequence of n
// uses recursion and memoization to improve performance
if (n < 0)
return 0;
if (n == 1)
return 1;
if (n < MEM_SIZE && MEM[n] > 0)
return MEM[n];
int res = 1;
if (~n & 1)
res += getCollatzSeq(n >> 1);
else
res += getCollatzSeq(3 * n + 1);
if (n < MEM_SIZE)
MEM[n] = res;
return res;
}
void preComputeSeq()
{
// precomputes the collatz sequences for all n in given range 5*10^6
// and caches the the result for each number beforehand
for (int i = 0; i < MEM_SIZE; ++i)
MEM[i] = -1;
int seq = 0, max_seq = -1, max_idx = -1;
for (int i = 1; i < CACHE_SIZE; ++i)
{
seq = getCollatzSeq(i);
if (seq >= max_seq)
{
max_seq = seq;
max_idx = i;
}
CACHE[i] = max_idx;
}
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
preComputeSeq();
int t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
cout << CACHE[n] << "\n";
}
return 0;
}
<file_sep>class Solution
{
public:
bool checkInclusion(string s1, string s2)
{
vector<int> MEM(128, 0);
int window_size = s1.length(), count = 0, l = 0;
for (char &c : s1)
++MEM[c];
for (int r = 0; r < s2.length(); ++r)
{
if (--MEM[s2[r]] >= 0)
++count;
if (count == window_size)
return true;
if (r - l + 1 == window_size && ++MEM[s2[l++]] > 0)
--count;
}
return false;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Google.
* Suppose we represent our file system by a string in the following manner:
* The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:
-----------------------------------------
| dir |
| subdir1 |
| subdir2 |
| file.ext |
-----------------------------------------
* The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext.
* The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents:
-----------------------------------------
| dir |
| subdir1 |
| file1.ext |
| subsubdir1 |
| subdir2 |
| subsubdir2 |
| file2.ext |
-----------------------------------------
* The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext.
* We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes).
* Given a string representing the file system in the above format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0.
*
* Note:
* The name of a file contains at least a period and an extension.
* The name of a directory or sub-directory will not contain a period.
*
*
* Online Judge: https://leetcode.com/problems/longest-absolute-file-path/
*
*
*/
class Solution
{
public:
int lengthLongestPath(string input)
{
istringstream paths(input);
string path;
int max_path_len = 0, depth = 0;
unordered_map<int, int> depth_map;
while (getline(paths, path))
{
depth = path.find_last_of("\t");
depth = (depth == string::npos) ? 0 : depth + 1;
if (path.find(".") != string::npos)
{ // it is a file
max_path_len = max(max_path_len, int(depth_map[depth] + path.length()));
}
else
{
depth_map[depth + 1] = depth_map[depth] + path.length() - depth;
}
}
return max_path_len;
}
};
<file_sep>// O(nlogn) solution (better overall performance for the test cases)
class Solution
{
public:
int findPairs(vector<int> &nums, int k)
{
int result = 0;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); ++i)
{
if (i > 0 && nums[i] == nums[i - 1])
continue;
if (binary_search(nums.begin() + i + 1, nums.end(), nums[i] + k))
++result;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(n) solution
class Solution
{
public:
int findPairs(vector<int> &nums, int k)
{
int result = 0;
unordered_map<int, vector<int>> mem;
unordered_set<int> seen;
for (int i = 0; i < nums.size(); ++i)
{
mem[nums[i]].emplace_back(i);
}
for (int i = 0; i < nums.size(); ++i)
{
if (!seen.count(nums[i]))
{
if (k == 0)
{
if (mem[nums[i]].size() > 1)
++result;
}
else
{
if (mem.count(nums[i] + k))
++result;
}
}
seen.insert(nums[i]);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int R;
cin >> R;
cin.ignore();
int L;
cin >> L;
cin.ignore();
vector<int> res, ans;
res.push_back(R);
while (--L)
{
int i = 0, ct = 0;
while (i < res.size())
{
ct = 0;
int t = res[i];
while (i < res.size() && res[i] == t)
{
++i;
++ct;
}
ans.push_back(ct);
ans.push_back(t);
}
res = ans;
ans.clear();
}
for (int i = 0; i < res.size(); ++i)
{
if (i + 1 < res.size())
cout << res[i] << " ";
else
cout << res[i];
}
}<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Dropbox.
* Conway's Game of Life takes place on an infinite two-dimensional board of square cells. Each cell is either dead or alive, and at each tick, the following rules apply:
Any live cell with less than two live neighbours dies.
Any live cell with two or three live neighbours remains living.
Any live cell with more than three live neighbours dies.
Any dead cell with exactly three live neighbours becomes a live cell.
* A cell neighbours another cell if it is horizontally, vertically, or diagonally adjacent.
* Implement Conway's Game of Life. It should be able to be initialized with a starting list of live cell coordinates and the number of steps it should run for. Once initialized, it should print out the board state at each step. Since it's an infinite board, print out only the relevant coordinates, i.e. from the top-leftmost live cell to bottom-rightmost live cell.
* You can represent a live cell with an asterisk (*) and a dead cell with a dot (.).
*
*
*
* Online Judge: https://leetcode.com/problems/game-of-life/
*
*/
class Solution
{
public:
void gameOfLife(vector<vector<int>> &board)
{
vector<pair<int, int>> dirs = {
{-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}};
int x = 0, y = 0, live_count = 0;
for (int i = 0; i < board.size(); ++i)
{
for (int j = 0; j < board[i].size(); ++j)
{
live_count = 0;
for (auto &d : dirs)
{
x = i + d.first;
y = j + d.second;
if (x >= 0 && x < board.size() && y >= 0 && y < board[x].size())
{
if (board[x][y] == 1 || board[x][y] == '*')
++live_count;
;
}
}
if (board[i][j] == 1)
{
if (live_count < 2 || live_count > 3)
board[i][j] = '*';
}
else
{
if (live_count == 3)
board[i][j] = '?';
}
}
}
for (int i = 0; i < board.size(); ++i)
{
for (int j = 0; j < board[i].size(); ++j)
{
board[i][j] = (board[i][j] == 1 || board[i][j] == '?') ? 1 : 0;
}
}
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int climbStairs(int n)
{ // simply fibonacci numbers
if (n <= 0)
return 0;
if (n == 1)
return 1;
if (n == 2)
return 2;
int f = 1, s = 2, ret = 0;
for (int i = 0; i < n - 2; ++i)
{
ret = f + s;
f = s;
s = ret;
}
return ret;
}
};<file_sep>// https://www.hackerearth.com/practice/data-structures/advanced-data-structures/segment-trees/tutorial/
#include <bits/stdc++.h>
using namespace std;
vector<int> a, tree;
void build(int idx, int s, int e)
{
if (s == e)
{
tree[idx] = a[s];
return;
}
int mid = (s + e) >> 1;
int left = 2 * idx + 1;
int right = left + 1;
build(left, s, mid);
build(right, mid + 1, e);
tree[idx] = min(tree[left], tree[right]);
}
void update(int idx, int s, int e, int ind, int val)
{
if (s == e)
{
a[ind] = val;
tree[idx] = val;
return;
}
int mid = (s + e) >> 1;
int left = 2 * idx + 1;
int right = left + 1;
if (ind <= mid)
{
update(left, s, mid, ind, val);
}
else
{
update(right, mid + 1, e, ind, val);
}
tree[idx] = min(tree[left], tree[right]);
}
int query(int idx, int s, int e, int l, int r)
{
if (r < s || l > e)
{ // completely outside the range
return 999999;
}
if (s >= l && e <= r)
{ // completely within the range
return tree[idx];
}
int mid = (s + e) >> 1;
int left = 2 * idx + 1;
int right = left + 1;
int o1 = query(left, s, mid, l, r);
int o2 = query(right, mid + 1, e, l, r);
return min(o1, o2);
}
int main()
{
int n, q, x, y, l, r;
char c;
cin >> n >> q;
a = vector<int>(1000005, 0);
tree = vector<int>(2000005, 0);
for (int i = 0; i < n; ++i)
{
cin >> a[i];
}
build(0, 0, n - 1);
while (q--)
{
cin >> c;
if (c == 'q')
{
cin >> l >> r;
--l;
--r;
cout << query(0, 0, n - 1, l, r) << "\n";
}
else
{
cin >> x >> y;
--x;
update(0, 0, n - 1, x, y);
}
}
return 0;
}
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
bool isValidIdx(int i, int j, int N, int len) {
if(i<0 || j<0 || i>= N || j>= len) return false;
return true;
}
bool isDigit(char c) {
return (c >= '0' && c <= '9');
}
int main()
{
int N;
cin >> N; cin.ignore();
vector<string> comp;
vector<pair<int, int>> dirs = {{-1, 0}, {0, 3}, {1, 0}, {0, -3}};
for (int i = 0; i < N; i++) {
string COMPOUND;
getline(cin, COMPOUND);
comp.push_back(COMPOUND);
}
int len = 0, h_c = 0, b_c = 0, x = -1, y = -1;
for(int i=0; i<N; ++i) {
len = comp[i].length();
for(int j=0; j<len; ++j) {
if(comp[i][j] == 'H') {
h_c = b_c = 0;
h_c = comp[i][j+1] - '0';
for(auto d : dirs) {
x = i + d.first;
y = j + d.second;
if(isValidIdx(x, y, N, len) && isDigit(comp[x][y])) {
b_c += comp[x][y] - '0';
}
}
if(h_c + b_c != 4) {
cout<<"INVALID\n";
return 0;
}
}
}
}
cout<<"VALID\n";
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
int t = 0, n = 0, pos = 0;
ll k = 0, count = 0;
cin >> t;
while (t--)
{
cin >> n >> k;
vector<ll> A(n, 0);
count = 0;
for (int i = 0; i < n; ++i)
{
cin >> A[i];
if (i > 0)
A[i] += A[i - 1];
if (abs(A[i]) > k)
++count;
}
sort(A.begin(), A.end());
for (int i = 0; i < n; ++i)
{
pos = upper_bound(A.begin(), A.end(), A[i] + k) - A.begin();
count += (n - pos);
}
cout << count << "\n";
}
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int n; // the number of temperatures to analyse
cin >> n; cin.ignore();
int min_temp = 5527;
for (int i = 0; i < n; i++) {
int t; // a temperature expressed as an integer ranging from -273 to 5526
cin >> t; cin.ignore();
if(abs(t) < abs(min_temp)) {
min_temp = t;
}
else if(abs(t) == abs(min_temp)) {
if(t > 0) min_temp = t;
}
}
if(min_temp == 5527) min_temp = 0;
cout << min_temp << endl;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
bool vis[100007] = {false};
int getDigitSum(int x){
return x ? x%10 + getDigitSum(x/10) : 0;
}
bool isPartOfRiver(int r, int p) {
while(r <= p) {
if(vis[r]) return false;
vis[r] = true;
if(r == p) return true;
r += getDigitSum(r);
}
return false;
}
int main()
{
int r1;
cin >> r1; cin.ignore();
bool flag = false;
for(int i=1; i<r1; ++i) {
if(!vis[i] && isPartOfRiver(i, r1)) {
flag = true;
break;
}
}
if(flag) cout << "YES" << endl;
else cout << "NO" << endl;
}<file_sep>// dfs solution
class Solution {
public:
bool isBipartiteUtil(vector<vector<int>> &graph, vector<int> &vis, int src,
int color = 1) {
vis[src] = color;
bool result = true;
for (int &nxt : graph[src]) {
if (vis[nxt] == 0 && isBipartiteUtil(graph, vis, nxt, -color) == false)
return false;
else if (vis[nxt] != 0 && vis[nxt] == color)
return false;
}
return result;
}
bool isBipartite(vector<vector<int>> &graph) {
int n = graph.size();
vector<int> vis(n, 0);
for (int i = 0; i < n; ++i) {
if (vis[i] == 0 && isBipartiteUtil(graph, vis, i) == false)
return false;
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// bfs solution
class Solution {
public:
bool isBipartite(vector<vector<int>> &graph) {
int n = graph.size(), cur = 0, q_size = 0, color = 1;
vector<int> vis(n, 0);
for (int i = 0; i < n; ++i) {
if (vis[i] == 0) {
queue<int> Q;
Q.push(i);
color = 1;
while (Q.size()) {
q_size = Q.size();
color = -color;
while (q_size--) {
cur = Q.front();
Q.pop();
vis[cur] = color;
for (int &nxt : graph[cur]) {
if (vis[nxt] == 0)
Q.push(nxt);
else if (vis[nxt] == color)
return false;
}
}
}
}
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>class Solution
{
public:
int minimumSwap(string s1, string s2)
{
int xy = 0, yx = 0;
for (int i = 0; i < s1.length(); ++i)
{
if (s1[i] != s2[i])
{
if (s1[i] == 'x')
++xy;
if (s1[i] == 'y')
++yx;
}
}
if ((xy + yx) & 1)
return -1;
return (xy >> 1) + (yx >> 1) + 2 * (xy % 2);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// Iterative DP solution O(mxn) time & O(min(m, n)) space
class Solution
{
public:
int minDistance(string word1, string word2)
{
if (word1.length() > word2.length())
return minDistance(word2, word1);
int m = word1.length(), n = word2.length();
if (m == 0)
return n;
if (n == 0)
return m;
int tab[m + 1];
tab[0] = 0;
int prev = 0, tmp = 0;
for (int i = 1; i <= m; ++i)
tab[i] = i;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j <= m; ++j)
{
if (j == 0)
{
prev = tab[j];
tab[j] = i + 1;
}
else
{
tmp = tab[j];
if (word1[j - 1] != word2[i])
{
tab[j] = 1 + min(min(tab[j], tab[j - 1]), prev);
}
else
{
tab[j] = prev;
}
prev = tmp;
}
}
}
return tab[m];
}
};
// Iterative DP solution O(mxn) time & O(mxn) space
class Solution
{
public:
int minDistance(string word1, string word2)
{
int m = word1.length(), n = word2.length();
if (m == 0)
return n;
if (n == 0)
return m;
int tab[m + 1][n + 1];
tab[0][0] = 0;
for (int i = 1; i <= n; ++i)
tab[0][i] = i;
for (int i = 1; i <= m; ++i)
tab[i][0] = i;
for (int i = 1; i <= m; ++i)
{
for (int j = 1; j <= n; ++j)
{
tab[i][j] = 0;
if (word1[i - 1] == word2[j - 1])
tab[i][j] = tab[i - 1][j - 1];
else
{
tab[i][j] = 1 + min(
min(
tab[i - 1][j], // delete a character from word1
tab[i][j - 1] // insert a character in word1
),
tab[i - 1][j - 1] // replace a character in word1
);
}
}
}
return tab[m][n];
}
};
// recursive solution with memoization
class Solution
{
public:
vector<vector<int>> MEM;
int minDistanceUtil(string &word1, string &word2, int idx1 = 0, int idx2 = 0)
{
if (idx1 == word1.length())
return word2.length() - idx2;
if (idx2 == word2.length())
return word1.length() - idx1;
if (MEM[idx1][idx2] > 0)
return MEM[idx1][idx2];
int result = 0;
if (word1[idx1] != word2[idx2])
{
result = 1 + min(min(
minDistanceUtil(word1, word2, idx1, idx2 + 1), // insert a char in word1
minDistanceUtil(word1, word2, idx1 + 1, idx2) // delete a char from word1
),
minDistanceUtil(word1, word2, idx1 + 1, idx2 + 1) // replace a char in word1
);
}
else
result = minDistanceUtil(word1, word2, idx1 + 1, idx2 + 1);
MEM[idx1][idx2] = result;
return result;
}
int minDistance(string word1, string word2)
{
MEM = vector<vector<int>>(word1.size() + 1, vector<int>(word2.size() + 1, -1));
return minDistanceUtil(word1, word2);
}
};<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Amazon.
* Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
* For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb".
*
*
* Online Judge: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
* Online Judge used: https://www.lintcode.com/problem/longest-substring-with-at-most-k-distinct-characters/description
*
*/
class Solution
{
public:
/**
* @param s: A string
* @param k: An integer
* @return: An integer
*/
int lengthOfLongestSubstringKDistinct(string &s, int k)
{
if (s.length() == 0 || k == 0)
return 0;
if (k >= s.size())
return s.size();
unordered_map<char, int> M;
int i = 0, j = 0, max_len = 0;
while (i < s.size())
{
if (M.size() < k || M.find(s[i]) != M.end())
{
++M[s[i]];
++i;
max_len = max(max_len, i - j);
}
else
{
--M[s[j]];
if (M[s[j]] == 0)
M.erase(s[j]);
++j;
}
}
return max_len;
}
};<file_sep>// O(n) approach using unordered_map
class Solution
{
public:
int maxOperations(vector<int> &nums, int k)
{
int result = 0;
unordered_map<int, int> mem;
for (int &n : nums)
{
if (mem[k - n] > 0)
{
++result;
--mem[k - n];
}
else
++mem[n];
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(nlogn) approach using sorting and two pointer approach
class Solution
{
public:
int maxOperations(vector<int> &nums, int k)
{
sort(nums.begin(), nums.end());
int l = 0, r = nums.size() - 1, result = 0, sum = 0;
while (l < r)
{
sum = nums[l] + nums[r];
if (sum == k)
{
++result;
++l;
--r;
}
else if (sum < k)
++l;
else
--r;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// dfs approach
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
pair<TreeNode *, int> isCousinsUtil(TreeNode *root, TreeNode *parent, int val, int depth = 0)
{
if (!root)
return {NULL, -1};
if (root->val == val)
{
return {parent, depth};
}
auto l = isCousinsUtil(root->left, root, val, depth + 1);
auto r = isCousinsUtil(root->right, root, val, depth + 1);
if (l.second == -1)
return r;
return l;
}
bool isCousins(TreeNode *root, int x, int y)
{
auto x_info = isCousinsUtil(root, NULL, x);
auto y_info = isCousinsUtil(root, NULL, y);
return (x_info.first != y_info.first) && (x_info.second == y_info.second);
}
};
// bfs approach
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
bool isCousins(TreeNode *root, int x, int y)
{
if (!root || root->val == x || root->val == y)
return false;
queue<TreeNode *> Q;
TreeNode *tmp;
int cur_size = 0;
Q.push(root);
bool found_x = false, found_y = false;
while (!Q.empty())
{
cur_size = Q.size();
while (cur_size--)
{
tmp = Q.front();
Q.pop();
if (tmp->val == x)
found_x = true;
if (tmp->val == y)
found_y = true;
if (tmp->left && tmp->right)
{
if ((tmp->left->val == x && tmp->right->val == y) || tmp->left->val == y && tmp->right->val == x)
return false;
}
if (tmp->left)
Q.push(tmp->left);
if (tmp->right)
Q.push(tmp->right);
}
if (found_x ^ found_y)
return false;
if (found_x && found_y)
return true;
}
return false;
}
};<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
bool isValid(ll p, ll n)
{
int sum = 0;
while (p)
{
sum += p / 5;
p /= 5;
}
return sum >= n;
}
int main()
{
ll t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
ll l = 1, r = 1e10, mid = 0, ans = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
if (isValid(mid, n))
{
ans = mid;
r = mid - 1;
}
else
l = mid + 1;
}
cout << ans << "\n";
}
return 0;
}<file_sep>class Solution
{
public:
string longestCommonPrefix(vector<string> &strs)
{
if (strs.size() == 0)
return "";
if (strs.size() == 1)
return strs[0];
for (int p = 0;; ++p)
{
if (p >= strs[0].size())
return strs[0];
char c = strs[0][p];
for (int i = 1; i < strs.size(); ++i)
{
if (p >= strs[i].size())
return strs[i];
if (strs[i][p] != c)
return strs[i].substr(0, p);
}
}
return "";
}
};<file_sep>// solved on : https://www.lintcode.com/problem/the-maze/description
// bfs solution
class Solution
{
public:
/**
* @param maze: the maze
* @param start: the start
* @param destination: the destination
* @return: whether the ball could stop at the destination
*/
bool hasPath(vector<vector<int>> &maze, vector<int> &start, vector<int> &destination)
{
// write your code here
queue<pair<int, int>> Q;
vector<vector<bool>> vis(maze.size(), vector<bool>(maze[0].size(), false));
vector<pair<int, int>> dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int x = 0, y = 0;
pair<int, int> tmp;
Q.push({start[0], start[1]});
while (!Q.empty())
{
tmp = Q.front();
Q.pop();
vis[tmp.first][tmp.second] = true;
for (auto d : dirs)
{
x = tmp.first + d.first;
y = tmp.second + d.second;
while (x >= 0 && x < maze.size() && y >= 0 && y < maze[x].size() && maze[x][y] == 0)
{
x += d.first;
y += d.second;
}
x -= d.first;
y -= d.second;
if (x == destination[0] && y == destination[1])
return true;
if (!vis[x][y])
Q.push({x, y});
}
}
return false;
}
};
// dfs solution
class Solution
{
public:
/**
* @param maze: the maze
* @param start: the start
* @param destination: the destination
* @return: whether the ball could stop at the destination
*/
bool hasPathUtil(vector<vector<int>> &maze, vector<vector<bool>> &vis, int row, int col, vector<int> &dest)
{
if (vis[row][col])
return false;
if (row == dest[0] && col == dest[1])
return true;
vis[row][col] = true;
static vector<pair<int, int>> dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int x = 0, y = 0;
for (auto d : dirs)
{
x = row + d.first;
y = col + d.second;
while (x >= 0 && x < maze.size() && y >= 0 && y < maze[x].size() && maze[x][y] == 0)
{
x += d.first;
y += d.second;
}
if (hasPathUtil(maze, vis, x - d.first, y - d.second, dest))
return true;
}
return false;
}
bool hasPath(vector<vector<int>> &maze, vector<int> &start, vector<int> &destination)
{
// write your code here
vector<vector<bool>> vis(maze.size(), vector<bool>(maze[0].size(), false));
return hasPathUtil(maze, vis, start[0], start[1], destination);
}
};<file_sep>// class Solution
// {
// public:
// bool searchMatrix(vector<vector<int>> &matrix, int target)
// {
// if (matrix.size() == 0)
// return false;
// if (matrix[0].size() == 0)
// return false;
// if (target < matrix[0][0])
// return false;
// if (target > matrix[matrix.size() - 1][matrix[0].size() - 1])
// return false;
// int m = matrix.size();
// int n = matrix[0].size();
// int l = 0, r = m * n - 1, mid = 0, val = 0;
// while (l <= r)
// {
// mid = l + ((r - l) >> 1);
// val = matrix[mid / n][mid % n];
// if (val == target)
// return true;
// else if (val < target)
// l = mid + 1;
// else
// r = mid - 1;
// }
// return false;
// }
// };
class Solution
{
public:
bool searchMatrix(vector<vector<int>> &matrix, int target)
{
if (matrix.size() == 0)
return false;
if (matrix[0].size() == 0)
return false;
if (target < matrix[0][0])
return false;
if (target > matrix[matrix.size() - 1][matrix[0].size() - 1])
return false;
int row = lower_bound(matrix.begin(), matrix.end(), target, [](const vector<int> &o, const int &t) {
return o[o.size() - 1] < t;
}) -
matrix.begin();
return binary_search(matrix[row].begin(), matrix[row].end(), target);
}
};<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Google.
* The power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set.
* For example, given the set {1, 2, 3}, it should return {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}.
* You may also use a list or array to represent a set.
*
*
* Online Judge: https://leetcode.com/problems/subsets/
*
*/
class Solution
{
public:
vector<vector<int>> subsets(vector<int> &nums)
{
vector<vector<int>> result;
int limit = 1 << nums.size();
cout << limit;
for (int i = 0; i < limit; ++i)
{
vector<int> res;
for (int j = 0; j < nums.size(); ++j)
{
if (i & (1 << j))
res.emplace_back(nums[j]);
}
result.emplace_back(res);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// a more efficient solution
class Solution
{
public:
int lengthOfLongestSubstring(string s)
{
int result = 0, l = 0;
vector<int> MEM(128, 0);
for (int r = 0; r < s.length(); ++r)
{
if (MEM[s[r]] > 0)
{
while (s[l] != s[r])
--MEM[s[l++]];
--MEM[s[l++]];
}
++MEM[s[r]];
result = max(result, r - l + 1);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// normal solution
class Solution
{
public:
int lengthOfLongestSubstring(string s)
{
if (s.length() == 0)
return 0;
unordered_set<char> H;
int i = 0, j = 0, n = s.length(), max_len = 0;
while (i < n)
{
if (H.find(s[i]) == H.end())
{
H.insert(s[i]);
++i;
max_len = max(max_len, i - j);
}
else
{
H.erase(s[j]);
++j;
}
}
return max_len;
}
};<file_sep>class Solution {
public:
int findOneCount(vector<int> &v) {
int l = 0, r = v.size() - 1, m = 0, res = -1;
while (l <= r) {
m = l + ((r - l) >> 1);
if (v[m] == 1) {
res = m;
l = m + 1;
} else
r = m - 1;
}
return res == -1 ? 0 : res + 1;
}
vector<int> kWeakestRows(vector<vector<int>> &mat, int k) {
vector<int> result;
priority_queue<pair<int, int>> pq;
int sum = 0;
for (int i = 0; i < mat.size(); ++i) {
sum = findOneCount(mat[i]);
if (pq.size() < k)
pq.push({sum, i});
else if (sum < pq.top().first) {
pq.pop();
pq.push({sum, i});
}
}
while (pq.size()) {
result.emplace_back(pq.top().second);
pq.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
bool isValid(vector<ll> &a, ll window, ll limit)
{
ll sum = 0;
for (int i = 0; i < window; ++i)
{
sum += a[i];
if (sum > limit)
return false;
}
for (int i = window; i < a.size(); ++i)
{
sum -= a[i - window];
sum += a[i];
if (sum > limit)
return false;
}
return true;
}
int main()
{
ll n = 0, x = 0;
cin >> n >> x;
vector<ll> a(n, 0);
for (int i = 0; i < n; ++i)
cin >> a[i];
ll l = 1, r = n, mid = 0, ans = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
if (isValid(a, mid, x))
{
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
cout << ans;
return 0;
}
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int n;
int max_so_far = -999999;
int max_diff = 0;
cin >> n;
cin.ignore();
for (int i = 0; i < n; i++)
{
int v;
cin >> v;
cin.ignore();
if (v > max_so_far)
{
max_so_far = v;
}
else
{
max_diff = max(max_diff, max_so_far - v);
}
}
cout << max_diff * -1 << "\n";
}<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Google.
* Given a singly linked list and an integer k, remove the kth last element from the list. k is guaranteed to be smaller than the length of the list.
* The list is very long, so making more than one pass is prohibitively expensive.
* Do this in constant space and in one pass.
*
*
* Online Judge: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
*
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *removeNthFromEnd(ListNode *head, int n)
{
if (!head)
return head;
ListNode *slow = head;
ListNode *fast = head;
ListNode *to_delete = head;
while (n--)
fast = fast->next;
if (!fast)
{
head = head->next;
delete (to_delete);
return head;
}
while (fast->next)
{
slow = slow->next;
fast = fast->next;
}
to_delete = slow->next;
slow->next = slow->next->next;
delete (to_delete);
return head;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Amazon.
* Implement a stack that has the following methods:
push(val), which pushes an element onto the stack
pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it should throw an error or return null.
max(), which returns the maximum value in the stack currently. If there are no elements in the stack, then it should throw an error or return null.
* Each method should run in constant time.
*
* ref: https://leetcode.com/articles/max-stack/#
* Online Judge: https://leetcode.com/problems/max-stack/
* Online Judge: https://leetcode.com/problems/min-stack/
*
*/
// solution of https://leetcode.com/problems/max-stack/ | solved on : https://www.lintcode.com/problem/max-stack/description
#include <bits/stdc++.h>
class MaxStack
{
public:
list<int> S;
map<int, vector<list<int>::iterator>, greater<int>> mem;
MaxStack()
{
// do intialization if necessary
}
/*
* @param number: An integer
* @return: nothing
*/
void push(int number)
{
// write your code here
mem[number].emplace_back(S.emplace(S.end(), number)); // S.emplace returns an iterator to the newly added element unlike emplace_back which returns void
}
/*
* @return: An integer
*/
int pop()
{
// write your code here
int t = S.back();
S.pop_back();
mem[t].pop_back();
return t;
}
/*
* @return: An integer
*/
int top()
{
// write your code here
return S.back();
}
/*
* @return: An integer
*/
int peekMax()
{
// write your code here
return mem.begin()->first;
}
/*
* @return: An integer
*/
int popMax()
{
// write your code here
int t = mem.begin()->first;
S.erase(mem[t].back());
mem[t].pop_back();
return t;
}
};
// modified solution of min stack (https://leetcode.com/problems/min-stack/)
class MinStack
{
stack<pair<int, int>> S;
public:
/** initialize your data structure here. */
MinStack()
{
}
void push(int x)
{
int max_element = 0;
if (this->S.empty())
max_element = x;
else
max_element = max(x, this->S.top().second);
this->S.push({x, max_element});
}
void pop()
{
this->S.pop();
}
int top()
{
return this->S.top().first;
}
int getMin()
{
return this->S.top().second;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int processCard(string card)
{
if (card[0] == 'J')
return 11;
if (card[0] == 'Q')
return 12;
if (card[0] == 'K')
return 13;
if (card[0] == 'A')
return 14;
int i = 0;
while (isdigit(card[i]))
++i;
return stoi(card.substr(0, i));
}
int Fight(queue<int> &P1, queue<int> &P2, queue<int> &t1, queue<int> &t2, bool war = false)
{
if (war && (P1.size() == 0 || P2.size() == 0))
return 0;
int p1_c = P1.front();
int p2_c = P2.front();
P1.pop();
P2.pop();
t1.push(p1_c);
t2.push(p2_c);
if (p1_c > p2_c)
{ // player 1 wins
return 1;
}
else if (p1_c < p2_c)
{ // player 2 wins
return 2;
}
else
{ // war
for (int i = 0; i < 3; ++i)
{
t1.push(P1.front());
t2.push(P2.front());
P1.pop();
P2.pop();
if (P1.size() == 0 || P2.size() == 0)
return 0;
}
return Fight(P1, P2, t1, t2, true);
}
}
int main()
{
int n; // the number of cards for player 1
cin >> n;
cin.ignore();
queue<int> P1, P2, t1, t2;
for (int i = 0; i < n; i++)
{
string cardp1; // the n cards of player 1
cin >> cardp1;
cin.ignore();
P1.push(processCard(cardp1));
}
int m; // the number of cards for player 2
cin >> m;
cin.ignore();
for (int i = 0; i < m; i++)
{
string cardp2; // the m cards of player 2
cin >> cardp2;
cin.ignore();
P2.push(processCard(cardp2));
}
int num_rounds = 0, res;
while (true)
{
++num_rounds;
res = Fight(P1, P2, t1, t2);
if (res == 1)
{
if (P2.size() == 0)
break;
while (!t1.empty())
{
P1.push(t1.front());
t1.pop();
}
while (!t2.empty())
{
P1.push(t2.front());
t2.pop();
}
}
else if (res == 2)
{
if (P1.size() == 0)
break;
while (!t1.empty())
{
P2.push(t1.front());
t1.pop();
}
while (!t2.empty())
{
P2.push(t2.front());
t2.pop();
}
}
else
{
cout << "PAT\n";
return 0;
}
}
cout << res << " " << num_rounds << endl;
}<file_sep>// actual node swapping
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode *swapNodes(ListNode *head, int k) {
if (!head)
return NULL;
int len = k;
ListNode *cur1 = head;
ListNode *cur2 = head;
ListNode *prev1 = NULL;
ListNode *prev2 = NULL;
for (int i = 1; i < k; ++i) {
prev1 = cur1;
cur1 = cur1->next;
}
ListNode *tmp = cur1;
cur2 = head;
while (tmp->next) {
++len;
tmp = tmp->next;
prev2 = cur2;
cur2 = cur2->next;
}
if (k > (len >> 1)) {
swap(prev1, prev2);
swap(cur1, cur2);
}
tmp = cur2->next;
cur2->next = cur1->next == cur2 ? cur1 : cur1->next;
cur1->next = tmp;
if (prev1 && prev2) {
prev1->next = cur2;
prev2->next = cur1 == prev2 ? cur1->next : cur1;
} else if (prev1 && !prev2) {
prev1->next = cur2;
head = cur1;
} else if (!prev1 && prev2) {
prev2->next = cur1 == prev2 ? cur1->next : cur1;
head = cur2;
}
return head;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// simple value swapping
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode *swapNodes(ListNode *head, int k) {
if (!head)
return NULL;
ListNode *cur1 = head;
ListNode *cur2 = head;
for (int i = 1; i < k; ++i)
cur1 = cur1->next;
ListNode *tmp = cur1;
cur2 = head;
while (tmp->next) {
tmp = tmp->next;
cur2 = cur2->next;
}
swap(cur1->val, cur2->val);
return head;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>class Solution
{
public:
bool isValid(vector<vector<char>> &board, char e, int i, int j)
{
for (int k = 0; k < 9; ++k)
{
if (board[k][j] == e)
return false;
if (board[i][k] == e)
return false;
if (board[(i / 3) * 3 + (k / 3)][(j / 3) * 3 + (k % 3)] == e)
return false;
}
return true;
}
bool solveSudokuUtil(vector<vector<char>> &board)
{
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
{
if (board[i][j] == '.')
{
for (char c = '1'; c <= '9'; ++c)
{
if (isValid(board, c, i, j))
{
board[i][j] = c;
if (solveSudokuUtil(board))
return true;
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
void solveSudoku(vector<vector<char>> &board)
{
cout << solveSudokuUtil(board);
}
};<file_sep>class Solution
{
public:
vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0)
{
vector<vector<int>> result;
vector<pair<int, int>> dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int count = 0, size = R * C, r = r0, c = c0, dir = 0, stride = 1, cur_len = 0;
while (count < size)
{
if (r >= 0 && r < R && c >= 0 && c < C)
{
result.emplace_back(vector<int>{r, c});
++count;
}
if (cur_len == stride)
{
dir = (dir + 1) % 4;
if (dir % 2 == 0)
++stride;
cur_len = 0;
}
r += dirs[dir].first;
c += dirs[dir].second;
++cur_len;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
bool closeStrings(string word1, string word2)
{
if (word1.length() != word2.length())
return false;
vector<int> freq1(26, 0), freq2(26, 0), word_count1(26, 0), word_count2(26, 0);
for (int i = 0; i < word1.size(); ++i)
{
freq1[word1[i] - 'a']++;
freq2[word2[i] - 'a']++;
word_count1[word1[i] - 'a'] = 1;
word_count2[word2[i] - 'a'] = 1;
}
sort(freq1.begin(), freq1.end());
sort(freq2.begin(), freq2.end());
return word_count1 == word_count2 && freq1 == freq2;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
bool isValid(vector<int> &BX, vector<int> &TR, int time)
{
int count = 0;
for (int i = 0; i < TR.size(); ++i)
{
for (int j = 0; j < time && count < BX.size() && TR[i] >= BX[count]; j += 2)
++count;
}
return count == BX.size();
}
int main()
{
int n = 0, m = 0;
cin >> n >> m;
vector<int> boxes(n, 0);
vector<int> trucks(m, 0);
vector<bool> vis(m, false);
for (int i = 0; i < n; ++i)
cin >> boxes[i];
for (int i = 0; i < m; ++i)
cin >> trucks[i];
sort(boxes.begin(), boxes.end());
sort(trucks.begin(), trucks.end());
int l = 1, r = 2 * (n - 1) + 1, mid = 0;
while (l < r)
{
mid = l + ((r - l) >> 1);
if (isValid(boxes, trucks, mid))
r = mid;
else
l = mid + 1;
}
cout << l;
return 0;
}<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Two Sigma.
* Using a function rand7() that returns an integer from 1 to 7 (inclusive) with uniform probability, implement a function rand5() that returns an integer from 1 to 5 (inclusive).
*
*
* ref: https://leetcode.com/problems/implement-rand10-using-rand7/discuss/395824/Easily-implement-rand5()-and-rand6()-then-rand10()-is-straightforward
*
*/
// assuming rand7() is already availeble
class Solution
{
public:
int rand5()
{
val = rand7();
while (val > 5)
val = rand7();
return val;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>class Solution
{
public:
bool increasingTriplet(vector<int> &nums)
{
int min1 = INT_MAX, min2 = INT_MAX;
for (int &n : nums)
{
if (n <= min1)
min1 = n;
else if (n <= min2)
min2 = n;
else
return true;
}
return false;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
vector<int> Counts;
vector<vector<string>> groupAnagrams(vector<string> &strs)
{
vector<vector<string>> ret;
unordered_map<string, vector<string>> M;
string key;
Counts = vector<int>(26, 0);
for (string s : strs)
{
key = CountSort(s);
M[key].push_back(s);
}
for (auto m : M)
ret.push_back(m.second);
return ret;
}
string CountSort(string s)
{
fill(Counts.begin(), Counts.end(), 0);
string s_string;
for (int i = 0; i < s.length(); ++i)
++Counts[s[i] - 'a'];
for (int i = 0; i < 26; ++i)
{
if (Counts[i] > 0)
{
s_string += string(Counts[i], i + 'a');
}
}
return s_string;
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
size_t n;
cin >> n; cin.ignore();
size_t n_sq = n*n, a=0, b=0;
for(size_t i=1; i<=n; ++i) {
if(n_sq%i != 0) continue;
a = i;
b = n_sq/i;
cout << "1/"<<n<<" = 1/"<<b+n<<" + 1/"<<a+n<< endl;
}
}<file_sep>class Solution
{
public:
int firstMissingPositive(vector<int> &nums)
{
if (nums.size() == 0)
return 1;
int p = 0, x = 0;
for (int i = 0; i < nums.size(); ++i)
{
if (nums[i] > 0)
swap(nums[i], nums[p++]);
}
for (int i = 0; i < p; ++i)
{
x = abs(nums[i]) - 1;
if (x < p && nums[x] > 0)
nums[x] = -nums[x];
}
for (int i = 0; i < p; ++i)
{
if (nums[i] > 0)
return i + 1;
}
return p + 1;
}
};<file_sep>class Solution
{
public:
int brokenCalc(int X, int Y)
{
int result = 0;
while (Y > X)
{
if (~Y & 1)
Y >>= 1;
else
++Y;
++result;
}
return result + (X - Y);
}
};<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int getMaxFromIdx(vector<vector<int>> &grid, int row, int col)
{
if (grid[row][col] == 0)
return 0;
int res = 1, max_res = -999999;
if (col < 17)
{ // along the row horizontally
for (int i = col; i < col + 4; ++i)
{
res *= grid[row][i];
if (res == 0)
break;
}
max_res = max(max_res, res);
}
if (row < 17)
{ // along the col vertically
res = 1;
for (int i = row; i < row + 4; ++i)
{
res *= grid[i][col];
if (res == 0)
break;
}
max_res = max(max_res, res);
}
if (row < 17 && col < 17)
{ // along the diagonal (down-right)
res = 1;
for (int i = 0; i < 4; ++i)
{
res *= grid[row + i][col + i];
if (res == 0)
break;
}
max_res = max(max_res, res);
}
if (row < 17 && col > 2)
{ // along the diagonal (down-left)
res = 1;
for (int i = 0; i < 4; ++i)
{
res *= grid[row + i][col - i];
if (res == 0)
break;
}
max_res = max(max_res, res);
}
return max_res;
}
int getLargestProductInGrid(vector<vector<int>> &grid)
{
int max_res = 0;
for (int i = 0; i < 20; ++i)
{
for (int j = 0; j <= 20; ++j)
{
max_res = max(max_res, getMaxFromIdx(grid, i, j));
}
}
return max_res;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
vector<vector<int>> grid(20, vector<int>(20, 0));
for (int i = 0; i < 20; ++i)
{
for (int j = 0; j < 20; ++j)
cin >> grid[i][j];
}
cout << getLargestProductInGrid(grid) << "\n";
return 0;
}
<file_sep>// bfs solution
class Solution
{
public:
bool possibleBipartitionUtil(vector<vector<int>> &graph, vector<int> &colors, int src)
{
colors[src] = 0;
queue<int> Q;
Q.push(src);
while (!Q.empty())
{
src = Q.front();
Q.pop();
for (int &dis : graph[src])
{
if (colors[dis] == colors[src])
return false;
if (colors[dis] == -1)
Q.push(dis);
colors[dis] = !colors[src];
}
}
return true;
}
bool possibleBipartition(int N, vector<vector<int>> &dislikes)
{
vector<vector<int>> graph(N + 1);
vector<int> colors(N + 1, -1);
for (auto d : dislikes)
{
graph[d[0]].emplace_back(d[1]);
graph[d[1]].emplace_back(d[0]);
}
for (int i = 1; i <= N; ++i)
{
if (colors[i] == -1 && !possibleBipartitionUtil(graph, colors, i))
return false;
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// dfs solution
class Solution
{
public:
bool possibleBipartitionUtil(vector<vector<int>> &graph, vector<int> &colors, int src, bool col)
{
colors[src] = col;
for (int &dest : graph[src])
{
if (colors[dest] != -1 && colors[dest] == col)
return false;
if (colors[dest] == -1 && !possibleBipartitionUtil(graph, colors, dest, !col))
return false;
}
return true;
}
bool possibleBipartition(int N, vector<vector<int>> &dislikes)
{
vector<vector<int>> graph(N + 1);
vector<int> colors(N + 1, -1);
for (auto d : dislikes)
{
graph[d[0]].emplace_back(d[1]);
graph[d[1]].emplace_back(d[0]);
}
for (int i = 1; i <= N; ++i)
{
if (colors[i] == -1 && !possibleBipartitionUtil(graph, colors, i, 0))
return false;
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// log(n) solution
class Solution
{
public:
int findKthPositive(vector<int> &arr, int k)
{
int l = 0, r = arr.size() - 1, mid = 0, ans = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
if (arr[mid] - mid - 1 < k)
{
ans = mid + 1;
l = mid + 1;
}
else
{
ans = mid;
r = mid - 1;
}
}
return k + ans;
}
};
// linear solution
class Solution
{
public:
int findKthPositive(vector<int> &arr, int k)
{
int prev = 0, missing = 0;
for (int i = 0; i < arr.size(); ++i)
{
missing = arr[i] - prev - 1;
if (k <= missing)
{
return prev + k;
}
k -= missing;
prev = arr[i];
}
return arr.back() + k;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <list>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
unordered_map<int, list<int>> adj;
unordered_map<int, pair<bool, int>> mem;
unordered_set<int> vert;
int dfs(int src)
{
if (adj[src].size() == 0)
return 0;
if (mem[src].first)
return mem[src].second;
int max_depth = 0;
auto it = adj[src].begin();
for (; it != adj[src].end(); ++it)
{
max_depth = max(max_depth, 1 + dfs(*it));
}
mem[src] = {true, max_depth};
return max_depth;
}
int main()
{
int n; // the number of relationships of influence
cin >> n;
cin.ignore();
for (int i = 0; i < n; i++)
{
int x; // a relationship of influence between two people (x influences y)
int y;
cin >> x >> y;
cin.ignore();
x;
y;
vert.insert(x);
vert.insert(y);
adj[x].push_back(y);
if (mem.find(x) == mem.end())
mem.insert({x, {false, 0}});
if (mem.find(y) == mem.end())
mem.insert({y, {false, 0}});
}
int max_ct = 0;
for (auto e : vert)
{
max_ct = max(max_ct, dfs(e));
}
cout << max_ct + 1;
}<file_sep>class Solution
{
public:
double getArea(int x0, int y0, int x1, int y1, int x2, int y2)
{
return 0.5 * abs(x0 * (y1 - y2) - y0 * (x1 - x2) + (x1 * y2 - x2 * y1));
}
double largestTriangleArea(vector<vector<int>> &points)
{
double max_area = 0;
for (int i = 0; i < points.size(); ++i)
{
for (int j = i + 1; j < points.size(); ++j)
{
for (int k = j + 1; k < points.size(); ++k)
{
max_area = max(max_area, getArea(points[i][0], points[i][1], points[j][0], points[j][1], points[k][0], points[k][1]));
}
}
}
return max_area;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// bfs solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
vector<string> binaryTreePaths(TreeNode *root)
{
if (!root)
return {};
vector<string> result;
queue<pair<TreeNode *, string>> Q;
Q.push({root, ""});
while (!Q.empty())
{
auto cur = Q.front();
Q.pop();
string path = cur.second;
path += to_string(cur.first->val);
// leaf node
if (cur.first->left == NULL && cur.first->right == NULL)
result.push_back(path);
if (cur.first->left)
Q.push({cur.first->left, path + "->"});
if (cur.first->right)
Q.push({cur.first->right, path + "->"});
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// dfs solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void binaryTreePathsUtil(TreeNode *root, string path, vector<string> &result)
{
if (root->left == NULL && root->right == NULL)
{ // leaf node
result.push_back(path + (path.length() ? "->" : "") + to_string(root->val));
return;
}
if (root->left)
binaryTreePathsUtil(root->left, path + (path.length() ? "->" : "") + to_string(root->val), result);
if (root->right)
binaryTreePathsUtil(root->right, path + (path.length() ? "->" : "") + to_string(root->val), result);
}
vector<string> binaryTreePaths(TreeNode *root)
{
if (!root)
return {};
vector<string> result;
binaryTreePathsUtil(root, "", result);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int countPairs(vector<int> &deliciousness)
{
const int MOD = 1e9 + 7;
int result = 0;
int limit = 1 << 21;
unordered_map<int, int> mem;
for (int &d : deliciousness)
{
for (int x = 1; x <= limit; x <<= 1)
{
if (x < d)
continue;
result += mem[x - d];
result = (result >= MOD ? result - MOD : result);
}
++mem[d];
}
return result;
}
};<file_sep>class Solution
{
public:
int lengthLongestPath(string input)
{
istringstream paths(input);
string path;
int max_path_len = 0, depth = 0;
unordered_map<int, int> depth_map;
while (getline(paths, path))
{
depth = path.find_last_of("\t");
depth = (depth == string::npos) ? 0 : depth + 1;
if (path.find(".") != string::npos)
{ // it is a file
max_path_len = max(max_path_len, int(depth_map[depth] + path.length()));
}
else
{
depth_map[depth + 1] = depth_map[depth] + path.length() - depth;
}
}
return max_path_len;
}
};<file_sep>// sort solution O(nlogn)
class Solution
{
public:
int twoCitySchedCost(vector<vector<int>> &costs)
{
sort(costs.begin(), costs.end(), [](const vector<int> &a, const vector<int> &b) {
return (a[0] - a[1]) < (b[0] - b[1]);
});
int result = 0;
int offset = costs.size() >> 1;
for (int i = 0; i < offset; ++i)
result += costs[i][0] + costs[i + offset][1];
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// dp solution O(n^2)
class Solution
{
public:
int twoCitySchedCost(vector<vector<int>> &costs)
{
int n = costs.size() >> 1;
vector<vector<int>> tab(n + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= n; ++i)
tab[i][0] = tab[i - 1][0] + costs[i - 1][0];
for (int i = 1; i <= n; ++i)
tab[0][i] = tab[0][i - 1] + costs[i - 1][1];
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
{
tab[i][j] = min(tab[i - 1][j] + costs[i + j - 1][0], tab[i][j - 1] + costs[i + j - 1][1]);
}
}
return tab[n][n];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
vector<bool> kidsWithCandies(vector<int> &candies, int extraCandies)
{
int maximum_candies = *max_element(candies.begin(), candies.end());
vector<bool> result;
for (int &candy : candies)
result.emplace_back(candy + extraCandies >= maximum_candies);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int getLargestPythagoreanTriplet(int n)
{
/*
returns the larget pythagorean triplet whose sum is n
a + b + c = n
a^2 + b^2 = c^2
a^2 + b^2 = (n-(a+b))^2
solve it to get:
b = (n^2 - 2*a*n)/(2*n - 2*a)
also c = n - a - b
*/
int a = 0, b = 0, c = 0;
int res = -1;
for (a = 1; a < n; ++a)
{
b = ((n * n - 2 * a * n) / (n - a)) / 2;
if (b <= 0 || b <= a)
continue;
c = n - b - a;
if (c <= b)
continue;
if (a * a + b * b == c * c) // if it is a pythagorean triplet
res = max(res, a * b * c);
}
return res;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
cout << getLargestPythagoreanTriplet(n) << "\n";
}
return 0;
}
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
string *grid;
int init_x, init_y;
int width;
int height;
bool isValidDir(int x, int y) {
if(x < 0 || y < 0 || x >= height || y >= width) return false;
return true;
}
int getDir(char dir) {
if(dir == '^') return 0;
if(dir == '>') return 1;
if(dir == 'v') return 2;
if(dir == '<') return 3;
}
void moveAlong(int &x, int &y, char &dir, string side) {
vector<pair<int, int> > DIRS = {{-1,0}, {0,1}, {1,0}, {0,-1}};
vector<char> DIRS_C = {'^', '>', 'v', '<'};
int ind = getDir(dir);
int t_x = 0, t_y = 0;
int inc_first = 1, inc_after = 3;
if(side == "L") {
inc_first = 3;
inc_after = 1;
}
ind = (ind+inc_first)%4;
for(int i=0; i<4; ++i) {
t_x = x + DIRS[ind].first;
t_y = y + DIRS[ind].second;
if(isValidDir(t_x, t_y) && grid[t_x][t_y] != '#') {
x = t_x;
y = t_y;
dir = DIRS_C[ind];
return;
}
ind = (ind+inc_after)%4;
}
grid[x][y] = '0';
}
int main()
{
cin >> width >> height; cin.ignore();
grid = new string[height];
int x = 0, y = 0;
init_x = init_y = 0;
char dir;
for (int i = 0; i < height; i++) {
cin >> grid[i]; cin.ignore();
int pos_right = grid[i].find(">");
int pos_left = grid[i].find("<");
int pos_up = grid[i].find("^");
int pos_down = grid[i].find("v");
if(pos_right != string::npos) {
dir = '>';
x = i;
y = pos_right;
}
else if(pos_left != string::npos) {
dir = '<';
x = i;
y = pos_left;
}
else if(pos_up != string::npos) {
dir = '^';
x = i;
y = pos_up;
}
else if(pos_down != string::npos) {
dir = 'v';
x = i;
y = pos_down;
}
}
init_x = x;
init_y = y;
string side;
cin >> side; cin.ignore();
grid[x][y] = '1';
moveAlong(x, y, dir, side);
++grid[x][y];
while(!(x == init_x && y == init_y)) {
moveAlong(x, y, dir, side);
++grid[x][y];
}
--grid[init_x][init_y];
for (int i = 0; i < height; i++) {
cout << grid[i] << endl;
}
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_set>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Paths
{
public:
int x;
int y;
int dir;
Paths(int x, int y, int dir)
{
this->x = x;
this->y = y;
this->dir = dir;
}
bool operator==(const Paths &o) const
{
return (this->x == o.x && this->y == o.y && this->dir == o.dir);
}
};
class MyHash
{
public:
size_t operator()(const Paths &o) const
{
return (hash<int>()(o.x) ^ hash<int>()(o.y) ^ hash<int>()(o.dir));
}
};
class Bender
{
public:
bool dir_priority; // true-> anti-clockwise(default) else clockwise
bool breaker_mode; // can break X
Bender()
{
this->dir_priority = true;
this->breaker_mode = false;
}
};
string getDir(int x)
{
if (x == 0)
return "SOUTH";
if (x == 1)
return "EAST";
if (x == 2)
return "NORTH";
if (x == 3)
return "WEST";
}
string moveBender(int &x, int &y, int &start_dir, vector<string> &grid, bool &grid_changed, Bender b)
{
static vector<pair<int, int>> dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
int next_dir = 1;
if (!b.dir_priority)
next_dir = 3;
int t_x = x + dirs[start_dir].first;
int t_y = y + dirs[start_dir].second;
if (grid[t_x][t_y] != '#' && grid[t_x][t_y] != 'X')
{
x = t_x;
y = t_y;
return getDir(start_dir);
}
if (grid[t_x][t_y] == 'X' && b.breaker_mode)
{
grid[t_x][t_y] = ' ';
grid_changed = true;
x = t_x;
y = t_y;
return getDir(start_dir);
}
start_dir = b.dir_priority ? 0 : 3;
for (int i = 0; i < 4; ++i)
{
t_x = x + dirs[start_dir].first;
t_y = y + dirs[start_dir].second;
if (grid[t_x][t_y] != '#' && grid[t_x][t_y] != 'X')
{
x = t_x;
y = t_y;
return getDir(start_dir);
}
if (grid[t_x][t_y] == 'X' && b.breaker_mode)
{
grid[t_x][t_y] == ' ';
grid_changed = true;
x = t_x;
y = t_y;
return getDir(start_dir);
}
start_dir = (start_dir + next_dir) % 4;
}
}
int main()
{
int L;
int C;
cin >> L >> C;
cin.ignore();
unordered_set<Paths, MyHash> prev_paths;
bool grid_changed = false;
int start_pos_x = 0, start_pos_y = 0, suicide_pos_x = 0, suicide_pos_y = 0;
int t1_x = 0, t2_x = 0, t1_y = 0, t2_y = 0, start_dir = 0;
bool start_found = false;
bool suicide_found = false;
bool teleporter_found = false;
bool another_teleporter_found = false;
vector<string> grid(L);
for (int i = 0; i < L; i++)
{
getline(cin, grid[i]);
if (!start_found)
{
int pos = grid[i].find('@');
if (pos != string::npos)
{
start_pos_x = i;
start_pos_y = pos;
start_found = true;
}
}
if (!suicide_found)
{
int pos = grid[i].find('$');
if (pos != string::npos)
{
suicide_pos_x = i;
suicide_pos_y = pos;
suicide_found = true;
}
}
if (!teleporter_found)
{
int pos = grid[i].find('T');
if (pos != string::npos)
{
t1_x = i;
t1_y = pos;
teleporter_found = true;
}
// if both teleporters are in same row
pos = grid[i].find('T', pos + 1);
if (pos != string::npos)
{
t2_x = i;
t2_y = pos;
another_teleporter_found = true;
}
}
else if (teleporter_found && !another_teleporter_found)
{
int pos = grid[i].find('T');
if (pos != string::npos)
{
t2_x = i;
t2_y = pos;
another_teleporter_found = true;
}
}
}
Bender b;
vector<string> op;
while (true)
{
Paths obj(start_pos_x, start_pos_y, start_dir);
if (prev_paths.find(obj) != prev_paths.end())
{
if (!grid_changed && !b.breaker_mode)
{
cout << "LOOP\n";
return 0;
}
else
{
grid_changed = false;
prev_paths.clear();
}
}
prev_paths.insert(obj);
if (start_pos_x == suicide_pos_x && start_pos_y == suicide_pos_y)
break;
if (start_pos_x == t1_x && start_pos_y == t1_y)
{
start_pos_x = t2_x;
start_pos_y = t2_y;
}
else if (start_pos_x == t2_x && start_pos_y == t2_y)
{
start_pos_x = t1_x;
start_pos_y = t1_y;
}
if (grid[start_pos_x][start_pos_y] == 'S')
start_dir = 0;
if (grid[start_pos_x][start_pos_y] == 'E')
start_dir = 1;
if (grid[start_pos_x][start_pos_y] == 'N')
start_dir = 2;
if (grid[start_pos_x][start_pos_y] == 'W')
start_dir = 3;
if (grid[start_pos_x][start_pos_y] == 'I')
b.dir_priority = !b.dir_priority;
if (grid[start_pos_x][start_pos_y] == 'B')
b.breaker_mode = !b.breaker_mode;
string dir = moveBender(start_pos_x, start_pos_y, start_dir, grid, grid_changed, b);
op.push_back(dir);
}
for (auto o : op)
cout << o << "\n";
}<file_sep>class Solution
{
public:
vector<vector<int>> ret;
void permuteUniqueUtil(vector<int> nums, int ind = 0)
{
if (ind == nums.size())
{
ret.push_back(nums);
return;
}
for (int i = ind; i < nums.size(); ++i)
{
if (i > ind && nums[i] == nums[ind])
continue;
swap(nums[i], nums[ind]);
permuteUniqueUtil(nums, ind + 1);
}
}
vector<vector<int>> permuteUnique(vector<int> &nums)
{
sort(nums.begin(), nums.end());
permuteUniqueUtil(nums);
return ret;
}
};<file_sep>class Solution
{
public:
int numSubarrayProductLessThanK(vector<int> &nums, int k)
{
if (k <= 1)
return 0;
int l = 0, prod = 1, result = 0;
for (int r = 0; r < nums.size(); ++r)
{
prod *= nums[r];
while (prod >= k)
prod /= nums[l++];
result += (r - l + 1);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// efficient soution (same linear time complexity)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
pair<int, int> robUtil(TreeNode *root)
{
if (!root)
return {0, 0};
pair<int, int> l = robUtil(root->left);
pair<int, int> r = robUtil(root->right);
int excl = max(l.first, l.second) + max(r.first, r.second);
int incl = root->val + l.first + r.first;
return {excl, incl};
}
int rob(TreeNode *root)
{
pair<int, int> res = robUtil(root);
return max(res.first, res.second);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// simple solution with recursive memoization
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
unordered_map<TreeNode *, int> mem;
int rob(TreeNode *root)
{
if (!root)
return 0;
if (mem.count(root))
return mem[root];
int res = root->val;
if (root->left)
res += rob(root->left->left) + rob(root->left->right);
if (root->right)
res += rob(root->right->left) + rob(root->right->right);
mem[root] = max(res, rob(root->left) + rob(root->right));
return mem[root];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int scoreOfParentheses(string S)
{
int score = 0, depth = 0;
for (int i = 0; i < S.length(); ++i)
{
if (S[i] == '(')
++depth;
else
{
--depth;
if (S[i - 1] == '(')
score += 1 << depth;
}
}
return score;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int divide(long long int dividend, long long int divisor)
{
bool neg = (dividend < 0) ^ (divisor < 0);
long long int ret = 0, t = 1, d = 0;
long long int dvd = labs(dividend);
long long int dvs = labs(divisor);
while (dvd >= dvs)
{
t = 1;
d = dvs;
while (d << 1 < dvd)
{
d = d << 1;
t = t << 1;
}
dvd -= d;
ret += t;
}
ret = neg ? -ret : ret;
ret = ret > INT_MAX ? INT_MAX : ret;
ret = ret < INT_MIN ? INT_MIN : ret;
return ret;
}
};<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
ListNode *head;
public:
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
Solution(ListNode *head)
{
this->head = head;
}
/** Returns a random node's value. */
int getRandom()
{
int result = head->val, idx = 2;
ListNode *cur = this->head->next;
while (cur)
{
if (((double)rand() / RAND_MAX) <= (double)(1.0 / (double(idx++))))
result = cur->val;
cur = cur->next;
}
return result;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
bool containsNearbyAlmostDuplicate(vector<int> &nums, int k, int t)
{
unordered_map<int, int> buckets;
int bucket;
if (t < 0 || k < 0)
return false;
for (int i = 0; i < nums.size(); ++i)
{
bucket = nums[i] / (1L * t + 1);
if (nums[i] < 0)
--bucket;
if (buckets.count(bucket))
return true;
if ((buckets.count(bucket - 1) && 1L * nums[i] - buckets[bucket - 1] <= t) || (buckets.count(bucket + 1) && 1L * buckets[bucket + 1] - nums[i] <= t))
return true;
buckets[bucket] = nums[i];
if (i >= k)
{
bucket = nums[i - k] / (1L * t + 1);
if (nums[i - k] < 0)
--bucket;
buckets.erase(bucket);
}
}
return false;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int lengthOfLastWord(string s)
{
if (s.length() == 0)
return 0;
int endIdx = s.length() - 1;
while (endIdx > 0 && s[endIdx] == ' ')
--endIdx;
if (s[endIdx] == ' ')
return 0;
if (endIdx == 0 && s[endIdx] != ' ')
return 1;
int startIdx = endIdx - 1;
while (startIdx > 0 && s[startIdx] != ' ')
--startIdx;
return endIdx - startIdx + (s[startIdx] == ' ' ? 0 : 1);
}
};<file_sep>class Solution
{
public:
vector<string> ret;
void generateParenthesis(string cb, int o, int c)
{
if (o == 0 && c == 0)
{
ret.push_back(cb);
return;
}
if (o > 0)
generateParenthesis(cb + "(", o - 1, c + 1);
if (c > 0)
generateParenthesis(cb + ")", o, c - 1);
}
vector<string> generateParenthesis(int n)
{
if (n < 1)
return {};
generateParenthesis("", n, 0);
return ret;
}
};<file_sep>// identical to 538 (did a recursive traversal there, so doing a Morris
// traversal here)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
TreeNode *bstToGst(TreeNode *root) {
TreeNode *cur = root;
TreeNode *tmp = NULL;
int sum = 0;
while (cur) {
if (cur->right) {
tmp = cur->right;
while (tmp->left && tmp->left != cur) {
tmp = tmp->left;
}
if (tmp->left == cur) {
tmp->left = NULL;
cur->val += sum;
sum = cur->val;
cur = cur->left;
} else {
tmp->left = cur;
cur = cur->right;
}
} else {
cur->val += sum;
sum = cur->val;
cur = cur->left;
}
}
return root;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int ct = 0;
void printPossibilities(int rem_score, int turn) {
if(turn > 4) return;
if(turn <= 4 && rem_score == 0) {
++ct;
}
for(int i=1; i<=12; ++i) {
printPossibilities(rem_score - i, turn + 1);
if(i > 1)
printPossibilities(rem_score - i, turn + 1);
}
}
int main()
{
int n;
cin >> n; cin.ignore();
printPossibilities(50 - n, 0);
cout<<ct<<"\n";
}<file_sep>class Solution
{
public:
vector<vector<int>> generate(int numRows)
{
if (numRows == 0)
return {};
vector<vector<int>> result;
for (int i = 1; i <= numRows; ++i)
{
vector<int> res(i, 0);
result.emplace_back(res);
}
result[0][0] = 1;
for (int i = 1; i < numRows; ++i)
{
for (int j = 0; j < result[i].size(); ++j)
{
if (j == 0)
result[i][j] = result[i - 1][j];
else if (j == result[i].size() - 1)
result[i][j] = result[i - 1][j - 1];
else
result[i][j] = result[i - 1][j] + result[i - 1][j - 1];
}
}
return result;
}
};<file_sep>class Solution
{
public:
vector<int> intersect(vector<int> &nums1, vector<int> &nums2)
{
if (nums1.empty() || nums2.empty())
return {};
unordered_map<int, int> mem;
vector<int> result;
for (int &n : nums1)
++mem[n];
for (int &n : nums2)
if (mem.count(n))
{
result.push_back(n);
--mem[n];
if (mem[n] == 0)
mem.erase(n);
}
return result;
}
};
auto speed = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// trie based solution
class TrieNode {
public:
unordered_map<char, TrieNode *> nxt;
};
class Solution {
public:
int minimumLengthEncoding(vector<string> &words) {
int result = 0;
TrieNode *root = new TrieNode();
TrieNode *cur = root;
vector<pair<TrieNode *, int>> leaves;
for (string word : unordered_set<string>(words.begin(), words.end())) {
cur = root;
for (int i = word.length() - 1; i >= 0; --i) {
if (cur->nxt.count(word[i]) == 0)
cur->nxt[word[i]] = new TrieNode();
cur = cur->nxt[word[i]];
}
leaves.emplace_back(cur, word.length());
}
for (auto &leaf : leaves)
result += leaf.first->nxt.size() == 0 ? leaf.second + 1 : 0;
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// efficient sorting based solution
class Solution {
public:
int minimumLengthEncoding(vector<string> &words) {
int result = 0;
for (string &word : words)
reverse(word.begin(), word.end());
sort(words.begin(), words.end());
for (int i = 0; i < words.size() - 1; ++i)
result += words[i] == words[i + 1].substr(0, words[i].length())
? 0
: words[i].length() + 1;
return result + words[words.size() - 1].length() + 1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// set based solution
class Solution {
public:
int minimumLengthEncoding(vector<string> &words) {
int result = 0;
unordered_set<string> s(words.begin(), words.end());
for (string word : s) {
for (int i = 1; i < word.length(); ++i) {
s.erase(word.substr(i));
}
}
for (string word : s) {
result += word.length() + 1;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *insert(ListNode *head, int val)
{
if (head == NULL)
return new ListNode(val);
ListNode *t = head;
while (t->next != NULL)
t = t->next;
t->next = new ListNode(val);
return head;
}
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
{
ListNode *ret = NULL;
int carry = 0, sum = 0;
while (l1 != NULL && l2 != NULL)
{
sum = l1->val + l2->val + carry;
ret = insert(ret, sum % 10);
carry = sum / 10;
l1 = l1->next;
l2 = l2->next;
}
while (l1 != NULL)
{
sum = l1->val + carry;
ret = insert(ret, sum % 10);
carry = sum / 10;
l1 = l1->next;
}
while (l2 != NULL)
{
sum = l2->val + carry;
ret = insert(ret, sum % 10);
carry = sum / 10;
l2 = l2->next;
}
if (carry)
ret = insert(ret, carry);
return ret;
}
};<file_sep>// constant space & linear time complexity
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node *copyRandomList(Node *head) {
if (!head)
return NULL;
Node *result;
Node *tmp = head;
Node *nxt = NULL;
while (tmp) {
nxt = tmp->next;
tmp->next = new Node(tmp->val);
tmp->next->next = nxt;
tmp = tmp->next->next;
}
tmp = head;
nxt = head->next;
while (tmp) {
nxt->random = tmp->random ? tmp->random->next : NULL;
nxt = nxt->next ? nxt->next->next : NULL;
tmp = tmp->next->next;
}
tmp = head;
nxt = head->next;
result = nxt;
while (tmp) {
tmp->next = tmp->next->next;
nxt->next = nxt->next ? nxt->next->next : NULL;
tmp = tmp->next;
nxt = nxt->next;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int N;
cin >> N; cin.ignore();
bool flag = false;
for (int i = 0; i < N; i++) {
long long F;
cin >> F; cin.ignore();
flag = false;
while(F) {
if(F == 1) {
flag = true;
break;
}
if(F%2 == 0) F /= 2;
else if(F%3 == 0) F /= 3;
else if(F%5 == 0) F /= 5;
else break;
}
if(flag) cout<<"VICTORY\n";
else cout<<"DEFEAT\n";
}
}<file_sep>// simple bellman ford
class Solution
{
public:
int findCheapestPrice(int n, vector<vector<int>> &flights, int src, int dst, int K)
{
vector<int> cost(n, 1000001);
cost[src] = 0;
for (int i = 0; i <= K; ++i)
{
vector<int> c(cost);
for (auto &f : flights)
c[f[1]] = min(c[f[1]], cost[f[0]] + f[2]);
cost = c;
}
return cost[dst] == 1000001 ? -1 : cost[dst];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// priority queue solution (dijkstras)
typedef tuple<int, int, int> tup;
class Solution
{
public:
int findCheapestPrice(int n, vector<vector<int>> &flights, int src, int dst, int K)
{
vector<vector<pair<int, int>>> graph(n);
for (auto &f : flights)
graph[f[0]].emplace_back(f[1], f[2]);
priority_queue<tup, vector<tup>, greater<tup>> PQ;
PQ.emplace(0, K, src);
int cost, stops, cur;
while (!PQ.empty())
{
auto [cost, stops, cur] = PQ.top();
PQ.pop();
if (cur == dst)
return cost;
if (stops >= 0)
{
for (auto d : graph[cur])
{
PQ.emplace(cost + d.second, stops - 1, d.first);
}
}
}
return -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
int maxVaidLength(string &s, int &k, char &ch)
{
int ct = 0, max_res = 0, l = 0;
for (int r = 0; r < s.length(); ++r)
{
if (s[r] != ch)
++ct;
while (ct > k)
{
if (s[l] != ch)
--ct;
++l;
}
max_res = max(max_res, r - l + 1);
}
return max_res;
}
int main()
{
int t = 0, n = 0, k = 0;
string s;
cin >> t;
while (t--)
{
cin >> n >> k;
cin >> s;
int max_res = 0;
for (char c = 'a'; c <= 'z'; ++c)
max_res = max(max_res, maxVaidLength(s, k, c));
for (char c = 'A'; c <= 'Z'; ++c)
max_res = max(max_res, maxVaidLength(s, k, c));
cout << max_res << "\n";
}
return 0;
}<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
int findTiltUtil(TreeNode *root, int &result)
{
if (!root)
return 0;
int l = findTiltUtil(root->left, result);
int r = findTiltUtil(root->right, result);
result += abs(l - r);
return root->val + l + r;
}
int findTilt(TreeNode *root)
{
int result = 0;
findTiltUtil(root, result);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Facebook.
* Given a list of integers, return the largest product that can be made by multiplying any three integers.
* For example, if the list is [-10, -10, 5, 2], we should return 500, since that's -10 * -10 * 5.
* You can assume the list has at least three integers.
*
*
* Online Judge: https://leetcode.com/problems/maximum-product-of-three-numbers/
*
*/
// O(N) solution
class Solution
{
public:
int maximumProduct(vector<int> &nums)
{
int min1 = INT_MAX, min2 = INT_MAX, max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN;
for (int &n : nums)
{
if (n < min1)
{
min2 = min1;
min1 = n;
}
else if (n < min2)
min2 = n;
if (n > max1)
{
max3 = max2;
max2 = max1;
max1 = n;
}
else if (n > max2)
{
max3 = max2;
max2 = n;
}
else if (n > max3)
max3 = n;
}
return max(min1 * min2 * max1, max1 * max2 * max3);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(NlogN) sorting solution
class Solution
{
public:
int maximumProduct(vector<int> &nums)
{
sort(nums.begin(), nums.end());
int n = nums.size();
return max(nums[0] * nums[1] * nums[n - 1], nums[n - 1] * nums[n - 2] * nums[n - 3]);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Microsoft.
* Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null.
* For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox'].
* Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond'].
*
*
* Online Judge: https://leetcode.com/problems/word-break-ii/
*
*
*/
class Solution
{
public:
bool isPossible(string &s, unordered_set<string> &wDict)
{
vector<bool> tab(s.length() + 1, false);
tab[0] = true;
string subWord;
for (int i = 0; i < s.length(); ++i)
{
for (int j = i; j >= 0; --j)
{
if (tab[j])
{
subWord = s.substr(j, i - j + 1);
if (wDict.count(subWord))
{
tab[i + 1] = true;
break;
}
}
}
}
return tab[s.length()];
}
vector<string> wordBreak(string s, vector<string> &wordDict)
{
unordered_set<string> wDict(wordDict.begin(), wordDict.end());
vector<vector<string>> tab(s.length() + 1, vector<string>(0));
tab[0] = {""};
string subWord;
if (!isPossible(s, wDict))
return {};
for (int i = 0; i < s.length(); ++i)
{
for (int j = i; j >= 0; --j)
{
if (tab[j].size())
{
subWord = s.substr(j, i - j + 1);
if (wDict.count(subWord))
{
for (string &s : tab[j])
tab[i + 1].emplace_back(s + (s.length() ? " " : "") + subWord);
break; // the break ensures only one solution is taken into consideration
}
}
}
}
return tab[s.length()];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int maximumWealth(vector<vector<int>> &accounts)
{
int result = 0;
for (auto &acc : accounts)
result = max(result, accumulate(acc.begin(), acc.end(), 0));
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int nthUglyNumber(int n)
{
vector<long long int> mem = {1};
int idx2 = 0, idx3 = 0, idx5 = 0;
long long int tmp2 = 0, tmp3 = 0, tmp5 = 0, tmp = 0;
while (mem.size() < n)
{
tmp2 = mem[idx2] * 2;
tmp3 = mem[idx3] * 3;
tmp5 = mem[idx5] * 5;
tmp = min(tmp2, min(tmp3, tmp5));
mem.emplace_back(tmp);
if (tmp2 == tmp)
++idx2;
if (tmp3 == tmp)
++idx3;
if (tmp5 == tmp)
++idx5;
}
return mem.back();
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution {
public:
vector<int> findErrorNums(vector<int> &nums) {
int n = nums.size(), nums_xor = 0, pos = 0, duplicate = 0, missing = 0;
for (int &num : nums)
nums_xor ^= num;
for (int i = 1; i <= n; ++i)
nums_xor ^= i;
pos = nums_xor & ~(nums_xor - 1);
for (int &num : nums) {
if (num & pos)
duplicate ^= num;
else
missing ^= num;
}
for (int i = 1; i <= n; ++i) {
if (i & pos)
duplicate ^= i;
else
missing ^= i;
}
for (int &num : nums) {
if (missing == num) {
return {missing, duplicate};
}
}
return {duplicate, missing};
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>// catalan number O(n)
class Solution
{
public:
size_t ncr(int n, int r)
{
if (r > n - r)
r = n - r;
size_t res = 1;
for (int i = 0; i < r; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
int numTrees(int n)
{
// nth catalan number : 2nCn/(n+1)
return ncr(2 * n, n) / (n + 1);
}
};
// dp solution O(n^2)
class Solution
{
public:
int numTrees(int n)
{
vector<int> tab(n + 1, 0);
tab[0] = 1;
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= i; ++j)
tab[i] += tab[j - 1] * tab[i - j];
}
return tab[n];
}
};
/**
Let's consider the values 1 to N inclusive.
Any value X can be our root node. Let's say we just have an empty tree
so root = null. That is technically one unique subtree. Now let's say
1 is our root node, X = 1, and N = 1. This is a super simple example.
THe result for X = 1, when N = 1, is just 1 unique subtree.
Now let's say X = 1, but now N = 2. How many unique subtrees exist now?
Remember that X represents the root node value. For the left subtree
you just have a null substree, which we said earlier is 1. SO the left subtree
yeilds only 1 option. For the right subtree, you must place 2 there, so the number of
options is also 1.
So when X = 1, answer is 1. But N = 2, so now we consider when X = 2. THe left subtree
would have node 1, so only 1 option. The right subtree is just null, so that is also
1 option. We know that the result we want for N=2, is exactly 2. We can get this result
by summing the result of X = 1 and X = 2 -> 1+1 = 2.
We can generalize the num of options for left and right subtrees given X as...
left = X-1, right = N-X
T[X] = left * right
Why multiply the left and right options? Because one subtree on the right
can be used, but for the left subtree you can try every single unique subtree.
Same occurs when you keep the left subtree the same, you can try every single
unique variation of the right subtree.
When we have a set of combinations, we multiply them to count all possible
variations between the two combinations.
So based on these simple observations, we can assume that when N = 2:
numTrees(2) = numTrees(1) + numTrees(2)
numTrees(2) = 1 + 1 = 2
But does this work for N = 3?
When X = 1, N = 1 we get => 1 //Base Case Assumption
When X = 1, N = 2 we get => 1
When X = 2, N = 2 we get => 1 //Because only option for left and right subtrees -> 1*1
When X = 1, N = 3 we get => 2 //Because only 1 option for left & 2 options for right -> 2*1
When X = 2, N = 3 we get => 1
When X = 3, N = 3 we get => 2
For N = 2, we want te result to be 2, so we sum up the values we get X being 1 to N
For N = 3, we want the result to be 5, so we sum up the values we get with X being 1 to N
Now we can further generalize the solution as being...
numTrees(N) = numTrees(1) + numTrees(2) + ... + numTrees(N);
Let's denote each func. call in the above sum as -> numTrees(i)
For any numTrees(i) where are simply trying X = 1, X = 2, ..., X = i
So given N, just try every single value as X. And for every X,
calculate how many options are available on the left and right subtrees, given nodes 1 to X.
So numTrees(i) is a subproblem where we cound all the unique trees given nodes 1 to i.
i becomes the new N for these smaller subproblems.
*/<file_sep>// bfs solution
class Solution
{
public:
vector<vector<int>> floodFill(vector<vector<int>> &image, int sr, int sc, int newColor)
{
if (image[sr][sc] == newColor)
return image;
vector<pair<int, int>> dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
queue<pair<int, int>> Q;
pair<int, int> tmp;
Q.push({sr, sc});
int color = image[sr][sc], x = 0, y = 0;
while (!Q.empty())
{
tmp = Q.front();
Q.pop();
image[tmp.first][tmp.second] = newColor;
for (auto d : dirs)
{
x = tmp.first + d.first;
y = tmp.second + d.second;
if (x >= 0 && x < image.size() && y >= 0 && y < image[x].size() && image[x][y] == color)
{
Q.push({x, y});
}
}
}
return image;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// dfs solution
class Solution
{
public:
void floodFillUtil(vector<vector<int>> &image, int r, int c, int oldColor, int newColor)
{
if (r < 0 || r >= image.size() || c < 0 || c >= image[r].size() || image[r][c] != oldColor)
return;
static vector<pair<int, int>> dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
image[r][c] = newColor;
for (auto d : dirs)
{
floodFillUtil(image, r + d.first, c + d.second, oldColor, newColor);
}
}
vector<vector<int>> floodFill(vector<vector<int>> &image, int sr, int sc, int newColor)
{
if (image[sr][sc] == newColor)
return image;
floodFillUtil(image, sr, sc, image[sr][sc], newColor);
return image;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 0, m = 0, idx = -1, x = 0;
cin >> n >> m;
for (int i = 0; i < n; ++i)
{
cin >> x;
if (x == m)
idx = i;
}
cout << idx + 1;
return 0;
}<file_sep>// iterative solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> result;
stack<TreeNode *> S;
TreeNode *cur = root;
TreeNode *last = NULL;
while (S.size() || cur)
{
while (cur)
{
S.push(cur);
cur = cur->left;
}
cur = S.top();
if (cur->right && last != cur->right)
{
cur = cur->right;
}
else
{
result.emplace_back(cur->val);
S.pop();
last = cur;
cur = NULL;
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// recursive solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void postorderTraversalUtil(TreeNode *root, vector<int> &result)
{
if (!root)
return;
postorderTraversalUtil(root->left, result);
postorderTraversalUtil(root->right, result);
result.emplace_back(root->val);
}
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> result;
postorderTraversalUtil(root, result);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
bool isValid(const string &s, const int &len, const int &k)
{
unordered_map<char, int> mem;
int ct = 0;
for (int i = 0; i < len; ++i)
{
++mem[s[i]];
if (mem[s[i]] % 2 == 0)
ct += 2;
if (ct + 1 >= k)
return true;
}
for (int i = len; i < s.length(); ++i)
{
if (mem[s[i - len]] % 2 == 0)
ct -= 2;
--mem[s[i - len]];
++mem[s[i]];
if (mem[s[i]] % 2 == 0)
ct += 2;
if (ct + 1 >= k)
return true;
}
return false;
}
int main()
{
string s;
cin >> s;
int t = 0, k = 0, l = 0, r = 0, mid = 0;
cin >> t;
while (t--)
{
cin >> k;
l = k, r = s.length();
while (l < r)
{
mid = l + ((r - l) >> 1);
if (isValid(s, mid, k))
r = mid;
else
l = mid + 1;
}
if (isValid(s, l, k))
cout << l << "\n";
else
cout << "-1\n";
}
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
bool isOpening(char c) {
if(c == '[' || c == '(' || c == '{') return true;
return false;
}
bool isClosing(char c) {
if(c == ']' || c == ')' || c == '}') return true;
return false;
}
char getPair(char c) {
if(c == ']') return '[';
if(c == ')') return '(';
if(c == '}') return '{';
}
int main()
{
string p;
cin >> p; cin.ignore();
stack<char> S;
bool flag = true;
for(int i=0; i<p.length(); ++i) {
if(isOpening(p[i])) {
S.push(p[i]);
}
else if(isClosing(p[i])) {
if(S.empty() || S.top() != getPair(p[i])) {
flag = false;
break;
}
else S.pop();
}
}
if(flag) flag = S.empty();
if(flag) cout<<"true"<<endl;
else cout<<"false"<<endl;
}<file_sep>// easier to understand solution
class Solution
{
public:
int largestRectangleArea(vector<int> &heights)
{
int n = heights.size(), cur = 0, result = 0;
vector<int> left(n, 0), right(n, 0);
for (int i = 0; i < n; ++i)
{
cur = i - 1;
while (cur >= 0 && heights[cur] >= heights[i])
cur = left[cur];
left[i] = cur;
}
for (int i = n - 1; i >= 0; --i)
{
cur = i + 1;
while (cur < n && heights[cur] >= heights[i])
cur = right[cur];
right[i] = cur;
}
for (int i = 0; i < n; ++i)
result = max(result, heights[i] * (right[i] - left[i] - 1));
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// stack based solution
class Solution
{
public:
int largestRectangleArea(vector<int> &heights)
{
heights.emplace_back(0);
int n = heights.size(), h = 0, w = 0, result = 0;
stack<int> S;
S.push(-1);
for (int i = 0; i < n; ++i)
{
while (S.size() > 1 && heights[i] < heights[S.top()])
{
h = heights[S.top()];
S.pop();
w = i - S.top() - 1;
result = max(result, h * w);
}
S.push(i);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>
// Online Judge used: https://www.lintcode.com/problem/longest-substring-with-at-most-k-distinct-characters/description
class Solution
{
public:
/**
* @param s: A string
* @param k: An integer
* @return: An integer
*/
int lengthOfLongestSubstringKDistinct(string &s, int k)
{
if (s.length() == 0 || k == 0)
return 0;
if (k >= s.size())
return s.size();
unordered_map<char, int> M;
int i = 0, j = 0, max_len = 0;
while (i < s.size())
{
if (M.size() < k || M.find(s[i]) != M.end())
{
++M[s[i]];
++i;
max_len = max(max_len, i - j);
}
else
{
--M[s[j]];
if (M[s[j]] == 0)
M.erase(s[j]);
++j;
}
}
return max_len;
}
};<file_sep>class Solution
{
public:
string processEmail(string s)
{
string result = "";
int i = 0;
while (i < s.length())
{
if (s[i] == '@')
{
result += s.substr(i);
break;
}
if (s[i] == '+')
{
while (s[i] != '@')
++i;
}
else if (s[i] == '.')
++i;
else
result += s[i++];
}
return result;
}
int numUniqueEmails(vector<string> &emails)
{
unordered_set<string> emailSet;
for (string &e : emails)
{
emailSet.insert(processEmail(e));
}
return emailSet.size();
}
};
// reduces submission time
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// dfs solution time: O(N), space: O(N)
class Solution
{
public:
bool dfs(vector<vector<int>> &graph, vector<int> &status, vector<int> &result, int src)
{
if (status[src] == 0)
return false;
if (status[src] == 1)
return true;
status[src] = 0;
for (int &dest : graph[src])
{
if (!dfs(graph, status, result, dest))
return false;
}
status[src] = 1;
result.emplace_back(src);
return true;
}
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites)
{
vector<int> result;
vector<vector<int>> graph(numCourses);
vector<int> status(numCourses, -1);
for (auto &p : prerequisites)
{
graph[p[1]].emplace_back(p[0]);
}
for (int i = 0; i < numCourses; ++i)
{
if (status[i] == -1 && !dfs(graph, status, result, i))
return {};
}
reverse(result.begin(), result.end());
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// bfs solution (without queue) time: O(V+E), space: O(V+E)
class Solution
{
public:
vector<int> findOrder(int numCourses, vector<vector<int>> &prerequisites)
{
vector<int> result;
vector<vector<int>> graph(numCourses);
vector<int> inDegree(numCourses, 0);
for (auto &prereq : prerequisites)
{
graph[prereq[1]].emplace_back(prereq[0]);
++inDegree[prereq[0]];
}
for (int i = 0; i < inDegree.size(); ++i)
if (inDegree[i] == 0)
result.emplace_back(i);
for (int i = 0; i < result.size(); ++i)
{
for (int &d : graph[result[i]])
if (--inDegree[d] == 0)
result.emplace_back(d);
}
return result.size() == numCourses ? result : vector<int>();
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int longestCommonSubsequence(string text1, string text2)
{
int m = text1.length();
int n = text2.length();
if (m == 0 || n == 0)
return 0;
int tab[m + 1][n + 1];
for (int i = 0; i <= m; ++i)
tab[i][0] = 0;
for (int i = 0; i <= n; ++i)
tab[0][i] = 0;
for (int i = 1; i <= m; ++i)
{
for (int j = 1; j <= n; ++j)
{
if (text1[i - 1] == text2[j - 1])
tab[i][j] = tab[i - 1][j - 1] + 1;
else
tab[i][j] = max(tab[i - 1][j], tab[i][j - 1]);
}
}
return tab[m][n];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
vector<int> largestDivisibleSubset(vector<int> &nums)
{
if (nums.size() == 0)
return {};
int n = nums.size(), pos = 0;
sort(nums.begin(), nums.end());
vector<int> tab(n, 1);
vector<int> mem(n, -1);
for (int i = 1; i < n; ++i)
{
for (int j = 0; j < i; ++j)
{
if (nums[i] % nums[j] == 0 && 1 + tab[j] > tab[i])
{
tab[i] = 1 + tab[j];
mem[i] = j;
if (tab[pos] < tab[i])
pos = i;
}
}
}
vector<int> result;
while (pos != -1)
{
result.emplace_back(nums[pos]);
pos = mem[pos];
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// O(1) solution (think of it like detecting a cycle in a linked list)
class Solution
{
public:
int getSumOfSquareOfDigits(int n)
{
int res = 0;
while (n)
{
res += pow(n % 10, 2);
n /= 10;
}
return res;
}
bool isHappy(int n)
{
if (n == 1)
return true;
int slow = n;
int fast = n;
while (true)
{
slow = getSumOfSquareOfDigits(slow);
if (slow == 1)
return true;
fast = getSumOfSquareOfDigits(getSumOfSquareOfDigits(fast));
if (fast == 1)
return true;
if (fast == slow)
return false;
}
return true;
}
};
// first approach
class Solution
{
public:
int getSumOfSquareOfDigits(int n)
{
int res = 0;
while (n)
{
res += pow(n % 10, 2);
n /= 10;
}
return res;
}
bool isHappy(int n)
{
unordered_set<int> seen;
while (true)
{
if (n == 1)
return true;
n = getSumOfSquareOfDigits(n);
if (seen.count(n))
return false;
seen.insert(n);
}
return false;
}
};<file_sep>// O(n^2) approach besides the naive approach which uses two loops // gives TLE
class Solution
{
public:
vector<int> countSmaller(vector<int> &nums)
{
vector<int> result(nums.size(), 0);
multiset<int> tab;
for (int i = nums.size() - 1; i >= 0; --i)
{
result[i] = distance(tab.begin(), tab.lower_bound(nums[i]));
tab.insert(nums[i]);
}
return result;
}
};
// merge sort based approach O(nlogn)
class Solution
{
typedef vector<pair<int, int>>::iterator it;
public:
void countSmallerUtil(it l, it r, vector<int> &result)
{
if (r - l <= 1)
return;
it m = l + ((r - l) >> 1);
countSmallerUtil(l, m, result);
countSmallerUtil(m, r, result);
it j = m;
for (it i = l; i < m; ++i)
{
while (j < r && (*j) < (*i))
++j;
result[i->second] += (j - m);
}
inplace_merge(l, m, r);
}
vector<int> countSmaller(vector<int> &nums)
{
vector<int> result(nums.size(), 0);
vector<pair<int, int>> mem;
for (int i = 0; i < nums.size(); ++i)
mem.emplace_back(nums[i], i);
countSmallerUtil(mem.begin(), mem.end(), result);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// BIT based approach O(nlogn) best approach
class Solution
{
vector<int> f;
public:
void update(int x)
{
while (x < f.size())
{
++f[x];
x += (x & -x);
}
}
int get(int x)
{
int res = 0;
while (x > 0)
{
res += f[x];
x -= (x & -x);
}
return res;
}
vector<int> countSmaller(vector<int> &nums)
{
f = vector<int>(20002, 0); // to take into account -ve numbers
vector<int> result(nums.size(), 0);
int n = nums.size();
for (int i = n - 1; i >= 0; --i)
{
result[i] = get(9999 + nums[i]); // to take into account -ve numbers
update(10000 + nums[i]); // to take into account -ve numbers
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>class Solution
{
public:
vector<vector<string>> solutions;
vector<string> getBoard(vector<int> &qPos)
{
vector<string> ret(qPos.size(), string(qPos.size(), '.'));
int ind = 0;
for (int i = 0; i < qPos.size(); ++i)
{
ret[ind++][qPos[i]] = 'Q';
}
return ret;
}
bool isValid(vector<int> &qPos, int val, int col)
{
for (int i = 0; i < col; ++i)
{
if (qPos[i] == val || abs(qPos[i] - val) == abs(i - col))
return false;
}
return true;
}
bool solveUtil(vector<int> &qPos, int col = 0)
{
if (col == qPos.size())
{
solutions.emplace_back(getBoard(qPos));
return true;
}
for (int i = 0; i < qPos.size(); ++i)
{
if (isValid(qPos, i, col))
{
qPos[col] = i;
solveUtil(qPos, col + 1);
qPos[col] = 0;
}
}
return false;
}
vector<vector<string>> solveNQueens(int n)
{
vector<int> qPos(n, 0);
solveUtil(qPos);
return solutions;
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
bool isValidDir(int x, int y, int size) {
if(x < 0 || x >= size || y < 0 || y >= size) return false;
return true;
}
void spreadLight(char **grid, int i, int j, int l, int size, int flag) {
if(l <= 0) return;
vector<pair<int, int> > dirs = {{-1,-1}, {1,1}, {-1,1}, {1,-1}, {0,-1}, {0,1}, {1,0}, {-1,0}};
if(grid[i][j] == 'C' && flag) grid[i][j] = l + '0';
if(grid[i][j] == 'X') grid[i][j] = '0';
grid[i][j] = char(max(int(grid[i][j]), int(l + '0')));
for(auto d : dirs) {
int x = i + d.first;
int y = j + d.second;
if(isValidDir(x, y, size)) spreadLight(grid, x, y, l-1, size, 0);
}
}
int main()
{
int N;
cin >> N; cin.ignore();
int L;
cin >> L; cin.ignore();
char **grid = new char*[N];
for (int i = 0; i < N; i++) {
grid[i] = new char[N];
for (int j = 0; j < N; j++) {
cin>>grid[i][j];
}
}
for(int i = 0; i < N; i++) {
for(int j=0; j<N; ++j) {
if(grid[i][j] == 'C') {
spreadLight(grid, i, j, L, N, 1);
}
else if(grid[i][j] == 'X') {
grid[i][j] = '0';
}
}
}
int ct = 0;
for(int i = 0; i < N; i++)
for(int j=0; j<N; ++j)
if(grid[i][j] == '0') ++ct;
cout << ct << endl;
}<file_sep>// better solution with modulo 14
class Solution
{
public:
vector<int> prisonAfterNDays(vector<int> &cells, int N)
{
vector<int> res(8, 0);
N = (N % 14 == 0) ? 14 : N % 14;
while (N--)
{
for (int i = 1; i < 7; ++i)
res[i] = cells[i - 1] == cells[i + 1] ? 1 : 0;
cells = res;
}
return cells;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// simple solution with memoization
class Solution
{
public:
int getHash(vector<int> &cells)
{
int hash = 0;
for (int i = 0; i < 8; ++i)
{
hash += cells[i] ? 1 << (7 - i) : 0;
}
return hash;
}
vector<int> prisonAfterNDays(vector<int> &cells, int N)
{
vector<int> res;
vector<int> mem(256, -1);
int seen = 0;
while (N)
{
res = vector<int>(8, 0);
mem[getHash(cells)] = N--;
for (int i = 1; i < 7; ++i)
res[i] = cells[i - 1] == cells[i + 1] ? 1 : 0;
seen = mem[getHash(res)];
if (seen != -1)
N %= (seen - N);
cells = res;
}
return cells;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// space efficient dp solution : O(m*n) time, O(n) space
class Solution
{
public:
int maximalSquare(vector<vector<char>> &matrix)
{
if (matrix.empty())
return 0;
int m = matrix.size(), n = matrix[0].size(), result = 0, prev = 0, cur = 0;
int tab[n];
memset(tab, 0, sizeof(tab));
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
cur = tab[j];
if (matrix[i][j] == '1')
{
if (i == 0 || j == 0)
tab[j] = 1;
else
tab[j] = min(prev, min(tab[j], tab[j - 1])) + 1;
result = max(result, tab[j]);
}
else
tab[j] = 0;
prev = cur;
}
}
return result * result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// dp solution : O(m*n) time, O(m*n) space
class Solution
{
public:
int maximalSquare(vector<vector<char>> &matrix)
{
if (matrix.empty())
return 0;
int m = matrix.size(), n = matrix[0].size(), result = 0;
int tab[m][n];
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (matrix[i][j] == '1')
{
if (i == 0 || j == 0)
tab[i][j] = 1;
else
tab[i][j] = min(tab[i - 1][j - 1], min(tab[i - 1][j], tab[i][j - 1])) + 1;
result = max(result, tab[i][j]);
}
else
tab[i][j] = 0;
}
}
return result * result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// brute force : O((m*n)^2) time, O(1) space
class Solution
{
public:
int getArea(vector<vector<char>> &matrix, int r, int c)
{
int offset = 1, limit = 2, result = 1;
while (true)
{
if (r + offset >= matrix.size() || c + offset >= matrix[r].size())
break;
for (int i = c; i < c + limit; ++i)
{
if (matrix[r + offset][i] != '1')
return result * result;
}
for (int i = r; i < r + limit; ++i)
{
if (matrix[i][c + offset] != '1')
return result * result;
}
++result;
++offset;
++limit;
}
return result * result;
}
int maximalSquare(vector<vector<char>> &matrix)
{
if (matrix.size() == 0 || matrix[0].size() == 0)
return 0;
int m = matrix.size();
int n = matrix[0].size();
int result = 0;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (matrix[i][j] == '1')
{
result = max(result, getArea(matrix, i, j));
}
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// bit manipulation based solution (faster)
class Solution
{
public:
int countConsistentStrings(string allowed, vector<string> &words)
{
int result = 0;
bool flag = true;
int mem = 0;
for (char &c : allowed)
mem ^= (1 << (c - 'a'));
for (string &word : words)
{
flag = true;
for (char &c : word)
{
if ((mem & (1 << (c - 'a'))) == 0)
{
flag = false;
break;
}
}
if (flag)
++result;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// simple solution
class Solution
{
public:
int countConsistentStrings(string allowed, vector<string> &words)
{
int result = 0;
bool flag = true;
unordered_set<char> mem(allowed.begin(), allowed.end());
for (string &word : words)
{
flag = true;
for (char &c : word)
{
if (!mem.count(c))
{
flag = false;
break;
}
}
if (flag)
++result;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
int n = 0, x = 0;
cin >> n;
vector<ll> countSum(100000, 0);
int max_ele = INT_MIN;
int min_ele = INT_MAX;
for (int i = 0; i < n; ++i)
{
cin >> x;
countSum[x] += x;
max_ele = max(max_ele, x);
min_ele = min(min_ele, x);
}
if (min_ele == max_ele)
{
cout << "NO\n";
return 0;
}
for (int i = min_ele + 1; i <= max_ele; ++i)
countSum[i] += countSum[i - 1];
int l = min_ele, r = max_ele, mid = 0;
bool flag = true;
while (l <= r)
{
mid = l + ((r - l) >> 1);
if (countSum[mid - 1] == (countSum[max_ele] - countSum[mid]))
{
cout << "YES\n";
flag = false;
break;
}
else if (countSum[mid - 1] < (countSum[max_ele] - countSum[mid]))
{
l = mid + 1;
}
else
r = mid - 1;
}
if (flag)
cout << "NO\n";
return 0;
}<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long int
bool isPalindrome(ll n)
{
if (n < 0 || (n % 10 == 0 && n != 0))
return false;
ll x = n;
ll y = 0;
while (y < x)
{
y = y * 10 + x % 10;
x /= 10;
}
return x == y || x == y / 10;
}
ll getLargestPalinProduct(ll n)
{
/*
a 6-digit palindrome can be represented as:
10^5*(a) + 10^4*(b) + 10^3*(c) + 10^2*(c) + 10^1*(b) + 10^0*(a)
simplified as: 100001*(a) + 10010*(b) + 1100*(c)
taking out 11: 11*(991*(a) + 910*(b) + 100*(c))
this number must be equal to the product of two 3-digit numbers
*** Hence, one of the numbers must be divisible by 11 (optimization)
*** the fact that the product must not exceed the given value (optimization)
*** if at any point the product for a current j for i goes below (optimization)
the current maximum, we can stop looking further down the value
of j for the given i
*/
int result = 0;
int step = 1;
int start = 999;
for (int i = 999; i >= 100; --i)
{
// atleast one of the numbers must be divisible by 11
if (i % 11)
{
step = 11;
start = min((ll)990, (n / i) - ((n / i) % 11));
}
else
{
step = 1;
start = min((ll)999, n / i);
}
for (int j = start; j >= 100; j -= step)
{
int product = i * j;
if (product < result)
break;
if (product < n && product < 1000000 && isPalindrome(product))
{
result = max(result, product);
}
}
}
return result;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
ll t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
cout << getLargestPalinProduct(n) << "\n";
}
return 0;
}
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_set>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Line
{
public:
int a;
int b;
int c;
Line(int a, int b, int c)
{
int gg = __gcd(__gcd(a, b), c);
this->a = a / gg;
this->b = b / gg;
this->c = c / gg;
}
bool operator==(const Line &obj) const
{
return (this->a == obj.a && this->b == obj.b && this->c == obj.c);
}
int solve(int x, int y)
{
return x * this->a + y * this->b + this->c;
}
};
class MyHash
{
public:
size_t operator()(const Line &obj) const
{
return hash<int>()(obj.a) ^ hash<int>()(obj.b) ^ hash<int>()(obj.c);
}
};
int main()
{
int xA;
int yA;
int xB;
int yB;
cin >> xA >> yA >> xB >> yB;
cin.ignore();
int n;
cin >> n;
cin.ignore();
unordered_set<Line, MyHash> L;
for (int i = 0; i < n; i++)
{
int a;
int b;
int c;
cin >> a >> b >> c;
cin.ignore();
Line obj(a, b, c);
if (L.find(obj) == L.end())
L.insert(obj);
}
int res = 1;
for (auto l : L)
{
int sa = l.solve(xA, yA);
int sb = l.solve(xB, yB);
if (sa == 0 || sb == 0)
{
cout << "ON A LINE\n";
return 0;
}
res *= (sa * sb < 0 ? -1 : 1);
}
if (res < 0)
cout << "NO\n";
else
cout << "YES\n";
}<file_sep>/**
*
*
* the idea of recurrence relation is simple:
* for a number X : 10011001
* result[i >> 1] -> gives the number of ones in X/2 -> number of ones in : 1001100
* (i & 1) -> gives the 1 if the number is odd else 0
*
* */
class Solution
{
public:
vector<int> countBits(int num)
{
vector<int> result = {0};
for (int i = 1; i <= num; ++i)
result.push_back(result[i >> 1] + (i & 1));
return result;
}
};<file_sep>// O(n) solution
class Solution
{
public:
int hIndex(vector<int> &citations)
{
int len = citations.size(), count = 0;
vector<int> buckets(len + 1, 0);
for (int &c : citations)
{
if (c >= len)
++buckets[len];
else
++buckets[c];
}
for (int i = len; i >= 0; --i)
{
count += buckets[i];
if (count >= i)
return i;
}
return 0;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(nlogn) solution
class Solution
{
public:
int hIndex(vector<int> &citations)
{
sort(citations.begin(), citations.end());
int len = citations.size();
for (int i = 0; i < citations.size(); ++i)
{
if (citations[i] >= len - i)
return len - i;
}
return 0;
}
};<file_sep>// bidirectional bfs
class Solution
{
public:
int ladderLength(string beginWord, string endWord, vector<string> &wordList)
{
unordered_set<string> wList(wordList.begin(), wordList.end()), start, end, *p_start, *p_end;
if (wList.count(endWord) == 0)
return 0;
int result = 2;
start.insert(beginWord);
end.insert(endWord);
char tmp_char;
while (start.size() && end.size())
{
if (start.size() <= end.size())
{
p_start = &start;
p_end = &end;
}
else
{
p_start = &end;
p_end = &start;
}
unordered_set<string> tmp;
for (string word : *p_start)
{
for (int i = 0; i < word.length(); ++i)
{
for (char c = 'a'; c <= 'z'; ++c)
{
if (c != word[i])
{
tmp_char = word[i];
word[i] = c;
if (p_end->count(word))
return result;
if (wList.count(word))
{
tmp.insert(word);
wList.erase(word);
}
word[i] = tmp_char;
}
}
}
}
p_start->swap(tmp);
++result;
}
return 0;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// standard bfs solution
class Solution
{
public:
int ladderLength(string beginWord, string endWord, vector<string> &wordList)
{
unordered_set<string> wList(wordList.begin(), wordList.end());
if (wList.count(endWord) == 0)
return 0;
if (wList.count(beginWord))
wList.erase(beginWord);
int result = 0, q_size = 0;
queue<string> Q;
Q.push(beginWord);
string cur;
char tmp;
while (Q.size())
{
q_size = Q.size();
while (q_size--)
{
cur = Q.front();
Q.pop();
if (cur == endWord)
return result + 1;
for (int i = 0; i < cur.length(); ++i)
{
for (char c = 'a'; c <= 'z'; ++c)
{
if (c != cur[i])
{
tmp = cur[i];
cur[i] = c;
if (wList.count(cur))
{
Q.push(cur);
wList.erase(cur);
}
cur[i] = tmp;
}
}
}
}
++result;
}
return 0;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int N;
int bfs(int src, vector<int> g[]) {
queue<int> Q;
Q.push(src);
vector<bool> vis(N+1, false);
int ct = -1;
while(!Q.empty()) {
int q_size = Q.size();
for(int i=0; i<q_size; ++i) {
int tmp = Q.front();
Q.pop();
vis[tmp] = true;
for(int j=0; j<g[tmp].size(); ++j) {
if(!vis[g[tmp][j]]) {
Q.push(g[tmp][j]);
}
}
}
++ct;
}
return ct;
}
int main()
{
cin >> N; cin.ignore();
vector<int> g[N+1];
for (int i = 0; i < N; i++) {
int A;
int B;
cin >> A >> B; cin.ignore();
g[A].push_back(B);
g[B].push_back(A);
}
int min_days = 999999;
for(int i=0; i<N; ++i) {
min_days = min(min_days, bfs(i, g));
}
cout << min_days << endl;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int N;
cin >> N;
cin.ignore();
int min_x = 999999, max_x = -999999;
long long int total_length = 0;
vector<pair<int, int>> B;
for (int i = 0; i < N; i++)
{
int X;
int Y;
cin >> X >> Y;
cin.ignore();
B.push_back({X, Y});
min_x = min(min_x, X);
max_x = max(max_x, X);
}
total_length += max_x - min_x;
auto median = B.begin() + N / 2;
nth_element(B.begin(), median, B.end(), [](const pair<int, int> o1, const pair<int, int> o2) {
return o1.second < o2.second;
});
for (int i = 0; i < N; i++)
{
total_length += abs(B[i].second - (median->second));
}
cout << total_length << endl;
}<file_sep>/**
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Facebook.
* You are given an array of non-negative integers that represents a two-dimensional elevation map where each element is unit-width wall and the integer is the height. Suppose it will rain and all spots between two walls get filled up.
* Compute how many units of water remain trapped on the map in O(N) time and O(1) space.
* For example, given the input [2, 1, 2], we can hold 1 unit of water in the middle.
* Given the input [3, 0, 1, 3, 0, 5], we can hold 3 units in the first index, 2 in the second, and 3 in the fourth index (we cannot hold 5 since it would run off to the left), so we can trap 8 units of water.
*
*
*
* Online Judge: https://leetcode.com/problems/trapping-rain-water/
*
*/
class Solution
{
public:
int trap(vector<int> &height)
{
if (height.size() < 3)
return 0;
int result = 0;
int max_left = INT_MIN, max_right = INT_MIN;
int l = 0, r = height.size() - 1;
while (l < r)
{
max_left = max(max_left, height[l]);
max_right = max(max_right, height[r]);
if (height[l] < max_left)
result += (max_left - height[l]);
if (height[r] < max_right)
result += (max_right - height[r]);
if (max_left <= max_right)
++l;
else
--r;
}
return result;
}
};<file_sep>class Solution {
public:
vector<string> findRestaurant(vector<string> &list1, vector<string> &list2) {
vector<string> result;
unordered_map<string, int> mem;
int min_idx_sum = INT_MAX;
for (int i = 0; i < list1.size(); ++i)
mem[list1[i]] = i;
for (int i = 0; i < list2.size(); ++i) {
if (mem.count(list2[i])) {
if (mem[list2[i]] + i == min_idx_sum)
result.emplace_back(list2[i]);
else if (mem[list2[i]] + i < min_idx_sum) {
min_idx_sum = mem[list2[i]] + i;
result.clear();
result.emplace_back(list2[i]);
}
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
#define ll long long int
unordered_map<ll, string> M = {
{1, "One"}, {2, "Two"}, {3, "Three"}, {4, "Four"}, {5, "Five"}, {6, "Six"}, {7, "Seven"}, {8, "Eight"}, {9, "Nine"}, {10, "Ten"}, {11, "Eleven"}, {12, "Twelve"}, {13, "Thirteen"}, {14, "Fourteen"}, {15, "Fifteen"}, {16, "Sixteen"}, {17, "Seventeen"}, {18, "Eighteen"}, {19, "Nineteen"}, {20, "Twenty"}, {30, "Thirty"}, {40, "Forty"}, {50, "Fifty"}, {60, "Sixty"}, {70, "Seventy"}, {80, "Eighty"}, {90, "Ninety"}, {100, "Hundred"}};
unordered_map<int, string> Level{
{0, ""}, {1, "Thousand"}, {2, "Million"}, {3, "Billion"}, {4, "Trillion"}};
string getNumeralUtil(ll n)
{
if (n == 0)
return "";
if (n < 100 && M.count(n))
return M[n];
string result = "";
int hundreds = n / 100;
n %= 100;
int tens = n / 10;
n %= 10;
int ones = n;
if (hundreds)
result += M[hundreds] + " Hundred";
if (10 * tens + ones < 21)
{
if (hundreds)
result += " ";
result += M[10 * tens + ones];
}
else
{
if (tens)
{
if (hundreds)
result += " ";
result += M[10 * tens];
}
if (ones)
{
if (hundreds || tens)
result += " ";
result += M[ones];
}
}
return result;
}
string getNumeral(ll n)
{
int lvl = 0;
string result = "";
string tmp;
while (n)
{
tmp = getNumeralUtil(n % 1000);
if (tmp.length())
result = tmp + " " + Level[lvl] + " " + result;
n /= 1000;
++lvl;
}
int i = result.length() - 1;
while (result[i] == ' ')
--i;
result = result.substr(0, i + 1);
i = 0;
while (result[i] == ' ')
++i;
return result.substr(i);
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
ll t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
if (n == 0)
cout << "Zero\n";
else
cout << getNumeral(n) << "\n";
}
return 0;
}
<file_sep>// time: O(N), space: O(logN) solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
ListNode *head;
public:
int getLength(ListNode *head)
{
int len = 0;
ListNode *cur = head;
while (cur)
{
++len;
cur = cur->next;
}
return len;
}
TreeNode *sortedListToBSTUtil(int l, int r)
{
if (l > r)
return NULL;
int mid = l + ((r - l) >> 1);
TreeNode *left = sortedListToBSTUtil(l, mid - 1);
TreeNode *root = new TreeNode(head->val);
head = head->next;
TreeNode *right = sortedListToBSTUtil(mid + 1, r);
root->left = left;
root->right = right;
return root;
}
TreeNode *sortedListToBST(ListNode *head)
{
this->head = head;
return sortedListToBSTUtil(0, getLength(head) - 1);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int myAtoi(string str)
{
int ind = 0;
bool neg = false;
while (str[ind] == ' ')
++ind;
if (str[ind] == '-')
{
neg = true;
++ind;
}
if (str[ind] == '+')
{
if (neg)
return 0;
neg = false;
++ind;
}
if (!isdigit(str[ind]))
return 0;
long ret = 0;
while (isdigit(str[ind]))
{
if (!neg && ret * 10 + (str[ind] - '0') >= INT_MAX)
return INT_MAX;
if (neg && ret * -10 - (str[ind] - '0') <= INT_MIN)
return INT_MIN;
ret = ret * 10 + str[ind] - '0';
++ind;
}
return neg ? ret * -1 : ret;
}
};<file_sep>class OrderedStream
{
vector<string> stream;
int idx;
public:
OrderedStream(int n)
{
stream = vector<string>(n, "?");
idx = 0;
}
vector<string> insert(int id, string value)
{
vector<string> result;
--id;
stream[id] = value;
if (idx == id)
{
while (idx < stream.size() && stream[idx] != "?")
{
result.emplace_back(stream[idx++]);
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
/**
* Your OrderedStream object will be instantiated and called as such:
* OrderedStream* obj = new OrderedStream(n);
* vector<string> param_1 = obj->insert(id,value);
*/<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 0, count = 0;
long long int w = 0, h = 0, ratio1 = 0, ratio2 = 0;
cin >> n;
while (n--)
{
cin >> w >> h;
if (w < h)
swap(w, h);
if ((16 * h) <= (10 * w) && (17 * h) >= (10 * w))
++count;
}
cout << count;
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int getInt(char c) {
if(c >= '0' && c <= '9') return c - '0';
return 0;
}
int getProcessedNum(char c) {
int p = getInt(c)*2;
return p > 9 ? p - 9 : p;
}
void validateCard(string card) {
int n = card.length();
if(n != 19) {
cout<<"NO\n";
return;
}
int sum1 = 0, sum2 = 0, ct = 0;
for(int i=n-2; i>=0; i-=2) {
sum1 += getProcessedNum(card[i]);
++ct;
if(ct%2 == 0) --i;
}
ct = 0;
for(int i=n-1; i>=1; i-=2) {
sum2 += getInt(card[i]);
++ct;
if(ct%2 == 0) --i;
}
if((sum1+sum2)%10 == 0) cout<<"YES\n";
else cout<<"NO\n";
}
int main()
{
int n;
cin >> n; cin.ignore();
for (int i = 0; i < n; i++) {
string card;
getline(cin, card);
validateCard(card);
}
}<file_sep>class Solution
{
public:
int minSteps(string s, string t)
{
int count = t.length();
vector<int> mem(26, 0);
for (char c : s)
++mem[c - 'a'];
for (char c : t)
{
if (mem[c - 'a'] > 0)
{
--mem[c - 'a'];
--count;
}
}
return count;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
int main()
{
ll n, q, c;
cin >> n >> q;
vector<ll> A(n, 0);
for (int i = 0; i < n; ++i)
{
cin >> A[i];
if (i > 0)
A[i] += A[i - 1];
}
while (q--)
{
cin >> c;
cout << (lower_bound(A.begin(), A.end(), c) - A.begin() + 1) << "\n";
}
return 0;
}<file_sep>// XOR approach
class Solution
{
public:
char findTheDifference(string s, string t)
{
char result = 0;
for (char &c : s)
result ^= c;
for (char &c : t)
result ^= c;
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// difference approach
class Solution
{
public:
char findTheDifference(string s, string t)
{
int result = 0;
for (int i = 0; i < s.length(); ++i)
{
result -= s[i];
result += t[i];
}
result += t[t.length() - 1];
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int getDigitSum(int a) {
return a ? a%10 + getDigitSum(a/10) : 0;
}
int main()
{
long long r1;
cin >> r1; cin.ignore();
long long r2;
cin >> r2; cin.ignore();
while(r1 != r2) {
if(r1 < r2) r1 += getDigitSum(r1);
else if(r1 > r2) r2 += getDigitSum(r2);
}
cout << r1 << endl;
}<file_sep>#include <iostream>
using namespace std;
#define ll long long int
int main()
{
ll n = 0, t = 0, count = 0;
cin >> t;
while (t--)
{
cin >> n;
string s;
cin >> s;
count = 0;
for (char c : s)
{
if (c == '0')
++count;
}
cout << count << "\n";
}
return 0;
}<file_sep>//recursive solution without stack O(n)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
int idx = 0;
TreeNode *bstFromPreorder(vector<int> &preorder, int limit = INT_MAX)
{
if (idx >= preorder.size() || preorder[idx] >= limit)
return NULL;
TreeNode *root = new TreeNode(preorder[idx++]);
root->left = bstFromPreorder(preorder, root->val);
root->right = bstFromPreorder(preorder, limit);
return root;
}
};
// recursive solution without stack O(n^2)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
TreeNode *bstFromPreorderUtil(vector<int> &preorder, int l, int r)
{
if (l == r)
return new TreeNode(preorder[l]);
if (l > r)
return NULL;
int mid = l;
for (int i = l + 1; i <= r; ++i)
{
if (preorder[i] > preorder[l])
break;
++mid;
}
TreeNode *root = new TreeNode(preorder[l]);
root->left = bstFromPreorderUtil(preorder, l + 1, mid);
root->right = bstFromPreorderUtil(preorder, mid + 1, r);
return root;
}
TreeNode *bstFromPreorder(vector<int> &preorder)
{
if (preorder.size() == 0)
return NULL;
TreeNode *root = bstFromPreorderUtil(preorder, 0, preorder.size() - 1);
return root;
}
};
// stack solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
TreeNode *bstFromPreorder(vector<int> &preorder)
{
if (preorder.size() == 0)
return NULL;
stack<TreeNode *> S;
TreeNode *root = new TreeNode(preorder[0]);
S.push(root);
for (int i = 1; i < preorder.size(); ++i)
{
TreeNode *tmp = new TreeNode(preorder[i]);
if (S.top()->val > preorder[i])
{
S.top()->left = tmp;
}
else
{
TreeNode *cur = S.top();
S.pop();
while (!S.empty() && S.top()->val < preorder[i])
{
cur = S.top();
S.pop();
}
cur->right = tmp;
}
S.push(tmp);
}
return root;
}
};<file_sep>// cyclic sort solution
class Solution
{
public:
string restoreString(string s, vector<int> &indices)
{
for (int i = 0; i < indices.size(); ++i)
{
while (i != indices[i])
{
swap(s[i], s[indices[i]]);
swap(indices[i], indices[indices[i]]);
}
}
return s;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// simple approach
class Solution
{
public:
string restoreString(string s, vector<int> &indices)
{
string res = s;
for (int i = 0; i < indices.size(); ++i)
res[indices[i]] = s[i];
return res;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// controlled recursive solution (efficient approach)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class BSTIterator
{
public:
stack<TreeNode *> mem;
TreeNode *cur;
BSTIterator(TreeNode *root)
{
cur = root;
}
/** @return the next smallest number */
int next()
{
while (cur)
{
mem.push(cur);
cur = cur->left;
}
cur = mem.top();
mem.pop();
int result = cur->val;
cur = cur->right;
return result;
}
/** @return whether we have a next smallest number */
bool hasNext()
{
return cur || mem.size();
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
// simple O(n) time and O(n) space solution with O(1) next() & hasNext() each
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class BSTIterator
{
TreeNode *root;
vector<TreeNode *> inorder;
int itr;
void generateIteration(TreeNode *root)
{
if (root)
{
generateIteration(root->left);
inorder.emplace_back(root);
generateIteration(root->right);
}
}
public:
BSTIterator(TreeNode *root)
{
this->root = root;
generateIteration(root);
itr = 0;
}
/** @return the next smallest number */
int next()
{
return inorder[itr++]->val;
}
/** @return whether we have a next smallest number */
bool hasNext()
{
return itr < inorder.size();
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/<file_sep>class Solution
{
public:
int subarraySum(vector<int> &nums, int k)
{
int n = nums.size(), sum = 0, result = 0;
unordered_map<int, int> preSum = {{0, 1}};
for (int i = 0; i < n; ++i)
{
sum += nums[i];
if (preSum.count(sum - k))
result += preSum[sum - k];
++preSum[sum];
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Point{
public:
int x;
int y;
Point(int x, int y) {
this->x = x;
this->y = y;
}
};
int getOrientation(Point a, Point b, Point c) {
int ret = (b.x - a.x)*(c.y - b.y) - (c.x - b.x)*(b.y - a.y);
if(ret == 0) return 0;
return ret > 0 ? 1 : 2;
}
bool isInside(vector<Point> polygon, Point p) {
int n = polygon.size();
int next = 0, o = 0, flag = 0;
for(int i=0; i<n; ++i) {
next = (i+1)%n;
o = getOrientation(polygon[i], polygon[next], p);
flag |= o;
if(flag == 3) return false;
}
return true;
}
int main()
{
int N;
cin >> N; cin.ignore();
vector<Point> polygon;
for (int i = 0; i < N; i++) {
int x;
int y;
cin >> x >> y; cin.ignore();
polygon.push_back({x, y});
}
int M;
cin >> M; cin.ignore();
for (int i = 0; i < M; i++) {
int x;
int y;
cin >> x >> y; cin.ignore();
if(isInside(polygon, {x, y})) cout<<"hit\n";
else cout<<"miss\n";
}
}<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
vector<pair<ll, ll>> mergeIntervals(vector<pair<ll, ll>> &ranges)
{
ll s = ranges[0].first, e = ranges[0].second;
vector<pair<ll, ll>> result;
for (int i = 1; i < ranges.size(); ++i)
{
// interval to be merged
if (ranges[i].first >= s && ranges[i].first <= e)
{
e = max(e, ranges[i].second);
}
// disjoint interval
else
{
result.push_back({s, e});
s = ranges[i].first, e = ranges[i].second;
}
}
result.push_back({s, e});
return result;
}
int main()
{
int t = 0, n = 0, q = 0, pos;
ll a = 0, b = 0, k = 0;
cin >> t;
while (t--)
{
cin >> n >> q;
vector<pair<ll, ll>> ranges(n);
for (int i = 0; i < n; ++i)
{
cin >> a >> b;
ranges[i] = make_pair(a, b);
}
sort(ranges.begin(), ranges.end());
vector<pair<ll, ll>> range = mergeIntervals(ranges);
vector<ll> rangeSum(range.size(), 0);
for (int i = 0; i < rangeSum.size(); ++i)
{
rangeSum[i] = range[i].second - range[i].first + 1;
if (i > 0)
rangeSum[i] += rangeSum[i - 1];
}
while (q--)
{
cin >> k;
pos = lower_bound(rangeSum.begin(), rangeSum.end(), k) - rangeSum.begin();
if (pos == rangeSum.size())
cout << "-1\n";
else
{
if (pos > 0)
{
k -= rangeSum[pos - 1];
}
cout << range[pos].first + k - 1 << "\n";
}
}
}
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int w;
int h;
int countX;
int countY;
cin >> w >> h >> countX >> countY; cin.ignore();
int ct = 0;
unordered_map<int, int> M;
int *X = new int[countX+2];
int *Y = new int[countY+2];
X[0] = Y[0] = 0;
X[countX+1] = w;
Y[countY+1] = h;
for (int i = 0; i < countX; i++) {
cin >> X[i+1]; cin.ignore();
}
for (int i = 0; i < countY; i++) {
cin >> Y[i+1]; cin.ignore();
}
for (int i = 0; i < countX+2; i++) {
for(int j=i+1; j<countX+2; ++j) {
++M[abs(X[i] - X[j])];
}
}
int tmp = 0;
for (int i = 0; i < countY+2; i++) {
for(int j=i+1; j<countY+2; ++j) {
tmp = abs(Y[i] - Y[j]);
if(M.find(tmp) != M.end()) {
ct += M[tmp];
}
}
}
cout << ct << endl;
}<file_sep>// a better solution using vector time: O(N) , space: O(N)
class RLEIterator
{
public:
vector<int> A;
int pos;
RLEIterator(vector<int> &A)
{
this->A = A;
pos = 0;
}
int next(int n)
{
while (pos < A.size())
{
if (n <= A[pos])
{
A[pos] -= n;
if (A[pos] == 0)
{
pos += 2;
return A[pos - 1];
}
return A[pos + 1];
}
else
{
n -= A[pos];
pos += 2;
}
}
return -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
/**
* Your RLEIterator object will be instantiated and called as such:
* RLEIterator* obj = new RLEIterator(A);
* int param_1 = obj->next(n);
*/
// solution using deque, time: O(N) , space: O(N)
class RLEIterator
{
public:
deque<int> A;
RLEIterator(vector<int> &A)
{
this->A = deque<int>(A.begin(), A.end());
}
int next(int n)
{
int result = -1;
while (A.size() >= 2 && n > A.front())
{
n -= A.front();
A.pop_front();
A.pop_front();
}
A.front() -= n;
result = A.size() ? A[1] : -1;
if (A.front() == 0)
{
A.pop_front();
A.pop_front();
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
/**
* Your RLEIterator object will be instantiated and called as such:
* RLEIterator* obj = new RLEIterator(A);
* int param_1 = obj->next(n);
*/<file_sep>class Solution
{
public:
int jump(vector<int> &nums)
{
int n = nums.size();
if (n <= 1)
return 0;
int jumps = 0, cur = 0, end = 0;
for (int i = 0; i < n; ++i)
{
end = max(end, i + nums[i]);
if (i == cur)
{
cur = end;
++jumps;
if (cur >= n - 1)
break;
}
}
return jumps;
}
};<file_sep>// smaller solution with stringstream
class Solution
{
public:
string simplifyPath(string path)
{
vector<string> tab;
istringstream S(path);
string dirname;
while (getline(S, dirname, '/'))
{
if (dirname.length() == 0 || dirname == ".")
continue;
else if (dirname == "..")
{
if (tab.size())
tab.pop_back();
}
else
tab.emplace_back(dirname);
}
if (tab.size() == 0)
return "/";
string result = "";
for (string &t : tab)
{
result += "/" + t;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// my first approach
class Solution
{
public:
string simplifyPath(string path)
{
vector<string> tab;
int i = 0, next = 0;
while (i < path.length())
{
if (path[i] == '.')
{
next = path.find('/', i + 1);
if (next == string::npos)
next = path.length();
if (next - i == 2)
{ // go back from current directory
if (tab.size())
tab.pop_back();
}
else if (next - i > 2)
{ // it is a directory with dots
tab.emplace_back(path.substr(i, next - i));
i = next;
}
// else it is just a single dot, stay in the same directory
}
else if (path[i] != '/')
{ // it is a directory
next = path.find('/', i + 1);
if (next == string::npos)
next = path.length();
tab.emplace_back(path.substr(i, next - i));
i = next;
}
++i;
}
string result = "/";
for (int i = 0; i < tab.size(); ++i)
{
result += tab[i];
if (i < tab.size() - 1)
result += "/";
}
return result;
}
};<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void pseudoPalindromicPathsUtil(TreeNode *root, int &result, int path = 0)
{
if (!root)
return;
path ^= (1 << root->val);
if (!root->left && !root->right)
if ((path & (path - 1)) == 0)
++result;
pseudoPalindromicPathsUtil(root->left, result, path);
pseudoPalindromicPathsUtil(root->right, result, path);
}
int pseudoPalindromicPaths(TreeNode *root)
{
int result = 0;
pseudoPalindromicPathsUtil(root, result);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int compareVersion(string version1, string version2)
{
vector<string> v1, v2;
istringstream S1(version1), S2(version2);
string tmp;
while (getline(S1, tmp, '.'))
{
v1.emplace_back(tmp);
}
while (getline(S2, tmp, '.'))
{
v2.emplace_back(tmp);
}
int i = 0, j = 0, x = 0, y = 0;
while (i < v1.size() && j < v2.size())
{
x = stoi(v1[i++]);
y = stoi(v2[j++]);
if (x > y)
return 1;
else if (x < y)
return -1;
}
while (i < v1.size())
{
if (stoi(v1[i++]) > 0)
return 1;
}
while (j < v2.size())
{
if (stoi(v2[j++]) > 0)
return -1;
}
return 0;
}
};<file_sep>/**
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Palantir.
* Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of strings which represents each line, fully justified.
* More specifically, you should have as many words as possible in each line. There should be at least one space between each word. Pad extra spaces when necessary so that each line has exactly length k. Spaces should be distributed as equally as possible, with the extra spaces, if any, distributed starting from the left.
* If you can only fit one word on a line, then you should pad the right-hand side with spaces.
* Each word is guaranteed not to be longer than k.
* For example, given the list of words ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"] and k = 16, you should return the following:
["the quick brown", # 1 extra space on the left
"fox jumps over", # 2 extra spaces distributed evenly
"the lazy dog"] # 4 extra spaces distributed evenly
*
*
*
* Online Judge: https://leetcode.com/problems/text-justification/
*
*/
class Solution
{
public:
string getJustifiedLine(vector<string> &words, int maxWidth, int start, int end, int len, int space_count, bool is_last)
{
string res = "";
int spaces = maxWidth - len;
spaces += space_count;
int same_spaces = (is_last || space_count == 0) ? 0 : spaces / space_count;
int extra_spaces = (is_last || space_count == 0) ? space_count : spaces % space_count;
int trail_spaces = (is_last || space_count == 0) ? maxWidth - len : 0;
for (int i = start; i <= end; ++i)
{
res.append(words[i]);
if (i < end)
{
res.append(same_spaces, ' ');
if (extra_spaces)
{
res.append(1, ' ');
--extra_spaces;
}
}
}
if (trail_spaces)
res.append(trail_spaces, ' ');
return res;
}
vector<string> fullJustify(vector<string> &words, int maxWidth)
{
vector<string> result;
int len = -1, space_count = -1, start = 0;
for (int i = 0; i < words.size(); ++i)
{
if (len + words[i].length() + 1 <= maxWidth)
{
len += words[i].length() + 1;
++space_count;
}
else
{
result.emplace_back(getJustifiedLine(words, maxWidth, start, i - 1, len, space_count, false));
start = i;
len = -1;
space_count = -1;
--i;
}
}
result.emplace_back(getJustifiedLine(words, maxWidth, start, words.size() - 1, len, space_count, true));
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* The while loop represents the game.
* Each iteration represents a turn of the game
* where you are given inputs (the heights of the mountains)
* and where you have to print an output (the index of the mountain to fire on)
* The inputs you are given are automatically updated according to your last actions.
**/
int main()
{
// game loop
while (1) {
int max_ind = 0, max_val = -999;
for (int i = 0; i < 8; i++) {
int mountainH; // represents the height of one mountain.
cin >> mountainH; cin.ignore();
if(mountainH > max_val) {
max_val = mountainH;
max_ind = i;
}
}
cout << max_ind << endl; // The index of the mountain to fire on.
}
}<file_sep>class Solution
{
public:
bool isValid(string sub_ip)
{
int num = stoi(sub_ip);
if (sub_ip.length() > 1 && sub_ip[0] == '0')
return false;
return num <= 255 && num >= 0;
}
void restoreIpAddressesUtil(string &s, vector<string> &result, string sol, int start = 0, int count = 0)
{
if (count == 4 && start == s.length())
{
result.emplace_back(sol);
return;
}
if (count > 4 || s.length() - start > (4 - count) * 3 || s.length() - start < (4 - count))
return;
string subWord;
int limit = (start + 3 < s.length() ? 3 : s.length() - start);
for (int len = 1; len <= limit; ++len)
{
subWord = s.substr(start, len);
if (isValid(subWord))
{
restoreIpAddressesUtil(s, result, sol + (count ? "." : "") + subWord, start + len, count + 1);
}
}
}
vector<string> restoreIpAddresses(string s)
{
vector<string> result;
string sol = "";
restoreIpAddressesUtil(s, result, sol);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int M;
cin >> M; cin.ignore();
vector<double> data;
double sum = 0, n_60 = 0, x = 0;
for (int i = 0; i < M; i++) {
for(int j=0; j<15; ++j) {
cin>>x;
data.push_back(x);
sum += x;
}
n_60 += 10.0 + (sum - 40.0)/7.0;
sum = 0;
}
n_60 /= (double)M;
cout<<fixed<<setprecision(1)<<n_60<<"\n";
if(n_60 >= 5 && n_60 <= 30) {
double n_8 = 0;
int len = data.size();
len = (len%2 == 0) ? len : len-1;
for(int i=0; i<len; i++) {
n_8 += data[i];
}
len /= 2;
n_8 += 5.0*(double)len;
n_8 /= ((double)len);
cout<<fixed<<setprecision(1)<<n_8<<"\n";
}
}<file_sep>class Solution
{
public:
int largestPerimeter(vector<int> &A)
{
sort(A.begin(), A.end());
for (int i = A.size() - 3; i >= 0; --i)
{
if (A[i] + A[i + 1] > A[i + 2])
return A[i] + A[i + 1] + A[i + 2];
}
return 0;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Stripe.
* Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
* For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
* You can modify the input array in-place.
*
*
* Online Judge: https://leetcode.com/problems/first-missing-positive/
*
*/
class Solution
{
public:
int firstMissingPositive(vector<int> &nums)
{
int j = 0, i = 0, val = 0;
for (i = 0; i < nums.size(); ++i)
if (nums[i] > 0)
swap(nums[i], nums[j++]);
for (i = 0; i < j; ++i)
{
val = abs(nums[i]) - 1;
if (val < j && nums[val] > 0)
nums[val] = -nums[val];
}
for (i = 0; i < j; ++i)
if (nums[i] > 0)
return i + 1;
return j + 1;
}
};<file_sep>class Solution {
public:
int removePalindromeSub(string s) {
if (!s.length())
return 0;
int len = s.length();
bool flag = false;
for (int i = 0; i < len >> 1; ++i) {
if (s[i] != s[len - i - 1]) {
flag = true;
break;
}
}
return flag ? 2 : 1;
}
};
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
vector<string> getOptions(string clause)
{
vector<string> ret;
size_t cur_pos = 0;
size_t pos = clause.find('|');
while (pos != string::npos)
{
ret.push_back(clause.substr(cur_pos, pos - cur_pos));
cur_pos = pos + 1;
pos = clause.find('|', cur_pos);
}
ret.push_back(clause.substr(cur_pos, clause.length() - cur_pos));
return ret;
}
int main()
{
int N;
cin >> N;
cin.ignore();
int ct = 0;
vector<string> clauses;
string completeString;
for (int i = 0; i < N; i++)
{
string line;
getline(cin, line);
completeString += line + "\n";
}
for (int j = 0; j < completeString.length(); ++j)
{
if (completeString[j] == '(')
{
int next_j = completeString.find(')', j + 1);
clauses = getOptions(completeString.substr(j + 1, next_j - j - 1));
cout << clauses[ct % clauses.size()];
j = next_j + 1;
++ct;
}
cout << completeString[j];
}
cout << "\n";
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
size_t getVolume(size_t r)
{
return r * r * r;
}
size_t getSurfaceArea(size_t r)
{
return r * r;
}
bool isFun(size_t go1, size_t go2, size_t so1, size_t so2)
{
return (go1 != so1 && go1 != so2 && go2 != go1 && go2 != so1 && go2 != so2 && so1 != so2);
}
bool isValid(size_t go1, size_t go2, size_t so1, size_t so2)
{
return getVolume(go1) + getVolume(go2) == getVolume(so1) + getVolume(so2);
}
size_t interestingVal(size_t o1, size_t o2)
{
o2 = max(o1, o2);
o2 = min(o1, o2);
return (o2 * o2 - o1 * o1);
}
int main()
{
size_t orbSizeMin;
size_t orbSizeMax;
cin >> orbSizeMin >> orbSizeMax;
cin.ignore();
size_t glowingSize1;
size_t glowingSize2;
cin >> glowingSize1 >> glowingSize2;
cin.ignore();
map<size_t, pair<size_t, size_t>> interesting;
for (size_t i = orbSizeMin; i <= orbSizeMax; ++i)
{
for (size_t j = orbSizeMin; j < orbSizeMax; ++j)
{
if (isValid(glowingSize1, glowingSize2, i, j))
{
if (isFun(glowingSize1, glowingSize2, i, j))
{
interesting.insert({interestingVal(i, j), {i, j}});
}
}
}
}
if (interesting.size() == 0)
{
cout << "VALID\n";
return 0;
}
auto f = interesting.begin();
cout << f->second.first << " " << f->second.second << "\n";
}<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
ll t = 0, a = 0, b = 0, c = 0, d = 0, k = 0;
cin >> t;
while (t--)
{
cin >> a >> b >> c >> d >> k;
int l = 0, r = 1e6, mid = 0, fin_t = 0;
size_t cur_ft = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
cur_ft = a * powl(mid, 3) + b * powl(mid, 2) + c * powl(mid, 1) + d;
if (cur_ft <= k)
{
fin_t = mid;
l = mid + 1;
}
else
r = mid - 1;
}
cout << fin_t << "\n";
}
return 0;
}<file_sep>class Solution
{
public:
vector<int> plusOne(vector<int> &digits)
{
if (digits.size() == 0)
return {1};
if (digits.size() == 1)
{
if (digits[0] == 9)
return {1, 0};
else
return {digits[0] + 1};
}
int n = digits.size();
vector<int> ret;
digits[n - 1] += 1;
for (int i = n - 1; i >= 0; --i)
{
if (digits[i] == 10)
{
digits[i] = 0;
if (i - 1 >= 0)
digits[i - 1] += 1;
else
ret.emplace_back(1);
}
else
break;
}
for (int i : digits)
ret.emplace_back(i);
return ret;
}
};<file_sep>// better solution
class Solution
{
public:
bool wordPattern(string pattern, string str)
{
unordered_map<string, int> mem;
vector<string> split;
istringstream S(str);
string tmp;
while (getline(S, tmp, ' '))
{
split.emplace_back(tmp);
}
if (split.size() != pattern.size())
return false;
for (int i = 0; i < pattern.length(); ++i)
{
tmp = "p_" + string(1, pattern[i]);
if (!mem.count(tmp))
mem[tmp] = i;
if (!mem.count(split[i]))
mem[split[i]] = i;
if (mem[tmp] != mem[split[i]])
return false;
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// simple solution
class Solution
{
public:
bool wordPattern(string pattern, string str)
{
unordered_map<char, string> mem;
unordered_set<string> seen;
vector<string> split;
istringstream S(str);
string tmp;
while (getline(S, tmp, ' '))
{
split.emplace_back(tmp);
}
if (split.size() != pattern.size())
return false;
for (int i = 0; i < pattern.length(); ++i)
{
if (mem.count(pattern[i]) && mem[pattern[i]] != split[i])
return false;
if (!mem.count(pattern[i]) && seen.count(split[i]))
return false;
mem[pattern[i]] = split[i];
seen.insert(split[i]);
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <cmath>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
#define EARTH_RADIUS 6371
class City
{
public:
string msg;
long double lat;
long double lon;
City(string lat, string lon)
{
this->lat = this->getDecimal(lat);
this->lon = this->getDecimal(lon);
}
long double getDecimal(string sg)
{
char dir = sg[0];
long double degree, minutes, arc_minutes;
if (dir == 'N' || dir == 'S')
{
degree = stod(sg.substr(1, 2));
minutes = stod(sg.substr(3, 2));
arc_minutes = stod(sg.substr(5, 2));
}
else
{
degree = stod(sg.substr(1, 3));
minutes = stod(sg.substr(4, 2));
arc_minutes = stod(sg.substr(6, 2));
}
minutes += arc_minutes / 60.0;
degree += minutes / 60.0;
if (dir == 'W' || dir == 'S')
degree *= -1;
return degree;
}
long double toRadian(long double degree)
{
return degree * 0.0174533;
}
int getDistance(string l_lat, string l_lon)
{
long double lt = this->getDecimal(l_lat);
long double ln = this->getDecimal(l_lon);
long double lat1 = this->toRadian(this->lat);
long double lat2 = this->toRadian(lt);
long double delta_lat = this->toRadian(abs(this->lat - lt));
long double delta_lon = this->toRadian(abs(ln - this->lon));
// long double d = acos(sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2)*cos(delta_lon));
// long double dist = d*EARTH_RADIUS;
long double a = sin(delta_lat / 2.0) * sin(delta_lat / 2.0) + cos(lat1) * cos(lat2) * sin(delta_lon / 2.0) * sin(delta_lon / 2.0);
long double c = 2 * atan2(sqrt(a), sqrt(1 - a));
long double dist = EARTH_RADIUS * c;
return round(dist);
}
};
int main()
{
int n; // number of capitals
cin >> n;
cin.ignore();
int m; // number of geolocations for which to find the closest capital
cin >> m;
cin.ignore();
vector<City> cities;
map<size_t, vector<City>> op;
for (int i = 0; i < n; i++)
{
string cityName, lat, lon;
cin >> cityName >> lat >> lon;
cin.ignore();
cities.push_back({lat, lon});
}
for (int i = 0; i < n; i++)
{
string message;
getline(cin, message);
cities[i].msg = message;
}
for (int i = 0; i < m; i++)
{
string l_lat, l_lon;
cin >> l_lat >> l_lon;
cin.ignore();
op.clear();
for (auto c : cities)
{
int dist = c.getDistance(l_lat, l_lon);
op[dist].push_back(c);
}
auto it = op.begin();
vector<City> mesg = it->second;
for (int i = 0; i < mesg.size(); ++i)
{
if (i + 1 < mesg.size())
cout << mesg[i].msg << " ";
else
cout << mesg[i].msg;
}
cout << "\n";
}
}<file_sep>class AttrCls:
def __init__(self, value, get_change="INIT"):
self.value = value
self.get_change = get_change
def __getattr__(self, name):
return getattr(self.value, name)
def __repr__(self):
return str(self.value)
def __bool__(self):
return bool(self.value)
def __call__(self):
return self.value()
def __eq__(self, other):
return self.value == other
def __add__(self, other):
return self.value + other
def __sub__(self, other):
return self.value - other
def __mul__(self, other):
return self.value * other
def __truediv__(self, other):
return self.value / other
def __radd__(self, other):
return other + self.value
def __rsub__(self, other):
return other - self.value
def __rmul__(self, other):
return other * self.value
def __rtruediv__(self, other):
return other / self.value
def change_detection(cls):
def __getattribute__(self, name):
pass
def __setattr__(self, name, value):
pass
def __delattr__(self, name):
pass
setattr(cls, '__getattribute__', __getattribute__)
setattr(cls, '__setattr__', __setattr__)
setattr(cls, '__delattr__', __delattr__)
return cls
y = AttrCls(11)
x = AttrCls(12)
print(y+x, y.get_change)
print(y-x, y.get_change)
print(y*x, y.get_change)
print(y/x, y.get_change)
<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
bool isValid(ll months, ll d, ll a, ll m, ll b, ll x)
{
ll a_mult = (months / (m + 1)) * m + months % (m + 1);
ll b_mult = (months / (m + 1));
return (d + a * a_mult + b * b_mult) >= x;
}
int main()
{
ll t = 0, d = 0, a = 0, m = 0, b = 0, x = 0;
cin >> t;
while (t--)
{
cin >> d >> a >> m >> b >> x;
ll left = 0, right = 1000000000, mid = 0;
bool val = false;
while (left < right)
{
mid = left + ((right - left) >> 1);
val = isValid(mid, d, a, m, b, x);
if (val)
right = mid;
else
left = mid + 1;
}
cout << left << "\n";
}
return 0;
}<file_sep>class Solution
{
public:
vector<string> summaryRanges(vector<int> &nums)
{
vector<string> result;
if (nums.size() == 0)
return result;
int start_idx = 0, end_idx = 0;
for (int i = 1; i < nums.size(); ++i)
{
if ((long)nums[i] - (long)nums[i - 1] > 1)
{
if (start_idx == end_idx)
result.emplace_back(to_string(nums[start_idx]));
else
result.emplace_back(to_string(nums[start_idx]) + "->" + to_string(nums[end_idx]));
start_idx = i;
}
end_idx = i;
}
if (start_idx == end_idx)
result.emplace_back(to_string(nums[start_idx]));
else
result.emplace_back(to_string(nums[start_idx]) + "->" + to_string(nums[end_idx]));
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int numPairsDivisibleBy60(vector<int> &time)
{
vector<int> mem(60, 0);
int count = 0, idx = -1;
for (int &t : time)
{
idx = (60 - (t % 60)) % 60;
if (mem[idx])
count += mem[idx];
++mem[t % 60];
}
return count;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
string reverseStr(string s, int k)
{
int limit = 0;
for (int i = 0; i < s.length(); i += k + k)
{
limit = i + k <= s.length() ? i + k : s.length();
reverse(s.begin() + i, s.begin() + limit);
}
return s;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// efficient solution with hashing
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
TreeNode *buildTreeUtil(vector<int> &preorder, vector<int> &inorder, int &idx, int l, int r, unordered_map<int, int> &mem)
{
if (l > r)
return NULL;
int i = mem[preorder[idx]];
TreeNode *root = new TreeNode(preorder[idx++]);
root->left = buildTreeUtil(preorder, inorder, idx, l, i - 1, mem);
root->right = buildTreeUtil(preorder, inorder, idx, i + 1, r, mem);
return root;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder)
{
unordered_map<int, int> mem;
for (int i = 0; i < inorder.size(); ++i)
mem[inorder[i]] = i;
int idx = 0;
return buildTreeUtil(preorder, inorder, idx, 0, preorder.size() - 1, mem);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// normal recursive solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
int idx = 0;
public:
TreeNode *buildTreeUtil(vector<int> &preorder, vector<int> &inorder, int l, int r)
{
if (l > r)
return NULL;
int i = l;
for (; i <= r; ++i)
if (preorder[idx] == inorder[i])
break;
TreeNode *root = new TreeNode(preorder[idx++]);
root->left = buildTreeUtil(preorder, inorder, l, i - 1);
root->right = buildTreeUtil(preorder, inorder, i + 1, r);
return root;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder)
{
return buildTreeUtil(preorder, inorder, 0, preorder.size() - 1);
}
};<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long int
vector<int> monthMap = {-1, 3, 0, 3, 2, 3, 2, 3, 3, 2, 3, 2, 3};
class Date
{
public:
ll year;
int month;
int day;
Date(ll year, int month, int day)
{
this->year = year;
this->month = month;
this->day = day;
}
bool operator>(const Date &o)
{
if (this->year > o.year)
return true;
else if (this->year == o.year && this->month > o.month)
return true;
else if (this->year == o.year && this->month == o.month && this->day > o.day)
return true;
return false;
}
};
bool isLeapYear(ll y)
{
return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
}
int Zellercongruence(int day, int month, ll year)
{
if (month == 1)
{
month = 13;
year--;
}
if (month == 2)
{
month = 14;
year--;
}
int q = day;
int m = month;
ll k = year % 100;
ll j = year / 100;
ll h = q + 13 * (m + 1) / 5 + k + k / 4 + j / 4 + 5 * j;
h %= 7;
h += 6;
h %= 7;
return h;
}
int getSundayCount(Date &d1, Date &d2)
{
if (d1 > d2)
return getSundayCount(d2, d1);
ll start = Zellercongruence(1, 1, d1.year);
int result = 0;
if (d1.year == d2.year)
{
for (int m = 1; m <= d2.month; ++m)
{
if (start == 0 && (m > d1.month || (m == d1.month && d1.day == 1)))
++result;
if (m == 2 && isLeapYear(d1.year))
start += 1;
else
start += monthMap[m];
start %= 7;
}
return result;
}
for (int m = 1; m <= 12; ++m)
{
if (start == 0 && (m > d1.month || (m == d1.month && d1.day == 1)))
++result;
if (m == 2 && isLeapYear(d1.year))
start += 1;
else
start += monthMap[m];
start %= 7;
}
for (size_t y = d1.year + 1; y < d2.year; ++y)
{
for (int m = 1; m <= 12; ++m)
{
if (start == 0)
++result;
if (m == 2 && isLeapYear(y))
start += 1;
else
start += monthMap[m];
start %= 7;
}
}
for (int m = 1; m <= d2.month; ++m)
{
if (start == 0)
++result;
if (m == 2 && isLeapYear(d2.year))
start += 1;
else
start += monthMap[m];
start %= 7;
}
return result;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t = 0, m = 0, d = 0;
ll y;
cin >> t;
while (t--)
{
cin >> y >> m >> d;
Date d1(y, m, d);
cin >> y >> m >> d;
Date d2(y, m, d);
cout << getSundayCount(d1, d2) << "\n";
}
return 0;
}
<file_sep>class Solution
{
public:
vector<int> findSubstring(string s, vector<string> &words)
{
if (s.length() == 0 || words.size() == 0)
return {};
int word_size = words[0].length();
int window_size = word_size * words.size();
if (window_size > s.length())
return {};
vector<int> ret;
unordered_map<string, int> wordsHash, stringHash;
for (string word : words)
++wordsHash[word];
int i = 0;
while (i + window_size <= s.length())
{
stringHash.clear();
for (int j = 0; j < window_size; j += word_size)
{
string tt = s.substr(i + j, word_size);
if (wordsHash.find(tt) == wordsHash.end())
break;
++stringHash[tt];
}
if (stringHash == wordsHash)
ret.emplace_back(i);
++i;
}
return ret;
}
};<file_sep>class Solution
{
public:
vector<string> letterCombinations(string digits)
{
if (digits.length() == 0)
return {};
vector<string> NUMS = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> ret = {""}, tmp;
for (char d : digits)
{
tmp.clear();
for (string e : ret)
{
for (char c : NUMS[d - '0'])
{
tmp.push_back(e + c);
}
}
ret = tmp;
}
return ret;
}
};<file_sep>// iterative solution (constant space) [Morris Traversal] (note that we do in inorder traversal instead of preorder, and have changed the calulation process accordingly -> technically any dfs approach can be used)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
int sumRootToLeaf(TreeNode *root)
{
TreeNode *cur = root;
TreeNode *tmp = NULL;
int result = 0, num = 0, count = 0;
while (cur)
{
if (cur->left)
{
tmp = cur->left;
count = 1;
while (tmp->right && tmp->right != cur)
{
tmp = tmp->right;
++count;
}
if (tmp->right == NULL)
{
num = (num << 1) | cur->val;
tmp->right = cur;
cur = cur->left;
}
else
{
if (tmp->left == NULL)
result += num;
num >>= count;
tmp->right = NULL;
cur = cur->right;
}
}
else
{
num = (num << 1) | cur->val;
if (cur->right == NULL)
{
result += num;
}
cur = cur->right;
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// iterative solution (using stack)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
int sumRootToLeaf(TreeNode *root)
{
stack<pair<TreeNode *, int>> S;
TreeNode *cur = root;
int result = 0, num = 0;
while (cur || S.size())
{
while (cur)
{
num = ((num << 1) | cur->val);
S.push({cur, num});
cur = cur->left;
}
tie(cur, num) = S.top();
S.pop();
if (!cur->left && !cur->right)
result += num;
cur = cur->right;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// recursive solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void sumRootToLeafUtil(TreeNode *root, int num, int &result)
{
if (root)
{
num = ((num << 1) | root->val);
if (!root->left && !root->right)
{
result += num;
return;
}
sumRootToLeafUtil(root->left, num, result);
sumRootToLeafUtil(root->right, num, result);
}
}
int sumRootToLeaf(TreeNode *root)
{
int result = 0;
sumRootToLeafUtil(root, 0, result);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>// class Solution
// {
// public:
// int mySqrt(int x)
// {
// if (x == 0)
// return 0;
// if (x <= 3)
// return 1;
// long long int r = x;
// while (r > x / r)
// r = (r + x / r) >> 1;
// return r;
// }
// };
class Solution
{
public:
int mySqrt(int x)
{
if (x == 0)
return 0;
if (x <= 3)
return 1;
int l = 1, r = x, mid = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
if (mid == x / mid)
return mid;
else if (mid < x / mid)
l = mid + 1;
else
r = mid - 1;
}
return r;
}
};<file_sep>// single pass iterative approach
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
vector<int> getAllElements(TreeNode *root1, TreeNode *root2)
{
vector<int> result;
stack<TreeNode *> s1, s2;
TreeNode *cur1 = root1;
TreeNode *cur2 = root2;
TreeNode *dummy = new TreeNode(INT_MAX);
while (s1.size() || cur1 != NULL || s2.size() || cur2 != NULL)
{
while (cur1 != NULL)
{
s1.push(cur1);
cur1 = cur1->left;
}
while (cur2 != NULL)
{
s2.push(cur2);
cur2 = cur2->left;
}
cur1 = s1.size() ? s1.top() : dummy;
cur2 = s2.size() ? s2.top() : dummy;
if (cur1->val <= cur2->val)
{
result.emplace_back(cur1->val);
s1.pop();
cur1 = cur1->right;
cur2 = NULL;
}
else
{
result.emplace_back(cur2->val);
s2.pop();
cur1 = NULL;
cur2 = cur2->right;
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// two pass recursive traversal + merge approach
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void preorder(TreeNode *root, vector<int> &arr)
{
if (root == NULL)
return;
preorder(root->left, arr);
arr.emplace_back(root->val);
preorder(root->right, arr);
}
vector<int> merge(vector<int> &a, vector<int> &b)
{
vector<int> result;
int i = 0, j = 0;
while (i < a.size() && j < b.size())
{
if (a[i] <= b[j])
result.emplace_back(a[i++]);
else
result.emplace_back(b[j++]);
}
while (i < a.size())
result.emplace_back(a[i++]);
while (j < b.size())
result.emplace_back(b[j++]);
return result;
}
vector<int> getAllElements(TreeNode *root1, TreeNode *root2)
{
vector<int> arr1, arr2;
preorder(root1, arr1);
preorder(root2, arr2);
return merge(arr1, arr2);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/*
simply use any solution of house robber 1 (198) and call it for
1. all houses except the first
2. all houses except the last
return the maximum of the two results
*/
class Solution
{
public:
int robUtil(vector<int> &nums, int start, int end)
{
int incl = 0, excl = 0, tmp;
for (int i = start; i < end; ++i)
{
tmp = incl;
incl = max(incl, nums[i] + excl);
excl = tmp;
}
return max(incl, excl);
}
int rob(vector<int> &nums)
{
if (nums.size() < 2)
return nums.size() ? nums[0] : 0;
return max(robUtil(nums, 0, nums.size() - 1), robUtil(nums, 1, nums.size()));
}
};<file_sep>// recursive solution with memoization
class Solution
{
public:
unordered_map<string, bool> MEM;
bool wordBreakUtil(string s, unordered_set<string> &wDict)
{
if (s.length() == 0)
return true;
if (wDict.count(s) > 0)
return true;
if (MEM.count(s) > 0)
return MEM[s];
for (int i = 1; i < s.length(); ++i)
{
if (wDict.count(s.substr(0, i)) > 0)
{
if (wordBreakUtil(s.substr(i, s.length() - i), wDict))
{
MEM[s] = true;
return true;
}
}
}
MEM[s] = false;
return false;
}
bool wordBreak(string s, vector<string> &wordDict)
{
unordered_set<string> wDict(wordDict.begin(), wordDict.end());
return wordBreakUtil(s, wDict);
}
};
// iterative solution with DP
class Solution
{
public:
bool wordBreak(string s, vector<string> &wordDict)
{
unordered_set<string> wDict(wordDict.begin(), wordDict.end());
vector<bool> tab(s.length() + 1, false);
tab[0] = true;
string subWord;
for (int i = 1; i <= s.length(); ++i)
{
for (int j = i - 1; j >= 0; --j)
{
if (tab[j])
{
subWord = s.substr(j, i - j);
if (wDict.count(subWord) > 0)
{
tab[i] = true;
break;
}
}
}
}
return tab[s.length()];
}
};
// bfs based solution (think of it as a bfs of a graph)
class Solution
{
public:
bool wordBreak(string s, vector<string> &wordDict)
{
unordered_set<string> wDict(wordDict.begin(), wordDict.end());
vector<bool> vis(s.length(), false);
queue<int> Q;
string subWord;
int idx = -1;
Q.push(0);
while (!Q.empty())
{
idx = Q.front();
Q.pop();
if (!vis[idx])
{
vis[idx] = true;
for (int i = 1; i <= s.size() - idx; ++i)
{
subWord = s.substr(idx, i);
if (wDict.count(subWord) > 0)
{
if (idx + i == s.length())
return true;
Q.push(idx + i);
}
}
}
}
return false;
}
};<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
int result;
int longestUnivaluePathUtil(TreeNode *root)
{
if (!root || (!root->left && !root->right))
return 0;
int left = longestUnivaluePathUtil(root->left);
int right = longestUnivaluePathUtil(root->right);
int res = 0;
if (root->left && root->left->val == root->val)
res += ++left;
else
left = 0;
if (root->right && root->right->val == root->val)
res += ++right;
else
right = 0;
result = max(result, res);
return max(left, right);
}
int longestUnivaluePath(TreeNode *root)
{
result = 0;
longestUnivaluePathUtil(root);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
bool arrayStringsAreEqual(vector<string> &word1, vector<string> &word2)
{
int row1 = 0, col1 = 0, row2 = 0, col2 = 0;
while (true)
{
if (col1 == word1[row1].length())
{
++row1;
col1 = 0;
}
if (col2 == word2[row2].length())
{
++row2;
col2 = 0;
}
if (row1 == word1.size() && row2 == word2.size())
break;
if ((row1 == word1.size() && row2 != word2.size()) || (row1 != word1.size() && row2 == word2.size()))
return false;
if (word1[row1][col1++] != word2[row2][col2++])
return false;
}
return true;
}
};<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
class MyHash
{
public:
size_t operator()(const array<ll, 3> &o) const
{
return (hash<ll>()(o[0]) ^ hash<ll>()(o[1]) ^ hash<ll>()(o[2]));
}
};
int main()
{
int n = 0, ct = 0;
array<ll, 3> input;
unordered_map<array<ll, 3>, int, MyHash> MEM;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> input[0] >> input[1] >> input[2];
sort(input.begin(), input.end());
++MEM[input];
}
for (auto e : MEM)
{
if (e.second == 1)
++ct;
}
cout << ct;
return 0;
}<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *reverseKGroup(ListNode *head, int k)
{
if (head == NULL)
return NULL;
ListNode *t = head;
for (int i = 0; i < k; ++i)
{
if (t == NULL)
return head;
t = t->next;
}
t = head;
ListNode *prev = NULL;
ListNode *nxt = head->next;
for (int i = 0; i < k; ++i)
{
t->next = prev;
prev = t;
t = nxt;
if (nxt == NULL)
break;
nxt = nxt->next;
}
head->next = reverseKGroup(t, k);
return prev;
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int L;
cin >> L; cin.ignore();
int N;
cin >> N; cin.ignore();
vector<pair<int, int> > a, b;
for (int i = 0; i < N; i++) {
int st;
int ed;
cin >> st >> ed; cin.ignore();
a.push_back({min(st, ed), max(st, ed)});
}
sort(a.begin(), a.end());
int f = a[0].first;
int s = a[0].second;
for(int i=1; i<a.size(); ++i) {
if(f < a[i].first && s < a[i].first) { // dosjoint range
b.push_back({f, s});
f = a[i].first;
s = a[i].second;
}
else if(f <= a[i].first && s < a[i].second) { // overlapping range
s = a[i].second;
}
}
if(f == 0 && s == L) {
cout<<"All painted";
return 0;
}
b.push_back({f, s});
int st = 0;
for(auto c : b) {
if(c.first != st) cout<<st<<" "<<c.first<<"\n";
st = c.second;
}
if(L != st) cout<<st<<" "<<L<<"\n";
}<file_sep>import uuid
import datetime
BOOKING_STATUS = ['Booked', 'Reserved']
ALTER_BOOKING_STATUS = ['Closed', 'Canceled']
DATE_FORMAT = "%d%m%Y"
class Booking:
id_counter = 1
def __init__(self, bookingId: int, tableNo: int, bookingDate: str, guests: int, status: str):
self.bookingId = bookingId
self.tableNo = tableNo
self.bookingDate = bookingDate
self.guests = guests
self.status = status
self._date = datetime.datetime.strptime(
bookingDate, DATE_FORMAT).date()
Booking.id_counter += 1
class Restaurant:
def __init__(self, tableList: dict, bookingList: list):
self.tableList = tableList
self.bookingList = bookingList
def isAvailable(self, tableNo, bookingDate):
for booking in self.bookingList:
if booking.tableNo == tableNo and booking.bookingDate == bookingDate and booking.status in BOOKING_STATUS:
return False
return True
def bookTable(self, guests: int, date: str, status: str):
for k, v in self.tableList.items():
if v == guests:
if self.isAvailable(k, date):
self.bookingList.append(
Booking(Booking.id_counter, k, date, guests, status))
else:
pass
def updateBookingStatus(self, date: str)
given_date = datetime.datetime.strptime(date, DATE_FORMAT).date()
one_past = given_date - datetime.timedelta(days=1)
two_past = given_date - datetime.timedelta(days=2)
for booking in self.bookingList:
if booking._date <= two_past and booking.status == BOOKING_STATUS[1]:
booking.status = ALTER_BOOKING_STATUS[1]
if booking._date <= one_past and booking.status == BOOKING_STATUS[0]:
booking.status = ALTER_BOOKING_STATUS[0]
<file_sep>class Solution
{
public:
int findJudge(int N, vector<vector<int>> &trust)
{
vector<int> trust_balance(N + 1, 0);
for (auto &t : trust)
{
--trust_balance[t[0]];
++trust_balance[t[1]];
}
for (int i = 1; i <= N; ++i)
if (trust_balance[i] == N - 1)
return i;
return -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// time: O(m*n), space: O(m*n), DP solution
class Solution
{
public:
int countSquares(vector<vector<int>> &matrix)
{
int m = matrix.size(), n = matrix[0].size(), count = 0;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (matrix[i][j])
{
if (i && j && matrix[i - 1][j] && matrix[i][j - 1] && matrix[i - 1][j - 1])
{
matrix[i][j] = 1 + min(matrix[i - 1][j - 1], min(matrix[i][j - 1], matrix[i - 1][j]));
}
count += matrix[i][j];
}
}
}
return count;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// constatnt extra space solution
class Solution
{
public:
string reverseWords(string s)
{
int l = 0, r = 0;
while (r <= s.length())
{
if (s[r] == ' ' || r == s.length())
{
reverse(s.begin() + l, s.begin() + r);
l = r + 1;
}
++r;
}
return s;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(N) extra space solution
class Solution
{
public:
string reverseWords(string s)
{
istringstream SS(s);
string token;
string result;
while (getline(SS, token, ' '))
{
reverse(token.begin(), token.end());
result += token + " ";
}
return result.substr(0, result.length() - 1);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <cmath>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
bool liesWithinCircle(double radius, double x, double y) {
return (x*x + y*y) <= (radius*radius);
}
bool liesWithinSquare(double side, double x, double y) {
return (max(abs(x), abs(y)) <= side/2);
}
bool liesWithinDiamond(double side, double x, double y) {
return (abs(x) + abs(y) <= side/2);
}
int getScore(double sq_size, double x, double y) {
if(liesWithinDiamond(sq_size, x, y)) return 15;
if(liesWithinCircle(sq_size/2, x, y)) return 10;
if(liesWithinSquare(sq_size, x, y)) return 5;
return 0;
}
class MySort{
public:
bool operator()(const pair<string, int> o1, const pair<string, int> o2) {
return o1.second > o2.second;
}
};
int main()
{
double SIZE;
cin >> SIZE; cin.ignore();
int N;
cin >> N; cin.ignore();
unordered_map<string, int> scores;
vector<pair<string, int>> board;
for (int i = 0; i < N; i++) {
string name;
getline(cin, name);
scores.insert({name, 0});
board.push_back({name, 0});
}
int T;
cin >> T; cin.ignore();
for (int i = 0; i < T; i++) {
string throwName;
double throwX;
double throwY;
cin >> throwName >> throwX >> throwY; cin.ignore();
scores[throwName] += getScore(SIZE, throwX, throwY);
}
for(int i=0; i<N; ++i) {
board[i].second = scores[board[i].first];
}
stable_sort(board.begin(), board.end(), MySort());
for(auto c : board) cout<<c.first<<" "<<c.second<<"\n";
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
size_t getDistance(pair<int, int> h1, pair<int, int> h2) {
return abs(h2.first - h1.first) + abs(h2.second - h1.second);
}
int main()
{
int N;
cin >> N; cin.ignore();
vector<pair<int, int> > horses;
for (int i = 0; i < N; i++) {
int V;
int E;
cin >> V >> E; cin.ignore();
horses.push_back({V, E});
}
size_t min_dist = 1e9+9;
for(int i=0; i<N; ++i) {
for(int j=i+1; j<N; ++j) {
min_dist = min(min_dist, getDistance(horses[i], horses[j]));
}
}
cout<<min_dist<<"\n";
}<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Google.
* Given an array of strictly the characters 'R', 'G', and 'B', segregate the values of the array so that all the Rs come first, the Gs come second, and the Bs come last. You can only swap elements of the array.
* Do this in linear time and in-place.
* For example, given the array ['G', 'B', 'R', 'R', 'B', 'R', 'G'], it should become ['R', 'R', 'R', 'G', 'G', 'B', 'B'].
*
*
*
* Online Judge: https://leetcode.com/problems/sort-colors/
*
*
*/
// consider 0 = R, 1 = G, 2 = B
class Solution
{
public:
void sortColors(vector<int> &nums)
{
int idx_1 = 0, idx_2 = nums.size() - 1;
for (int i = 0; i < nums.size(); ++i)
{
if (nums[i] == 0 && i > idx_1)
swap(nums[i--], nums[idx_1++]);
if (nums[i] == 2 && i < idx_2)
swap(nums[i--], nums[idx_2--]);
}
}
};<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
long long int n = 0, count = 0, distinct_size = 0;
cin >> n;
vector<long long int> A(n, 0);
unordered_map<long long int, long long int> D;
for (int i = 0; i < n; ++i)
{
cin >> A[i];
D.insert({A[i], 0});
}
distinct_size = D.size();
D.clear();
int i = 0, j = 0;
for (int i = 0; i < n; ++i)
{
while (D.size() < distinct_size && j < n)
{
++D[A[j++]];
}
if (D.size() == distinct_size)
{
count += n - j + 1;
}
--D[A[i]];
if (D[A[i]] == 0)
D.erase(A[i]);
}
cout << count;
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
vector<int> month_days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
class Date
{
public:
int day;
int month;
int year;
Date(string date)
{
this->day = stoi(date.substr(0, 2));
this->month = stoi(date.substr(3, 2));
this->year = stoi(date.substr(6, 4));
}
bool operator>(Date obj)
{
if (this->year > obj.year)
return true;
else if (this->year == obj.year)
{
if (this->month > obj.month)
return true;
else if (this->month == obj.month)
{
return this->day >= obj.day;
}
}
return false;
}
void operator-(Date obj)
{
int y_diff = 0, m_diff = 0, d_diff = 0;
y_diff = this->year - obj.year;
m_diff = this->month - obj.month;
if (m_diff < 0)
{
m_diff = (m_diff + 12) % 12;
--y_diff;
}
d_diff = this->day - obj.day;
if (d_diff < 0)
{
--m_diff;
}
cerr << "\n ++++++++ " << y_diff << " :: " << m_diff << " :: " << d_diff << "\n";
d_diff = 0;
int y_days = 0;
int m_days_o = 0;
int m_days_t = 0;
for (int i = obj.year + 1; i < this->year; ++i)
{
y_days += 365;
if (i % 4 == 0)
++y_days;
}
cerr << "\n ............ y_days " << y_days << "\n";
if (this->year == obj.year)
{
for (int i = obj.month + 1; i < this->month; ++i)
{
if (i == 2 && obj.year % 4 == 0)
++m_days_o;
m_days_o += month_days[i - 1];
}
cerr << "\n ............m_days_o _ same year " << m_days_o << "\n";
}
else
{
for (int i = obj.month + 1; i <= 12; ++i)
{
if (i == 2 && obj.year % 4 == 0)
++m_days_o;
m_days_o += month_days[i - 1];
}
cerr << "\n ............m_days_o " << m_days_o << "\n";
for (int i = 1; i < this->month; ++i)
{
if (i == 2 && this->year % 4 == 0)
++m_days_t;
m_days_t += month_days[i - 1];
}
cerr << "\n ............m_days_t " << m_days_t << "\n";
}
d_diff = y_days + m_days_o + m_days_t;
if (this->year == obj.year && this->month == obj.month)
{
d_diff += this->day - obj.day;
}
else
{
d_diff += month_days[obj.month - 1] - obj.day;
if (obj.month == 2 && obj.year % 4 == 0)
++d_diff;
d_diff += this->day;
}
if (y_diff > 0)
cout << y_diff << ((y_diff > 1) ? " years, " : " year, ");
if (m_diff > 0)
cout << m_diff << ((m_diff > 1) ? " months, " : " month, ");
cout << "total " << d_diff << " days";
}
};
int main()
{
string BEGIN;
cin >> BEGIN;
cin.ignore();
string END;
cin >> END;
cin.ignore();
Date begin(BEGIN);
Date end(END);
if (begin > end)
begin - end;
else
end - begin;
}<file_sep>// in place linking
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
TreeNode *head = NULL;
TreeNode *prev = NULL;
void increasingBSTUtil(TreeNode *root)
{
if (!root)
return;
increasingBSTUtil(root->left);
if (!head)
head = root;
if (prev)
{
root->left = NULL;
prev->right = root;
}
prev = root;
increasingBSTUtil(root->right);
}
TreeNode *increasingBST(TreeNode *root)
{
increasingBSTUtil(root);
return head;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
{
int total_gas = 0, total_cost = 0, start = 0, cur_cost = 0;
for (int i = 0; i < gas.size(); ++i)
{
cur_cost += gas[i] - cost[i];
if (cur_cost < 0)
{
start = i + 1;
cur_cost = 0;
}
total_gas += gas[i];
total_cost += cost[i];
}
return total_gas >= total_cost ? start : -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// BIT based solution
class Solution
{
vector<int> f;
public:
void update(int x)
{
while (x < f.size())
{
f[x]++;
x += (x & -x);
}
}
int get(int x)
{
int res = 0;
while (x > 0)
{
res += f[x];
x -= (x & -x);
}
return res;
}
int createSortedArray(vector<int> &instructions)
{
int result = 0, MOD = 1e9 + 7, n = instructions.size();
f = vector<int>(100001, 0);
for (int i = 0; i < n; ++i)
{
result = (result + min(get(instructions[i] - 1), (i - get(instructions[i])))) % MOD;
update(instructions[i]);
}
return result;
}
};<file_sep>// prefix sum
class Solution
{
public:
vector<int> runningSum(vector<int> &nums)
{
for (int i = 1; i < nums.size(); ++i)
nums[i] += nums[i - 1];
return nums;
}
};
// direct use of partial_sum
class Solution
{
public:
vector<int> runningSum(vector<int> &nums)
{
partial_sum(nums.begin(), nums.end(), nums.begin());
return nums;
}
};<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
TreeNode *addOneRowUtil(TreeNode *root, int v, int d) {
if (!root)
return NULL;
if (d == 2) {
root->left = new TreeNode(v, root->left, NULL);
root->right = new TreeNode(v, NULL, root->right);
}
root->left = addOneRowUtil(root->left, v, d - 1);
root->right = addOneRowUtil(root->right, v, d - 1);
return root;
}
TreeNode *addOneRow(TreeNode *root, int v, int d) {
if (d == 1)
return new TreeNode(v, root, NULL);
return addOneRowUtil(root, v, d);
}
};
auto speedu = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>// the target array has all distinct elements, so we map them to an increasing sequence,
// and find the LIS on the arr only for those mapped elements and return the difference between the target size and the LIS
class Solution
{
public:
int minOperations(vector<int> &target, vector<int> &arr)
{
int c = 0, idx = 0;
unordered_map<int, int> transformed;
vector<int> tab;
for (int i = 0; i < target.size(); ++i)
transformed[target[i]] = i;
for (int &a : arr)
{
if (transformed.count(a))
{
c = transformed[a];
if (tab.empty() || c > tab.back())
tab.emplace_back(c);
else
{
idx = lower_bound(tab.begin(), tab.end(), c) - tab.begin();
tab[idx] = c;
}
}
}
return target.size() - tab.size();
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// constant space solution (Morris Traversal)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void recoverTree(TreeNode *root)
{
TreeNode *cur = root;
TreeNode *tmp = NULL;
TreeNode *first = NULL;
TreeNode *second = NULL;
TreeNode *prev = new TreeNode(INT_MIN);
while (cur)
{
if (cur->left)
{
tmp = cur->left;
while (tmp->right && tmp->right != cur)
tmp = tmp->right;
if (tmp->right)
{
tmp->right = NULL;
if (!first && cur->val < prev->val)
first = prev;
if (first && cur->val < prev->val)
second = cur;
prev = cur;
cur = cur->right;
}
else
{
tmp->right = cur;
cur = cur->left;
}
}
else
{
if (!first && cur->val < prev->val)
first = prev;
if (first && cur->val < prev->val)
second = cur;
prev = cur;
cur = cur->right;
}
}
int t = first->val;
first->val = second->val;
second->val = t;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// solution with stack
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void recoverTree(TreeNode *root)
{
TreeNode *first = NULL;
TreeNode *second = NULL;
TreeNode *prev = new TreeNode(INT_MIN);
stack<TreeNode *> S;
TreeNode *cur = root;
while (!S.empty() || cur)
{
while (cur)
{
S.push(cur);
cur = cur->left;
}
cur = S.top();
S.pop();
if (!first && cur->val < prev->val)
first = prev;
if (first && cur->val < prev->val)
second = cur;
prev = cur;
cur = cur->right;
}
int tmp = first->val;
first->val = second->val;
second->val = tmp;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// better solution with recursion
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
TreeNode *first = NULL;
TreeNode *second = NULL;
TreeNode *prev = new TreeNode(INT_MIN);
void inorderTraversal(TreeNode *root)
{
if (!root)
return;
inorderTraversal(root->left);
if (!first && root->val < prev->val)
first = prev;
if (first && root->val < prev->val)
second = root;
prev = root;
inorderTraversal(root->right);
}
void recoverTree(TreeNode *root)
{
inorderTraversal(root);
int tmp = first->val;
first->val = second->val;
second->val = tmp;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(n) space solution with recursion
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void inorderTraversal(TreeNode *root, vector<TreeNode *> &order)
{
if (!root)
return;
inorderTraversal(root->left, order);
order.emplace_back(root);
inorderTraversal(root->right, order);
}
void recoverTree(vector<TreeNode *> &order)
{
int i = 1, j = 0;
while (i < order.size() && order[i]->val > order[i - 1]->val)
++i;
j = i;
for (int k = i; k < order.size(); ++k)
{
if (order[j]->val > order[k]->val)
j = k;
}
int tmp = order[i - 1]->val;
order[i - 1]->val = order[j]->val;
order[j]->val = tmp;
}
void recoverTree(TreeNode *root)
{
vector<TreeNode *> order;
inorderTraversal(root, order);
recoverTree(order);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int binarySearch(vector<ll> &a, ll x)
{
int l = 0, r = a.size() - 1, mid = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
if (a[mid] == x)
return mid;
else if (a[mid] < x)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
int main()
{
ll n = 0, q = 0, x = 0;
cin >> n;
vector<ll> A(n, 0);
for (int i = 0; i < n; ++i)
{
cin >> A[i];
}
sort(A.begin(), A.end());
cin >> q;
while (q--)
{
cin >> x;
cout << binarySearch(A, x) + 1 << "\n";
}
return 0;
}<file_sep>// better solution (same time & space complexity though)
class Solution
{
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k)
{
vector<int> result;
deque<int> win;
for (int i = 0; i < nums.size(); ++i)
{
// add the new element meanwhile replacing all smaller elements
while (win.size() && nums[i] >= nums[win.back()])
win.pop_back();
win.push_back(i);
if (i >= k - 1)
result.push_back(nums[win.front()]);
// remove all indices outside the next window in left
while (win.size() && win.front() <= i - k + 1)
win.pop_front();
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// first solution
class Solution
{
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k)
{
vector<int> result;
deque<int> window;
// process the first k elements
for (int i = 0; i < k; ++i)
{
while (!window.empty() && nums[i] >= nums[window.back()])
window.pop_back();
window.emplace_back(i);
}
result.emplace_back(nums[window.front()]);
int win_start = 1;
for (int win_end = k; win_end < nums.size(); ++win_end)
{
// remove all indices outside the window in left
while (!window.empty() && window.front() < win_start)
window.pop_front();
// add the new element at win_end
while (!window.empty() && nums[win_end] >= nums[window.back()])
window.pop_back();
window.emplace_back(win_end);
result.emplace_back(nums[window.front()]);
++win_start;
}
return result;
}
};<file_sep>class Solution
{
public:
int findPoisonedDuration(vector<int> &timeSeries, int duration)
{
if (timeSeries.size() == 0)
return 0;
int result = 0;
for (int i = 0; i < timeSeries.size() - 1; ++i)
{
result += min(timeSeries[i + 1] - timeSeries[i], duration);
}
return result + duration;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int getMaximumGenerated(int n)
{
if (n <= 1)
return n;
int result = 0;
vector<int> mem(n + 1, 0);
mem[1] = 1;
for (int i = 2; i <= n; ++i)
{
mem[i] = (i & 1) ? mem[i >> 1] + mem[(i >> 1) + 1] : mem[i >> 1];
result = max(result, mem[i]);
}
return result;
}
};<file_sep>class Solution
{
public:
int orangesRotting(vector<vector<int>> &grid)
{
queue<pair<int, int>> rotten;
int fresh_count = 0;
for (int i = 0; i < grid.size(); ++i)
{
for (int j = 0; j < grid[i].size(); ++j)
{
if (grid[i][j] == 2)
rotten.push({i, j});
else if (grid[i][j] == 1)
++fresh_count;
}
}
if (fresh_count == 0)
return 0;
pair<int, int> tmp;
int x = 0, y = 0, minutes = -1, q_size;
vector<pair<int, int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!rotten.empty())
{
q_size = rotten.size();
++minutes;
while (q_size--)
{
tmp = rotten.front();
rotten.pop();
for (auto d : dirs)
{
x = tmp.first + d.first;
y = tmp.second + d.second;
// if the cell is valid and has a fresh orange
if (x >= 0 && x < grid.size() && y >= 0 && y < grid[x].size() && grid[x][y] == 1)
{
grid[x][y] = 2; // make the cell's orange as rotten
--fresh_count;
rotten.push({x, y});
}
}
}
}
if (fresh_count > 0)
return -1;
return minutes;
}
};<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Amazon.
* An sorted array of integers was rotated an unknown number of times.
* Given such an array, find the index of the element in the array in faster than linear time. If the element doesn't exist in the array, return null.
* For example, given the array [13, 18, 25, 2, 8, 10] and the element 8, return 4 (the index of 8 in the array).
* You can assume all the integers in the array are unique.
*
*
*
* Online Judge: https://leetcode.com/problems/search-in-rotated-sorted-array/
*
*/
class Solution
{
public:
int search(vector<int> &nums, int target)
{
int l = 0, r = nums.size() - 1, mid = 0, val = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
val = (target < nums[0] ? nums[mid] < nums[0] ? nums[mid] : INT_MIN : nums[mid] < nums[0] ? INT_MAX : nums[mid]);
if (val == target)
return mid;
else if (val < target)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// divide and conquer solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
vector<TreeNode *> generateTreesUtil(int start, int end)
{
if (start > end)
return {{NULL}};
vector<TreeNode *> result;
for (int i = start; i <= end; ++i)
{
vector<TreeNode *> left_subtrees = generateTreesUtil(start, i - 1);
vector<TreeNode *> right_subtrees = generateTreesUtil(i + 1, end);
for (auto l : left_subtrees)
{
for (auto r : right_subtrees)
{
TreeNode *root = new TreeNode(i);
root->left = l;
root->right = r;
result.push_back(root);
}
}
}
return result;
}
vector<TreeNode *> generateTrees(int n)
{
if (n == 0)
return {};
return generateTreesUtil(1, n);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int maxProfit(vector<int> &prices)
{
if (prices.size() == 0)
return 0;
int min_so_far = prices[0], max_profit = INT_MIN;
for (int i = 1; i < prices.size(); ++i)
{
max_profit = max(max_profit, prices[i] - min_so_far);
min_so_far = min(min_so_far, prices[i]);
}
return max(max_profit, 0);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Twitter.
* You run an e-commerce website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API:
* -> record(order_id): adds the order_id to the log
* -> get_last(i): gets the ith last element from the log. i is guaranteed to be smaller than or equal to N.
* You should be as efficient with time and space as possible.
*
*
*/
#include <iostream>
#include <vector>
using namespace std;
class LogBase
{
vector<size_t> log; // assuming order id to be unsigned
size_t size; // size can be very large and unsigned
public:
LogBase(size_t size)
{
this->log = {};
this->size = size;
}
void print()
{
for (auto e : this->log)
cout << e << " ";
}
void record(size_t order_id)
{
if (this->log.size() >= 2 * this->size)
{
for (size_t i = 0; i < this->size - 1; ++i)
{
this->log[i] = this->log[this->log.size() - (this->size - 1) + i];
}
this->log.resize(this->size - 1);
}
this->log.push_back(order_id); // ammortized O(1)
}
size_t get_last(size_t i)
{
if (i <= this->size && this->log.size() - i >= 0)
return this->log[this->log.size() - i]; // O(1)
return -1;
}
};
int main()
{
LogBase lb(3);
lb.record(12);
lb.record(99);
lb.record(84);
// current state of log: [12, 99, 84]
cout << "\nCurrent state: ";
lb.print();
cout << "\n--------------------------------------------\n";
cout << "\nFirst record from last: " << lb.get_last(1); // get the first record from last
cout << "\nSecond record from last: " << lb.get_last(2); // get the second record from last
cout << "\nThird record from last: " << lb.get_last(3); // get the third record from last
// inserting more elements beyond capacity
lb.record(17);
lb.record(66);
lb.record(11);
cout << "\n\n";
cout << "\nCurrent state: ";
lb.print();
cout << "\n--------------------------------------------\n";
cout << "\nFirst record from last: " << lb.get_last(1); // get the first record from last
cout << "\nSecond record from last: " << lb.get_last(2); // get the second record from last
cout << "\nThird record from last: " << lb.get_last(3); // get the third record from last
// adding an element to update vector and perform resizing
lb.record(213);
lb.record(113);
cout << "\n\n";
cout << "\nCurrent state: ";
lb.print();
cout << "\n--------------------------------------------\n";
return 0;
}
<file_sep>class Solution
{
public:
void nextPermutation(vector<int> &nums)
{
int ind = nums.size() - 2;
while (ind >= 0 && nums[ind] >= nums[ind + 1])
--ind;
if (ind >= 0)
{
int i = nums.size() - 1;
while (i > ind)
{
if (nums[i] > nums[ind])
{
swap(nums[i], nums[ind]);
break;
}
--i;
}
}
reverse(nums.begin() + ind + 1, nums.end());
}
};<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> getNumVecFromString(string s)
{
// returns a vector of the given string of a very large number
vector<int> res;
for (char c : s)
res.push_back(int(c - '0'));
return res;
}
long long int getLargestProduct(string s, int k)
{
// returns the larges product of a window of size k
vector<int> num = getNumVecFromString(s);
long long int max_res = 0, res = 1;
int l = 0, r = k, n = num.size(); // using l and r for tracking the window
bool flag = true, f = true;
while (l + k < n && r < n)
{
if (flag)
{ // calculate window
res = 1;
f = true;
for (int i = l; i < r; ++i)
{
if (num[i] == 0)
{ // 0 is found, calculate next window
f = false;
l = i + 1;
r = l + k;
break;
}
res *= num[i];
}
if (f)
{
max_res = max(max_res, res);
flag = false;
}
}
else
{ // slide window
if (num[r] == 0)
{
flag = true;
l = r + 1;
r = l + k;
}
else
{
res /= num[l++];
res *= num[r++];
max_res = max(max_res, res);
}
}
}
return max_res;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t = 0, n = 0, k = 0;
string num;
cin >> t;
while (t--)
{
cin >> n >> k;
cin >> num;
cout << getLargestProduct(num, k) << "\n";
}
return 0;
}
<file_sep>#include <stdio.h>
int main()
{
int r, h;
float area;
printf("Enter radius of the cylinder: \n");
scanf("%d", &r);
printf("enter height of cylinder: \n");
scanf("%d", &h);
area = 3.14 * r * r * h;
printf("area of cylinder is= %f \n", area);
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int W, H;
bool isValid(int i, int j) {
if(i < 0 || j < 0 || i>=H || j >=W) return false;
return true;
}
int main()
{
cin >> W; cin.ignore();
cin >> H; cin.ignore();
vector<vector<int> > grid(H);
vector<pair<int, int> > dirs = {{-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}};
for (int i = 0; i < H; i++) {
grid[i] = vector<int>(W);
for (int j = 0; j < W; j++) {
cin >> grid[i][j]; cin.ignore();
}
}
for(auto r : grid) {
for(auto e : r) {
cerr<<e<<" ";
}
cerr<<"\n";
}
int x=0, y=0;
bool flag = true;
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
if(grid[i][j] == 0) {
flag = true;
for(auto d:dirs) {
x = i + d.first;
y = j + d.second;
if(isValid(x, y) && grid[x][y] != 1) {
flag = false;
break;
}
}
if(flag) {
cout<<j<<" "<<i<<"\n";
return 0;
}
}
}
}
}<file_sep>class Solution
{
public:
vector<vector<int>> combine(int n, int k)
{
vector<vector<int>> ret;
vector<int> sol(k, 0);
int i = 0;
while (i >= 0)
{
++sol[i];
if (sol[i] > n)
--i;
else if (i == k - 1)
ret.emplace_back(sol);
else
{
++i;
sol[i] = sol[i - 1];
}
}
return ret;
}
};<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long int
ll sumOfEvenFibonacciUpto(ll n)
{
//finds and returns the sum of all even fibonacci numbers upto n
ll result = 0;
ll f = 1, s = 1;
while (s <= n)
{
if (~s & 1)
result += s;
s = f + s;
f = s - f;
}
return result;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
ll t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
cout << sumOfEvenFibonacciUpto(n) << "\n";
}
return 0;
}
<file_sep>class LRUCache
{
public:
list<pair<int, int>> C;
unordered_map<int, list<pair<int, int>>::iterator> M;
int capacity;
LRUCache(int capacity)
{
this->capacity = capacity;
}
int get(int key)
{
if (M.count(key))
{ // key present
auto it = M[key];
C.splice(C.begin(), C, it); // bring to front
return C.front().second;
}
return -1;
}
void put(int key, int value)
{
if (get(key) != -1)
{ // key already present (already brought to front)
C.front().second = value;
return;
}
if (C.size() >= capacity)
{ // remove least recently used element
int key_to_remove = C.back().first;
C.pop_back();
M.erase(key_to_remove);
}
C.push_front({key, value});
M[key] = C.begin();
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 0, k = 0;
cin >> n;
vector<int> A(n, 0);
vector<int> Hash(100001, 0);
for (int i = 0; i < n; ++i)
{
cin >> A[i];
++Hash[A[i]];
}
cin >> k;
for (int i = 0; i < 100001; ++i)
{
if (Hash[i] == k)
{
cout << i;
break;
}
}
return 0;
}<file_sep>class Solution
{
public:
string getPermutation(int n, int k)
{
vector<int> factorials = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
vector<char> seq;
string seq_permutation(n, '\0');
int idx = 0;
for (int i = 0; i < n; ++i)
{
seq.push_back(i + '1');
seq_permutation[i] = i + '1';
}
if (k == 1)
return seq_permutation;
--k;
for (int i = n; i > 0; --i)
{
idx = k / factorials[i - 1];
k -= idx * factorials[i - 1];
seq_permutation[n - i] = seq[idx];
seq.erase(seq.begin() + idx);
}
return seq_permutation;
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int getDropCount(string s) {
int ct = 0;
int n = s.length();
int i = 0;
while(i<n) {
if(s[i] == 'f') {
++ct;
i += 2;
}
++i;
}
return ct;
}
int main()
{
int N;
cin >> N; cin.ignore();
for (int i = 0; i < N; i++) {
string line;
getline(cin, line);
cout<<getDropCount(line)<<"\n";
}
}<file_sep>#include <bits/stdc++.h>
using namespace std;
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
int main()
{
int n = 0, q = 0, k = 0;
cin >> n >> q;
vector<int> a(n, 0);
vector<int> preSum(n + 1, 0);
for (int i = 0; i < n; ++i)
{
cin >> a[i];
preSum[i + 1] = preSum[i] + __builtin_popcount(a[i]);
}
while (q--)
{
cin >> k;
int min_len = INT_MAX;
for (int i = 0; i < preSum.size(); ++i)
{
auto it = lower_bound(preSum.begin(), preSum.end(), preSum[i] + k);
if (it == preSum.end())
break;
min_len = min(min_len, max((int)(it - (preSum.begin() + i)), 1));
}
if (min_len == INT_MAX)
cout << "-1\n";
else
cout << min_len << "\n";
}
return 0;
}<file_sep>// fastest priority queue version
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
typedef tuple<int, int, int> t3_int;
auto compare = [](const t3_int &a, const t3_int &b) {
if (get<0>(a) > get<0>(b))
return true;
else if (get<0>(a) < get<0>(b))
return false;
else
{
if (get<1>(a) > get<1>(b))
return true;
else if (get<1>(a) < get<1>(b))
return false;
else
{
return get<2>(a) > get<2>(b);
}
}
};
class Solution
{
public:
void verticalTraversalUtil(TreeNode *root, priority_queue<t3_int, vector<t3_int>, decltype(compare)> &pq, int x = 0, int y = 0)
{
if (root)
{
pq.push(make_tuple(x, y, root->val));
verticalTraversalUtil(root->left, pq, x - 1, y + 1);
verticalTraversalUtil(root->right, pq, x + 1, y + 1);
}
}
vector<vector<int>> verticalTraversal(TreeNode *root)
{
if (!root)
return {};
vector<vector<int>> result;
priority_queue<t3_int, vector<t3_int>, decltype(compare)> pq(compare);
verticalTraversalUtil(root, pq);
int x = 0, y = 0, cur = 0, prev_x, idx = 0;
while (pq.size())
{
tie(x, y, cur) = pq.top();
pq.pop();
if (result.empty())
{
result.emplace_back();
idx = 0;
result[idx].emplace_back(cur);
}
else
{
if (prev_x == x)
{
result[idx].emplace_back(cur);
}
else
{
result.emplace_back();
++idx;
result[idx].emplace_back(cur);
}
}
prev_x = x;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// bfs solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
vector<vector<int>> verticalTraversal(TreeNode *root)
{
if (!root)
return {};
vector<vector<int>> result;
map<int, map<int, multiset<int>>> res;
queue<tuple<int, int, TreeNode *>> Q;
Q.push(make_tuple(0, 0, root));
TreeNode *cur = NULL;
int x = 0, y = 0;
while (Q.size())
{
tie(x, y, cur) = Q.front();
Q.pop();
res[x][y].insert(cur->val);
if (cur->left)
Q.push(make_tuple(x - 1, y + 1, cur->left));
if (cur->right)
Q.push(make_tuple(x + 1, y + 1, cur->right));
}
for (auto x_r : res)
{
vector<int> tmp;
for (auto y_r : x_r.second)
tmp.insert(tmp.end(), y_r.second.begin(), y_r.second.end());
result.emplace_back(tmp);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// dfs solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void verticalTraversalUtil(TreeNode *root, map<int, map<int, multiset<int>>> &res, int x = 0, int y = 0)
{
if (root)
{
res[x][y].insert(root->val);
verticalTraversalUtil(root->left, res, x - 1, y + 1);
verticalTraversalUtil(root->right, res, x + 1, y + 1);
}
}
vector<vector<int>> verticalTraversal(TreeNode *root)
{
vector<vector<int>> result;
map<int, map<int, multiset<int>>> res;
verticalTraversalUtil(root, res);
for (auto x_r : res)
{
vector<int> tmp;
for (auto y_r : x_r.second)
tmp.insert(tmp.end(), y_r.second.begin(), y_r.second.end());
result.emplace_back(tmp);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
vector<string> splitString(string s, char c)
{
vector<string> ret;
size_t cur_pos = 0;
size_t pos = s.find(c);
if (pos == string::npos)
return ret;
while (pos != string::npos)
{
ret.push_back(s.substr(cur_pos, pos - cur_pos));
cur_pos = pos + 1;
pos = s.find(c, cur_pos);
}
ret.push_back(s.substr(cur_pos, s.length() - cur_pos));
return ret;
}
int getProcessedNumber(string s)
{
if (s == "X")
return -20;
if (s.find('*') == string::npos)
return stoi(s);
vector<string> mul = splitString(s, '*');
int ret = 1;
for (auto m : mul)
ret *= stoi(m);
return ret;
}
int getLastRound(string streak)
{
vector<string> plays = splitString(streak, ' ');
vector<int> playScores;
for_each(plays.begin(), plays.end(), [&playScores](const string &o) {
playScores.push_back(getProcessedNumber(o));
});
int score = 0;
int prev_round_score = 0;
int num_rounds = 0;
int n = playScores.size();
int i = 0, j = 0;
for (i = 0; i < n; ++i)
{
++num_rounds;
for (j = i; j < min(n, i + 3); ++j)
{
int tmp = playScores[j];
if (tmp == -20 && j > i && playScores[j - 1] == -20)
{
tmp = -30;
if (j - 1 > i && playScores[j - 2] == -20)
{
tmp = score * -1;
}
}
score += tmp;
if (score == 101)
return num_rounds;
if (score > 101)
{
score = prev_round_score;
++j;
break;
}
}
prev_round_score = score;
i = j - 1;
}
return 999999;
}
int main()
{
int N;
cin >> N;
cin.ignore();
vector<pair<string, int>> players;
for (int i = 0; i < N; i++)
{
string PLAYER;
getline(cin, PLAYER);
players.push_back({PLAYER, 0});
}
for (int i = 0; i < N; i++)
{
string SHOOTS;
getline(cin, SHOOTS);
players[i].second = getLastRound(SHOOTS);
}
int idx = 0;
for (int i = 1; i < N; ++i)
{
if (players[i].second < players[idx].second)
idx = i;
}
cout << players[idx].first << "\n";
}<file_sep>class Solution
{
public:
vector<int> spiralOrder(vector<vector<int>> &matrix)
{
if (matrix.size() == 0)
return {};
int h_start = 0, h_end = matrix[0].size() - 1;
int v_start = 0, v_end = matrix.size() - 1;
vector<int> ret;
while (true)
{
if (h_start > h_end)
break;
for (int i = h_start; i <= h_end; ++i)
ret.emplace_back(matrix[v_start][i]);
++v_start;
if (v_start > v_end)
break;
for (int i = v_start; i <= v_end; ++i)
ret.emplace_back(matrix[i][h_end]);
--h_end;
if (h_start > h_end)
break;
for (int i = h_end; i >= h_start; --i)
ret.emplace_back(matrix[v_end][i]);
--v_end;
if (v_start > v_end)
break;
for (int i = v_end; i >= v_start; --i)
ret.emplace_back(matrix[i][h_start]);
++h_start;
}
return ret;
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_set>
#include <queue>
#include <list>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int N; // the total number of nodes in the level, including the gateways
int L; // the number of links
int E; // the number of exit gateways
void bfs(int src, vector<list<int>> &g, unordered_set<int> gw, int &start, int &end)
{
queue<int> Q;
Q.push(src);
vector<bool> vis(N, false);
while (!Q.empty())
{
int sz = Q.size();
for (int i = 0; i < sz; ++i)
{
int s = Q.front();
Q.pop();
vis[s] = true;
auto it = g[s].begin();
for (; it != g[s].end(); ++it)
{
if (gw.find(*it) != gw.end())
{
start = s;
end = *it;
g[s].erase(it); // sever the link
return;
}
if (!vis[*it])
Q.push(*it);
}
}
}
}
int main()
{
cin >> N >> L >> E;
cin.ignore();
vector<list<int>> G(N);
unordered_set<int> gateway;
for (int i = 0; i < L; i++)
{
int N1; // N1 and N2 defines a link between these nodes
int N2;
cin >> N1 >> N2;
cin.ignore();
G[N1].push_back(N2);
G[N2].push_back(N1);
}
for (int i = 0; i < E; i++)
{
int EI; // the index of a gateway node
cin >> EI;
cin.ignore();
gateway.insert(EI);
}
// game loop
int x, y;
while (1)
{
int SI; // The index of the node on which the Skynet agent is positioned this turn
cin >> SI;
cin.ignore();
x = y = 0;
bfs(SI, G, gateway, x, y);
cout << x << " " << y << endl;
}
}<file_sep>// non-iterative & non-recursive O(1) solution
class Solution
{
public:
bool isPowerOfThree(int n)
{
return (n > 0 && 1162261467 % n == 0);
}
};
// recursive solution
class Solution
{
public:
bool isPowerOfThree(int n)
{
return n > 0 ? (n > 1 ? (n % 3 != 0 ? false : isPowerOfThree(n / 3)) : true) : false;
}
};
// iterative solution
class Solution
{
public:
bool isPowerOfThree(int n)
{
if (n <= 0)
return false;
while (n > 1)
{
if ((n % 3) != 0)
return false;
n /= 3;
}
return true;
}
};<file_sep>// better solution
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7
class Solution
{
public:
int rand10()
{
int result = 0;
while (true)
{
result = (rand7() - 1) * 7 + rand7();
if (result <= 40)
return (result - 1) % 10 + 1;
result -= 40;
result = (result - 1) * 7 + rand7();
if (result <= 60)
return (result - 1) % 10 + 1;
result -= 60;
result = (result - 1) * 7 + rand7();
if (result <= 20)
return (result - 1) % 10 + 1;
}
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// simple solution
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7
class Solution
{
public:
int rand10()
{
int result = 0;
do
{
result = (rand7() - 1) * 7 + rand7();
} while (result > 40);
return 1 + ((result - 1) % 10);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
*
*
* while(x) {
cerr<<"\n ---------- "<<i<<" :: "<<x<<" -> "<<ct<<" : "<<prev_ct<<"\n";
int rem = x%10;
int m = rem%i;
++ct;
while(x && rem%i == m) {
x /= 10;
rem = x%10;
}
}
*
**/
int getInt(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
return 0;
}
int getClump(string N)
{
int ct = 0, prev_ct = 1, len = N.length();
for (int i = 2; i <= 9; ++i)
{
ct = 0;
for (int j = 0; j < len; ++j)
{
++ct;
int m = getInt(N[j]) % i;
while (j < len && getInt(N[j]) % i == m)
{
++j;
}
--j;
}
if (prev_ct > ct)
return i;
prev_ct = ct;
}
return -1;
}
int main()
{
string N;
getline(cin, N);
int res = getClump(N);
if (res == -1)
cout << "Normal\n";
else
cout << res << "\n";
}<file_sep>// solution using KMP lps array
class Solution
{
public:
bool repeatedSubstringPattern(string s)
{
int n = s.length();
vector<int> lps(n, 0);
int i = 1, len = 0;
while (i < n)
{
if (s[i] == s[len])
lps[i++] = ++len;
else
{
if (len > 0)
len = lps[len - 1];
else
lps[i++] = 0;
}
}
return lps[n - 1] > 0 && n % (n - lps[n - 1]) == 0;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// simple solution
class Solution
{
public:
bool repeatedSubstringPattern(string s)
{
return (s + s).substr(1, 2 * s.length() - 2).find(s) != string::npos;
}
};
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
void transpose(vector<string> &g)
{
for (int i = 0; i < g.size() - 1; ++i)
{
for (int j = i + 1; j < g[i].size(); ++j)
{
swap(g[i][j], g[j][i]);
}
}
}
void reverseRows(vector<string> &g)
{
for (int i = 0; i < g.size(); ++i)
reverse(g[i].begin(), g[i].end());
}
void rotateLeft(vector<string> &g)
{
reverseRows(g);
transpose(g);
}
void rotateRight(vector<string> &g)
{
transpose(g);
reverseRows(g);
}
void printPat(vector<string> g)
{
int n = g.size();
int num_spaces = g.size() - 1;
int ct = 1;
while (ct <= n)
{
for (int i = 0; i < num_spaces; ++i)
cout << " ";
int j = 0;
for (int i = ct - 1; i >= 0; --i)
{
cout << g[i][j];
if (i > 0)
cout << " ";
++j;
}
for (int i = 0; i < num_spaces; ++i)
cout << " ";
cout << "\n";
++ct;
--num_spaces;
}
ct -= 2;
num_spaces = 1;
while (ct > 0)
{
for (int i = 0; i < num_spaces; ++i)
cout << " ";
int j = n - ct;
for (int i = n - 1; i > n - ct - 1; --i)
{
cout << g[i][j];
if (i > n - ct)
cout << " ";
++j;
}
for (int i = 0; i < num_spaces; ++i)
cout << " ";
cout << "\n";
--ct;
++num_spaces;
}
}
int main()
{
int size;
cin >> size;
cin.ignore();
int angle;
cin >> angle;
cin.ignore();
vector<string> grid(size);
angle %= 360;
int rot_ct = angle / 45;
for (int i = 0; i < size; i++)
{
string p;
for (int i = 0; i < size; ++i)
{
char c;
cin >> c;
p += c;
}
grid[i] = p;
}
switch (rot_ct)
{
case 1:
rotateLeft(grid);
break;
case 3:
rotateRight(grid);
rotateRight(grid);
break;
case 5:
rotateRight(grid);
break;
default:
break;
}
printPat(grid);
}<file_sep>class Solution
{
public:
string validIPAddress(string IP)
{
int dot_count = 0, colon_count = 0;
for (char &c : IP)
{
if (c == '.')
++dot_count;
if (c == ':')
++colon_count;
}
stringstream S(IP);
string tmp;
int val = 0, count = 0;
if (dot_count == 3 && colon_count == 0)
{ // possible IPv4
while (getline(S, tmp, '.'))
{
for (char &c : tmp)
if (!isdigit(c))
return "Neither";
if (tmp.length() == 0 || tmp.length() > 3 || (tmp[0] == '0' && tmp.length() > 1) || stoi(tmp) > 255)
return "Neither";
++count;
}
return count == 4 ? "IPv4" : "Neither";
}
else if (dot_count == 0 && colon_count == 7)
{ // possible IPv6
while (getline(S, tmp, ':'))
{
for (char &c : tmp)
if (!isdigit(c) && !(tolower(c) >= 'a' && tolower(c) <= 'f'))
return "Neither";
stringstream ss;
ss << hex << tmp;
ss >> val;
if (tmp.length() > 4 || tmp.length() == 0 || val > 65535)
return "Neither";
++count;
}
return count == 8 ? "IPv6" : "Neither";
}
return "Neither";
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int countSplits(vector<int> &nums, long long int largestSum)
{
long long int count = 1, tmp_sum = 0;
for (int &n : nums)
{
if (tmp_sum + n > largestSum)
{
++count;
tmp_sum = n;
}
else
tmp_sum += n;
}
return count;
}
int splitArray(vector<int> &nums, int m)
{
long long int l = INT_MIN, r = 0, mid = 0;
for (int &n : nums)
{
l = max(l, (long long int)n);
r += n;
}
while (l < r)
{
mid = l + ((r - l) >> 1);
if (countSplits(nums, mid) > m)
l = mid + 1;
else
r = mid;
}
return l;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int N;
cin >> N; cin.ignore();
int try_limit = N/5;
int trans_limit = try_limit;
int pen_limit = N/3;
for(int t=0; t<=try_limit; ++t) {
for(int ts=0; ts<=t; ++ts) {
for(int p=0; p<=pen_limit; ++p) {
if(t*5+ts*2+p*3 == N) {
cout<<t<<" "<<ts<<" "<<p<<"\n";
}
}
}
}
}<file_sep>class Solution
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
int l = 0, r = numbers.size() - 1;
while (l < r)
{
if (numbers[l] + numbers[r] == target)
return {l + 1, r + 1};
else if (numbers[l] + numbers[r] < target)
++l;
else
--r;
}
return {};
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int N;
cin >> N; cin.ignore();
priority_queue<int, vector<int>, greater<int>> cards;
int c;
for (int i = 0; i < N; i++) {
cin >> c; cin.ignore();
cards.push(c);
}
int sum=0, total_sum = 0;
while(!cards.empty()) {
if(!cards.empty()) {
sum = cards.top();
cards.pop();
}
if(!cards.empty()) {
sum += cards.top();
cards.pop();
}
total_sum += sum;
if(cards.empty()) break;
cards.push(sum);
}
cout<<total_sum<<"\n";
}<file_sep>class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t result = 0;
forint i = 0;
i < (32; ++i) {
if ((1 << i) & n) {
result |= (1 << (31 - i));
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>class Solution
{
public:
bool canConstruct(string ransomNote, string magazine)
{
vector<int> mem(128, 0);
for (char &c : magazine)
++mem[c];
for (char &c : ransomNote)
{
if (mem[c] > 0)
--mem[c];
else
return false;
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Trie
{
public:
/** Initialize your data structure here. */
bool isWord;
Trie *children[26];
Trie()
{
this->isWord = false;
memset(this->children, NULL, sizeof(this->children));
}
/** Inserts a word into the trie. */
void insert(string word)
{
Trie *cur = this;
int idx = -1;
for (int i = 0; i < word.length(); ++i)
{
idx = word[i] - 'a';
if (cur->children[idx] == NULL)
{
cur->children[idx] = new Trie();
}
cur = cur->children[idx];
}
cur->isWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word, bool checkEnd = true)
{
Trie *cur = this;
int idx = -1;
for (int i = 0; i < word.length(); ++i)
{
idx = word[i] - 'a';
if (cur->children[idx] == NULL)
{
return false;
}
cur = cur->children[idx];
}
return cur->isWord || !checkEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix)
{
return this->search(prefix, false);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/<file_sep>class Solution {
public:
void letterCasePermutationUtil(string &s, vector<string> &result,
int idx = 0) {
if (idx == s.length()) {
result.emplace_back(s);
return;
}
letterCasePermutationUtil(s, result, idx + 1);
if (isalpha(s[idx])) {
s[idx] ^= 32;
letterCasePermutationUtil(s, result, idx + 1);
}
}
vector<string> letterCasePermutation(string S) {
vector<string> result;
letterCasePermutationUtil(S, result);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
vector<int> multiplyVectors(vector<int> a, vector<int> b)
{
vector<int> result(a.size() + b.size(), 0);
for (int i = a.size() - 1; i >= 0; --i)
{
for (int j = b.size() - 1; j >= 0; --j)
{
result[i + j + 1] += a[i] * b[j];
result[i + j] += result[i + j + 1] / 10;
result[i + j + 1] %= 10;
}
}
if (result[0] == 0)
result.erase(result.begin());
return result;
}
vector<int> getVector(int &n)
{
vector<int> result;
while (n)
{
result.push_back(n % 10);
n /= 10;
}
reverse(result.begin(), result.end());
return result;
}
vector<int> getFactorial(int n)
{
if (n <= 1)
return {1};
return multiplyVectors(getVector(n), getFactorial(n - 1));
}
int getFactorialDigitSum(int &n)
{
vector<int> fact = getFactorial(n);
return accumulate(fact.begin(), fact.end(), 0);
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
cout << getFactorialDigitSum(n) << "\n";
}
return 0;
}
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <set>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Tribute {
public:
string name;
string killer;
set<string> killed;
Tribute(string name) {
this->name = name;
this->killer = "Winner";
}
void killedTribute(string name) {
this->killed.insert(name);
}
void killedBy(string name) {
this->killer = name;
}
void print() {
cout<<"Name: "<<this->name<<"\n";
cout<<"Killed: ";
if(this->killed.size() == 0) cout<<"None\n";
else {
auto it = this->killed.begin();
for(it=this->killed.begin(); it!=this->killed.end(); ++it) {
if(next(it) == this->killed.end()) cout<<(*it)<<"\n";
else cout<<(*it)<<", ";
}
}
cout<<"Killer: "<<this->killer<<"\n";
}
};
int main()
{
int tributes;
cin >> tributes; cin.ignore();
unordered_map<string, Tribute> T;
for (int i = 0; i < tributes; i++) {
string playerName;
getline(cin, playerName);
Tribute obj(playerName);
T.insert({playerName, obj});
}
int turns;
cin >> turns; cin.ignore();
for (int i = 0; i < turns; i++) {
string info;
getline(cin, info);
size_t pos = info.find(' ');
string killer_name = info.substr(0, pos);
auto killer_it = T.find(killer_name);
pos = info.find(' ', pos+1);
string killed_name_list = info.substr(pos+1, info.length()-pos-1);
size_t cur_pos = 0;
pos = 0;
pos = killed_name_list.find(',');
while(pos != string::npos) {
string killed_name = killed_name_list.substr(cur_pos, pos - cur_pos);
cur_pos = pos+2;
auto killed_it = T.find(killed_name);
killer_it->second.killedTribute(killed_name);
killed_it->second.killedBy(killer_name);
pos = killed_name_list.find(',', pos+1);
}
string killed_name = killed_name_list.substr(cur_pos, pos - cur_pos);
auto killed_it = T.find(killed_name);
killer_it->second.killedTribute(killed_name);
killed_it->second.killedBy(killer_name);
}
vector<Tribute> op;
for_each(T.begin(), T.end(), [&op](const pair<string, Tribute> &o){
op.push_back(o.second);
});
sort(op.begin(), op.end(), [](const Tribute &o1, const Tribute &o2){
return o1.name < o2.name;
});
for(int i=0; i<op.size(); ++i) {
op[i].print();
if(i+1 < op.size()) cout<<"\n";
}
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
string getPos(int row, int col)
{
string ret(1, col + 'a');
ret += (8 - row) + '0';
return ret;
}
void posToIdx(string pos, int &row, int &col)
{
col = pos[0] - 'a';
row = 8 - (pos[1] - '0');
}
int main()
{
string rookPosition;
cin >> rookPosition;
cin.ignore();
int nbPieces;
cin >> nbPieces;
cin.ignore();
vector<string> result;
unordered_map<string, int> oPieces;
vector<string> kills;
int i = 0, j = 0;
posToIdx(rookPosition, i, j);
int row_left = 0, row_right = 7, col_up = 0, col_down = 7;
int t_x = 0, t_y = 0;
for (int ind = 0; ind < nbPieces; ind++)
{
int colour;
string onePiece;
cin >> colour >> onePiece;
cin.ignore();
oPieces.insert({onePiece, colour});
posToIdx(onePiece, t_x, t_y);
if (t_x == i)
{ // same row
if (t_y < j)
{ // to the left of rook
if (colour == 0)
++t_y;
row_left = max(row_left, t_y);
}
else
{ // to the right of rook
if (colour == 0)
--t_y;
row_right = min(row_right, t_y);
}
}
else if (t_y == j)
{ // same col
if (t_x < i)
{ // above the rook
if (colour == 0)
++t_x;
col_up = max(col_up, t_x);
}
else
{ // below the rook
if (colour == 0)
--t_x;
col_down = min(col_down, t_x);
}
}
}
cerr << row_left << " :: " << row_right << " -> " << col_up << " :: " << col_down << "\n";
for (int cols = row_left; cols <= row_right; ++cols)
{
if (cols == j)
{ // consider all rows
for (int rows = col_down; rows >= col_up; --rows)
{
if (rows == i)
continue;
// row -> rows
// col -> cols
string op = getPos(rows, cols);
if (oPieces.find(op) == oPieces.end())
cout << "R" << rookPosition << "-" << op << "\n";
else if (oPieces[op] == 1)
kills.push_back("R" + rookPosition + "x" + op);
}
}
else
{
// row -> i
// col -> cols
string op = getPos(i, cols);
if (oPieces.find(op) == oPieces.end())
cout << "R" << rookPosition << "-" << op << "\n";
else if (oPieces[op] == 1)
kills.push_back("R" + rookPosition + "x" + op);
}
}
for (auto k : kills)
cout << k << "\n";
}<file_sep>// O(1) solution
class Solution
{
public:
int rob(vector<int> &nums)
{
int incl = 0, excl = 0, tmp;
for (int &n : nums)
{
tmp = incl;
incl = max(incl, n + excl);
excl = tmp;
}
return max(incl, excl);
}
};
// iterative DP solution
class Solution
{
public:
int rob(vector<int> &nums)
{
vector<int> tab(nums.size() + 2);
tab[nums.size()] = tab[nums.size() + 1] = 0;
for (int i = nums.size() - 1; i >= 0; --i)
{
tab[i] = max(nums[i] + tab[i + 2], tab[i + 1]);
}
return tab[0];
}
};
// recursive approach with memoization
class Solution
{
public:
unordered_map<int, int> MEM;
int robUtil(vector<int> &nums, int idx)
{
if (idx >= nums.size())
return 0;
if (MEM.count(idx))
return MEM[idx];
int including_cur = nums[idx] + robUtil(nums, idx + 2);
int excluding_cur = robUtil(nums, idx + 1);
int result = max(including_cur, excluding_cur);
MEM[idx] = result;
return result;
}
int rob(vector<int> &nums)
{
return robUtil(nums, 0);
}
};
<file_sep>// solved on lintcode: https://www.lintcode.com/problem/paint-house-ii/description
class Solution
{
public:
/**
* @param costs: n x k cost matrix
* @return: an integer, the minimum cost to paint all houses
*/
int minCostII(vector<vector<int>> &costs)
{
// write your code here
if (costs.size() == 0)
return 0;
if (costs.size() == 1)
return *min_element(costs[0].begin(), costs[0].end());
pair<int, int> minTab; // stores the minimum and second minimum of each preceeding row
int first_min = 0, second_min = 0;
for (int i = 0; i < costs.size(); ++i)
{
first_min = 0, second_min = 1;
for (int j = 0; j < costs[i].size(); ++j)
{
if (i > 0)
{
if (j == minTab.first)
{
costs[i][j] += costs[i - 1][minTab.second];
}
else
{
costs[i][j] += costs[i - 1][minTab.first];
}
}
if (costs[i][first_min] > costs[i][j])
{
second_min = first_min;
first_min = j;
}
else if (costs[i][second_min] > costs[i][j] && j != first_min)
{
second_min = j;
}
}
minTab = {first_min, second_min};
}
return *min_element(costs[costs.size() - 1].begin(), costs[costs.size() - 1].end());
}
};
<file_sep>class Solution
{
public:
vector<int> mostCompetitive(vector<int> &nums, int k)
{
int n = nums.size(), j = 0;
vector<int> result(k);
for (int i = 0; i < n; ++i)
{
while (j && result[j - 1] > nums[i] && j + n - i - 1 >= k)
--j;
if (j < k)
result[j++] = nums[i];
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
bool checkStraightLine(vector<vector<int>> &coordinates)
{
if (coordinates.size() <= 2)
return true;
int a = 0, b = 0;
for (int i = 1; i < coordinates.size() - 1; ++i)
{
a = (coordinates[i + 1][0] - coordinates[0][0]) * (coordinates[i][1] - coordinates[0][1]);
b = (coordinates[i][0] - coordinates[0][0]) * (coordinates[i + 1][1] - coordinates[0][1]);
if (a != b)
return false;
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
ll getValue(vector<ll> &A, ll y, ll k)
{
ll s = 0;
for (ll i = 0; i < A.size(); ++i)
{
s += max(A[i] - y * (i + 1), (ll)0);
}
return s;
}
int main()
{
int t = 0, n = 0;
ll k = 0;
cin >> t;
while (t--)
{
cin >> n >> k;
vector<ll> A(n, 0);
for (int i = 0; i < n; ++i)
cin >> A[i];
ll l = 0, r = 1e12, mid = 0;
ll s = 0;
ll ans = 0, val = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
s = getValue(A, mid, k);
if (s >= k)
{
ans = mid;
val = s;
l = mid + 1;
}
else
r = mid - 1;
}
cout << ans << " " << val << "\n";
}
return 0;
}<file_sep>class Solution {
public:
int numFactoredBinaryTrees(vector<int> &arr) {
long result = 0, div = 0, MOD = 1e9 + 7;
unordered_map<int, long> mem;
sort(arr.begin(), arr.end());
for (int &a : arr)
mem[a] = 1;
for (int i = 0; i < arr.size(); ++i) {
for (int j = 0; j < i; ++j) {
if (arr[i] % arr[j] == 0) {
div = arr[i] / arr[j];
if (mem.count(div))
mem[arr[i]] = (mem[arr[i]] + mem[arr[j]] * mem[div]) % MOD;
}
}
}
for (auto &m : mem) {
result += m.second;
if (result >= MOD)
result -= MOD;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>// an even better approach
class Solution
{
public:
vector<bool> canMakePaliQueries(string s, vector<vector<int>> &queries)
{
vector<bool> result;
vector<int> tab(s.length() + 1, 0);
for (int i = 0; i < s.length(); ++i)
tab[i + 1] = tab[i] ^ (1 << (s[i] - 'a'));
for (auto q : queries)
result.push_back(((bitset<26>(tab[q[1] + 1] ^ tab[q[0]]).count()) >> 1) <= q[2]);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// a better approach
class Solution
{
public:
vector<bool> canMakePaliQueries(string s, vector<vector<int>> &queries)
{
if (queries.size() == 0)
return {};
vector<bool> result;
vector<vector<bool>> tab(s.length() + 1, vector<bool>(26, false));
int ct = 0;
for (int i = 0; i < s.length(); ++i)
{
for (int j = 0; j < 26; ++j)
{
tab[i + 1][j] = tab[i][j];
}
tab[i + 1][s[i] - 'a'] = tab[i + 1][s[i] - 'a'] ^ true;
}
for (auto q : queries)
{
ct = 0;
for (int i = 0; i < 26; ++i)
{
ct += (tab[q[1] + 1][i] ^ tab[q[0]][i]) ? 1 : 0;
}
result.push_back(((ct >> 1) <= q[2]));
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// normal approach
class Solution
{
public:
vector<bool> canMakePaliQueries(string s, vector<vector<int>> &queries)
{
if (queries.size() == 0)
return {};
vector<bool> result;
vector<vector<int>> tab(s.length() + 1, vector<int>(26, 0));
int ct = 0;
for (int i = 0; i < s.length(); ++i)
{
for (int j = 0; j < 26; ++j)
{
tab[i + 1][j] = tab[i][j];
}
++tab[i + 1][s[i] - 'a'];
}
for (auto q : queries)
{
ct = 0;
for (int i = 0; i < 26; ++i)
{
ct += ((tab[q[1] + 1][i] - tab[q[0]][i]) % 2);
}
result.push_back(((ct >> 1) <= q[2]));
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
bool canPlaceFlowers(vector<int> &flowerbed, int n)
{
bool prev = false, next = false;
int last_flower_idx = -2, count = 0;
for (int i = 0; i < flowerbed.size(); ++i)
{
if (flowerbed[i] == 1)
last_flower_idx = i;
else
{
prev = i > 0 ? flowerbed[i - 1] == 0 : true;
next = i < flowerbed.size() - 1 ? flowerbed[i + 1] == 0 : true;
if (prev && next && i - last_flower_idx > 1)
{
last_flower_idx = i;
++count;
}
}
if (count >= n)
return true;
}
return false;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
-cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was recently asked by Google.
* Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
* For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
* Bonus: Can you do this in one pass?
*
* Online Judge: https://leetcode.com/problems/two-sum/
*
*/
class Solution
{
public:
vector<int> twoSum(vector<int> &nums, int target)
{
unordered_map<int, int> H;
for (int i = 0; i < nums.size(); ++i)
{
if (H.find(target - nums[i]) != H.end())
return {H[target - nums[i]], i};
H.insert({nums[i], i});
}
return {0, 0};
}
};<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int x = 0, y = 0, s = 0, t = 0, count = 0;
cin >> x >> y >> s >> t;
for (int i = x; i <= x + s; ++i)
{
for (int j = y; j <= y + s; ++j)
{
if (i + j <= t)
++count;
}
}
cout << count;
return 0;
}<file_sep>class Solution
{
public:
string addBinary(string a, string b)
{
if (a.length() == 0)
return b;
if (b.length() == 0)
return a;
if (a.length() < b.length())
return addBinary(b, a);
string ret(a.length() + 1, '0');
int i = a.length() - 1, j = b.length() - 1;
int val = 0, carry = 0;
while (i >= 0)
{
val = (a[i] - '0') + (j >= 0 ? b[j] - '0' : 0) + carry;
carry = val / 2;
ret[i + 1] = val % 2 + '0';
--i;
--j;
}
if (carry)
{
ret[0] = '1';
return ret;
}
return ret.substr(1, a.length());
}
};<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
ll getPrice(vector<int> &B, ll ct)
{
vector<ll> tmp(B.size(), 0);
for (int i = 0; i < B.size(); ++i)
{
tmp[i] = B[i] + ct * (i + 1);
}
sort(tmp.begin(), tmp.end());
ll sum = accumulate(tmp.begin(), tmp.begin() + ct, 0);
return sum;
}
int main()
{
int n = 0;
ll sp = 0;
cin >> n >> sp;
vector<int> B(n, 0);
for (int i = 0; i < n; ++i)
cin >> B[i];
ll l = 0, r = n, mid = 0;
ll val = 0, ans = 0, price = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
val = getPrice(B, mid);
if (val <= sp)
{
l = mid + 1;
ans = mid;
price = val;
}
else
r = mid - 1;
}
cout << ans << " " << price << "\n";
return 0;
}<file_sep>class Solution
{
public:
int getMinRotations(vector<int> &A, vector<int> &B, int x)
{
int aRot = 0, bRot = 0;
for (int i = 0; i < A.size(); ++i)
{
if (A[i] != x && B[i] != x)
return -1;
if (A[i] == x && B[i] != x)
++bRot;
if (A[i] != x && B[i] == x)
++aRot;
}
return min(aRot, bRot);
}
int minDominoRotations(vector<int> &A, vector<int> &B)
{
int a = getMinRotations(A, B, A[0]);
int b = getMinRotations(A, B, B[0]);
if (a == -1)
return b;
else if (b == -1)
return a;
return min(a, b);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// O(n) solution
class Solution {
public:
int findLHS(vector<int> &nums) {
int result = 0;
unordered_set<int> mem;
unordered_map<int, int> freq;
for (int &n : nums) {
++freq[n];
mem.insert(n);
}
for (int e : mem) {
if (freq.count(e - 1)) {
result = max(result, freq[e] + freq[e - 1]);
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(nlogn) solution with constant space
class Solution {
public:
int findLHS(vector<int> &nums) {
int result = 0, prev_count = 1, count = 0;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); ++i) {
count = 1;
if (i > 0 && nums[i] - nums[i - 1] == 1) {
while (i < nums.size() - 1 && nums[i] == nums[i + 1]) {
++i;
++count;
}
result = max(result, count + prev_count);
} else {
while (i < nums.size() - 1 && nums[i] == nums[i + 1]) {
++i;
++count;
}
}
prev_count = count;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>// iterative solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void flatten(TreeNode *root)
{
stack<TreeNode *> S;
TreeNode *cur = root;
TreeNode *prev = NULL;
while (cur || !S.empty())
{
while (cur)
{
if (prev)
{
prev->right = cur;
prev->left = NULL;
}
prev = cur;
if (cur->right)
S.push(cur->right);
cur = cur->left;
}
if (S.size())
{
cur = S.top();
S.pop();
}
}
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// recursive solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
TreeNode *prev;
public:
void flatten(TreeNode *root)
{
if (!root)
return;
flatten(root->right);
flatten(root->left);
root->right = prev;
root->left = NULL;
prev = root;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
string countAndSayUtil(string num)
{
string ret;
int ct = 1;
for (int i = 0; i < num.length(); ++i)
{
ct = 1;
while (i + 1 < num.length() && num[i] == num[i + 1])
{
++ct;
++i;
}
ret += to_string(ct) + string(1, num[i]);
}
return ret;
}
string countAndSay(int n)
{
if (n == 1)
return "1";
string s = "1";
while (--n)
s = countAndSayUtil(s);
return s;
}
};<file_sep>class Solution {
public:
int distributeCandies(vector<int> &candyType) {
return min(unordered_set<int>(candyType.begin(), candyType.end()).size(),
(candyType.size() >> 1));
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>#include <bits/stdc++.h>
using namespace std;
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
int main()
{
int n = 0, q = 0, ele = 0, x = 0, y = 0, min_dist = 0, d = 0, p = 0;
cin >> n >> q;
vector<vector<int>> MEM(100001, vector<int>());
for (int i = 0; i < n; ++i)
{
cin >> ele;
MEM[ele].emplace_back(i + 1);
}
while (q--)
{
cin >> x >> y;
min_dist = INT_MAX;
for (int &pos : MEM[x])
{
p = lower_bound(MEM[y].begin(), MEM[y].end(), pos) - MEM[y].begin();
if (p == 0)
{
d = min(MEM[y][p] - pos, pos + n - MEM[y][MEM[y].size() - 1]);
min_dist = min(min_dist, d >> 1);
}
else if (p == MEM[y].size())
{
d = min(pos - MEM[y][p - 1], MEM[y][0] + n - pos);
min_dist = min(min_dist, d >> 1);
}
else
{
d = min(MEM[y][p] - pos, pos + n - MEM[y][MEM[y].size() - 1]);
min_dist = min(min_dist, d >> 1);
d = min(pos - MEM[y][p - 1], MEM[y][0] + n - pos);
min_dist = min(min_dist, d >> 1);
}
}
cout << min_dist << "\n";
}
return 0;
}<file_sep>class Solution
{
public:
int numDecodings(string s)
{
int MOD = 1e9 + 7, n = s.length(), result = 0, prev = 1, p_prev = 0;
for (int i = 0; i < n; ++i)
{
if (s[i] == '*')
{
result = (9 * prev) % MOD;
if (i > 0)
{
if (s[i - 1] == '1')
result += (9 * p_prev) % MOD;
if (s[i - 1] == '2')
result += (6 * p_prev) % MOD;
if (s[i - 1] == '*')
result += (15 * p_prev) % MOD;
}
}
else
{
if (s[i] > '0')
result = prev;
if (i > 0 && (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] < '7')))
result += p_prev;
if (i > 0 && s[i - 1] == '*')
result += (((s[i] < '7') ? 2 : 1) * p_prev) % MOD;
}
result %= MOD;
p_prev = prev % MOD;
prev = result % MOD;
result = 0;
}
return prev;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// a better dp approach
// extension of largest rectangle in histogram
class Solution
{
public:
int maximalRectangleUtil(vector<int> &heights)
{
int result = 0, cur = 0;
stack<int> S;
S.push(-1);
for (int i = 0; i < heights.size(); ++i)
{
while (S.size() > 1 && heights[i] < heights[S.top()])
{
cur = S.top();
S.pop();
result = max(result, (i - (S.top() + 1)) * heights[cur]);
}
S.push(i);
}
return result;
}
int maximalRectangle(vector<vector<char>> &matrix)
{
if (matrix.empty())
return 0;
int m = matrix.size(), n = matrix[0].size();
vector<int> heights(n + 1, 0);
int result = 0;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (matrix[i][j] == '1')
++heights[j];
else
heights[j] = 0;
}
result = max(result, maximalRectangleUtil(heights));
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
int n = 0, q = 0;
cin >> n >> q;
vector<ll> L(n, 0);
vector<ll> R(n, 0);
vector<ll> range(n, 0);
for (int i = 0; i < n; ++i)
{
cin >> L[i] >> R[i];
range[i] = R[i] - L[i] + 1;
if (i > 0)
range[i] += range[i - 1];
}
ll k = 0;
int pos = -1;
while (q--)
{
cin >> k;
pos = lower_bound(range.begin(), range.end(), k) - range.begin();
if (pos == 0)
{
cout << L[0] + k - 1 << "\n";
}
else
{
cout << L[pos] + (abs(range[pos - 1] - k)) - 1 << "\n";
}
}
return 0;
}<file_sep>class Solution
{
public:
int minSwap(vector<int> &A, vector<int> &B)
{
int w1 = 0, w2 = 0, s1 = 1, s2 = 0;
for (int i = 1; i < A.size(); ++i)
{
w2 = s2 = 2001;
if (A[i] > A[i - 1] && B[i] > B[i - 1])
{
w2 = w1;
s2 = 1 + s1;
}
if (A[i] > B[i - 1] && B[i] > A[i - 1])
{
w2 = min(w2, s1);
s2 = min(s2, 1 + w1);
}
w1 = w2;
s1 = s2;
}
return min(w1, s1);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
bool isPerfectSquare(int num)
{
long l = 1, r = num, mid = 0, sq = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
sq = mid * mid;
if (sq == num)
return true;
else if (sq < num)
l = mid + 1;
else
r = mid - 1;
}
return false;
}
};<file_sep>#include <bits/stdc++.h>
using namespace std;
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
int main()
{
long long int n = 0, count = 0, ct = 0;
cin >> n;
string s;
cin >> s;
if (s.length() < 4)
{
cout << "0";
return 0;
}
unordered_map<char, long long> MEM1;
unordered_map<char, long long> MEM2;
for (int i = 0; i < n; ++i)
{
if (MEM1.count(s[i]))
{
if (MEM2.count(s[i]))
{
count += MEM2[s[i]];
}
ct = 1;
for (int j = MEM1[s[i]] + 1; j < i; ++j)
{
if (MEM2.count(s[j]))
MEM2[s[j]] += ct;
else
MEM2[s[j]] = ct;
if (s[j] == s[i])
++ct;
}
}
else
{
MEM1[s[i]] = i;
}
}
cout << count;
return 0;
}
Language : C++ 14
<file_sep>class Solution
{
public:
int thirdMax(vector<int> &nums)
{
long first_max = LONG_MIN, second_max = LONG_MIN, third_max = LONG_MIN;
for (int &n : nums)
{
if (n == first_max || n == second_max || n == third_max)
continue;
if (n > first_max)
{
third_max = second_max;
second_max = first_max;
first_max = n;
}
else if (n > second_max)
{
third_max = second_max;
second_max = n;
}
else if (n > third_max)
third_max = n;
}
if (third_max == LONG_MIN)
return first_max;
return third_max;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
string tolower(string s) {
for(int i=0; i<s.length(); ++i) {
if(s[i] >= 65 && s[i] <= 90) {
s[i] += 32;
}
}
return s;
}
string getExtension(string fname) {
int i;
for(i=fname.length()-1; i>=0; --i) {
if(fname[i] == '.') break;
}
if(i < 0) return "?";
else return tolower(fname.substr(i+1, fname.length()-i-1));
}
int main()
{
int N; // Number of elements which make up the association table.
cin >> N; cin.ignore();
int Q; // Number Q of file names to be analyzed.
cin >> Q; cin.ignore();
unordered_map<string, string> tab;
tab["?"] = "UNKNOWN";
for (int i = 0; i < N; i++) {
string EXT; // file extension
string MT; // MIME type.
cin >> EXT >> MT; cin.ignore();
tab[tolower(EXT)] = MT;
}
for (int i = 0; i < Q; i++) {
string FNAME;
getline(cin, FNAME); // One file name per line.
string ext = getExtension(FNAME);
if(tab.find(ext) != tab.end())
cout<< tab[ext] <<endl;
else
cout<< "UNKNOWN" <<endl;
}
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int N;
cin >> N; cin.ignore();
cout<<".";
int spaces = 2*N-1, stars1=1, stars2=1;
int omit = spaces;
for(int i=0; i<2*N; ++i) {
if(i < N) {
for(int j=1; j<spaces; ++j) cout<<" ";
for(int j=0; j<stars1; ++j) cout<<"*";
stars1 += 2;
}
else {
for(int j=1; j<spaces; ++j) cout<<" ";
for(int j=0; j<stars2; ++j) cout<<"*";
for(int j=0; j<omit; ++j) cout<<" ";
for(int j=0; j<stars2; ++j) cout<<"*";
omit -= 2;
stars2 += 2;
}
if(i>0) --spaces;
cout<<"\n";
}
}<file_sep>class Solution
{
public:
int maxSubArray(vector<int> &nums)
{
if (nums.size() == 1)
return nums[0];
int max_sum = INT_MIN, sum = 0;
for (int n : nums)
{
sum += n;
max_sum = max(max_sum, sum);
if (sum < 0)
sum = 0;
}
return max_sum;
}
};<file_sep>class Solution
{
public:
int ct;
bool isValid(vector<int> &qPos, int val, int col)
{
for (int i = 0; i < col; ++i)
if (qPos[i] == val || abs(i - col) == abs(qPos[i] - val))
return false;
return true;
}
void nQueensUtil(vector<int> &qPos, int col = 0)
{
if (col == qPos.size())
{
++ct;
return;
}
for (int i = 0; i < qPos.size(); ++i)
{
if (isValid(qPos, i, col))
{
qPos[col] = i;
nQueensUtil(qPos, col + 1);
qPos[col] = 0;
}
}
}
int totalNQueens(int n)
{
if (n <= 1)
return 1;
if (n < 4)
return 0;
ct = 0;
vector<int> qPos(n, 0);
nQueensUtil(qPos);
return ct;
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
#define G 3.711
#define MAX_V_SPEED 40
#define MAX_H_SPEED 20
#define MAX_ANGLE 90
#define MAX_POW 4
#define RAD2DEG 57.29578
int main()
{
int surfaceN; // the number of points used to draw the surface of Mars.
cin >> surfaceN;
cin.ignore();
int start_x = -1, start_y = -1;
int end_x = -1, end_y = -1;
bool flag = true;
for (int i = 0; i < surfaceN; i++)
{
int landX; // X coordinate of a surface point. (0 to 6999)
int landY; // Y coordinate of a surface point. By linking all the points together in a sequential fashion, you form the surface of Mars.
cin >> landX >> landY;
cin.ignore();
if (flag)
{
if (start_y == landY)
{
end_x = landX;
end_y = landY;
flag = false;
}
else
{
start_x = landX;
start_y = landY;
}
}
}
int land_x = (start_x + end_x) / 2;
int land_y = start_y;
int landing_x, landing_y;
// game loop
while (1)
{
int X;
int Y;
int hSpeed; // the horizontal speed (in m/s), can be negative.
int vSpeed; // the vertical speed (in m/s), can be negative.
int fuel; // the quantity of remaining fuel in liters.
int rotate; // the rotation angle in degrees (-90 to 90).
int power; // the thrust power (0 to 4).
cin >> X >> Y >> hSpeed >> vSpeed >> fuel >> rotate >> power;
cin.ignore();
int tAngle = 21;
power = 4;
rotate = 0;
int speed = sqrt(hSpeed * hSpeed + vSpeed * vSpeed);
if (X < start_x || X > end_x)
{
if ((X < start_x && hSpeed < 0) || (X > end_x && hSpeed > 0) || abs(hSpeed) > 4.2 * MAX_H_SPEED)
{ // too fast or in the wrong direction
rotate = asin(((double)hSpeed / (double)speed)) * RAD2DEG;
}
else if (abs(hSpeed) < 2 * MAX_H_SPEED)
{ // too slow
rotate = (X < start_x) ? -tAngle : (X > end_x) ? tAngle : 0;
}
else if (vSpeed >= 0)
{
power = 3;
}
}
else
{
if (Y < 200 + land_y)
{
power = 4;
}
else if (abs(hSpeed) <= MAX_H_SPEED && abs(vSpeed) <= MAX_V_SPEED)
{
power = 3;
}
else
{
rotate = asin(((double)hSpeed / (double)speed)) * RAD2DEG;
}
}
if ((abs(X - start_x) < 150 || abs(end_x - X) < 150) && Y > 500 + land_y)
{ // going beyond the surface to the other side
if (asin(((double)hSpeed / (double)speed)) < 0)
rotate = -30;
else
rotate = 30;
}
// rotate power. rotate is the desired rotation angle. power is the desired thrust power.
cout << rotate << " " << power << endl;
}
}<file_sep>class Solution
{
public:
int singleNumber(vector<int> &nums)
{
int single_num = 0;
for (int &n : nums)
single_num ^= n;
return single_num;
}
};<file_sep>class Solution
{
public:
string multiply(string num1, string num2)
{
if (num1[0] == '0' || num2[0] == '0')
return "0";
string M(num1.size() + num2.size(), '0');
int val = 0, mul = 0;
for (int i = num1.size() - 1; i >= 0; --i)
{
val = num1[i] - '0';
for (int j = num2.size() - 1; j >= 0; --j)
{
mul = val * (num2[j] - '0') + (M[i + j + 1] - '0');
M[i + j + 1] = mul % 10 + '0';
M[i + j] += mul / 10;
}
}
for (int i = 0; i < M.length(); ++i)
{
if (M[i] != '0')
return M.substr(i);
}
return M;
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int getNumeral(const vector<vector<string>> &map, const vector<string> &S)
{
for (int i = 0; i < 20; ++i)
if (map[i] == S)
return i;
return 0;
}
vector<int> getMayan(ll num)
{
if (num == 0)
return {0};
vector<int> ret;
int rem = 0;
while (num)
{
rem = num % 20;
num /= 20;
ret.push_back(rem);
}
reverse(ret.begin(), ret.end());
return ret;
}
void printMayan(const vector<vector<string>> &map, ll num)
{
vector<int> t = getMayan(num);
for (int i = 0; i < t.size(); ++i)
{
int idx = t[i];
for (auto ss : map[idx])
cout << ss << "\n";
}
}
int main()
{
int L;
int H;
cin >> L >> H;
cin.ignore();
vector<vector<string>> map(20);
for (int i = 0; i < H; i++)
{
string numeral;
cin >> numeral;
cin.ignore();
for (int j = 0; j < 20; ++j)
{
map[j].push_back(numeral.substr(j * L, L));
}
}
int S1;
cin >> S1;
cin.ignore();
int digits1 = S1 / H;
vector<vector<string>> n1(digits1);
int j = 0;
for (int i = 0; i < S1; i++)
{
string num1Line;
cin >> num1Line;
cin.ignore();
n1[j / H].push_back(num1Line);
++j;
}
int S2;
cin >> S2;
cin.ignore();
int digits2 = S2 / H;
vector<vector<string>> n2(digits2);
j = 0;
for (int i = 0; i < S2; i++)
{
string num2Line;
cin >> num2Line;
cin.ignore();
n2[j / H].push_back(num2Line);
++j;
}
string operation;
cin >> operation;
cin.ignore();
ll o1 = 0;
ll o2 = 0;
for (int i = 0; i < digits1; ++i)
{
o1 += pow((ll)20, digits1 - i - 1) * (ll)getNumeral(map, n1[i]);
}
for (int i = 0; i < digits2; ++i)
{
o2 += pow((ll)20, digits2 - i - 1) * (ll)getNumeral(map, n2[i]);
}
if (operation == "+")
printMayan(map, o1 + o2);
if (operation == "-")
printMayan(map, o1 - o2);
if (operation == "*")
printMayan(map, o1 * o2);
if (operation == "/")
printMayan(map, o1 / o2);
}<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long int
ll getSumSquareDiff(ll n)
{
// returns the difference between the square of sum of first n numbers [1,n]
// and the sum of square of the first n numbers [1,n]
// square of sum of first n numbers = (n*(n+1)/2)^2
// sum of square of first n numbers = n*(n+1)*(2*n+1)/6
// solve the difference to get the formula = n*(3*n^3 + 2*n^2 - 3*n - 2)/12
return ((n * (3 * n * n * n + 2 * n * n - 3 * n - 2)) / 12);
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
ll t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
cout << getSumSquareDiff(n) << "\n";
}
return 0;
}
<file_sep>class Solution
{
public:
string addStrings(string num1, string num2)
{
if (num1.length() < num2.length())
return addStrings(num2, num1);
// num1 is always larger or equal in size to num2
string result(num1.size() + 1, '0');
int i = num1.size() - 1, sum = 0;
for (int j = num2.size() - 1; j >= 0; --j)
{
sum = (num1[i] - '0') + (num2[j] - '0') + (result[i + 1] - '0');
result[i + 1] = sum % 10 + '0';
result[i] += sum / 10;
--i;
}
while (i >= 0)
{
sum = (result[i + 1] - '0') + (num1[i] - '0');
result[i + 1] = sum % 10 + '0';
result[i] += sum / 10;
--i;
}
return result[0] == '0' ? result.substr(1, result.length() - 1) : result;
}
};<file_sep>// solution without converting to string
class Solution
{
public:
int maximum69Number(int num)
{
int last_six = -1, tmp = num, i = 0;
while (tmp)
{
if (tmp % 10 == 6)
last_six = i;
tmp /= 10;
++i;
}
if (last_six == -1)
return num;
num += 3 * pow(10, last_six);
return num;
}
};
// normal solution
class Solution
{
public:
int maximum69Number(int num)
{
string n = to_string(num);
for (int i = 0; i < n.length(); ++i)
if (n[i] == '6')
{
n[i] = '9';
break;
}
return stoi(n);
}
};<file_sep>class Solution
{
public:
int combinationSum4(vector<int> &nums, int target)
{
vector<unsigned int> tab(target + 1, 0);
tab[0] = 1;
for (int i = 1; i <= target; ++i)
{
for (int &n : nums)
{
if (i >= n)
tab[i] += tab[i - n];
}
}
return tab[target];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int numJewelsInStones(string J, string S)
{
unordered_set<char> mem(J.begin(), J.end());
int count = 0;
for (char &c : S)
if (mem.count(c))
++count;
return count;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// O(1) solution
class Solution
{
public:
int arrangeCoins(int n)
{
return sqrt(2 * (long)n + 0.25) - 0.5;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(logN) solution
class Solution
{
public:
int arrangeCoins(int n)
{
int l = 0, r = n, ans = 0;
long mid = 0;
while (l <= r)
{
mid = l + ((r - l) >> 1);
if (((mid * (mid + 1)) >> 1) <= n)
{
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
return ans;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(N) solution
class Solution
{
public:
int arrangeCoins(int n)
{
long long int res = 1;
while (true)
{
if ((res * (res + 1)) >> 1 <= n)
++res;
else
break;
}
return res - 1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
double stringToDouble(string s) {
if(s.find(",") != string::npos)
s.replace(s.find(","), 1, ".");
return stod(s);
}
string getSplit(string s, int c) {
int ind = -1;
while(c--) {
ind = s.find(";", ind+1);
}
if(s.find(";", ind+1) != string::npos)
return s.substr(ind+1, s.find(";", ind+1) - ind-1);
else
return s.substr(ind+1, s.length()-ind);
return "0,0";
}
double getDist(double lat_a, double lon_a, double lat_b, double lon_b) {
double x = (lon_b - lon_a) * cos((lat_a + lat_b)/2);
double y = lat_b - lat_a;
return sqrt(x*x + y*y) * 6371;
}
int main()
{
string LON;
cin >> LON; cin.ignore();
string LAT;
cin >> LAT; cin.ignore();
double lon = stringToDouble(LON);
double lat = stringToDouble(LAT);
int N;
cin >> N; cin.ignore();
string op;
double t_lon, t_lat, t_dist, min_dist = 999999;
for (int i = 0; i < N; i++) {
string DEFIB;
getline(cin, DEFIB);
t_lon = stringToDouble(getSplit(DEFIB, 4));
t_lat = stringToDouble(getSplit(DEFIB, 5));
t_dist = getDist(lat, lon, t_lat, t_lon);
if(t_dist < min_dist) {
min_dist = t_dist;
op = getSplit(DEFIB, 1);
}
}
cout << op << endl;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
ll n = 0, m = 0;
cin >> n >> m;
vector<vector<ll>> tab(n, vector<ll>(m, 0));
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
cin >> tab[i][j];
if (i > 0)
sort(tab[i].begin(), tab[i].end());
}
ll min_diff = LONG_MAX;
vector<ll>::iterator low;
for (int i = 0; i < n - 1; ++i)
{
for (int j = 0; j < m; ++j)
{
low = lower_bound(tab[i + 1].begin(), tab[i + 1].end(), tab[i][j]);
if (*low == tab[i][j])
{
cout << "0\n";
return 0;
}
if (low == tab[i + 1].end())
--low;
min_diff = min(min_diff, abs(tab[i][j] - *low));
if (low != tab[i + 1].begin())
min_diff = min(min_diff, abs(tab[i][j] - *(--low)));
}
}
cout << min_diff << "\n";
return 0;
}<file_sep>// the idea is to use the following rule:
// when n=3, we can get the result based on n=2. 00,01,11,10 -> (000,001,011,010)[already present] (110,111,101,100) [to be found]
class Solution
{
public:
vector<int> grayCode(int n)
{
vector<int> result;
result.push_back(0);
int cur_size = 0;
for (long i = 0; i < n; ++i)
{
cur_size = result.size();
for (int j = cur_size - 1; j >= 0; --j)
{
result.push_back(result[j] | 1 << i);
}
}
return result;
}
};
// alternative solution
class Solution
{
public:
vector<int> grayCode(int n)
{
vector<int> result;
n = powl(2, n);
for (int i = 0; i < n; ++i)
result.push_back((i ^ (i >> 1)));
return result;
}
};<file_sep>#include <bits/stdc++.h>
using namespace std;
int maxValidLength(string &s, int k, char ch)
{
int l = 0, r = 0, max_res = 0, ct = 0;
while (r < s.length())
{
if (s[r] != ch)
++ct;
while (ct > k)
{
if (s[l] != ch)
--ct;
++l;
}
max_res = max(max_res, r - l + 1);
++r;
}
return max_res;
}
int main()
{
int t = 0, n = 0, m = 0;
string s;
cin >> t;
while (t--)
{
cin >> n >> m;
cin >> s;
int ct = 0, max_res = 0;
for (char c = 'a'; c <= 'z'; ++c)
max_res = max(max_res, maxValidLength(s, m, c));
for (char c = 'A'; c <= 'Z'; ++c)
max_res = max(max_res, maxValidLength(s, m, c));
cout << max_res << "\n";
}
return 0;
}<file_sep>class Solution
{
public:
int maximumUnits(vector<vector<int>> &boxTypes, int truckSize)
{
sort(boxTypes.begin(), boxTypes.end(), [](const vector<int> &a, const vector<int> &b) {
return a[1] > b[1];
});
int used = 0, result = 0;
for (int i = 0; i < boxTypes.size() && truckSize > 0; ++i)
{
used = min(truckSize, boxTypes[i][0]);
truckSize -= used;
result += boxTypes[i][1] * used;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
bool isBelowThreshold(vector<int> &nums, int d, int thres)
{
int sum = 0;
for (int &n : nums)
{
sum += ceil((float)n / (float)d);
}
return sum <= thres;
}
int smallestDivisor(vector<int> &nums, int threshold)
{
int l = 1, r = nums[nums.size() - 1], ans = 0, mid = 0; // this assumes that nums[nums.size()-1] is the max element of nums
while (l <= r)
{
mid = l + ((r - l) >> 1);
if (isBelowThreshold(nums, mid, threshold))
{
ans = mid;
r = mid - 1;
}
else
l = mid + 1;
}
return ans;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>"""
#
# Good morning! Here's your coding interview problem for today.
# This problem was asked by Google.
# The area of a circle is defined as PIr^2. Estimate PI to 3 decimal places using a Monte Carlo method.
# Hint: The basic equation of a circle is x2 + y2 = r2.
#
#
# references:
# https://www.youtube.com/watch?v=VJTFfIqO4TU
# https://www.youtube.com/watch?v=5cNnf_7e92Q
#
#
# for a circle of radius "r"
# bounded by a square of side "2r"
# ratio of points which will lie within the circle (area of circle [PI*r^2])
# to that of the points which lie within the square (area of square [4r^2])
# PI*r^2/4*r^2 = PI/4
#
# Hence,
# PI = 4 * (number of points in circle / total number of points)
#
# """
import random
import math
def estimate(num_iterations=1000000, radius=5000):
total = 0
within_circle = 0
PI = 0
BEST_PI = 0
BEST_DIFF = 999
for _ in range(num_iterations):
x = random.randrange(-radius, radius+1)
y = random.randrange(-radius, radius+1)
total += 1
if x*x + y*y < radius*radius:
within_circle += 1
PI = 4.0 * (float(within_circle)/float(total))
if abs(PI - math.pi) < BEST_DIFF:
BEST_PI = PI
print(BEST_PI)
if __name__ == '__main__':
estimate()
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int W; // width of the building.
int H; // height of the building.
cin >> W >> H; cin.ignore();
int N; // maximum number of turns before game over.
cin >> N; cin.ignore();
int X0;
int Y0;
cin >> X0 >> Y0; cin.ignore();
int start_x = 0, start_y = 0;
int end_x = W, end_y = H;
// game loop
while (1) {
string bombDir; // the direction of the bombs from batman's current location (U, UR, R, DR, D, DL, L or UL)
cin >> bombDir; cin.ignore();
if(bombDir == "U") {
end_y = Y0;
Y0 = (Y0+start_y)/2;
}
else if(bombDir == "D") {
start_y = Y0;
Y0 = (Y0+end_y)/2;
}
else if(bombDir == "L") {
end_x = X0;
X0 = (X0+start_x)/2;
}
else if(bombDir == "R") {
start_x = X0;
X0 = (X0+end_x)/2;
}
else if(bombDir == "DL") {
start_y = Y0;
end_x = X0;
Y0 = (Y0+end_y)/2;
X0 = (X0+start_x)/2;
}
else if(bombDir == "DR") {
start_y = Y0;
start_x = X0;
Y0 = (Y0+end_y)/2;
X0 = (X0+end_x)/2;
}
else if(bombDir == "UL") {
end_y = Y0;
end_x = X0;
Y0 = (Y0+start_y)/2;
X0 = (X0+start_x)/2;
}
else if(bombDir == "UR") {
end_y = Y0;
start_x = X0;
Y0 = (Y0+start_y)/2;
X0 = (X0+end_x)/2;
}
cout<<X0<<" "<<Y0<<"\n";
}
}<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Amazon.
* There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
* For example, if N is 4, then there are 5 unique ways:
-----------------
| 1, 1, 1, 1 |
| 2, 1, 1 |
| 1, 2, 1 |
| 1, 1, 2 |
| 2, 2 |
-----------------
*
* What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
*
*
* Online Judge: https://leetcode.com/problems/climbing-stairs/
*
*/
// standard online judge solution
class Solution
{
public:
int climbStairs(int n)
{
if (n == 1)
return 1;
if (n == 2)
return 2;
if (n == 3)
return 3;
n -= 3;
int f = 2, s = 3;
while (n--)
{
s = f + s;
f = s - f;
}
return s;
}
};
// generic solution which handles any number of steps
class Solution
{
public:
int climbStairs(int n)
{
vector<int> steps = {1, 2};
vector<int> tab(n + 1, 0);
for (int i = 0; i < tab.size(); ++i)
{
for (int &s : steps)
{
tab[i] += i - s > 0 ? tab[i - s] : 0;
tab[i] += i == s ? 1 : 0;
}
}
return tab[n];
}
};
<file_sep>// O(n) solution using bucket sort
class Solution
{
public:
bool carPooling(vector<vector<int>> &trips, int capacity)
{
vector<int> tab(1001, 0);
int total = 0;
for (auto &trip : trips)
{
tab[trip[1]] += trip[0];
tab[trip[2]] -= trip[0];
}
for (auto &t : tab)
{
total += t;
if (total > capacity)
return false;
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(nlogn) solution
class Solution
{
public:
bool carPooling(vector<vector<int>> &trips, int capacity)
{
vector<pair<int, int>> tab;
int total = 0;
for (auto &trip : trips)
{
tab.emplace_back(trip[1], trip[0]);
tab.emplace_back(trip[2], -trip[0]);
}
sort(tab.begin(), tab.end());
for (auto &t : tab)
{
total += t.second;
if (total > capacity)
return false;
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
vector<int> sieve;
vector<int> preSum;
void generateSieve()
{
sieve = vector<int>(1000001, 1);
preSum = vector<int>(100001, 0);
sieve[1] = 0;
preSum[0] = 0;
for (int i = 2; i < sieve.size(); ++i)
{
for (int j = i + i; j < sieve.size(); j += i)
{
sieve[j] += i;
}
}
for (int i = 2; i < 100001; ++i)
{
if (sieve[i] != i && sieve[sieve[i]] == i)
{
preSum[i] += i;
}
preSum[i] += preSum[i - 1];
}
}
int getAmicableNumbersSum(int n)
{
return preSum[n];
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
generateSieve();
int t = 0, n = 0;
cin >> t;
while (t--)
{
cin >> n;
cout << getAmicableNumbersSum(n) << "\n";
}
return 0;
}
<file_sep>class Solution
{
public:
#define ll long long int
int nthUglyNumber(int n, ll a, ll b, ll c)
{
ll l = 1, r = 2 * 10e8, mid = 0, res = 0;
ll ab = (a * b) / __gcd(a, b);
ll ac = (a * c) / __gcd(a, c);
ll bc = (b * c) / __gcd(b, c);
ll abc = (a * bc) / __gcd(a, bc);
while (l < r)
{
mid = l + ((r - l) >> 1);
// count(a or b or c) = count(a) + count(b) + count(c) - count(a and b) - count(a and c) - count(b and c) + - count(a and b and c)
res = (mid / a + mid / b + mid / c - mid / ab - mid / ac - mid / bc + mid / abc);
if (res == n)
r = mid;
else if (res < n)
l = mid + 1;
else
r = mid - 1;
}
return r;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>def calc(expression):
try:
print(expression)
prec = {
'+': 1,
'-': 1,
'*': 2,
'/': 2
}
def filter(s):
while "--" in s:
s = s.replace('--', '+')
while "++" in s:
s = s.replace('++', '+')
while "+-" in s:
s = s.replace('+-', '-')
while "/+" in s:
s = s.replace('/+', '/')
while "*+" in s:
s = s.replace('*+', '*')
return s
expression = ''.join(expression.split(' '))
expression = filter(expression)
print(expression)
expression = expression.replace('-', ' - ').replace('+', ' + ').replace(
'*', ' * ').replace('/', ' / ').replace('(', ' ( ').replace(')', ' ) ')
expression = expression.split(' ')
expression = [e for e in expression if len(e) > 0]
print(expression)
def evaluate(left, right, op):
if op == '+':
return left + right
elif op == '-':
return left - right
elif op == '*':
return left * right
elif op == '/':
return left / right
return 0
expr = []
count = 0
for i, e in enumerate(expression):
if e == '-' and (i == 0 or expression[i-1] in prec or expression[i-1] == '('):
if expression[i+1] != '(':
expr.append('(')
count += 1
expr.append(-1)
expr.append('*')
elif e in prec:
expr.append(e)
elif e.isdigit():
expr.append(int(e))
if count > 0:
expr.append(')')
count -= 1
else:
expr.append(e)
while count > 0:
expr.append(')')
count -= 1
print('*****************************')
print(expr)
stack = []
exp = []
for e in expr:
if e == '(':
stack.append('(')
elif e == ')':
while stack[-1] != '(':
exp.append(stack[-1])
stack.pop()
stack.pop()
elif e in prec:
if len(stack) == 0 or stack[-1] == '(':
stack.append(e)
else:
if len(stack) and stack[-1] != '(':
while len(stack) and stack[-1] != '(' and prec[e] <= prec[stack[-1]]:
exp.append(stack[-1])
stack.pop()
stack.append(e)
else:
exp.append(e)
while len(stack):
exp.append(stack[-1])
stack.pop()
print('***********************************')
for e in exp:
print(e, end=', ')
stack = []
for e in exp:
if e in prec:
right = stack[-1]
stack.pop()
left = stack[-1]
stack.pop()
result = evaluate(left, right, e)
stack.append(result)
else:
stack.append(e)
return stack[-1]
except:
return -1
print("\n\n\n-*************************\n",
calc("(-3 * -(((-(-67 - 27)))) - 70)"))
<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
int minDepth(TreeNode *root)
{
if (!root)
return 0;
int l = minDepth(root->left);
int r = minDepth(root->right);
return 1 + ((l == 0 || r == 0) ? max(l, r) : min(l, r));
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
#define G 9.81
#define DEG2RAD 0.0174533
double getOptimalSpeed(double radius)
{
return sqrt(tan(60 * DEG2RAD) * radius * G);
}
class SortFall
{
public:
bool operator()(const pair<pair<char, int>, vector<int>> &o1, const pair<pair<char, int>, vector<int>> &o2)
{
if (o1.second.size() < o2.second.size())
return true;
if (o1.second.size() == o2.second.size())
return o1.first.second > o2.first.second;
if (o1.first.second > o2.first.second)
{
if (o1.second.size() > o2.second.size())
return false;
else if (o1.second.size() == o2.second.size())
{
if (o1.second.size() == 0)
return true;
else
{
int i = 0;
while (o1.second[i] == o2.second[i])
++i;
return o1.second[i] > o2.second[i];
}
}
}
return false;
}
};
int main()
{
int n;
cin >> n;
cin.ignore();
int v;
cin >> v;
cin.ignore();
vector<pair<pair<char, int>, vector<int>>> players;
for (int i = 0; i < n; i++)
{
int speed;
cin >> speed;
cin.ignore();
players.push_back({{'a' + i, speed}, {}});
}
int max_o_speed = 999999;
for (int i = 0; i < v; i++)
{
int bends;
cin >> bends;
cin.ignore();
int o_speed = getOptimalSpeed(bends);
max_o_speed = min(max_o_speed, o_speed);
for (int j = 0; j < players.size(); ++j)
{
if (players[j].first.second > o_speed)
{
players[j].second.push_back(i);
}
}
}
sort(players.begin(), players.end(), SortFall());
cout << max_o_speed << "\n";
cout << "y\n";
for (auto p : players)
{
cout << p.first.first << "\n";
}
}<file_sep>// time: O(logn), space: O(1) solution
class Solution
{
public:
int singleNonDuplicate(vector<int> &nums)
{
int l = 0, r = nums.size() - 1, mid = 0;
while (l < r)
{
mid = l + ((r - l) >> 1);
if (mid & 1)
{ // mid is odd
if (mid > 0 && nums[mid] == nums[mid - 1])
l = mid + 1;
else
r = mid;
}
else
{ // mid is even
if (mid + 1 < nums.size() && nums[mid] == nums[mid + 1])
l = mid + 1;
else
r = mid;
}
}
return nums[l];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// time: O(n), space: O(1) solution
class Solution
{
public:
int singleNonDuplicate(vector<int> &nums)
{
int res = 0;
for (auto n : nums)
res ^= n;
return res;
}
};<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
ll countPairs(vector<ll> &a, ll diff)
{
ll count = 0, l = 0;
for (ll r = 1; r < a.size(); ++r)
{
while (a[r] - a[l] > diff)
++l;
count += r - l;
}
return count;
}
int main()
{
ll n = 0, k = 0, val;
cin >> n >> k;
vector<ll> a(n, 0);
for (ll i = 0; i < n; ++i)
cin >> a[i];
sort(a.begin(), a.end());
ll l = 0, r = a[a.size() - 1] - a[0], mid = 0;
while (l < r)
{
mid = l + ((r - l) >> 1);
if (countPairs(a, mid) >= k)
r = mid;
else
l = mid + 1;
}
cout << l;
return 0;
}<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
pair<TreeNode *, int> subtreeWithAllDeepestUtil(TreeNode *root)
{
if (!root)
return {NULL, 0};
pair<TreeNode *, int> l = subtreeWithAllDeepestUtil(root->left);
pair<TreeNode *, int> r = subtreeWithAllDeepestUtil(root->right);
return {(l.second == r.second ? root : l.second > r.second ? l.first : r.first), 1 + max(l.second, r.second)};
}
TreeNode *subtreeWithAllDeepest(TreeNode *root)
{
return subtreeWithAllDeepestUtil(root).first;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// time: O(n), space: O(1) solution
class Solution
{
public:
int kadane(vector<int> &A, int start, int end)
{
if (start >= end)
return 0;
int ans = A[start], sum = 0;
for (int i = start; i < end; ++i)
{
sum = A[i] + max(sum, 0);
ans = max(ans, sum);
}
return ans;
}
int maxSubarraySumCircular(vector<int> &A)
{
int ans = kadane(A, 0, A.size());
int sum = accumulate(A.begin(), A.end(), 0);
transform(A.begin(), A.end(), A.begin(), bind(multiplies<int>(), placeholders::_1, -1));
return max(ans, sum + max(kadane(A, 0, A.size() - 1), kadane(A, 1, A.size())));
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// time: O(n), space: O(n) solution
class Solution
{
public:
int maxSubarraySumCircular(vector<int> &A)
{
int n = A.size(), ans = INT_MIN, sum = 0;
for (int i = 0; i < n; ++i)
{
sum = A[i] + max(sum, 0);
ans = max(ans, sum);
}
vector<int> rSum(n, 0);
rSum[n - 1] = A[n - 1];
for (int i = n - 2; i >= 0; --i)
rSum[i] = rSum[i + 1] + A[i];
for (int i = n - 2; i >= 0; --i)
rSum[i] = max(rSum[i], rSum[i + 1]);
sum = 0;
for (int i = 0; i < n - 2; ++i)
{
sum += A[i];
ans = max(ans, sum + rSum[i + 2]);
}
return ans;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// time: O(n), space: O(n) solution
class Solution
{
public:
int maxSubarraySumCircular(vector<int> &A)
{
int n = A.size(), ans = INT_MIN;
vector<int> B(2 * n + 1, 0);
deque<int> Q;
Q.push_back(0);
for (int i = 0; i < 2 * n; ++i)
B[i + 1] = B[i] + A[i % n];
for (int i = 1; i < 2 * n; ++i)
{
while (Q.front() < i - n)
Q.pop_front();
ans = max(ans, B[i] - B[Q.front()]);
while (!Q.empty() && B[i] <= B[Q.back()])
Q.pop_back();
Q.push_back(i);
}
return ans;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Facebook.
* Implement regular expression matching with the following special characters:
. (period) which matches any single character
* (asterisk) which matches zero or more of the preceding element
* That is, implement a function that takes in a string and a valid regular expression and returns whether or not the string matches the regular expression.
* For example, given the regular expression "ra." and the string "ray", your function should return true. The same regular expression on the string "raymond" should return false.
* Given the regular expression ".*at" and the string "chat", your function should return true. The same regular expression on the string "chats" should return false.
*
*
* Online Judge: https://leetcode.com/problems/regular-expression-matching/
*
*/
// dp solution
class Solution
{
public:
bool isMatch(string s, string p)
{
int s_len = s.length(), p_len = p.length();
vector<vector<bool>> tab(s_len + 1, vector<bool>(p_len + 1, false));
tab[0][0] = true;
for (int i = 2; i <= p_len; ++i)
{
if (p[i - 1] == '*')
tab[0][i] = tab[0][i - 2];
}
for (int i = 1; i <= s_len; ++i)
{
for (int j = 1; j <= p_len; ++j)
{
if (s[i - 1] == p[j - 1] || p[j - 1] == '.')
tab[i][j] = tab[i - 1][j - 1];
if (p[j - 1] == '*')
{
tab[i][j] = tab[i][j - 2];
if (s[i - 1] == p[j - 2] || p[j - 2] == '.')
tab[i][j] = tab[i][j] | tab[i - 1][j];
}
}
}
return tab[s_len][p_len];
}
};
// recursive solution
class Solution
{
public:
bool isMatch(string &s, string &p, int i = 0, int j = 0)
{
if (j >= p.length())
return i == s.length();
bool match = (i != s.length() && (s[i] == p[j] || p[j] == '.'));
if (p.length() - j >= 2 && p[j + 1] == '*')
{
return (isMatch(s, p, i, j + 2) || (match && isMatch(s, p, i + 1, j)));
}
else
{
return match && isMatch(s, p, i + 1, j + 1);
}
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// O(nlogn) solution with sorting
class Solution
{
public:
vector<int> minSubsequence(vector<int> &nums)
{
int sum = accumulate(nums.begin(), nums.end(), 0);
sort(nums.begin(), nums.end(), greater<int>()); // sort in non-increasing order
vector<int> result;
int cur_sum = 0;
for (int &n : nums)
{
cur_sum += n;
result.push_back(n);
if (cur_sum > sum - cur_sum)
break;
}
return result;
}
};
// O(nlogn) solution with priority queue
class Solution
{
public:
vector<int> minSubsequence(vector<int> &nums)
{
int sum = accumulate(nums.begin(), nums.end(), 0);
priority_queue<int> PQ(nums.begin(), nums.end());
vector<int> result;
int cur_sum = 0;
while (cur_sum <= sum - cur_sum)
{
cur_sum += PQ.top();
result.push_back(PQ.top());
PQ.pop();
}
return result;
}
};<file_sep>#include <bits/stdc++.h>
using namespace std;
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
void addElement(vector<int> &tab, vector<pair<int, int>> &hist, int a)
{
if (tab.empty() || a > tab.back())
{
tab.push_back(a);
hist.push_back({-1, a});
}
else
{
int pos = lower_bound(tab.begin(), tab.end(), a) - tab.begin();
int old = tab[pos];
tab[pos] = a;
hist.push_back({old, pos});
}
}
int main()
{
int n = 0, q = 0, c = 0, x = 0;
cin >> n >> q;
vector<int> tab;
vector<pair<int, int>> hist;
int pos = -1;
for (int i = 0; i < n; ++i)
{
cin >> x;
addElement(tab, hist, x);
}
while (q--)
{
cin >> c;
if (c == 1)
{
cin >> x;
addElement(tab, hist, x);
}
else
{
auto tmp = hist.back();
if (tmp.first == -1)
tab.pop_back();
else
{
tab[tmp.second] = tmp.first;
}
hist.pop_back();
}
cout << tab.size() << "\n";
}
return 0;
}<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int getMaxPathSum2(vector<vector<int>> &a)
{
int n = a.size();
for (int i = n - 2; i >= 0; --i)
{
for (int j = 0; j <= i; ++j)
{
a[i][j] += max(a[i + 1][j], a[i + 1][j + 1]);
}
}
return a[0][0];
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t = 0, n = 0, x = 0;
cin >> t;
while (t--)
{
cin >> n;
vector<vector<int>> a(n);
for (int i = 0; i < n; ++i)
{
for (int j = 0; j <= i; ++j)
{
cin >> x;
a[i].push_back(x);
}
}
cout << getMaxPathSum2(a) << "\n";
}
return 0;
}
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <iomanip>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Point
{
public:
int x;
int y;
Point(int x, int y)
{
this->x = x;
this->y = y;
}
};
double getDist(Point a, Point b)
{
return sqrt(pow((b.x - a.x), 2) + pow((b.y - a.y), 2));
}
int main()
{
int N;
cin >> N;
cin.ignore();
vector<Point> cities;
vector<bool> vis(N, false);
for (int i = 0; i < N; i++)
{
int X;
int Y;
cin >> X >> Y;
cin.ignore();
cities.push_back({X, Y});
}
int idx = 0;
double min_dist = 999999, total_dist = 0;
int min_idx = 0;
bool flag = false;
int X = N;
while (X--)
{
min_dist = 999999;
flag = false;
for (int i = 0; i < N; ++i)
{
if (i != idx && !vis[i])
{
double dd = getDist(cities[idx], cities[i]);
if (min_dist > dd)
{
min_dist = dd;
min_idx = i;
flag = true;
}
}
}
if (flag)
{
total_dist += min_dist;
vis[idx] = true;
idx = min_idx;
}
else
{
total_dist += getDist(cities[idx], cities[0]);
break;
}
}
cout << fixed << setprecision(0) << total_dist << "\n";
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_set>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int n;
int m;
int c;
int sum = 0, max_sum = -999999;
vector<int> devices;
cin >> n >> m >> c; cin.ignore();
for (int i = 0; i < n; i++) {
int nx;
cin >> nx; cin.ignore();
devices.push_back(nx);
}
for (int i = 0; i < m; i++) {
int mx;
cin >> mx; cin.ignore();
if(devices[mx-1] > c) {
cout<<"Fuse was blown.\n";
return 0;
}
sum += devices[mx-1];
if(sum > c) {
cout<<"Fuse was blown.\n";
return 0;
}
if(max_sum < sum) max_sum = sum;
devices[mx-1] *= -1;
}
cout<<"Fuse was not blown.\nMaximal consumed current was "<<max_sum<<" A.\n";
}<file_sep>// space efficient dp solution
class Solution
{
public:
bool isInterleave(string s1, string s2, string s3)
{
if (s1.length() + s2.length() != s3.length())
return false;
int m = s1.length(), n = s2.length();
vector<bool> tab(n + 1, false);
for (int i = 0; i <= m; ++i)
{
for (int j = 0; j <= n; ++j)
{
if (i == 0 && j == 0)
tab[j] = true;
else if (i == 0)
tab[j] = tab[j - 1] && s2[j - 1] == s3[j - 1];
else if (j == 0)
tab[j] = tab[j] && s1[i - 1] == s3[i - 1];
else
tab[j] = (tab[j] && s1[i - 1] == s3[i + j - 1]) || (tab[j - 1] && s2[j - 1] == s3[i + j - 1]);
}
}
return tab[n];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// dp solution
class Solution
{
public:
bool isInterleave(string s1, string s2, string s3)
{
if (s1.length() + s2.length() != s3.length())
return false;
int m = s1.length(), n = s2.length();
vector<vector<bool>> tab(m + 1, vector<bool>(n + 1, false));
tab[0][0] = true;
for (int i = 1; i <= m; ++i)
tab[i][0] = tab[i - 1][0] && s1[i - 1] == s3[i - 1];
for (int i = 1; i <= n; ++i)
tab[0][i] = tab[0][i - 1] && s2[i - 1] == s3[i - 1];
for (int i = 1; i <= m; ++i)
{
for (int j = 1; j <= n; ++j)
{
tab[i][j] = (tab[i - 1][j] && s1[i - 1] == s3[i + j - 1]) || (tab[i][j - 1] && s2[j - 1] == s3[i + j - 1]);
}
}
return tab[m][n];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// recursive memoization solution
class Solution
{
public:
vector<vector<int>> MEM;
bool isInterleaveUtil(string &s1, string &s2, string &s3, int i = 0, int j = 0, int k = 0)
{
if (MEM[i][j] != -2)
return MEM[i][j];
if (i == s1.length())
return s2.substr(j) == s3.substr(k);
if (j == s2.length())
return s1.substr(i) == s3.substr(k);
bool res = false;
if (s1[i] == s3[k])
res = res | isInterleaveUtil(s1, s2, s3, i + 1, j, k + 1);
if (s2[j] == s3[k])
res = res | isInterleaveUtil(s1, s2, s3, i, j + 1, k + 1);
MEM[i][j] = res;
return res;
}
bool isInterleave(string s1, string s2, string s3)
{
if (s1.length() + s2.length() != s3.length())
return false;
MEM = vector<vector<int>>(s1.length() + 1, vector<int>(s2.length() + 1, -2));
return isInterleaveUtil(s1, s2, s3);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// dp solution
class Solution
{
public:
bool isMatch(string s, string p)
{
int s_len = s.length(), p_len = p.length();
vector<vector<bool>> tab(s_len + 1, vector<bool>(p_len + 1, false));
tab[0][0] = true;
for (int i = 2; i <= p_len; ++i)
{
if (p[i - 1] == '*')
tab[0][i] = tab[0][i - 2];
}
for (int i = 1; i <= s_len; ++i)
{
for (int j = 1; j <= p_len; ++j)
{
if (s[i - 1] == p[j - 1] || p[j - 1] == '.')
tab[i][j] = tab[i - 1][j - 1];
if (p[j - 1] == '*')
{
tab[i][j] = tab[i][j - 2];
if (s[i - 1] == p[j - 2] || p[j - 2] == '.')
tab[i][j] = tab[i][j] | tab[i - 1][j];
}
}
}
return tab[s_len][p_len];
}
};
// recursive solution
class Solution
{
public:
bool isMatch(string &s, string &p, int i = 0, int j = 0)
{
if (j >= p.length())
return i == s.length();
bool match = (i != s.length() && (s[i] == p[j] || p[j] == '.'));
if (p.length() - j >= 2 && p[j + 1] == '*')
{
return (isMatch(s, p, i, j + 2) || (match && isMatch(s, p, i + 1, j)));
}
else
{
return match && isMatch(s, p, i + 1, j + 1);
}
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
string convert(string s, int numRows)
{
if (numRows == 1)
return s;
vector<string> op(numRows);
int idx = 0;
int f = 1;
for (int i = 0; i < s.length(); ++i)
{
op[idx] += s[i];
if (idx == numRows - 1)
f = -1;
if (idx == 0)
f = 1;
idx += f;
}
string ret;
for (auto l : op)
ret += l;
return ret;
}
};<file_sep>// iterative solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
bool isSymmetric(TreeNode *root)
{
if (!root)
return true;
stack<pair<TreeNode *, TreeNode *>> S;
pair<TreeNode *, TreeNode *> cur;
S.push({root->left, root->right});
while (!S.empty())
{
cur = S.top();
S.pop();
if (cur.first && cur.second)
{
if (cur.first->val != cur.second->val)
return false;
S.push({cur.first->left, cur.second->right});
S.push({cur.first->right, cur.second->left});
}
else if ((!cur.first && cur.second) || (cur.first && !cur.second))
return false;
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// recursive solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
bool isSymmetricUtil(TreeNode *root1, TreeNode *root2)
{
if (!root1 && !root2)
return true;
if (root1 && root2)
{
if (root1->val != root2->val)
return false;
else
return isSymmetricUtil(root1->left, root2->right) && isSymmetricUtil(root1->right, root2->left);
}
else
return false;
}
bool isSymmetric(TreeNode *root)
{
if (!root)
return true;
return isSymmetricUtil(root->left, root->right);
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
string encode(string m)
{
int n = m.length();
int i = 0, ct = 1;
deque<string> ret;
while (i < n)
{
if (ct & 1) // push back
ret.push_back(m.substr(i, min(n - i, ct)));
else // push front
ret.push_front(m.substr(i, min(n - i, ct)));
i += ct;
++ct;
}
string encoded_string;
for (auto s : ret)
encoded_string += s;
return encoded_string;
}
string decode(string m)
{
int n = m.length();
int i = 0, ct = 1, p_length = 1;
deque<string> ret;
while (p_length < n)
{
p_length += (ct + 1);
++ct;
}
int init_len = ct - (p_length - n);
if (ct & 1)
{ // last element at back
ret.push_front(m.substr(n - init_len, init_len));
n -= init_len;
init_len = 0;
}
else
{ // last element at front
ret.push_front(m.substr(0, init_len));
}
while (ct--)
{
if (ct & 1)
{ // last element at back
ret.push_front(m.substr(n - ct, ct));
n -= ct;
}
else
{ // last element at front
ret.push_front(m.substr(init_len, ct));
init_len += ct;
}
}
string decoded_string;
for (auto s : ret)
decoded_string += s;
return decoded_string;
}
int main()
{
int N;
cin >> N;
cin.ignore();
string MESSAGE;
getline(cin, MESSAGE);
if (N < 0)
{ // encode
while (N++)
MESSAGE = encode(MESSAGE);
}
else if (N > 0)
{ // decode
while (N--)
MESSAGE = decode(MESSAGE);
}
cout << MESSAGE << "\n";
}<file_sep>// iterative approach
class Solution
{
public:
vector<vector<int>> subsetsWithDup(vector<int> &nums)
{
sort(nums.begin(), nums.end());
vector<vector<int>> result = {{}};
vector<int> sol;
int cur_size = 0, count = 0;
for (int i = 0; i < nums.size(); ++i)
{
cur_size = result.size();
count = 0;
while (i + count < nums.size() && nums[i] == nums[i + count])
++count;
for (int j = 0; j < cur_size; ++j)
{
sol = result[j];
for (int k = 0; k < count; ++k)
{
sol.emplace_back(nums[i]);
result.emplace_back(sol);
}
}
i += count - 1;
}
return result;
}
};
// recursive approach
class Solution
{
public:
void subsetsWithDupUtil(vector<int> &nums, vector<vector<int>> &result, vector<int> &sol, int idx = 0)
{
result.push_back(sol);
for (int i = idx; i < nums.size(); ++i)
{
if (i == idx || nums[i] != nums[i - 1])
{
sol.push_back(nums[i]);
subsetsWithDupUtil(nums, result, sol, i + 1);
sol.pop_back();
}
}
}
vector<vector<int>> subsetsWithDup(vector<int> &nums)
{
sort(nums.begin(), nums.end());
vector<vector<int>> result;
vector<int> sol;
subsetsWithDupUtil(nums, result, sol);
return result;
}
};<file_sep>// iterative solution
class Solution
{
public:
vector<vector<int>> subsets(vector<int> &nums)
{
if (nums.size() == 0)
return {{}};
vector<vector<int>> ret = {{}};
vector<int> sol;
int sz = 0;
for (int n : nums)
{
sz = ret.size();
for (int i = 0; i < sz; ++i)
{
sol.clear();
sol = ret[i];
sol.emplace_back(n);
ret.emplace_back(sol);
}
}
return ret;
}
};
// recursive solution
class Solution
{
public:
void subsetsUtil(vector<int> &nums, vector<vector<int>> &result, vector<int> &sol, int idx = 0)
{
result.emplace_back(sol);
for (int i = idx; i < nums.size(); ++i)
{
sol.emplace_back(nums[i]);
subsetsUtil(nums, result, sol, i + 1);
sol.pop_back();
}
}
vector<vector<int>> subsets(vector<int> &nums)
{
vector<vector<int>> result;
vector<int> sol;
subsetsUtil(nums, result, sol);
return result;
}
};
// bit manipulation solution
class Solution
{
public:
vector<vector<int>> subsets(vector<int> &nums)
{
if (nums.size() == 0)
return {{}};
vector<vector<int>> ret;
vector<int> sol;
int count = 1 << nums.size();
for (int i = 0; i < count; ++i)
{
sol.clear();
for (int j = 0; j < nums.size(); ++j)
{
if (i & (1 << j))
sol.emplace_back(nums[j]);
}
ret.emplace_back(sol);
}
return ret;
}
};<file_sep>// divide and conquer solution
class Solution
{
public:
void swapPoints(vector<int> &a, vector<int> &b)
{
vector<int> tmp = a;
a = b;
b = tmp;
}
int distance(vector<int> &a)
{
return (a[0] * a[0] + a[1] * a[1]);
}
int partition(vector<vector<int>> &points, int l, int r)
{
vector<int> pivot = points[l];
int pivot_dist = distance(pivot);
int j = l + 1;
for (int i = l + 1; i <= r; ++i)
{
if (distance(points[i]) <= pivot_dist)
{
swap(points[i], points[j]);
++j;
}
}
swap(points[l], points[j - 1]);
return j - 1;
}
void sort(vector<vector<int>> &points, int K, int l, int r)
{
if (l >= r)
return;
int p = partition(points, l, r);
if (p < K)
sort(points, K, p + 1, r);
else if (p > K)
sort(points, K, l, p - 1);
}
vector<vector<int>> kClosest(vector<vector<int>> &points, int K)
{
--K;
sort(points, K, 0, points.size() - 1);
return vector<vector<int>>(points.begin(), points.begin() + K + 1);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// nth_element solution
class Solution
{
public:
vector<vector<int>> kClosest(vector<vector<int>> &points, int K)
{
--K;
nth_element(points.begin(), points.begin() + K, points.end(),
[](const vector<int> &a, const vector<int> &b) {
return (sqrt(a[0] * a[0] + a[1] * a[1]) < sqrt(b[0] * b[0] + b[1] * b[1]));
});
vector<vector<int>> result;
result.push_back(points[K]);
double kth_dist = sqrt(points[K][0] * points[K][0] + points[K][1] * points[K][1]);
for (int i = 0; i < points.size(); ++i)
{
if (result.size() == K + 1)
break;
if (i != K && sqrt(points[i][0] * points[i][0] + points[i][1] * points[i][1]) <= kth_dist)
result.emplace_back(points[i]);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// priority queue solution
class Solution
{
public:
vector<vector<int>> kClosest(vector<vector<int>> &points, int K)
{
auto myCompare = [](const pair<int, int> &a, const pair<int, int> &b) {
return (sqrt(a.first * a.first + a.second * a.second) < sqrt(b.first * b.first + b.second * b.second));
};
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(myCompare)> PQ(myCompare);
vector<vector<int>> result;
for (auto &p : points)
{
PQ.push({p[0], p[1]});
if (PQ.size() > K)
PQ.pop();
}
while (PQ.size())
{
result.push_back({PQ.top().first, PQ.top().second});
PQ.pop();
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class Person{
public:
string name;
string parent;
int birth;
string death;
string religion;
string gender;
vector<Person*> children;
Person(string name, string parent, int birth, string death, string religion, string gender) {
this->name = name;
this->parent = parent;
this->birth = birth;
this->death = death;
this->religion = religion;
this->gender = gender;
this->children = {};
}
};
class SortByGenderAndAge{
public:
bool operator()(const Person *p1, const Person * p2) {
return ((p1->gender == "M" && p2->gender == "F") ||
(p1->gender == p2->gender && p1->birth < p2->birth));
}
};
Person* addChild(Person* root, Person* child) {
if(root == NULL) {
root = child;
return root;
}
if(child->parent == root->name) {
root->children.push_back(child);
return root;
}
for(Person* c : root->children) {
c = addChild(c, child);
}
return root;
}
void printFamily(Person* root) {
if(root->death == "-" && root->religion != "Catholic") cout<<root->name<<"\n";
// sort children
sort(root->children.begin(), root->children.end(), SortByGenderAndAge());
for(Person *c : root->children) {
printFamily(c);
}
}
int main()
{
int n;
cin >> n; cin.ignore();
string name;
string parent;
int birth;
string death;
string religion;
string gender;
Person* root = NULL;
for (int i = 0; i < n; i++) {
cin >> name >> parent >> birth >> death >> religion >> gender; cin.ignore();
Person *child = new Person(name, parent, birth, death, religion, gender);
root = addChild(root, child);
}
printFamily(root);
}<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 0, m = 0, g = 0;
cin >> n >> m >> g;
vector<int> rains(n, 0);
vector<int> clothes(m, 0);
for (int i = 0; i < n; ++i)
cin >> rains[i];
for (int i = 0; i < m; ++i)
cin >> clothes[i];
int count = 0, start = 0, duration = 0;
for (int i = 1; i < n; ++i)
{
duration = rains[i] - rains[i - 1];
for (int j = 0; j < m; ++j)
{
if (clothes[j] <= duration)
{
++count;
clothes[j] = INT_MAX;
}
}
}
cout << count;
return 0;
}<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
unordered_map<char, int> Points = {
{'e', 1}, {'a', 1}, {'i', 1}, {'o', 1}, {'n', 1}, {'r', 1}, {'t', 1}, {'l', 1}, {'s', 1}, {'u', 1}, {'d', 2}, {'g', 2}, {'b', 3}, {'c', 3}, {'m', 3}, {'p', 3}, {'f', 4}, {'h', 4}, {'v', 4}, {'w', 4}, {'y', 4}, {'k', 5}, {'j', 8}, {'x', 8}, {'q', 10}, {'z', 10}};
unordered_map<char, int> available;
vector<string> words;
int N;
cin >> N;
cin.ignore();
for (int i = 0; i < N; i++)
{
string W;
getline(cin, W);
words.push_back(W);
}
string LETTERS;
getline(cin, LETTERS);
for (auto c : LETTERS)
++available[c];
int max_ct = -1, ct = 0;
unordered_map<char, int> t_available = available;
string op;
for (int i = 0; i < words.size(); ++i)
{
ct = 0;
t_available = available;
for (int j = 0; j < words[i].length(); ++j)
{
if (t_available[words[i][j]] > 0)
{
ct += Points[words[i][j]];
--t_available[words[i][j]];
}
else
{
ct = -1;
break;
}
}
if (max_ct < ct)
{
max_ct = ct;
op = words[i];
}
}
cout << op << endl;
}<file_sep>// bit manipulation approach
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
int getDecimalValue(ListNode *head)
{
int result = 0;
ListNode *cur = head;
while (cur)
{
result = result << 1 | cur->val;
cur = cur->next;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// standard approach
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
int getDecimalValue(ListNode *head)
{
int result = head->val;
ListNode *cur = head;
while (cur->next)
{
cur = cur->next;
result = result * 2 + cur->val;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>class Solution
{
public:
vector<int> intersection(vector<int> &nums1, vector<int> &nums2)
{
if (nums1.empty() || nums2.empty())
return {};
vector<int> result;
unordered_set<int> mem(nums1.begin(), nums1.end());
for (int &n : nums2)
if (mem.count(n))
{
result.push_back(n);
mem.erase(n);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
vector<int> partitionLabels(string S)
{
vector<int> result, mem(128, -1);
int last_idx = -1, len = 0;
for (int i = 0; i < S.length(); ++i)
mem[S[i]] = i;
for (int i = 0; i < S.length(); ++i)
{
last_idx = max(last_idx, mem[S[i]]);
++len;
if (i == last_idx)
{
result.emplace_back(len);
len = 0;
}
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
string largestNumber(vector<int> &nums)
{
vector<string> numbers;
for (int &n : nums)
numbers.emplace_back(to_string(n));
sort(numbers.begin(), numbers.end(), [](const string &a, const string &b) {
return a + b > b + a;
});
string result = "";
for (auto n : numbers)
result += n;
return result[0] == '0' ? "0" : result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution {
public:
vector<int> findDuplicates(vector<int> &nums) {
vector<int> result;
int idx = 0;
for (int &num : nums) {
idx = abs(num) - 1;
if (nums[idx] < 0)
result.emplace_back(idx + 1);
else
nums[idx] = -nums[idx];
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 0, m = 0, x = 0, y = 0;
unordered_set<int> A, C;
set<int> B;
bool flag = false;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> x;
A.insert(x);
}
cin >> m;
for (int i = 0; i < m; ++i)
{
cin >> x;
C.insert(x);
}
for (auto a : A)
{
for (auto c : C)
{
x = c - a;
flag = true;
for (auto aa : A)
{
y = aa + x;
if (C.find(y) == C.end())
{
flag = false;
break;
}
}
if (flag)
B.insert(x);
}
}
for (auto b : B)
cout << b << " ";
return 0;
}<file_sep>/**
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Microsoft.
* A number is considered perfect if its digits sum up to exactly 10.
* Given a positive integer n, return the n-th perfect number.
* For example, given 1, you should return 19. Given 2, you should return 28.
*
*
* Online Judge: https://codezen.codingninjas.com/practice/130452/4641/interview-shuriken-21:-n-th-prefect-number
*
*/
#include <bits/stdc++.h>
using namespace std;
int getSum(int n)
{
int sum = 0;
while (n)
{
sum += n % 10;
n /= 10;
}
return sum;
}
int main()
{
// Write your code here
int n = 0;
cin >> n;
int count = 0, result = 19;
while (true)
{
if (getSum(result) == 10)
{
++count;
}
if (count == n)
break;
result += 9;
}
cout << result;
}<file_sep>// best solution
class Solution
{
public:
string frequencySort(string s)
{
vector<int> freq(128, 0);
map<int, string, greater<int>> bucket;
int count = 0;
char c;
string res = "";
for (char &c : s)
++freq[c];
for (int i = 0; i < freq.size(); ++i)
{
if (freq[i])
{
c = i;
count = freq[i];
bucket[count].append(count, c);
}
}
for (auto b : bucket)
res += b.second;
return res;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// bucket sort O(n)
class Solution
{
public:
string frequencySort(string s)
{
vector<int> freq(128, 0);
vector<string> bucket(s.length() + 1, "");
int count = 0;
char c;
string res = "";
for (char &c : s)
++freq[c];
for (int i = 0; i < freq.size(); ++i)
{
if (freq[i])
{
c = i;
count = freq[i];
bucket[count].append(count, c);
}
}
for (int i = bucket.size() - 1; i >= 0; --i)
{
if (bucket[i].length())
res += bucket[i];
}
return res;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// sorting with custom comparator O(nlogn)
class Solution
{
public:
string frequencySort(string s)
{
int freq[128];
memset(freq, 0, sizeof(freq));
for (char &c : s)
++freq[c];
sort(s.begin(), s.end(), [&freq](const char &c1, const char &c2) {
if (freq[c1] > freq[c2] || (freq[c1] == freq[c2] && c1 > c2))
return true;
return false;
});
return s;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int maxProduct(vector<int> &nums)
{
int l = 0, r = 0, result = INT_MIN, len = nums.size();
for (int i = 0; i < nums.size(); ++i)
{
l = (l ? l : 1) * nums[i];
r = (r ? r : 1) * nums[len - i - 1];
result = max(result, max(l, r));
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
vector<int> nums;
public:
Solution(vector<int> &nums)
{
this->nums = nums;
}
int pick(int target)
{
int count = 0, idx = -1;
for (int i = 0; i < this->nums.size(); ++i)
{
if (this->nums[i] == target)
{
++count;
if (1 + (rand() % count) == 1)
idx = i;
}
}
return idx;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(nums);
* int param_1 = obj->pick(target);
*/
<file_sep>// bfs solution (topological sort solution) time : O(N + E), using queue
class Solution
{
public:
bool canFinish(int numCourses, vector<vector<int>> &prerequisites)
{
vector<vector<int>> graph(numCourses);
vector<int> inDegree(numCourses, 0);
for (auto &p : prerequisites)
{
graph[p[1]].emplace_back(p[0]);
++inDegree[p[0]];
}
queue<int> order;
int cur = 0;
for (int i = 0; i < inDegree.size(); ++i)
if (inDegree[i] == 0)
order.push(i);
while (!order.empty())
{
cur = order.front();
order.pop();
for (int d : graph[cur])
if (--inDegree[d] == 0)
order.push(d);
}
return accumulate(inDegree.begin(), inDegree.end(), 0) == 0;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// bfs solution (topological sort solution) time : O(N + E), without using queue
class Solution
{
public:
bool canFinish(int numCourses, vector<vector<int>> &prerequisites)
{
vector<vector<int>> graph(numCourses);
vector<int> inDegree(numCourses, 0);
for (auto &p : prerequisites)
{
graph[p[1]].emplace_back(p[0]);
++inDegree[p[0]];
}
vector<int> order;
for (int i = 0; i < inDegree.size(); ++i)
if (inDegree[i] == 0)
order.emplace_back(i);
for (int i = 0; i < order.size(); ++i)
for (int &d : graph[order[i]])
if (--inDegree[d] == 0)
order.emplace_back(d);
return order.size() == numCourses;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// dfs solution
class Solution
{
public:
bool dfs(vector<vector<int>> &graph, vector<bool> &seen, int src)
{
if (seen[src])
return false;
seen[src] = true;
for (int &dest : graph[src])
{
if (!dfs(graph, seen, dest))
return false;
}
seen[src] = false;
return true;
}
bool canFinish(int numCourses, vector<vector<int>> &prerequisites)
{
vector<vector<int>> graph(numCourses);
vector<bool> seen(numCourses, false);
for (auto &p : prerequisites)
{
graph[p[1]].emplace_back(p[0]);
}
for (int i = 0; i < numCourses; ++i)
{
if (!seen[i] && !dfs(graph, seen, i))
return false;
}
return true;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
inline int getMaxLen(const string &s)
{
int ct = 0, max_len = 0;
unordered_map<int, int> MEM;
for (int i = 0; i < s.length(); ++i)
{
ct += s[i] == '0' ? 1 : -1;
if (ct > 0)
max_len = max(max_len, i + 1);
if (!MEM.count(ct))
MEM[ct] = i;
if (MEM.count(ct - 1))
max_len = max(max_len, i - MEM[ct - 1]);
}
return max_len;
}
int main()
{
int n = 0;
string s;
cin >> n;
cin >> s;
cout << getMaxLen(s);
return 0;
}<file_sep>// binary search solution
class Solution
{
public:
int countPairs(vector<int> &nums, int diff)
{
int count = 0, l = 0;
for (int r = 1; r < nums.size(); ++r)
{
while (nums[r] - nums[l] > diff)
++l;
count += r - l;
}
return count;
}
int smallestDistancePair(vector<int> &nums, int k)
{
sort(nums.begin(), nums.end());
int l = 0, r = nums[nums.size() - 1] - nums[0], mid = 0;
while (l < r)
{
mid = l + ((r - l) >> 1);
if (countPairs(nums, mid) < k)
l = mid + 1;
else
r = mid;
}
return l;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(N^2(logN)) solution (TLE)
class Solution
{
public:
int smallestDistancePair(vector<int> &nums, int k)
{
auto compare = [&nums](const pair<int, int> &o1, const pair<int, int> &o2) {
return (abs(nums[o1.first] - nums[o1.second])) > (abs(nums[o2.first] - nums[o2.second]));
};
sort(nums.begin(), nums.end());
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(compare)> PQ(compare);
for (int i = 0; i < nums.size() - 1; ++i)
PQ.push({i, i + 1});
for (int i = 1; i < k; ++i)
{
auto e = PQ.top();
PQ.pop();
if (e.second + 1 < nums.size())
PQ.push({e.first, e.second + 1});
}
return abs(nums[PQ.top().first] - nums[PQ.top().second]);
}
};<file_sep>/*
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Google.
* A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
* Given the root to a binary tree, count the number of unival subtrees.
* For example, the following tree has 5 unival subtrees:
----------------
| 0 |
| / \ |
| 1 0 |
| / \ |
| 1 0 |
| / \ |
| 1 1 |
----------------
*
*
* Online Judge: https://leetcode.com/problems/count-univalue-subtrees/ (subscription required)
* Online Judge used: https://www.lintcode.com/en/old/problem/count-univalue-subtrees/
*
*/
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution
{
public:
/**
* @param root: the given tree
* @return: the number of uni-value subtrees.
*/
pair<int, bool> countUnivalSubtreesUtil(TreeNode *root)
{
if (root == NULL)
return {0, true};
// this check is optional as it gets handled even if removed. Just reduces the two calls per leaf nodes
if (root->left == NULL && root->right == NULL) // leaf node / single node
return {1, true};
pair<int, bool> left = countUnivalSubtreesUtil(root->left);
pair<int, bool> right = countUnivalSubtreesUtil(root->right);
// if both children are univalue
if (left.second && right.second)
{
if (root->left && root->left->val != root->val)
{
return {left.first + right.first, false};
}
if (root->right && root->right->val != root->val)
{
return {left.first + right.first, false};
}
return {left.first + right.first + 1, true};
}
// current node cannot form a uni-value tree
return {left.first + right.first, false};
}
int countUnivalSubtrees(TreeNode *root)
{
if (root == NULL)
return 0;
return countUnivalSubtreesUtil(root).first;
}
};<file_sep>class RandomizedCollection
{
vector<int> nums;
unordered_map<int, list<int>> mem;
public:
/** Initialize your data structure here. */
RandomizedCollection()
{
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
bool insert(int val)
{
bool res = !mem.count(val);
nums.emplace_back(val);
mem[val].emplace_back(nums.size() - 1);
return res;
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val)
{
if (!mem.count(val))
return false;
int idx = mem[val].back();
if (idx != nums.size() - 1)
{
nums[idx] = nums.back();
mem[nums.back()].pop_back();
if (mem[nums.back()].size() == 0 || mem[nums.back()].back() < idx)
mem[nums.back()].emplace_back(idx);
else
mem[nums.back()].emplace_front(idx);
}
nums.pop_back();
mem[val].pop_back();
if (mem[val].size() == 0)
mem.erase(val);
return true;
}
/** Get a random element from the collection. */
int getRandom()
{
return nums[rand() % nums.size()];
}
};
/**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection* obj = new RandomizedCollection();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int t = 0, count = 0;
string s;
unordered_set<char> Vowels;
Vowels.insert('A');
Vowels.insert('E');
Vowels.insert('I');
Vowels.insert('O');
Vowels.insert('U');
Vowels.insert('a');
Vowels.insert('e');
Vowels.insert('i');
Vowels.insert('o');
Vowels.insert('u');
cin >> t;
while (t--)
{
cin >> s;
count = 0;
for (int i = 0; i < s.length(); ++i)
{
if (Vowels.find(s[i]) != Vowels.end())
++count;
}
cout << count << "\n";
}
return 0;
}<file_sep>class Solution
{
public:
string getSmallestString(int n, int k)
{
string result(n, 'a');
int idx = n - 1, rem = 0;
k -= n;
while (k)
{
rem = min(k, 25);
result[idx--] += rem;
k -= rem;
}
return result;
}
};
<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long int
ll MEM[1000000];
ll getCountOfDivisors(int n)
{
if (MEM[n] > 0)
return MEM[n];
ll init_n = n;
ll ct = 0;
while (n % 2 == 0)
{
++ct;
n >>= 1;
}
ll result = ct == 0 ? 1 : ct + 1;
for (int i = 3; i * i <= n; ++i)
{
if (n % i == 0)
{
ct = 0;
while (n % i == 0)
{
++ct;
n /= i;
}
result *= (ct + 1);
}
}
if (n > 2)
result *= 2;
MEM[init_n] = result;
return result;
}
// *********************** initial approach (accepted) ***********************
// ll getFirstTriangularNumber(ll n) {
// ll val = 1, ct = 2;
// while(true) {
// // cout<<"\n"<<val<<" :: "<<getCountOfDivisors(val)<<"\n";
// if(getCountOfDivisors(val) > n) {
// return val;
// }
// val += ct;
// ++ct;
// }
// }
// *********************** optimal approach ***********************
ll getFirstTriangularNumberOptimal(ll n)
{
/*
refers this: https://projecteuler.net/overview=012
sum upto n numbers = n*(n+1)/2
number of divisors = num_divisors(n) * num_divisors((n+1)/2) (if n is odd)
number of divisors = num_divisors(n/2) * num_divisors(n+1) (if n is even)
we can also memoize the values that have already been conputed
in calculating the number of divisors
*/
ll val = 1, dvCt = 0;
while (true)
{
if (~val & 1)
{ // val is even
dvCt = getCountOfDivisors(val / 2) * getCountOfDivisors((val + 1));
}
else
{ // val is odd
dvCt = getCountOfDivisors(val) * getCountOfDivisors((val + 1) / 2);
}
if (dvCt > n)
{
return (val * (val + 1)) / 2;
}
++val;
}
return -1;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
ll t = 0, n = 0;
cin >> t;
for (int i = 0; i < 1000000; ++i)
MEM[i] = -1;
while (t--)
{
cin >> n;
// cout<<getFirstTriangularNumber(n)<<"\n";
cout << getFirstTriangularNumberOptimal(n) << "\n";
}
return 0;
}
<file_sep>class Solution
{
public:
vector<int> findAnagrams(string s, string p)
{
vector<int> result, MEM(128, 0);
int window_size = p.length(), count = 0;
for (char &c : p)
++MEM[c];
int l = 0;
for (int r = 0; r < s.length(); ++r)
{
if (--MEM[s[r]] >= 0)
++count;
if (count == window_size)
result.emplace_back(l);
if (r - l + 1 == window_size && ++MEM[s[l++]] > 0)
--count;
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// efficient solution using hashing
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
TreeNode *buildTreeUtil(vector<int> &inorder, vector<int> &postorder, int &idx, int l, int r, unordered_map<int, int> &mem)
{
if (l > r)
return NULL;
int i = mem[postorder[idx]];
TreeNode *root = new TreeNode(postorder[idx--]);
root->right = buildTreeUtil(inorder, postorder, idx, i + 1, r, mem);
root->left = buildTreeUtil(inorder, postorder, idx, l, i - 1, mem);
return root;
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
{
unordered_map<int, int> mem;
for (int i = 0; i < inorder.size(); ++i)
mem[inorder[i]] = i;
int idx = postorder.size() - 1;
return buildTreeUtil(inorder, postorder, idx, 0, postorder.size() - 1, mem);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// recursive solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
TreeNode *buildTreeUtil(vector<int> &inorder, vector<int> &postorder, int &idx, int l, int r)
{
if (l > r)
return NULL;
int i = l;
for (; i <= r; ++i)
if (inorder[i] == postorder[idx])
break;
TreeNode *root = new TreeNode(postorder[idx--]);
root->right = buildTreeUtil(inorder, postorder, idx, i + 1, r);
root->left = buildTreeUtil(inorder, postorder, idx, l, i - 1);
return root;
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
{
int idx = postorder.size() - 1;
return buildTreeUtil(inorder, postorder, idx, 0, postorder.size() - 1);
}
};<file_sep>class Solution
{
public:
vector<vector<int>> ret;
void combinationSumUtil(vector<int> &candidates, vector<int> &sol, int target, int ind = 0)
{
if (target == 0)
{
ret.push_back(sol);
}
if (target < 0)
return;
for (int i = ind; i < candidates.size(); ++i)
{
sol.push_back(candidates[i]);
combinationSumUtil(candidates, sol, target - candidates[i], i);
sol.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int> &candidates, int target)
{
vector<int> sol;
combinationSumUtil(candidates, sol, target);
return ret;
}
};<file_sep>// O(N) solution
class Solution
{
public:
int maximumProduct(vector<int> &nums)
{
int min1 = INT_MAX, min2 = INT_MAX, max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN;
for (int &n : nums)
{
if (n < min1)
{
min2 = min1;
min1 = n;
}
else if (n < min2)
min2 = n;
if (n > max1)
{
max3 = max2;
max2 = max1;
max1 = n;
}
else if (n > max2)
{
max3 = max2;
max2 = n;
}
else if (n > max3)
max3 = n;
}
return max(min1 * min2 * max1, max1 * max2 * max3);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// O(NlogN) sorting solution
class Solution
{
public:
int maximumProduct(vector<int> &nums)
{
sort(nums.begin(), nums.end());
int n = nums.size();
return max(nums[0] * nums[1] * nums[n - 1], nums[n - 1] * nums[n - 2] * nums[n - 3]);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
vector<vector<int>> merge(vector<vector<int>> &intervals)
{
if (intervals.size() == 0)
return {};
if (intervals.size() == 1)
intervals;
sort(intervals.begin(), intervals.end(), [](const vector<int> &o1, const vector<int> &o2) {
return o1[0] < o2[0];
});
vector<vector<int>> ret;
int f = 0, s = 0;
int start = intervals[0][0], end = intervals[0][1];
for (int i = 1; i < intervals.size(); ++i)
{
// disjoint interval encountered
if (intervals[i][0] > end)
{
ret.push_back({start, end});
start = intervals[i][0];
end = intervals[i][1];
}
// overlapping intervals
else
{
end = max(end, intervals[i][1]);
}
}
ret.push_back({start, end});
return ret;
}
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <unordered_set>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
unordered_set<string> ST;
unordered_set<string> TR;
bool isHappy(string s) {
if(ST.find(s) != ST.end()) return true;
if(TR.find(s) != ST.end()) return false;
TR.insert(s);
size_t num = 0;
for(int i=0; i<s.length(); ++i) num += powl((s[i] - '0'), 2);
if(num == 1) {
ST.insert(s);
return true;
}
else{
if(isHappy(to_string(num))) {
ST.insert(s);
return true;
}
else {
TR.insert(s);
return false;
}
}
}
int main()
{
int N;
string happy = ":)";
string unhappy = ":(";
cin >> N; cin.ignore();
for (int i = 0; i < N; i++) {
string x;
getline(cin, x);
if(isHappy(x)) cout<<x<<" "<<happy<<"\n";
else cout<<x<<" "<<unhappy<<"\n";
}
}<file_sep>// relativley better approach
class Solution
{
public:
int firstUniqChar(string s)
{
int M[26];
int idx[26];
memset(M, 0, sizeof(M));
memset(idx, 999999, sizeof(idx));
for (int i = 0; i < s.length(); ++i)
{
++M[s[i] - 'a'];
idx[s[i] - 'a'] = i;
}
int result = s.length();
for (int i = 0; i < 26; ++i)
{
if (M[i] == 1)
{
result = min(result, idx[i]);
}
}
return result < s.length() ? result : -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// simple approach
class Solution
{
public:
int firstUniqChar(string s)
{
int M[26];
memset(M, 0, sizeof(M));
for (char &c : s)
++M[c - 'a'];
for (int i = 0; i < s.length(); ++i)
if (M[s[i] - 'a'] == 1)
return i;
return -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
string clean(string s)
{
int i = 0;
while (i < s.length() && s[i] == ' ')
++i;
s = s.substr(i);
i = s.length() - 1;
while (i >= 0 && s[i] == ' ')
--i;
s = s.substr(0, i + 1);
string res;
for (int i = 0; i < s.length(); ++i)
{
if (s[i] == ' ')
{
res += ' ';
while (s[i] == ' ')
++i;
}
res += s[i];
}
return res;
}
string reverseWords(string s)
{
s = clean(s);
if (s.length() == 0)
return "";
reverse(s.begin(), s.end());
int l = 0, r = 0;
while (r <= s.length())
{
if (s[r] == ' ' || r == s.length())
{
reverse(s.begin() + l, s.begin() + r);
l = r + 1;
}
++r;
}
return s;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep># #!/bin/python3
# import math
# import os
# import random
# import re
# import sys
# #
# # Complete the 'calculate_total_owed' function below.
# #
# # The function is expected to return an INTEGER.
# # The function accepts STRING_ARRAY actions as parameter.
# #
# id_pattern = ".*id=(\d+)"
# currency_pattern = ".*amount=(\d+)"
# def processString(s):
# first_split = s.split(" ")
# state = first_split[0]
# id_match = re.search(id_pattern, first_split[1].lower())
# ID = "empty"
# if(id_match):
# ID = id_match.group(1)
# if(state == "PAY:"):
# return state, ID, None
# if(s[-3:].lower() != "usd"):
# return "INVALID", 0, 0
# amount_match = re.search(currency_pattern, first_split[1])
# amount = "empty"
# if(amount_match):
# amount = amount_match.group(1)
# return state, ID, amount
# class Invoice():
# def __init__(self, state, ID, amount):
# self.state = state
# self.ID = ID
# self.amount = amount
# def finalize(self, state, ID, amount):
# self.state = state
# self.amount = amount
# def pay(self, state):
# self.state = state
# self.amount = 0
# def calculate_total_owed(actions):
# # Write your code here
# owed_amount = 0
# invoices = {}
# for action in actions:
# state, ID, amount = processString(action)
# if(ID == "empty"):
# continue
# if(state == "CREATE:" and ID not in invoices):
# obj = Invoice(state, ID, amount)
# invoices[ID] = obj
# elif(state == "FINALIZE:"):
# if(ID in invoices and invoices[ID].state == "CREATE:"):
# invoices[ID].finalize(state, ID, amount)
# elif(state == "PAY:"):
# if(ID in invoices and invoices[ID].state == "FINALIZE:"):
# invoices[ID].pay(state)
# else: # invalid
# pass
# for key, value in invoices.items():
# owed_amount += int(value.amount)
# # print(value.state, value.ID, value.amount)
# return owed_amount
# if __name__ == '__main__':
# actions = ["CREATE: id=13&amount=800¤cy=USD",
# "FINALIZE: id=13&amount=900¤cy=USD",
# "FINALIZE: id=10&amount=900¤cy=USD",
# "CREATE: id=10&amount=800¤cy=USD",
# "FINALIZE: id=10&amount=1300¤cy=USD",
# "PAY: id=13"
# ]
# result = calculate_total_owed(actions)
# print(result)
<file_sep>/**
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Two Sigma.
* Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, implement a function rand7() that returns an integer from 1 to 7 (inclusive).
*
*
* ref: https://leetcode.com/problems/implement-rand10-using-rand7/
*
* complementary of problem 71
*
*/
// The rand5() API is already defined for you.
// int rand5();
// @return a random integer in the range 1 to 5
class Solution
{
public:
int rand7()
{
int result = 0;
while (true)
{
result = (rand5() - 1) * 5 + rand5()(); // generates a number in range of 1-25
if (result <= 21)
return (result - 1) % 7 + 1;
}
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
void gameOfLife(vector<vector<int>> &board)
{
vector<pair<int, int>> dirs = {
{-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}};
int x = 0, y = 0, live_count = 0;
for (int i = 0; i < board.size(); ++i)
{
for (int j = 0; j < board[i].size(); ++j)
{
live_count = 0;
for (auto &d : dirs)
{
x = i + d.first;
y = j + d.second;
if (x >= 0 && x < board.size() && y >= 0 && y < board[x].size())
{
if (board[x][y] == 1 || board[x][y] == '*')
++live_count;
;
}
}
if (board[i][j] == 1)
{
if (live_count < 2 || live_count > 3)
board[i][j] = '*';
}
else
{
if (live_count == 3)
board[i][j] = '?';
}
}
}
for (int i = 0; i < board.size(); ++i)
{
for (int j = 0; j < board[i].size(); ++j)
{
board[i][j] = (board[i][j] == 1 || board[i][j] == '?') ? 1 : 0;
}
}
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution
{
public:
int lastStoneWeight(vector<int> &stones)
{
priority_queue<int> PQ;
int larger_stone = 0, next_larger_stone = 0;
for (int &stone : stones)
PQ.push(stone);
while (PQ.size() > 1)
{
// since the size is at least 2 there must be at least two stones
larger_stone = PQ.top();
PQ.pop();
next_larger_stone = PQ.top();
PQ.pop();
if (larger_stone != next_larger_stone)
PQ.push(larger_stone - next_larger_stone);
}
return PQ.size() == 0 ? 0 : PQ.top();
}
};<file_sep>/**
*
* Good morning! Here's your coding interview problem for today.
* This problem was asked by Amazon.
* Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
* Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.
*
*/
#include <bits/stdc++.h>
using namespace std;
string encode(string s)
{
string res = "";
int i = 0, count = 0;
while (i < s.length())
{
count = 1;
while (i + count < s.length() && s[i] == s[i + count])
++count;
res += to_string(count) + s[i];
i += count;
}
return res;
}
string decode(string s)
{
string res = "";
int i = 0, count = 0;
while (i < s.length())
{
count = s[i] - '0';
res.append(count, s[i + 1]);
i += 2;
}
return res;
}
int main()
{
string t1 = "AAAABBBCCDAA";
string r1 = "4A3B2C1D2A";
assert(("empty string encode error", encode("") == ""));
assert(("simple encode error", encode("AAA") == "3A"));
assert(("empty string decode error", decode("") == ""));
assert(("simple decode error", decode("3A") == "AAA"));
assert(("encoding error", encode(t1) == r1));
assert(("decoding error", decode(r1) == t1));
assert(("encode -> decode [complement error]", decode(encode(t1)) == t1));
assert(("decode -> encode [complement error]", encode(decode(r1)) == r1));
return 0;
}
<file_sep>class Solution
{
public:
int totalHammingDistance(vector<int> &nums)
{
int result = 0, count = 0, n = nums.size();
for (int i = 0; i < 32; ++i)
{
count = 0;
for (int &n : nums)
if (n & (1 << i))
++count;
result += count * (n - count);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// normal solution
class Solution
{
public:
void trim(string &s)
{
int i = 0;
while (i < s.length() && s[i] == ' ')
++i;
s = s.substr(i);
i = s.length() - 1;
while (i >= 0 && s[i] == ' ')
--i;
s = s.substr(0, i + 1);
}
bool isNumber(string s)
{
trim(s);
bool num_found = false, exponent_found = false, decimal_found = false;
for (int i = 0; i < s.length(); ++i)
{
switch (s[i])
{
case '.':
if (decimal_found || exponent_found)
return false;
decimal_found = true;
break;
case 'e':
if (exponent_found || !num_found)
return false;
exponent_found = true;
num_found = false;
break;
case '+':
case '-':
if (i != 0 && s[i - 1] != 'e')
return false;
break;
default:
if (!isdigit(s[i]))
return false;
num_found = true;
break;
}
}
return num_found;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// automaton solution
class Solution
{
public:
bool isNumber(string s)
{
string BLANK = "blank";
string SIGN = "sign";
string NUMBER = "number";
string DECIMAL = "decimal";
string EXPONENT = "exponent";
vector<unordered_map<string, int>> automaton = {
// *** => final state
{},
// state 1 : starting state | expects : blank, sign, number, decimal
{{BLANK, 1}, {SIGN, 2}, {NUMBER, 3}, {DECIMAL, 4}},
// state 2 : sign | expects : number, decimal
{{DECIMAL, 4}, {NUMBER, 3}},
// ***state 3 : number | expects : blank, number, decimal, exponent
{{BLANK, 9}, {NUMBER, 3}, {DECIMAL, 5}, {EXPONENT, 6}},
// state 4 : decimal | expects : number
{{NUMBER, 5}},
// ***state 5 : after decimal | expects : blank, number, exponent
{{BLANK, 9}, {NUMBER, 5}, {EXPONENT, 6}},
// state 6 : exponent | expects : sign, number
{{SIGN, 7}, {NUMBER, 8}},
// state 7 : sign after exponent | expects : number
{{NUMBER, 8}},
// ***state 8 : number after exponent/sign | expects : blank, number
{{BLANK, 9}, {NUMBER, 8}},
// ***state 9 : blank | expects : blank
{{BLANK, 9}}};
int cur_state = 1;
string state = "";
for (char &c : s)
{
if (c == ' ')
state = BLANK;
else if (c == '+' || c == '-')
state = SIGN;
else if (c == '.')
state = DECIMAL;
else if (c == 'e')
state = EXPONENT;
else if (isdigit(c))
state = NUMBER;
else
return false;
if (automaton[cur_state].count(state))
{
cur_state = automaton[cur_state][state];
}
else
return false;
}
return (cur_state == 3 || cur_state == 5 || cur_state == 8 || cur_state == 9);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
int n = 0, q = 0;
cin >> n;
vector<ll> A(n, 0);
for (int i = 0; i < n; ++i)
cin >> A[i];
sort(A.begin(), A.end());
cin >> q;
ll c = 0, x = 0;
while (q--)
{
cin >> c >> x;
if (c == 0)
{
cout << A.end() - lower_bound(A.begin(), A.end(), x) << "\n";
}
else
{
cout << A.end() - upper_bound(A.begin(), A.end(), x) << "\n";
}
}
return 0;
}<file_sep>class Solution
{
public:
string getHint(string secret, string guess)
{
int len = secret.size(), cow_count = 0, bull_count = 0;
vector<int> mem(128, 0);
for (int i = 0; i < len; ++i)
{
if (secret[i] == guess[i])
++bull_count;
else
{
if (mem[secret[i]]++ < 0)
++cow_count;
if (mem[guess[i]]-- > 0)
++cow_count;
}
}
return to_string(bull_count) + "A" + to_string(cow_count) + "B";
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/*
think an nxm lattice as an (n+1)x(m+1) grid,
then we need to calculate the unique paths in that grid
https://leetcode.com/problems/unique-paths/
*** the O(1) formula can be repurposed here: calculate fact(n+m)/(fact(n)*fact(m))
*/
/*
def getLatticePaths(x, y):
if x < y:
return getLatticePaths(y, x)
res = 1
for i in range(x+1, x+y+1):
res = res * i
res = res // (i-x)
return res % 1000000007
t = int(input())
while t:
x, y = map(int, input().split())
print(getLatticePaths(x, y))
t = t-1;
*/
#define ll long long int
#define MOD 1000000007
vector<vector<ll>> tab;
void preCompute()
{
tab = vector<vector<ll>>(501, vector<ll>(501, 0));
for (int i = 0; i < 501; ++i)
{
for (int j = 0; j < 501; ++j)
{
if (i == 0 || j == 0)
{
tab[i][j] = 1;
}
else
{
tab[i][j] = (tab[i - 1][j] + tab[i][j - 1]) % MOD;
}
}
}
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t = 0, n = 0, m = 0;
cin >> t;
preCompute();
while (t--)
{
cin >> n >> m;
cout << tab[n][m] << "\n";
}
return 0;
}
<file_sep>// BIT based solution
class Solution
{
vector<int> f;
public:
void update(int x)
{
while (x < f.size())
{
++f[x];
x += (x & -x);
}
}
int get(int x)
{
int res = 0;
while (x > 0)
{
res += f[x];
x -= (x & -x);
}
return res;
}
int reversePairs(vector<int> &nums)
{
int result = 0, n = nums.size(), l_pos = 0, pos = 0;
f = vector<int>(n + 1, 0);
vector<int> sorted_nums(nums.begin(), nums.end());
sort(sorted_nums.begin(), sorted_nums.end());
for (int i = nums.size() - 1; i >= 0; --i)
{
pos = lower_bound(sorted_nums.begin(), sorted_nums.end(), nums[i]) - sorted_nums.begin();
l_pos = lower_bound(sorted_nums.begin(), sorted_nums.end(), (int)((((long)nums[i]) + 1) >> 1)) - sorted_nums.begin();
result += get(l_pos);
update(pos + 1);
}
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// merge sort based solution
class Solution
{
typedef vector<int>::iterator it;
public:
void reversePairsUtil(it l, it r, int &result)
{
if (r - l <= 1)
return;
it m = l + ((r - l) >> 1);
reversePairsUtil(l, m, result);
reversePairsUtil(m, r, result);
it j = m;
for (it i = l; i < m; ++i)
{
while (j < r && (long)(*i) > 2 * (long)(*j))
++j;
result += (j - m);
}
inplace_merge(l, m, r);
}
int reversePairs(vector<int> &nums)
{
int result = 0;
reversePairsUtil(nums.begin(), nums.end(), result);
return result;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// time: O(n), space: O(n), iterative solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
int kthSmallest(TreeNode *root, int k)
{
stack<TreeNode *> ST;
TreeNode *cur = root;
while (cur || !ST.empty())
{
while (cur)
{
ST.push(cur);
cur = cur->left;
}
cur = ST.top();
ST.pop();
--k;
if (k == 0)
return cur->val;
cur = cur->right;
}
return -1;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
// time: O(n), space: O(n), recursive solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
void kthSmallestUtil(TreeNode *root, vector<int> &result)
{
if (!root)
return;
kthSmallestUtil(root->left, result);
result.emplace_back(root->val);
kthSmallestUtil(root->right, result);
}
int kthSmallest(TreeNode *root, int k)
{
vector<int> result;
kthSmallestUtil(root, result);
return result[k - 1];
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>class Solution {
public:
int concatenatedBinary(int n) {
long long int result = 0, MOD = 1e9+7, shift_len=0;
for(int i=1; i<=n; ++i) {
if((i&(i-1)) == 0) ++shift_len;
result = ((result<<shift_len) + i) % MOD;
}
return result % MOD;
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();
<file_sep>class Solution
{
public:
string minWindow(string s, string t)
{
if (s.length() < t.length())
return "";
unordered_map<char, int> mem;
for (char &c : t)
++mem[c];
int l = 0, min_len = INT_MAX, start = -1, window = t.length();
for (int r = 0; r < s.length(); ++r)
{
if (mem.count(s[r]))
{
--mem[s[r]];
if (mem[s[r]] >= 0)
--window;
}
while (window == 0)
{
if (min_len > r - l)
{
min_len = r - l;
start = l;
}
if (mem.count(s[l]))
{
++mem[s[l]];
if (mem[s[l]] > 0)
++window;
}
++l;
}
}
if (start == -1)
return "";
return s.substr(start, min_len + 1);
}
};
auto speedup = []() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return nullptr;
}();<file_sep>// dp solution
class Solution
{
public:
int change(int amount, vector<int> &coins)
{
vector<int> tab(amount + 1, 0);
tab[0] = 1;
for (int &c : coins)
{
for (int i = c; i <= amount; ++i)
tab[i] += tab[i - c];
}
return tab[amount];
}
};
|
46d489612ef4cf7a439e6f41f16642db4db3105c
|
[
"C",
"Python",
"C++"
] | 504 |
C++
|
underscoreanuj/Codes
|
5673b5631678cadd3bb3091106932ef72c1f8167
|
6e55fae10077146df15ce520734e5b3e7bd61df5
|
refs/heads/master
|
<repo_name>vichetuc/mediawiki-extensions-SoundManager2Button<file_sep>/SoundManager2Button.i18n.php
<?php
# Internationalisation file for SoundManager2Button extension.
#
# @file SoundManager2Button.i18n.php
# @ingroup SoundManager2Button
#
# @author kroocsiogsi
$messages = array();
$messages['en'] = array(
'soundmanager2button-desc' => 'Embeds a SoundManager 2 MP3 player into a wiki page',
'soundmanager2button-play' => 'Play',
);
/** Message documentation (Message documentation)
* @author Shirayuki
*/
$messages['qqq'] = array(
'soundmanager2button-desc' => '{{desc|name=Sound Manager 2 Button|url=http://www.mediawiki.org/wiki/Extension:SoundManager2Button}}',
'soundmanager2button-play' => 'Play button text, primarily for screenreaders.
{{Identical|Play}}',
);
/** Asturian (asturianu)
* @author Xuacu
*/
$messages['ast'] = array(
'soundmanager2button-desc' => 'Inxerta un reproductor MP3 SoundManager 2 nuna páxina de la wiki',
'soundmanager2button-play' => 'Reproducir',
);
/** Breton (brezhoneg)
* @author Fulup
*/
$messages['br'] = array(
'soundmanager2button-play' => 'Lenn',
);
/** Czech (česky)
* @author Vks
*/
$messages['cs'] = array(
'soundmanager2button-play' => 'Přehrát',
);
/** German (Deutsch)
* @author Kghbln
*/
$messages['de'] = array(
'soundmanager2button-desc' => 'Ermöglicht das Einbetten des MP3-Players SoundManager 2 in eine Wikiseite',
'soundmanager2button-play' => 'Abspielen',
);
/** Zazaki (Zazaki)
* @author Erdemaslancan
*/
$messages['diq'] = array(
'soundmanager2button-play' => 'Bıcın',
);
/** Lower Sorbian (dolnoserbski)
* @author Michawiki
*/
$messages['dsb'] = array(
'soundmanager2button-desc' => 'Zasajźijo MP3-wótegrawak SoundManager 2 do wikijowego boka',
'soundmanager2button-play' => 'Wótegraś',
);
/** Spanish (español)
* @author Armando-Martin
*/
$messages['es'] = array(
'soundmanager2button-desc' => 'Incorpora un reproductor de MP3 de SoundManager 2 en una página wiki',
'soundmanager2button-play' => 'Reproducir',
);
/** Persian (فارسی)
* @author Mjbmr
*/
$messages['fa'] = array(
'soundmanager2button-play' => 'پخش',
);
/** French (français)
* @author Seb35
* @author <NAME>
*/
$messages['fr'] = array(
'soundmanager2button-desc' => 'Inclut un lecteur MP3 SoundManager 2 dans une page wiki',
'soundmanager2button-play' => 'Lecture',
);
/** Galician (galego)
* @author Toliño
*/
$messages['gl'] = array(
'soundmanager2button-desc' => 'Incorpora un reprodutor MP3 SoundManager 2 ás páxinas do wiki',
'soundmanager2button-play' => 'Reproducir',
);
/** Hebrew (עברית)
* @author חיים
*/
$messages['he'] = array(
'soundmanager2button-play' => 'נגן',
);
/** Upper Sorbian (hornjoserbsce)
* @author Michawiki
*/
$messages['hsb'] = array(
'soundmanager2button-desc' => 'Zasadźi MP3-wothrawak SoundManager 2 do wikijoweje strony',
'soundmanager2button-play' => 'Wothrać',
);
/** Hungarian (magyar)
* @author Dj
*/
$messages['hu'] = array(
'soundmanager2button-desc' => 'SoundManager 2 MP3-lejátszó beágyazása wiki oldalakra',
'soundmanager2button-play' => 'Lejátszás',
);
/** Interlingua (interlingua)
* @author McDutchie
*/
$messages['ia'] = array(
'soundmanager2button-desc' => 'Incorpora un lector MP3 de SoundManager 2 in un pagina wiki',
'soundmanager2button-play' => 'Reproducer',
);
/** Italian (italiano)
* @author Beta16
*/
$messages['it'] = array(
'soundmanager2button-desc' => 'Incorpora un lettore SoundManager 2 MP3 in una pagina wiki',
'soundmanager2button-play' => 'Riproduci',
);
/** Japanese (日本語)
* @author Shirayuki
*/
$messages['ja'] = array(
'soundmanager2button-desc' => 'ウィキページに SoundManager 2 MP3 プレーヤーを埋め込む',
'soundmanager2button-play' => '再生',
);
/** Georgian (ქართული)
* @author David1010
*/
$messages['ka'] = array(
'soundmanager2button-play' => 'დაკვრა',
);
/** Korean (한국어)
* @author 아라
*/
$messages['ko'] = array(
'soundmanager2button-desc' => '위키 문서에 SoundManager 2 MP3 플레이어 포함',
'soundmanager2button-play' => '재생',
);
/** Luxembourgish (Lëtzebuergesch)
* @author Robby
*/
$messages['lb'] = array(
'soundmanager2button-play' => 'Ofspillen',
);
/** Macedonian (македонски)
* @author Bjankuloski06
*/
$messages['mk'] = array(
'soundmanager2button-desc' => 'Го вметнува MP3-изведувачот SoundManager 2 во викистраница',
'soundmanager2button-play' => 'Пушти',
);
/** Malay (Bahasa Melayu)
* @author Anakmalaysia
*/
$messages['ms'] = array(
'soundmanager2button-desc' => 'Membenamkan pemain MP3 SoundManager 2 pada halaman wiki',
'soundmanager2button-play' => 'Mainkan',
);
/** Dutch (Nederlands)
* @author SPQRobin
* @author Siebrand
*/
$messages['nl'] = array(
'soundmanager2button-desc' => 'Maakt het mogelijk een SoundManager 2 MP3-speler op te nemen in een wikipagina',
'soundmanager2button-play' => 'Afspelen',
);
/** Polish (polski)
* @author BeginaFelicysym
*/
$messages['pl'] = array(
'soundmanager2button-desc' => 'Osadza odtwarzacz SoundManager 2 MP3 na stronie wiki',
'soundmanager2button-play' => 'Odtwórz',
);
/** Piedmontese (Piemontèis)
* @author Borichèt
* @author Dragonòt
*/
$messages['pms'] = array(
'soundmanager2button-desc' => 'A anseriss un letor MP3 SoundManager 2 ant na pàgina wiki',
'soundmanager2button-play' => 'Fé parte',
);
/** Pashto (پښتو)
* @author Ahmed-Najib-Biabani-Ibrahimkhel
*/
$messages['ps'] = array(
'soundmanager2button-play' => 'غږول',
);
/** Portuguese (português)
* @author SandroHc
*/
$messages['pt'] = array(
'soundmanager2button-play' => 'Reproduzir',
);
/** Romanian (română)
* @author Minisarm
*/
$messages['ro'] = array(
'soundmanager2button-play' => 'Redare',
);
/** tarandíne (tarandíne)
* @author Joetaras
*/
$messages['roa-tara'] = array(
'soundmanager2button-desc' => "'Ngapsule 'nu esecutore SoundManager 2 MP3 jndr'à 'na pàgene uicchi",
'soundmanager2button-play' => 'Riproduce',
);
/** Sinhala (සිංහල)
* @author පසිඳු කාවින්ද
*/
$messages['si'] = array(
'soundmanager2button-play' => 'වයන්න',
);
/** Swedish (svenska)
* @author WikiPhoenix
*/
$messages['sv'] = array(
'soundmanager2button-play' => 'Spela upp',
);
/** Tamil (தமிழ்)
* @author மதனாஹரன்
*/
$messages['ta'] = array(
'soundmanager2button-play' => 'இயக்கு',
);
/** Tagalog (Tagalog)
* @author AnakngAraw
*/
$messages['tl'] = array(
'soundmanager2button-desc' => 'Nagbabaon ng isang pampaandar ng SoundManager 2 MP3 papasok sa loob ng isang pahina ng wiki',
'soundmanager2button-play' => 'Paandarin',
);
/** Turkish (Türkçe)
* @author Emperyan
*/
$messages['tr'] = array(
'soundmanager2button-play' => 'Oynat',
);
/** Ukrainian (українська)
* @author Base
*/
$messages['uk'] = array(
'soundmanager2button-desc' => 'Включає MP3-плеєр SoundManager 2 у вікісторінку',
'soundmanager2button-play' => 'Відтворити',
);
/** Urdu (اردو)
* @author පසිඳු කාවින්ද
*/
$messages['ur'] = array(
'soundmanager2button-play' => 'کھیل',
);
/** Simplified Chinese (中文(简体))
* @author Yfdyh000
*/
$messages['zh-hans'] = array(
'soundmanager2button-desc' => '嵌入SoundManager 2 MP3播放器到wiki页面',
'soundmanager2button-play' => '播放',
);
/** Traditional Chinese (中文(繁體))
* @author Shirayuki
*/
$messages['zh-hant'] = array(
'soundmanager2button-play' => '播放',
);
<file_sep>/script/args.js
soundManager.setup({
url: mw.config.get( 'wgExtensionAssetsPath' ) +'/SoundManager2Button/swf/',
debugMode: false,
});
|
70e98b9ce9c3c34dc125e85df3a2fec2e8b2e556
|
[
"JavaScript",
"PHP"
] | 2 |
PHP
|
vichetuc/mediawiki-extensions-SoundManager2Button
|
35d97ba7a9ce49b9f921fceede85e6196e7c5a0a
|
13c51d79998381aa2613f809177a67e5fdb1f60e
|
refs/heads/master
|
<repo_name>BBekker/CryostatControl<file_sep>/CryostatControlServer/Streams/IManagedStream.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IManagedStream.cs" company="SRON">
// bla
// </copyright>
// <summary>
// Defines the IManagedStream type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Streams
{
using System.Threading.Tasks;
/// <summary>
/// The ManagedStream interface.
/// </summary>
public interface IManagedStream
{
/// <summary>
/// Close the connections.
/// </summary>
void Close();
/// <summary>
/// Is the stream connected?
/// </summary>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
bool IsConnected();
/// <summary>
/// Open the connection.
/// </summary>
void Open();
/// <summary>
/// The read string.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
string ReadString();
/// <summary>
/// The read string async.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
Task<string> ReadStringAsync();
/// <summary>
/// The write string.
/// </summary>
/// <param name="stringToWrite">string to write to the device</param>
void WriteString(string stringToWrite);
}
}<file_sep>/CryostatControlClientTests/ViewModels/BlueforsViewModelTests.cs
//-----------------------------------------------------------------------
// <copyright file="CompressorViewModelTests.cs" company="SRON">
// Copyright (c) SRON. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlClient.ViewModels.Tests
{
using System.Windows;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass()]
public class BlueforsViewModelTests
{
private BlueforsViewModel blueforsViewModel;
[TestInitialize]
public void TestInitialize()
{
this.blueforsViewModel = new BlueforsViewModel();
}
[TestMethod()]
public void ColdPlate3KTempTest()
{
this.blueforsViewModel.ColdPlate3KTemp = 50;
Assert.AreEqual(this.blueforsViewModel.ColdPlate3KTemp, 50);
}
[TestMethod()]
public void ColdPlate50KTempTest()
{
this.blueforsViewModel.ColdPlate50KTemp = 50;
Assert.AreEqual(this.blueforsViewModel.ColdPlate50KTemp, 50);
}
[TestMethod()]
public void ConnectionStateTest()
{
this.blueforsViewModel.ConnectionState = 1;
Assert.AreEqual(this.blueforsViewModel.ConnectionState, 1);
}
[TestMethod()]
public void ConnectionStateConvertedTest()
{
this.blueforsViewModel.ConnectionState = 1;
Assert.AreNotEqual(this.blueforsViewModel.ConnectionStateConverted, string.Empty);
}
[TestMethod()]
public void ColdPlate3KVisibilityTest()
{
this.blueforsViewModel.ColdPlate3KVisibility = System.Windows.Visibility.Hidden;
Assert.AreEqual(this.blueforsViewModel.ColdPlate3KVisibility, Visibility.Hidden);
}
[TestMethod()]
public void ColdPlate50KVisibilityTest()
{
this.blueforsViewModel.ColdPlate50KVisibility = System.Windows.Visibility.Hidden;
Assert.AreEqual(this.blueforsViewModel.ColdPlate50KVisibility, Visibility.Hidden);
}
[TestMethod()]
public void OnColdPlate50KVisibilityTest()
{
this.blueforsViewModel.ColdPlate50KVisibility = System.Windows.Visibility.Hidden;
Assert.AreEqual(this.blueforsViewModel.ColdPlate50KVisibility, Visibility.Hidden);
}
}
}<file_sep>/CryostatControlClient/Models/He7Model.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="He7Model.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Models
{
using System;
using System.Windows;
using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Geared;
using LiveCharts.Wpf;
using System.Windows.Media;
/// <summary>
/// Model for the He7-cooler.
/// </summary>
public class He7Model : AbstractModel
{
#region Fields
/// <summary>
/// The he3 head temporary list
/// </summary>
private double[] he3HeadTemporaryList;
/// <summary>
/// The he3 head temporary list
/// </summary>
private double[] he3HeadTemporaryListBottom;
/// <summary>
/// The he3 pump temporary list
/// </summary>
private double[] he3PumpTemporaryList;
/// <summary>
/// The he3 switch temporary list
/// </summary>
private double[] he3SwitchTemporaryList;
/// <summary>
/// The he4 head temporary list
/// </summary>
private double[] he4HeadTemporaryList;
/// <summary>
/// The he4 head temporary list
/// </summary>
private double[] he4HeadTemporaryListBottom;
/// <summary>
/// The he4 pump temporary list
/// </summary>
private double[] he4PumpTemporaryList;
/// <summary>
/// The he4 switch temporary list
/// </summary>
private double[] he4SwitchTemporaryList;
/// <summary>
/// The two k plate temporary list
/// </summary>
private double[] twoKPlateTemporaryList;
/// <summary>
/// The four k plate temporary list
/// </summary>
private double[] fourKPlateTemporaryList;
/// <summary>
/// The four k plate temperature
/// </summary>
private double fourKPlateTemp;
/// <summary>
/// The he3 head temperature
/// </summary>
private double he3HeadTemp;
/// <summary>
/// The he3 pump temperature
/// </summary>
private double he3PumpTemp;
/// <summary>
/// The he3 switch temperature
/// </summary>
private double he3SwitchTemp;
/// <summary>
/// The he4 head temperature
/// </summary>
private double he4HeadTemp;
/// <summary>
/// The he4 pump temperature
/// </summary>
private double he4PumpTemp;
/// <summary>
/// The he4 switch temperature
/// </summary>
private double he4SwitchTemp;
/// <summary>
/// The two k plate temperature
/// </summary>
private double twoKPlateTemp;
#endregion Fields
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="He7Model"/> class.
/// </summary>
public He7Model()
{
this.twoKPlateTemporaryList = new double[this.TemporaryListSize];
this.fourKPlateTemporaryList = new double[this.TemporaryListSize];
this.he3HeadTemporaryList = new double[this.TemporaryListSize];
this.he3HeadTemporaryListBottom = new double[this.TemporaryListSize];
this.he3SwitchTemporaryList = new double[this.TemporaryListSize];
this.he3PumpTemporaryList = new double[this.TemporaryListSize];
this.he4HeadTemporaryList = new double[this.TemporaryListSize];
this.he4HeadTemporaryListBottom = new double[this.TemporaryListSize];
this.he4SwitchTemporaryList = new double[this.TemporaryListSize];
this.he4PumpTemporaryList = new double[this.TemporaryListSize];
this.TwoKPlateLineSeries = new GLineSeries { Title = "He7 - 2K Plate", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent};
this.FourKPlateLineSeries = new GLineSeries { Title = "He7 - 4K Plate", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
this.He3HeadLineSeries = new GLineSeries { Title = "He7 - He3 Head", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
this.He3PumpLineSeries = new GLineSeries { Title = "He7 - He3 Pump", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
this.He3SwitchLineSeries = new GLineSeries { Title = "He7 - He3 Switch", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
this.He4HeadLineSeries = new GLineSeries { Title = "He7 - He4 Head", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
this.He4PumpLineSeries = new GLineSeries { Title = "He7 - He4 Pump", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
this.He4SwitchLineSeries = new GLineSeries { Title = "He7 - He4 Switch", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
this.He3HeadLineSeriesBottom = new GLineSeries { Title = "He7 - He3 Head", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
this.He4HeadLineSeriesBottom = new GLineSeries { Title = "He7 - He4 Head", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
}
#endregion Constructor
#region Properties
/// <summary>
/// Gets or sets the two k plate visibility.
/// </summary>
/// <value>
/// The two k plate visibility.
/// </value>
public Visibility TwoKPlateVisibility
{
get
{
return this.TwoKPlateLineSeries.Visibility;
}
set
{
this.TwoKPlateLineSeries.Visibility = value;
}
}
/// <summary>
/// Gets or sets the four k plate visibility.
/// </summary>
/// <value>
/// The four k plate visibility.
/// </value>
public Visibility FourKPlateVisibility
{
get
{
return this.FourKPlateLineSeries.Visibility;
}
set
{
this.FourKPlateLineSeries.Visibility = value;
}
}
/// <summary>
/// Gets or sets the he3 head plate visibility.
/// </summary>
/// <value>
/// The he3 head plate visibility.
/// </value>
public Visibility He3HeadVisibility
{
get
{
return this.He3HeadLineSeries.Visibility;
}
set
{
this.He3HeadLineSeries.Visibility = value;
}
}
/// <summary>
/// Gets or sets the he3 switch visibility.
/// </summary>
/// <value>
/// The he3 switch visibility.
/// </value>
public Visibility He3SwitchVisibility
{
get
{
return this.He3SwitchLineSeries.Visibility;
}
set
{
this.He3SwitchLineSeries.Visibility = value;
}
}
/// <summary>
/// Gets or sets the he3 pump visibility.
/// </summary>
/// <value>
/// The he3 pump visibility.
/// </value>
public Visibility He3PumpVisibility
{
get
{
return this.He3PumpLineSeries.Visibility;
}
set
{
this.He3PumpLineSeries.Visibility = value;
}
}
/// <summary>
/// Gets or sets the he4 head visibility.
/// </summary>
/// <value>
/// The he4 head visibility.
/// </value>
public Visibility He4HeadVisibility
{
get
{
return this.He4HeadLineSeries.Visibility;
}
set
{
this.He4HeadLineSeries.Visibility = value;
}
}
/// <summary>
/// Gets or sets the he4 switch visibility.
/// </summary>
/// <value>
/// The he4 switch visibility.
/// </value>
public Visibility He4SwitchVisibility
{
get
{
return this.He4SwitchLineSeries.Visibility;
}
set
{
this.He4SwitchLineSeries.Visibility = value;
}
}
/// <summary>
/// Gets or sets the he4 pump visibility.
/// </summary>
/// <value>
/// The he4 pump visibility.
/// </value>
public Visibility He4PumpVisibility
{
get
{
return this.He4PumpLineSeries.Visibility;
}
set
{
this.He4PumpLineSeries.Visibility = value;
}
}
/// <summary>
/// Gets the he4 head line series.
/// </summary>
/// <value>
/// The he4 head line series.
/// </value>
public GLineSeries He4HeadLineSeriesBottom { get; }
/// <summary>
/// Gets the he3 head line series.
/// </summary>
/// <value>
/// The he3 head line series.
/// </value>
public GLineSeries He3HeadLineSeriesBottom { get; }
/// <summary>
/// Gets the he4 switch line series.
/// </summary>
/// <value>
/// The he4 switch line series.
/// </value>
public GLineSeries He4SwitchLineSeries { get; }
/// <summary>
/// Gets the he4 pump line series.
/// </summary>
/// <value>
/// The he4 pump line series.
/// </value>
public GLineSeries He4PumpLineSeries { get; }
/// <summary>
/// Gets the he4 head line series.
/// </summary>
/// <value>
/// The he4 head line series.
/// </value>
public GLineSeries He4HeadLineSeries { get; }
/// <summary>
/// Gets the he3 switch line series.
/// </summary>
/// <value>
/// The he3 switch line series.
/// </value>
public GLineSeries He3SwitchLineSeries { get; }
/// <summary>
/// Gets the he3 pump line series.
/// </summary>
/// <value>
/// The he3 pump line series.
/// </value>
public GLineSeries He3PumpLineSeries { get; }
/// <summary>
/// Gets the he3 head line series.
/// </summary>
/// <value>
/// The he3 head line series.
/// </value>
public GLineSeries He3HeadLineSeries { get; }
/// <summary>
/// Gets the two k plat line series.
/// </summary>
/// <value>
/// The two k plat line series.
/// </value>
public GLineSeries TwoKPlateLineSeries { get; }
/// <summary>
/// Gets the four k plate line series.
/// </summary>
/// <value>
/// The four k plate line series.
/// </value>
public GLineSeries FourKPlateLineSeries { get; }
/// <summary>
/// Gets or sets the four k plate temperature.
/// </summary>
/// <value>
/// The four k plate temperature.
/// </value>
public double FourKPlateTemp
{
get
{
return this.fourKPlateTemp;
}
set
{
this.fourKPlateTemp = value;
this.fourKPlateTemporaryList = this.AddToGraph(this.fourKPlateTemporaryList, this.FourKPlateLineSeries, value);
}
}
/// <summary>
/// Gets or sets the four k plate max 1.
/// </summary>
/// <value>
/// The four k plate max 1.
/// </value>
public double FourKPlateMax1 { get; set; }
/// <summary>
/// Gets or sets the four k plate max 2.
/// </summary>
/// <value>
/// The four k plate max 2.
/// </value>
public double FourKPlateMax2 { get; set; }
/// <summary>
/// Gets or sets the he3 head temperature.
/// </summary>
/// <value>
/// The he3 head temperature.
/// </value>
public double He3HeadTemp
{
get
{
return this.he3HeadTemp;
}
set
{
this.he3HeadTemp = value;
this.he3HeadTemporaryList = this.AddToGraph(this.he3HeadTemporaryList, this.He3HeadLineSeries, value);
this.he3HeadTemporaryListBottom = this.AddToGraph(this.he3HeadTemporaryListBottom, this.He3HeadLineSeriesBottom, Math.Log(value, 10));
}
}
/// <summary>
/// Gets or sets the he3 head maximum.
/// </summary>
/// <value>
/// The he3 head maximum.
/// </value>
public double He3HeadMax { get; set; }
/// <summary>
/// Gets or sets the he3 pump temperature.
/// </summary>
/// <value>
/// The he3 pump temperature.
/// </value>
public double He3PumpTemp
{
get
{
return this.he3PumpTemp;
}
set
{
this.he3PumpTemp = value;
this.he3PumpTemporaryList = this.AddToGraph(this.he3PumpTemporaryList, this.He3PumpLineSeries, value);
}
}
/// <summary>
/// Gets or sets the he 3 pump actual volt.
/// </summary>
/// <value>
/// The he3 pump actual volt.
/// </value>
public double He3PumpActualVolt { get; set; }
/// <summary>
/// Gets or sets the he 3 pump new volt.
/// </summary>
/// <value>
/// The he3 pump new volt.
/// </value>
public double He3PumpNewVolt { get; set; }
/// <summary>
/// Gets or sets the he 3 pump max.
/// </summary>
/// <value>
/// The he3 pump maximum.
/// </value>
public double He3PumpMax { get; set; }
/// <summary>
/// Gets or sets the he3 switch temperature.
/// </summary>
/// <value>
/// The he3 switch temperature.
/// </value>
public double He3SwitchTemp
{
get
{
return this.he3SwitchTemp;
}
set
{
this.he3SwitchTemp = value;
this.he3SwitchTemporaryList = this.AddToGraph(this.he3SwitchTemporaryList, this.He3SwitchLineSeries, value);
}
}
/// <summary>
/// Gets or sets the he 3 switch actual volt.
/// </summary>
/// <value>
/// The he3 switch actual volt.
/// </value>
public double He3SwitchActualVolt { get; set; }
/// <summary>
/// Gets or sets the he 3 switch new volt.
/// </summary>
/// <value>
/// The he3 switch new volt.
/// </value>
public double He3SwitchNewVolt { get; set; }
/// <summary>
/// Gets or sets the he 3 switch max 1.
/// </summary>
/// <value>
/// The he3 switch max1.
/// </value>
public double He3SwitchMax1 { get; set; }
/// <summary>
/// Gets or sets the he 3 switch max 2.
/// </summary>
/// <value>
/// The he3 switch max2.
/// </value>
public double He3SwitchMax2 { get; set; }
/// <summary>
/// Gets or sets the he4 head temperature.
/// </summary>
/// <value>
/// The he4 head temperature.
/// </value>
public double He4HeadTemp
{
get
{
return this.he4HeadTemp;
}
set
{
this.he4HeadTemp = value;
this.he4HeadTemporaryList = this.AddToGraph(this.he4HeadTemporaryList, this.He4HeadLineSeries, value);
this.he4HeadTemporaryListBottom = this.AddToGraph(this.he4HeadTemporaryListBottom, this.He4HeadLineSeriesBottom, Math.Log(value, 10));
}
}
/// <summary>
/// Gets or sets the he 4 head max.
/// </summary>
/// <value>
/// The he4 head maximum.
/// </value>
public double He4HeadMax { get; set; }
/// <summary>
/// Gets or sets the he4 pump temperature.
/// </summary>
/// <value>
/// The he4 pump temperature.
/// </value>
public double He4PumpTemp
{
get
{
return this.he4PumpTemp;
}
set
{
this.he4PumpTemp = value;
this.he4PumpTemporaryList = this.AddToGraph(this.he4PumpTemporaryList, this.He4PumpLineSeries, value);
}
}
/// <summary>
/// Gets or sets the he 4 pump actual volt.
/// </summary>
/// <value>
/// The he4 pump actual volt.
/// </value>
public double He4PumpActualVolt { get; set; }
/// <summary>
/// Gets or sets the he 4 pump new volt.
/// </summary>
/// <value>
/// The he4 pump new volt.
/// </value>
public double He4PumpNewVolt { get; set; }
/// <summary>
/// Gets or sets the he 4 pump max.
/// </summary>
/// <value>
/// The he4 pump maximum.
/// </value>
public double He4PumpMax { get; set; }
/// <summary>
/// Gets or sets the he4 switch temperature.
/// </summary>
/// <value>
/// The he4 switch temperature.
/// </value>
public double He4SwitchTemp
{
get
{
return this.he4SwitchTemp;
}
set
{
this.he4SwitchTemp = value;
this.he4SwitchTemporaryList = this.AddToGraph(this.he4SwitchTemporaryList, this.He4SwitchLineSeries, value);
}
}
/// <summary>
/// Gets or sets the he 4 switch actual volt.
/// </summary>
/// <value>
/// The he4 switch actual volt.
/// </value>
public double He4SwitchActualVolt { get; set; }
/// <summary>
/// Gets or sets the he 4 switch new volt.
/// </summary>
/// <value>
/// The he4 switch new volt.
/// </value>
public double He4SwitchNewVolt { get; set; }
/// <summary>
/// Gets or sets the he 4 switch max 1.
/// </summary>
/// <value>
/// The he4 switch max1.
/// </value>
public double He4SwitchMax1 { get; set; }
/// <summary>
/// Gets or sets the he 4 switch max 2.
/// </summary>
/// <value>
/// The he4 switch max2.
/// </value>
public double He4SwitchMax2 { get; set; }
/// <summary>
/// Gets or sets the two k plate temperature.
/// </summary>
/// <value>
/// The two k plate temperature.
/// </value>
public double TwoKPlateTemp
{
get
{
return this.twoKPlateTemp;
}
set
{
this.twoKPlateTemp = value;
this.twoKPlateTemporaryList = this.AddToGraph(this.twoKPlateTemporaryList, this.TwoKPlateLineSeries, value);
}
}
/// <summary>
/// Gets or sets the connection state.
/// </summary>
/// <value>
/// The state of the connection.
/// </value>
public double ConnectionState { get; set; }
#endregion Properties
}
}<file_sep>/CryostatControlClientTests/NotificationTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CryostatControlClientTests
{
using CryostatControlClient;
[TestClass]
public class NotificationTest
{
[TestMethod]
public void IsATimeTestCorrect()
{
string data = "Iets interessants of niet";
string level = "Error";
string time = DateTime.Now.ToString("HH:mm:ss");
Notification notification = new Notification(time, level, data);
Assert.AreEqual(data, notification.Data);
Assert.AreEqual(level, notification.Level);
Assert.AreEqual(time, notification.Time);
}
[TestMethod]
public void IsATimeTestCorrect2()
{
string data = "Iets interessants of niet";
string level = "Error";
string time = "02:50:40";
Notification notification = new Notification(time, level, data);
Assert.AreEqual(data, notification.Data);
Assert.AreEqual(level, notification.Level);
Assert.AreEqual(time, notification.Time);
}
[TestMethod]
public void IsATimeTestIncorrect()
{
string data = "Iets interessants of niet";
string level = "Error";
string time = "14:2:04";
Notification notification = new Notification(time, level, data);
Assert.AreEqual(data, notification.Data);
Assert.AreEqual(level, notification.Level);
Assert.AreEqual("Unknown", notification.Time);
}
[TestMethod]
public void IsATimeTestIncorrect2()
{
string data = "Iets interessants of niet";
string level = "Error";
string time = "02:40:77";
Notification notification = new Notification(time, level, data);
Assert.AreEqual(data, notification.Data);
Assert.AreEqual(level, notification.Level);
Assert.AreEqual("Unknown", notification.Time);
}
[TestMethod]
public void IsALevelTestCorrect()
{
string data = "Iets interessants of niet";
string level = "Error";
string level2 = "Warning";
string level3 = "Info";
string time = DateTime.Now.ToString("HH:mm:ss");
Notification notification = new Notification(time, level, data);
Notification notification2 = new Notification(time, level2, data);
Notification notification3 = new Notification(time, level3, data);
Assert.AreEqual(level, notification.Level);
Assert.AreEqual(level2, notification2.Level);
Assert.AreEqual(level3, notification3.Level);
}
[TestMethod]
public void IsALevelTestIncorrect()
{
string data = "Iets interessants of niet";
string level = "Errorr";
string level2 = "warning";
string level3 = "Information";
string time = DateTime.Now.ToString("HH:mm:ss");
Notification notification = new Notification(time, level, data);
Notification notification2 = new Notification(time, level2, data);
Notification notification3 = new Notification(time, level3, data);
Assert.AreEqual("Unknown", notification.Level);
Assert.AreEqual("Unknown", notification2.Level);
Assert.AreEqual("Unknown", notification3.Level);
}
}
}
<file_sep>/CryostatControlServer/HostService/IDataGet.cs
//-----------------------------------------------------------------------
// <copyright file="IDataGet.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.HostService
{
using System.ServiceModel;
/// <summary>
/// Service contract for subscribing for callback methods
/// </summary>
[ServiceContract(
SessionMode = SessionMode.Required,
CallbackContract = typeof(IDataGetCallback))]
public interface IDataGet
{
#region Methods
/// <summary>
/// Subscribes for data callback.
/// </summary>
/// <param name="interval">The interval.</param>
/// <param name="key">The key.</param>
[OperationContract(IsOneWay = true)]
void SubscribeForData(int interval, string key);
/// <summary>
/// Unsubscribes for data callback.
/// </summary>
/// <param name="key">The key.</param>
[OperationContract(IsOneWay = true)]
void UnsubscribeForData(string key);
/// <summary>
/// Subscribes for data callback for receiving update message.
/// </summary>
/// <param name="key">The key.</param>
[OperationContract(IsOneWay = true)]
void SubscribeForUpdates(string key);
/// <summary>
/// Unsubscribes for data callback for receiving update message.
/// </summary>
/// <param name="key">The key.</param>
[OperationContract(IsOneWay = true)]
void UnsubscribeForUpdates(string key);
#endregion Methods
}
}<file_sep>/CryostatControlServer/LakeShore/SensorEnum.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SensorEnum.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.LakeShore
{
/// <summary>
/// The sensor enum.
/// </summary>
public enum SensorEnum
{
/// <summary>
/// The sensor 1: 50K Plate.
/// </summary>
Plate50K,
/// <summary>
/// The sensor 2: 3K Plate.
/// </summary>
Plate3K,
}
}
<file_sep>/CryostatControlServer/Compressor/Enumerators/TemperatureEnum.cs
//-----------------------------------------------------------------------
// <copyright file="TemperatureEnum.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.Compressor
{
/// <summary>
/// Enumerator for the temperature scale
/// </summary>
public enum TemperatureEnum
{
/// <summary>
/// The fahrenheit scale
/// </summary>
Fahrenheit = 0,
/// <summary>
/// The celsius scale
/// </summary>
Celsius = 1,
/// <summary>
/// The kelvin scale
/// </summary>
Kelvin = 2
}
}<file_sep>/CryostatControlClient/Models/ModusModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ModusModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Models
{
using System;
/// <summary>
/// The model for the modi
/// </summary>
public class ModusModel
{
#region Fields
#endregion Fields
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ModusModel"/> class.
/// </summary>
public ModusModel()
{
this.Time = "Now";
this.SelectedDate = DateTime.Now;
}
#endregion Constructor
#region Properties
/// <summary>
/// Gets or sets the planned time.
/// </summary>
/// <value>
/// The planned time.
/// </value>
public DateTime PlannedTime { get; set; }
/// <summary>
/// Gets or sets the show date time.
/// </summary>
/// <value>
/// The show date time.
/// </value>
public string ShowDateTime { get; set; }
/// <summary>
/// Gets or sets the selected time.
/// </summary>
/// <value>
/// The selected time.
/// </value>
public DateTime SelectedTime { get; set; }
/// <summary>
/// Gets or sets the selected date.
/// </summary>
/// <value>
/// The selected date.
/// </value>
public DateTime SelectedDate { get; set; }
/// <summary>
/// Gets or sets the index of the selected combo index.
/// </summary>
/// <value>
/// The index of the selected combo index.
/// </value>
public int SelectedComboIndex { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the server is connected.
/// </summary>
/// <value>
/// <c>true</c> if server is connected; otherwise, <c>false</c>.
/// </value>
public bool ServerConnection { get; set; }
/// <summary>
/// Gets or sets the time.
/// </summary>
/// <value>
/// The time.
/// </value>
public string Time { get; set; }
/// <summary>
/// Gets or sets the modus.
/// </summary>
/// <value>
/// The modus.
/// </value>
public int Modus { get; set; }
#endregion Properties
}
}
<file_sep>/CryostatControlClient/ViewModels/LoggingPresets/LogBlueforsPreset.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LogBlueforsPreset.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels.LoggingPresets
{
/// <summary>
/// The log nothing preset.
/// </summary>
public class LogBlueforsPreset : ILoggingPreset
{
/// <summary>
/// Initializes a new instance of the <see cref="LogBlueforsPreset"/> class.
/// </summary>
/// <param name="loggingViewModel">
/// The logging view model.
/// </param>
public LogBlueforsPreset(LoggingViewModel loggingViewModel)
{
this.SetLoggingValues(loggingViewModel);
}
/// <summary>
/// Sets the logging values.
/// </summary>
/// <param name="loggingViewModel">The logging view model.</param>
public void SetLoggingValues(LoggingViewModel loggingViewModel)
{
loggingViewModel.LoggingInterval = 10.0;
loggingViewModel.He3PumpVolt = false;
loggingViewModel.He3SwitchVolt = false;
loggingViewModel.He4PumpVolt = false;
loggingViewModel.He4SwitchVolt = false;
loggingViewModel.FourKPlateTemp = false;
loggingViewModel.TwoKPlateTemp = false;
loggingViewModel.Bluefors3KShieldTemp = true;
loggingViewModel.Bluefors50KShieldTemp = true;
loggingViewModel.CompressorHeliumTemp = false;
loggingViewModel.CompressorOilTemp = false;
loggingViewModel.CompressorWaterInTemp = false;
loggingViewModel.CompressorWaterOutTemp = false;
loggingViewModel.He3HeadTemp = false;
loggingViewModel.He4SwitchTemp = false;
loggingViewModel.He4HeadTemp = false;
loggingViewModel.He3SwitchTemp = false;
loggingViewModel.He3PumpTemp = false;
loggingViewModel.He4PumpTemp = false;
loggingViewModel.CompressorDeltaAveragePressure = false;
loggingViewModel.CompressorDeltaAveragePressure = false;
loggingViewModel.CompressorHighPressure = false;
loggingViewModel.CompressorHighAveragePressure = false;
loggingViewModel.CompressorLowPressure = false;
loggingViewModel.CompressorLowAveragePressure = false;
}
}
}
<file_sep>/CryostatControlClient/ViewModels/LoggingPresets/ILoggingPreset.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ILoggingPreset.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels.LoggingPresets
{
/// <summary>
/// The general logging preset.
/// </summary>
public interface ILoggingPreset
{
/// <summary>
/// Sets the logging values.
/// </summary>
/// <param name="loggingViewModel">The logging view model.</param>
void SetLoggingValues(LoggingViewModel loggingViewModel);
}
}
<file_sep>/CryostatControlClient/Models/ChartModel.cs
//-----------------------------------------------------------------------
// <copyright file="ChartModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlClient.Models
{
using System;
using System.Windows.Input;
using LiveCharts;
using LiveCharts.Wpf;
/// <summary>
/// The chart model
/// </summary>
/// <seealso cref="CryostatControlClient.Models.AbstractModel" />
public class ChartModel : AbstractModel
{
#region Fields
/// <summary>
/// The room temperature
/// </summary>
private const int RoomTemperature = 300;
/// <summary>
/// The coldest temperature
/// </summary>
private const int ColdestTemperature = 0;
/// <summary>
/// The x axis
/// </summary>
private Axis xAxis;
/// <summary>
/// The y axis
/// </summary>
private Axis yAxis;
#endregion Fields
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ChartModel"/> class.
/// </summary>
public ChartModel()
{
this.ZoomingMode = ZoomingOptions.X;
this.xAxis = new Axis();
this.xAxis.Title = "Time";
this.XAxisCollection = new AxesCollection();
this.XAxisCollection.Add(this.xAxis);
this.yAxis = new Axis();
this.yAxis.Title = "Kelvin";
this.YAxisCollection = new AxesCollection();
this.YAxisCollection.Add(this.yAxis);
this.xAxis.LabelFormatter = val => this.GetDateTime(val).ToString("HH:mm");
}
#endregion Constructor
#region Properties
/// <summary>
/// Gets or sets the x axis maximum.
/// </summary>
/// <value>
/// The x axis maximum.
/// </value>
public DateTime XMax
{
get
{
return this.GetDateTime(this.xAxis.MaxValue);
}
set
{
if (value == DateTime.Now)
{
this.xAxis.MaxValue = double.NaN;
}
else
{
this.xAxis.MaxValue = value.Ticks;
}
}
}
/// <summary>
/// Gets or sets the x axis minimum.
/// </summary>
/// <value>
/// The x axis minimum.
/// </value>
public DateTime XMin
{
get
{
return this.GetDateTime(this.xAxis.MinValue);
}
set
{
if (value == DateTime.Now)
{
this.xAxis.MinValue = double.NaN;
}
else
{
this.xAxis.MinValue = value.Ticks;
}
}
}
/// <summary>
/// Gets or sets the y axis maximum.
/// </summary>
/// <value>
/// The y axis maximum.
/// </value>
public double YMax
{
get
{
double temp = this.yAxis.MaxValue;
if (double.IsNaN(temp))
{
return RoomTemperature;
}
else
{
return temp;
}
}
set
{
this.yAxis.MaxValue = value;
}
}
/// <summary>
/// Gets or sets the y axis maximum.
/// </summary>
/// <value>
/// The y axis maximum.
/// </value>
public double YMin
{
get
{
double temp = this.yAxis.MinValue;
if (double.IsNaN(temp))
{
return ColdestTemperature;
}
else
{
return temp;
}
}
set
{
this.yAxis.MinValue = value;
}
}
/// <summary>
/// Gets the x axis collection.
/// </summary>
/// <value>
/// The x axis collection.
/// </value>
public AxesCollection XAxisCollection { get; }
/// <summary>
/// Gets the y axis collection.
/// </summary>
/// <value>
/// The y axis collection.
/// </value>
public AxesCollection YAxisCollection { get; }
/// <summary>
/// Gets or sets the zooming mode.
/// </summary>
/// <value>
/// The zooming mode.
/// </value>
public ZoomingOptions ZoomingMode { get; set; }
#endregion Properties
#region Methods
/// <summary>
/// Gets the date time.
/// </summary>
/// <param name="val">The value.</param>
/// <returns>Time in hours and minutes.</returns>
public DateTime GetDateTime(double val)
{
try
{
return new DateTime((long)val);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.ToString());
return DateTime.Now;
}
}
#endregion Methods
}
}<file_sep>/CryostatControlServer/NotificationSender.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="NotificationSender.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer
{
using CryostatControlServer.HostService;
/// <summary>
/// The notification sender.
/// </summary>
public class NotificationSender
{
/// <summary>
/// The command service.
/// </summary>
private static CommandService commandService;
/// <summary>
/// The initialization of the Notification Sender.
/// </summary>
/// <param name="newCommandService">
/// The new command service.
/// </param>
public static void Init(CommandService newCommandService)
{
commandService = newCommandService;
}
/// <summary>
/// Sends an error.
/// </summary>
/// <param name="time">
/// The time.
/// </param>
/// <param name="data">
/// The data.
/// </param>
public static void Error(string time, string data)
{
string error = "ERROR";
string[] message = new[] { time, error, data };
SendData(message);
}
/// <summary>
/// Sends a warning.
/// </summary>
/// <param name="time">
/// The time.
/// </param>
/// <param name="data">
/// The data.
/// </param>
public static void Warning(string time, string data)
{
string warning = "Warning";
string[] message = new[] { time, warning, data };
SendData(message);
}
/// <summary>
/// Sends info.
/// </summary>
/// <param name="time">
/// The time.
/// </param>
/// <param name="data">
/// The data.
/// </param>
public static void Info(string time, string data)
{
string info = "Info";
string[] message = new[] { time, info, data };
SendData(message);
}
/// <summary>
/// Sends the data.
/// </summary>
/// <param name="message">
/// The message.
/// </param>
private static void SendData(string[] message)
{
commandService.UpdateNotification(message);
}
}
}
<file_sep>/CryostatControlClient/Models/SettingModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SettingModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Models
{
/// <summary>
/// The setting model.
/// </summary>
public class SettingModel
{
/// <summary>
/// Initializes a new instance of the <see cref="SettingModel"/> class.
/// </summary>
/// <param name="id">
/// The id.
/// </param>
/// <param name="value">
/// The value.
/// </param>
/// <param name="title">
/// The title.
/// </param>
/// <param name="unit">
/// The unit.
/// </param>
public SettingModel(int id, double value, string title, string unit)
{
this.Id = id;
this.Value = value;
this.Title = title;
this.Unit = unit;
}
/// <summary>
/// Gets the id.
/// </summary>
/// <value>
/// The identifier.
/// </value>
public int Id { get; }
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>
/// The title.
/// </value>
public string Title { get; set; }
/// <summary>
/// Gets the unit.
/// </summary>
/// <value>
/// The unit.
/// </value>
public string Unit { get; }
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>
/// The value.
/// </value>
public double Value { get; set; }
}
}<file_sep>/CryostatControlServer/Compressor/Enumerators/EnergizedEnum.cs
//-----------------------------------------------------------------------
// <copyright file="EnergizedEnum.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.Compressor
{
/// <summary>
/// Enumerator for Energy state.
/// </summary>
public enum EnergizedEnum
{
/// <summary>
/// On state
/// </summary>
On = 1,
/// <summary>
/// Off state
/// </summary>
Off = 2
}
}<file_sep>/CryostatControlClient/ViewModels/LoggingPresets/LogCompressorPreset.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LogCompressorPreset.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels.LoggingPresets
{
/// <summary>
/// The log compressor preset.
/// </summary>
public class LogCompressorPreset : ILoggingPreset
{
/// <summary>
/// Initializes a new instance of the <see cref="LogCompressorPreset"/> class.
/// </summary>
/// <param name="loggingViewModel">The logging view model.</param>
public LogCompressorPreset(LoggingViewModel loggingViewModel)
{
this.SetLoggingValues(loggingViewModel);
}
/// <summary>
/// Sets the logging values.
/// </summary>
/// <param name="loggingViewModel">The logging view model.</param>
public void SetLoggingValues(LoggingViewModel loggingViewModel)
{
loggingViewModel.LoggingInterval = 10.0;
loggingViewModel.He3PumpVolt = false;
loggingViewModel.He3SwitchVolt = false;
loggingViewModel.He4PumpVolt = false;
loggingViewModel.He4SwitchVolt = false;
loggingViewModel.FourKPlateTemp = false;
loggingViewModel.TwoKPlateTemp = false;
loggingViewModel.Bluefors3KShieldTemp = false;
loggingViewModel.Bluefors50KShieldTemp = false;
loggingViewModel.CompressorHeliumTemp = true;
loggingViewModel.CompressorOilTemp = true;
loggingViewModel.CompressorWaterInTemp = true;
loggingViewModel.CompressorWaterOutTemp = true;
loggingViewModel.He3HeadTemp = false;
loggingViewModel.He4SwitchTemp = false;
loggingViewModel.He4HeadTemp = false;
loggingViewModel.He3SwitchTemp = false;
loggingViewModel.He3PumpTemp = false;
loggingViewModel.He4PumpTemp = false;
loggingViewModel.CompressorDeltaAveragePressure = true;
loggingViewModel.CompressorDeltaAveragePressure = true;
loggingViewModel.CompressorHighPressure = true;
loggingViewModel.CompressorHighAveragePressure = true;
loggingViewModel.CompressorLowPressure = true;
loggingViewModel.CompressorLowAveragePressure = true;
}
}
}
<file_sep>/CryostatControlClient/Views/MainWindow.xaml.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainWindow.xaml.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Views
{
using System;
using System.Windows;
using CryostatControlClient.Communication;
using CryostatControlClient.ViewModels;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region Fields
/// <summary>
/// The viewmodel container
/// </summary>
private ViewModelContainer viewModelContainer;
#endregion Fields
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="MainWindow"/> class.
/// </summary>
public MainWindow()
{
this.Loaded += this.MainWindowLoaded;
}
#endregion Constructor
/// <summary>
/// Gets the view model container.
/// </summary>
/// <value>
/// The view model container.
/// </value>
public ViewModelContainer Container
{
get
{
return this.viewModelContainer;
}
}
#region Methods
/// <summary>
/// Handles the Loaded event of the MainWindow control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
private void MainWindowLoaded(object sender, RoutedEventArgs e)
{
this.viewModelContainer = new ViewModelContainer();
this.DataContext = this.viewModelContainer;
}
#endregion Methods
}
}<file_sep>/CryostatControlServer/Controller.StateMachine.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Controller.StateMachine.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer
{
using System;
using CryostatControlServer.Logging;
using CryostatControlServer.Properties;
/// <summary>
/// The sequential controller.
/// </summary>
public partial class Controller
{
/// <summary>
/// The state machine that controls the heater.
/// Controls the Cool down, Heat up and Recycle processes, by walking trough a state machine.
/// State should not be modified by external classes.
/// </summary>
/// <para>
/// State machine design
/// The entire state machine is intentionally placed in a single function.
/// Use of the State pattern was considered but rejected for clarity and maintainability.
/// The design of the state machine is discussed on github:
/// https://github.com/BBekker/CryostatControl/pull/88
/// Access can be requested by emailing: <EMAIL>
/// </para>
/// <para>
/// States
/// To view all states see <see cref="Controlstate"/>
/// </para>
private void StateMachine()
{
try
{
this.SafetyCheckHeatSwitch();
this.SafetyCheckPumps();
switch (this.State)
{
case Controlstate.Setup:
if (this.cooler != null && this.cooler.IsConnected() && this.lakeshore != null
&& this.compressor != null)
{
this.State = Controlstate.Standby;
}
break;
case Controlstate.Standby: break;
case Controlstate.Manual: break;
case Controlstate.CooldownStart:
if (DateTime.Now > this.startTime)
{
this.State = Controlstate.CooldownWaitForPressure;
}
break;
case Controlstate.CooldownWaitForPressure:
// TODO: wait for pressure when sensor is connected
this.State = Controlstate.CooldownStartCompressor;
break;
case Controlstate.CooldownStartCompressor:
try
{
this.compressor.TurnOn();
}
catch (Exception ex)
{
DebugLogger.Error(this.GetType().Name, "Compressor gave error: " + ex);
}
this.State = Controlstate.CooldownWait70K;
break;
case Controlstate.CooldownWait70K:
if (this.cooler.He3PumpT.Value < this.He7StartTemperature
|| this.cooler.He4PumpT.Value < this.He7StartTemperature)
{
this.State = Controlstate.CooldownWaitSwitches;
}
break;
case Controlstate.CooldownWaitSwitches:
this.SetHeaterTemperature(
this.cooler.He3Pump,
this.HeaterTemperatureSetpoint,
Settings.Default.ControllerHeaterLowPowerValue);
this.SetHeaterTemperature(
this.cooler.He4Pump,
this.HeaterTemperatureSetpoint,
Settings.Default.ControllerHeaterLowPowerValue);
if (this.cooler.He3SwitchT.Value < this.HeatSwitchOnTemperature
&& this.cooler.He4SwitchT.Value < this.HeatSwitchOnTemperature)
{
this.State = Controlstate.CooldownWait4K;
}
break;
case Controlstate.CooldownWait4K:
this.ControlHe3PumpHeater();
this.ControlHe4PumpHeater();
if (this.cooler.He3HeadT.Value < this.He4StartTemperature
&& this.cooler.He4HeadT.Value < this.He4StartTemperature)
{
this.State = Controlstate.CooldownCondenseHe4;
}
break;
case Controlstate.CooldownCondenseHe4:
this.ControlHe3PumpHeater();
this.ControlHe4PumpHeater();
if (this.cooler.He4HeadT.Value < this.He4StartTemperature)
{
this.State = Controlstate.CooldownTurnOffHe4;
}
break;
case Controlstate.CooldownTurnOffHe4:
this.ControlHe3PumpHeater();
this.SetHeaterVoltage(this.cooler.He4Pump, 0.0);
this.State = Controlstate.CooldownControlHe4Switch;
break;
case Controlstate.CooldownControlHe4Switch:
this.ControlHe3PumpHeater();
if (this.cooler.Plate4KT.Value < this.HeatSwitchSafeValue)
{
this.cooler.He4Switch.Voltage = this.He4SwitchVoltage;
}
if (this.cooler.He4SwitchT.Value > this.HeatSwitchOnTemperature)
{
this.State = Controlstate.CooldownWaitHe3Heater;
}
break;
case Controlstate.CooldownWaitHe3Heater:
this.ControlHe3PumpHeater();
if (this.cooler.He3PumpT.Value > this.HeaterTemperatureSetpoint * 0.8
&& this.cooler.He3PumpT.Value > 25.0)
{
this.state = Controlstate.CooldownDisableHe3PumpHeater;
}
break;
case Controlstate.CooldownDisableHe3PumpHeater:
this.SetHeaterVoltage(this.cooler.He3Pump, 0.0);
this.State = Controlstate.CooldownCondenseHe3;
break;
case Controlstate.CooldownCondenseHe3:
if (this.cooler.He3HeadT.Value < this.He3StartTemperature
|| (this.cooler.He3HeadT.Value < this.He3StartMinimalTemperature
&& (DateTime.Now - this.stateEnteredTime)
> new TimeSpan(0, (int)this.He3StartWaitTimeMinutes, 0)))
{
this.State = Controlstate.CooldownControlHe3;
}
break;
case Controlstate.CooldownControlHe3:
if (this.cooler.Plate4KT.Value < this.HeatSwitchSafeValue)
{
this.cooler.He3Switch.Voltage = this.He3SwitchVoltage;
}
if (this.cooler.He3SwitchT.Value > this.HeatSwitchOnTemperature)
{
this.State = Controlstate.CooldownFinished;
}
break;
case Controlstate.CooldownFinished:
this.State = Controlstate.Standby;
break;
case Controlstate.RecycleStart:
if (DateTime.Now > this.startTime)
{
this.SetHeaterVoltage(this.cooler.He3Switch, 0.0);
this.SetHeaterVoltage(this.cooler.He4Switch, 0.0);
this.compressor.TurnOn();
this.State = Controlstate.RecycleHeatPumps;
}
break;
case Controlstate.RecycleHeatPumps:
this.ControlHe3PumpHeater();
this.ControlHe4PumpHeater();
if (this.cooler.He3PumpT.Value > this.HeaterTemperatureSetpoint - 1.0
&& this.cooler.He4PumpT.Value > this.HeaterTemperatureSetpoint - 1.0)
{
this.State = Controlstate.CooldownCondenseHe4;
}
break;
case Controlstate.WarmupStart:
if (DateTime.Now > this.startTime)
{
try
{
this.compressor.TurnOff();
}
catch (Exception)
{
DebugLogger.Warning(
this.GetType().Name,
"Compressor not connected, make sure it is turned off!");
}
this.State = Controlstate.WarmupHeating;
}
break;
case Controlstate.WarmupHeating:
this.SetHeaterTemperature(
this.cooler.He3Pump,
this.HeatupTemperature,
Settings.Default.ControllerHe3HeaterPower);
this.SetHeaterTemperature(
this.cooler.He4Pump,
this.HeatupTemperature,
Settings.Default.ControllerHe4HeaterPower);
this.cooler.He3Switch.Voltage = this.He3SwitchVoltage;
this.cooler.He4Switch.Voltage = this.He4SwitchVoltage;
if (this.cooler.He4PumpT.Value > this.HeatupTemperature
&& this.cooler.He3PumpT.Value > this.HeatupTemperature
&& this.cooler.He4SwitchT.Value > this.HeatupTemperature
&& this.cooler.He3SwitchT.Value > this.HeatupTemperature)
{
this.State = Controlstate.WarmupFinished;
}
break;
case Controlstate.WarmupFinished:
this.State = Controlstate.Standby;
break;
case Controlstate.Cancel:
this.ResetAllValues();
this.State = Controlstate.Standby;
break;
case Controlstate.Stop:
this.SetHeaterVoltage(this.cooler.He3Pump, 0.0);
this.SetHeaterVoltage(this.cooler.He4Pump, 0.0);
this.SetHeaterVoltage(this.cooler.He3Switch, 0.0);
this.SetHeaterVoltage(this.cooler.He4Switch, 0.0);
if (this.compressor.IsConnected())
{
this.compressor.TurnOff();
}
this.State = Controlstate.Standby;
break;
}
}
catch (Exception e)
{
DebugLogger.Error("Controller", e.GetType().ToString() + $" in the controller in state {this.state}!");
Console.Write(e.ToString());
}
}
}
}
<file_sep>/CryostatControlServer/Streams/BaseManagedStream.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BaseManagedStream.cs" company="SRON">
// bla
// </copyright>
// <summary>
// Defines the BaseManagedStream type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// #define ShowCommunication
namespace CryostatControlServer.Streams
{
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// The base managed stream.
/// </summary>
public abstract class BaseManagedStream : IManagedStream
{
#region Fields
/// <summary>
/// The buffer size of the reader and writer.
/// </summary>
private const int BufferSize = 1024;
/// <summary>
/// The reader.
/// </summary>
private StreamReader reader;
/// <summary>
/// The stream writer.
/// </summary>
private StreamWriter writer;
#endregion Fields
#region Properties
/// <summary>
/// Gets or sets the contained stream.
/// </summary>
protected Stream ContainedStream { get; set; }
#endregion Properties
#region Methods
/// <summary>
/// The open.
/// </summary>
public abstract void Open();
/// <summary>
/// The close.
/// </summary>
public abstract void Close();
/// <summary>
/// The is connected.
/// </summary>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
public abstract bool IsConnected();
/// <summary>
/// Writes a string to the device. Does not add a terminator.
/// </summary>
/// <param name="stringToWrite">The string to write.</param>
public void WriteString(string stringToWrite)
{
#if (DEBUG && ShowCommunication)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(stringToWrite);
Console.ForegroundColor = ConsoleColor.White;
}
#endif
this.writer.Write(stringToWrite);
this.writer.Flush();
}
/// <summary>
/// Reads a complete line from the port.
/// Reads until either a newline (\n), carriage return (\r) or combination. The terminator is not included.
/// </summary>
/// <returns> The read string</returns>
public string ReadString()
{
var res = this.reader.ReadLine();
#if (DEBUG && ShowCommunication)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(res);
Console.ForegroundColor = ConsoleColor.White;
}
#endif
return res;
}
/// <summary>
/// Reads the string asynchronous. Same as ReadString
/// </summary>
/// <returns>the read string</returns>
public async Task<string> ReadStringAsync()
{
var res = await this.reader.ReadLineAsync();
#if (DEBUG && ShowCommunication)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(res);
Console.ForegroundColor = ConsoleColor.White;
}
#endif
return res;
}
/// <summary>
/// Initialization code shared by connectTCP and connectCOM.
/// </summary>
internal void Init()
{
this.reader = new StreamReader(this.ContainedStream, Encoding.ASCII, false, BufferSize, true);
this.writer = new StreamWriter(this.ContainedStream, Encoding.ASCII, BufferSize, true);
}
#endregion Methods
}
}<file_sep>/CryostatControlServerTests/He7Cooler/HeaterTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CryostatControlServerTests.He7Cooler
{
using System.Collections.Generic;
using System.Threading;
using CryostatControlServer.He7Cooler;
using Moq;
using Moq.Protected;
[TestClass]
public class HeaterTest
{
private Dictionary<Channels, double> values = new Dictionary<Channels, double>();
private Dictionary<Channels, double> outvalues = new Dictionary<Channels, double>();
private He7Cooler getCoolerMock()
{
var AgilentMock = new Mock<Agilent34972A>();
AgilentMock.Setup<double[]>((obj) => obj.GetVoltages(It.IsAny<Channels[]>())).Returns<Channels[]>(
(channels) =>
{
var res = new double[channels.Length];
for (int i = 0; i < channels.Length; i++)
{
if (!this.values.TryGetValue(channels[i], out res[i]))
{
res[i] = 0.0;
}
}
return res;
});
AgilentMock.Setup(obj => obj.SetHeaterVoltage(It.IsAny<Channels>(), It.IsAny<double>()))
.Callback<Channels, double>(
(channel, value) =>
{
if (this.outvalues.ContainsKey(channel))
{
this.outvalues[channel] = value;
}
else
{
this.outvalues.Add(channel, value);
}
});
var cooler = new He7Cooler();
cooler.Connect(AgilentMock.Object, false);
return cooler;
}
[TestMethod]
public void TestReadVoltage()
{
var cooler = this.getCoolerMock();
this.values.Add(Channels.SensHe3Pump, 1.0);
cooler.ReadVoltages();
He7Cooler.Heater heater = new He7Cooler.Heater(Channels.PumpHe3, Channels.SensHe3Pump, cooler);
Assert.AreEqual(1.0, heater.Voltage);
this.values[Channels.SensHe3Pump] = 10.0;
cooler.ReadVoltages();
Assert.AreEqual(10.0, heater.Voltage);
}
[TestMethod]
public void TestReadCurrent()
{
var cooler = this.getCoolerMock();
this.values.Add(Channels.SensHe3Pump, 1.0);
He7Cooler.Heater heater = new He7Cooler.Heater(Channels.PumpHe3, Channels.SensHe3Pump, cooler.He3PumpT, 100, Calibration.EmptyCalibration, cooler);
cooler.ReadVoltages();
Assert.AreEqual(0.01, heater.Current);
this.values[Channels.SensHe3Pump] = 10;
cooler.ReadVoltages();
Assert.AreEqual(0.1, heater.Current);
}
[TestMethod]
public void TestReadPower()
{
var cooler = this.getCoolerMock();
this.values.Add(Channels.SensHe3Pump, 1.0);
He7Cooler.Heater heater = new He7Cooler.Heater(Channels.PumpHe3, Channels.SensHe3Pump, cooler.He3PumpT, 100, Calibration.EmptyCalibration, cooler);
cooler.ReadVoltages();
Assert.AreEqual(0.01, heater.Power);
this.values[Channels.SensHe3Pump] = 10;
cooler.ReadVoltages();
Assert.AreEqual(1, heater.Power);
}
[TestMethod]
public void TestWritePower()
{
var cooler = this.getCoolerMock();
this.values.Add(Channels.SensHe3Pump, 1.0);
He7Cooler.Heater heater = new He7Cooler.Heater(Channels.PumpHe3, Channels.SensHe3Pump, cooler.He3PumpT, 10, Calibration.EmptyCalibration, cooler);
heater.Power = 1;
Assert.AreEqual(3.162, this.outvalues[Channels.PumpHe3], 0.001);
}
[TestMethod]
public void TestWriteCurrent()
{
var cooler = this.getCoolerMock();
this.values.Add(Channels.SensHe3Pump, 1.0);
He7Cooler.Heater heater = new He7Cooler.Heater(Channels.PumpHe3, Channels.SensHe3Pump, cooler.He3PumpT, 10, Calibration.EmptyCalibration, cooler);
heater.Current = 0.5;
Assert.AreEqual(5.0, this.outvalues[Channels.PumpHe3], 0.001);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException), "Should have thrown out of range exception, but didn't.")]
public void TestWriteVoltageSafety()
{
var cooler = this.getCoolerMock();
this.values.Add(Channels.SensHe3Pump, 1.0);
He7Cooler.Heater heater = new He7Cooler.Heater(Channels.PumpHe3, Channels.SensHe3Pump, cooler.He3PumpT, 10, Calibration.EmptyCalibration, cooler);
heater.SafeRangeHigh = 5.0;
heater.Voltage = 6.0;
}
[TestMethod]
public void TestWriteVoltageCalibration()
{
var cooler = this.getCoolerMock();
var calibration = new Calibration();
calibration.AddCalibrationDatapoint(new Tuple<double,double>(0.0,0.0));
calibration.AddCalibrationDatapoint(new Tuple<double, double>(10.0, 20.0));
He7Cooler.Heater heater = new He7Cooler.Heater(Channels.PumpHe3, Channels.SensHe3Pump, cooler.He3PumpT, 10, calibration, cooler);
heater.SafeRangeHigh = 20.0;
heater.Voltage = 5.0;
Assert.AreEqual(10, this.outvalues[Channels.PumpHe3], 0.001);
}
[TestMethod]
public void TestTemperatureControlPower()
{
var cooler = this.getCoolerMock();
He7Cooler.Heater heater = new He7Cooler.Heater(Channels.PumpHe3, Channels.SensHe3Pump, cooler.He3PumpT, 10, Calibration.EmptyCalibration, cooler);
heater.TemperatureSetpoint = 100.0;
heater.TemperatureControlEnabled = true;
heater.PowerLimit = 1.0;
this.values[Channels.SensHe3PumpT] = 1.7;
cooler.ReadVoltages();
heater.Notify();
Assert.AreEqual(3.162, this.outvalues[Channels.PumpHe3], 0.001);
}
}
}
<file_sep>/CryostatControlServerTests/Logging/LoggerDataObjectTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CryostatControlServerTests.Logging
{
using CryostatControlServer.Logging;
[TestClass]
public class LoggerDataObjectTest
{
[TestMethod]
public void LoggerDataObjectCreate()
{
AbstractDataLogger abstractDataLogger = new GeneralDataLogger();
string filePath = "test.csv";
LoggerDataObject loggerDataObject = new LoggerDataObject(abstractDataLogger, filePath);
Assert.AreEqual(abstractDataLogger, loggerDataObject.GetAbstractLogData());
Assert.AreEqual(filePath, loggerDataObject.GetFilePath());
}
}
}
<file_sep>/CryostatControlServer/He7Cooler/Calibration.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Calibration.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.He7Cooler
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using CryostatControlServer.Logging;
/// <summary>
/// Sensor calibration representation
/// </summary>
public class Calibration
{
/// <summary>
/// The diode file.
/// </summary>
private const string DIODEFile = "Calibrations\\DIODE.CAL";
/// <summary>
/// The ruox file.
/// </summary>
[SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1650:ElementDocumentationMustBeSpelledCorrectly",
Justification = "Reviewed. Suppression is OK here.")]
private const string RUOXFile = "Calibrations\\RUOX.CAL";
/// <summary>
/// The amplifiers calibration file.
/// </summary>
private const string AmplifiersFile = "Calibrations\\AMPLIFIERS.cal";
/// <summary>
/// The calibration data.
/// </summary>
private List<Tuple<double, double>> calibrationData = new List<Tuple<double, double>>();
/// <summary>
/// Initializes a new instance of the <see cref="Calibration"/> class.
/// Initializes an empty instance without calibration.
/// </summary>
public Calibration()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Calibration"/> class.
/// </summary>
/// <param name="filename">
/// The filename of the calibration file.
/// </param>
/// <param name="voltColumn">
/// The volt column index.
/// </param>
/// <param name="tempColumn">
/// The temp column index.
/// </param>
public Calibration(string filename, int voltColumn, int tempColumn)
{
this.LoadSensorCalibrationFromFile(filename, voltColumn, tempColumn);
}
/// <summary>
/// Gets the diode calibration.
/// </summary>
public static Calibration DiodeCalibration { get; } = new Calibration(DIODEFile, 1, 0);
/// <summary>
/// Gets the empty calibration.
/// </summary>
public static Calibration EmptyCalibration { get; } = new Calibration();
/// <summary>
/// Gets the he 3 calibration.
/// </summary>
public static Calibration He3Calibration { get; } = new Calibration(RUOXFile, 2, 0);
/// <summary>
/// Gets the he 4 calibration.
/// </summary>
public static Calibration He4Calibration { get; } = new Calibration(RUOXFile, 3, 0);
/// <summary>
/// Gets the he 3 amplifier calibration.
/// </summary>
public static Calibration He3AmplifierCalibration { get; } = new Calibration(AmplifiersFile, 1, 0);
/// <summary>
/// Gets the he 4 amplifier calibration.
/// </summary>
public static Calibration He4AmplifierCalibration { get; } = new Calibration(AmplifiersFile, 2, 0);
/// <summary>
/// The amount of data points in the calibration
/// </summary>
public int CalibrationSize => this.calibrationData.Count;
/// <summary>
/// Add a calibration data point.
/// Exists mainly to be able to test this class.
/// </summary>
/// <param name="datapoint">
/// The data point.
/// </param>
public void AddCalibrationDatapoint(Tuple<double, double> datapoint)
{
this.calibrationData.Add(datapoint);
this.calibrationData.Sort((first, second) => (int)(first.Item1 - second.Item1));
}
/// <summary>
/// Convert a voltage to a temperature using the loaded calibration
/// </summary>
/// <param name="readVolt">
/// The sensor voltage.
/// </param>
/// <returns>
/// The temperature in Kelvin <see cref="double"/>.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Thrown if there is no calibration found. Should never happen, does not need to be handled.
/// </exception>
public double ConvertValue(double readVolt)
{
// directly return for uncalibrated sensors
if (this.calibrationData.Count == 0)
{
return readVolt;
}
// Check if voltage is outside of the range of calibration values
if (readVolt > this.calibrationData[this.calibrationData.Count - 1].Item1)
{
return this.calibrationData[this.calibrationData.Count - 1].Item2;
}
if (readVolt < this.calibrationData[0].Item1)
{
return this.calibrationData[0].Item2;
}
// find closest calibration points and linearly interpolate between them.
for (int i = 1; i < this.calibrationData.Count; i++)
{
if (this.calibrationData[i].Item1 >= readVolt)
{
return InterpolateTemperature(readVolt, this.calibrationData[i - 1], this.calibrationData[i]);
}
}
// this should never be reached.
DebugLogger.Error(this.GetType().Name, "Calibration code failed.");
throw new InvalidOperationException("Calibration code failed.");
}
/// <summary>
/// Load sensor calibration from file.
/// </summary>
/// <param name="filename">
/// The filename.
/// </param>
/// <param name="voltColumn">
/// The volt column.
/// </param>
/// <param name="tempColumn">
/// The temp column.
/// </param>
public void LoadSensorCalibrationFromFile(string filename, int voltColumn, int tempColumn)
{
StreamReader reader = new StreamReader(filename);
try
{
// skip first line that contains headers
reader.ReadLine();
string line;
while ((line = reader.ReadLine()) != null)
{
string[] columns = line.Split('\t');
this.calibrationData.Add(
new Tuple<double, double>(
double.Parse(columns[voltColumn]),
double.Parse(columns[tempColumn])));
}
this.calibrationData.Sort((first, second) => (first.Item1 - second.Item1) < 0 ? -1 : 1);
}
finally
{
reader.Close();
}
}
/// <summary>
/// Standard linear interpolation of volt to temperature calibration values.
/// </summary>
/// <param name="voltage">
/// The read voltage.
/// </param>
/// <param name="lowValue">
/// The calibration value just below the read voltage.
/// </param>
/// <param name="highValue">
/// The calibration value just above the read voltage.
/// </param>
/// <returns>
/// Interpolated temperature. <see cref="double"/>.
/// </returns>
private static double InterpolateTemperature(
double voltage,
Tuple<double, double> lowValue,
Tuple<double, double> highValue)
{
return ((voltage - lowValue.Item1) / (highValue.Item1 - lowValue.Item1)
* (highValue.Item2 - lowValue.Item2)) + lowValue.Item2;
}
}
}<file_sep>/CryostatControlClient/Communication/DataClientCallback.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataClientCallback.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient
{
using System;
using CryostatControlClient.Communication;
using CryostatControlClient.ServiceReference1;
using CryostatControlClient.Views;
/// <summary>
/// Class which handles the data callback calls from the server
/// </summary>
/// <seealso cref="CryostatControlClient.ServiceReference1.IDataGetCallback" />
public class DataClientCallback : IDataGetCallback
{
#region Fields
/// <summary>
/// The main application
/// </summary>
private App mainApp;
/// <summary>
/// The main window
/// </summary>
private MainWindow mainWindow;
/// <summary>
/// The data receiver
/// </summary>
private DataReceiver dataReceiver;
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DataClientCallback"/> class.
/// </summary>
/// <param name="app">The main application.</param>
public DataClientCallback(App app)
{
this.mainApp = app;
this.dataReceiver = new DataReceiver();
}
#endregion Constructors
#region Methods
/// <summary>
/// Handles the data retrieved for all sensors.
/// </summary>
/// <param name="data">The data.</param>
public void SendData(double[] data)
{
this.mainApp.Dispatcher.Invoke(() =>
{
if (this.mainWindow == null)
{
this.mainWindow = this.mainApp.MainWindow as MainWindow;
}
this.dataReceiver.UpdateViewModels(data, ((MainWindow)this.mainApp.MainWindow).Container);
});
}
/// <summary>
/// Sends the modus.
/// </summary>
/// <param name="modus">The modus.</param>
public void SendModus(int modus)
{
this.mainApp.Dispatcher.Invoke(() =>
{
if (this.mainWindow == null)
{
this.mainWindow = this.mainApp.MainWindow as MainWindow;
}
this.dataReceiver.SetState(modus, ((MainWindow)this.mainApp.MainWindow).Container);
});
}
/// <summary>
/// Sets the state of the logging.
/// </summary>
/// <param name="status">if set to <c>true</c> [status].</param>
public void SetLoggingState(bool status)
{
this.mainApp.Dispatcher.Invoke(() =>
{
if (this.mainWindow == null)
{
this.mainWindow = this.mainApp.MainWindow as MainWindow;
}
this.dataReceiver.SetIsLogging(status, ((MainWindow)this.mainApp.MainWindow).Container);
});
}
/// <summary>
/// Updates the countdown.
/// </summary>
/// <param name="time">The time.</param>
public void UpdateCountdown(DateTime time)
{
this.mainApp.Dispatcher.Invoke(() =>
{
if (this.mainWindow == null)
{
this.mainWindow = this.mainApp.MainWindow as MainWindow;
}
this.dataReceiver.UpdateCountdown(time, ((MainWindow)this.mainApp.MainWindow).Container);
});
}
/// <summary>
/// The update notification.
/// </summary>
/// <param name="notification">
/// The notification.
/// </param>
public void UpdateNotification(string[] notification)
{
this.mainApp.Dispatcher.Invoke(() =>
{
if (this.mainWindow == null)
{
this.mainWindow = this.mainApp.MainWindow as MainWindow;
}
this.dataReceiver.UpdateNotification(notification, ((MainWindow)this.mainApp.MainWindow).Container);
});
}
#endregion Methods
}
}<file_sep>/CryostatControlServer/Logging/LogThreader.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LogThreader.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Logging
{
using System;
using System.IO;
using System.Threading;
using CryostatControlServer.Data;
using CryostatControlServer.Properties;
/// <summary>
/// The log threader.
/// </summary>
public class LogThreader
{
#region Fields
/// <summary>
/// The general log interval in seconds.
/// </summary>
private const int GeneralLogInterval = 10;
/// <summary>
/// The start time.
/// </summary>
private const int StartTime = 0;
/// <summary>
/// The controller.
/// </summary>
private readonly CryostatControl controller;
/// <summary>
/// The data reader.
/// </summary>
private DataReader dataReader;
/// <summary>
/// The specific logging thread.
/// </summary>
private Timer specificLoggingThread;
/// <summary>
/// The general logging thread.
/// </summary>
private Timer generalLoggingThread;
/// <summary>
/// Specific logging in progress boolean.
/// </summary>
private bool specificLoggingInProgress;
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LogThreader"/> class.
/// </summary>
/// <param name="dataReader">
/// The data reader.
/// </param>
/// <param name="controller">
/// The controller.
/// </param>
public LogThreader(DataReader dataReader, CryostatControl controller)
{
this.controller = controller;
this.dataReader = dataReader;
this.specificLoggingInProgress = false;
}
#endregion Constructors
/// <summary>
/// Gets the general main folder.
/// </summary>
private string GeneralMainFolder { get; } = Settings.Default.LoggingAddress + @"\General";
/// <summary>
/// Gets the specific main folder.
/// </summary>
private string SpecificMainFolder { get; } = Settings.Default.LoggingAddress + @"\Specific";
#region Methods
/// <summary>
/// The start specific data logging.
/// </summary>
/// <param name="interval">
/// The interval.
/// </param>
/// <param name="toBeLoggedOrNotToBeLogged">
/// The to be logged or not to be logged list.
/// </param>
public void StartSpecificDataLogging(int interval, bool[] toBeLoggedOrNotToBeLogged)
{
if (this.specificLoggingInProgress)
{
this.StopSpecificDataLogging();
}
SpecificDataLogger specificDataLogger = new SpecificDataLogger(toBeLoggedOrNotToBeLogged, interval);
LoggerDataObject loggerDataObject = this.CreateNewSpecificLoggingFile(specificDataLogger);
this.specificLoggingThread = new Timer(this.SpecificDataLogging, loggerDataObject, StartTime, this.ConvertSecondsToMs(interval));
this.specificLoggingInProgress = true;
}
/// <summary>
/// The stop specific data logging.
/// </summary>
public void StopSpecificDataLogging()
{
DebugLogger.Info(this.GetType().Name, "Specific Data logging has stopped");
if (this.specificLoggingThread != null)
{
this.specificLoggingThread.Dispose();
}
this.specificLoggingInProgress = false;
}
/// <summary>
/// The start general data logging.
/// </summary>
public void StartGeneralDataLogging()
{
GeneralDataLogger generalDataLogger = new GeneralDataLogger();
LoggerDataObject loggerDataObject = this.CreateNewGeneralLoggingFile(generalDataLogger);
this.generalLoggingThread = new Timer(this.GeneralDataLogging, loggerDataObject, StartTime, this.ConvertSecondsToMs(GeneralLogInterval));
}
/// <summary>
/// The stop general data logging.
/// </summary>
public void StopGeneralDataLogging()
{
this.generalLoggingThread.Dispose();
}
/// <summary>
/// Gets the specific logging in progress.
/// </summary>
/// <returns>True if it is in progress</returns>
public bool GetSpecificLoggingInProgress()
{
return this.specificLoggingInProgress;
}
/// <summary>
/// Convert seconds to milliseconds.
/// </summary>
/// <param name="seconds">
/// The seconds.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public int ConvertSecondsToMs(int seconds)
{
return seconds * 1000;
}
/// <summary>
/// The check if new file is needed.
/// </summary>
/// <param name="filepath">
/// The file path.
/// </param>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
public bool NewFileIsNeeded(string filepath)
{
string logDay = Path.GetFileName(filepath);
if (logDay == null || !logDay.Contains(".csv"))
{
DebugLogger.Error(this.GetType().Name, "Can't find logfile name for checking if a new file is needed.");
return false;
}
logDay = logDay.Replace(".csv", string.Empty);
string currentDay = DateTime.Now.Day.ToString();
if (!logDay.Equals(currentDay))
{
return true;
}
return false;
}
/// <summary>
/// The general data logging.
/// </summary>
/// <param name="loggerDataObject">
/// The logger data object.
/// </param>
private void GeneralDataLogging(object loggerDataObject)
{
GeneralDataLogger specificDataLogger = (GeneralDataLogger)((LoggerDataObject)loggerDataObject).GetAbstractLogData();
string filePath = ((LoggerDataObject)loggerDataObject).GetFilePath();
if (this.NewFileIsNeeded(filePath))
{
this.StopGeneralDataLogging();
this.StartGeneralDataLogging();
return;
}
double[] data = this.AddControlStateToArray(this.dataReader.GetDataArray());
specificDataLogger.WriteGeneralData(filePath, data, DateTime.Now.ToString("HH:mm:ss"));
}
/// <summary>
/// The specific data logging.
/// </summary>
/// <param name="loggerDataObject">
/// The logger data object.
/// </param>
private void SpecificDataLogging(object loggerDataObject)
{
SpecificDataLogger specificDataLogger = (SpecificDataLogger)((LoggerDataObject)loggerDataObject).GetAbstractLogData();
string filePath = ((LoggerDataObject)loggerDataObject).GetFilePath();
specificDataLogger.WriteSpecificData(filePath, this.dataReader.GetDataArray(), DateTime.Now.ToString("HH:mm:ss"));
}
/// <summary>
/// Creates the new general logging file.
/// </summary>
/// <param name="generalDataLogger">The general data logger.</param>
/// <returns>General Logger Data Object</returns>
private LoggerDataObject CreateNewGeneralLoggingFile(GeneralDataLogger generalDataLogger)
{
string filePath = generalDataLogger.CreateFile(this.GeneralMainFolder);
generalDataLogger.WriteInitialLine(filePath, generalDataLogger.CreateArrayWithOnlyTrue(), true);
DebugLogger.Info(this.GetType().Name, "General Data logging has started in file: " + filePath);
return new LoggerDataObject(generalDataLogger, filePath);
}
/// <summary>
/// Creates the new specific logging file.
/// </summary>
/// <param name="specificDataLogger">The specific data logger.</param>
/// <returns>Specific logger Data Object</returns>
private LoggerDataObject CreateNewSpecificLoggingFile(SpecificDataLogger specificDataLogger)
{
string filePath = specificDataLogger.CreateFile(this.SpecificMainFolder);
specificDataLogger.WriteInitialLine(filePath, specificDataLogger.GetToBeLoggedOrNotToBeLogged());
DebugLogger.Info(this.GetType().Name, "Specific Data logging has started in file: " + filePath);
return new LoggerDataObject(specificDataLogger, filePath);
}
/// <summary>
/// Add control state to an double array.
/// </summary>
/// <param name="data">
/// The data.
/// </param>
/// <returns>
/// The <see cref="double[]"/>.
/// </returns>
private double[] AddControlStateToArray(double[] data)
{
var data2 = new double[data.Length + 1];
data.CopyTo(data2, 0);
data2[data2.Length - 1] = (double)(this.controller?.ControllerState ?? 0);
return data2;
}
#endregion Methods
}
}<file_sep>/CryostatControlServer/ControlState.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ControlState.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer
{
/// <summary>
/// Enum of possible states for the control state machine
/// </summary>
public enum Controlstate
{
/// <summary>
/// Waiting for everything to be connected and ready
/// </summary>
Setup,
/// <summary>
/// Everything ready, waiting for a command
/// </summary>
Standby,
/// <summary>
/// Manual control mode
/// </summary>
Manual,
/// <summary>
/// Entry point for the cool down routine.
/// </summary>
CooldownStart,
/// <summary>
/// Wait for the pressure inside the cryostat to drop below the critical point.
/// </summary>
CooldownWaitForPressure,
/// <summary>
/// Start the pulse tube compressor.
/// </summary>
CooldownStartCompressor,
/// <summary>
/// Wait for the pulse tube to cool the cryostat to 70K.
/// </summary>
CooldownWait70K,
/// <summary>
/// Wait for the heat switches to turn OFF
/// </summary>
CooldownWaitSwitches,
/// <summary>
/// Activate pump heaters and wait to cool to 4K.
/// </summary>
CooldownWait4K,
/// <summary>
/// Wait for all He4 to be condensed
/// </summary>
CooldownCondenseHe4,
/// <summary>
/// Turn off the He4 heater
/// </summary>
CooldownTurnOffHe4,
/// <summary>
/// Turn on the He4 switch.
/// </summary>
CooldownControlHe4Switch,
/// <summary>
/// He4 cooling down the He3.
/// Wait for He3 to be condensed.
/// </summary>
CooldownCondenseHe3,
/// <summary>
/// Wait for He3 heater to reach the set point. Should always immediately skip.
/// </summary>
CooldownWaitHe3Heater,
/// <summary>
/// disable he3 pump heater
/// </summary>
CooldownDisableHe3PumpHeater,
/// <summary>
/// Turn on the He3 heat switch.
/// </summary>
CooldownControlHe3,
/// <summary>
/// "Fridge is cooling nicely."
/// - Chase Research He7 cooler manual
/// </summary>
CooldownFinished,
/// <summary>
/// Recycle sequence entry point
/// </summary>
RecycleStart,
/// <summary>
/// Heat pumps
/// Rest of recycle follows cool down from "CoolDownTurnOffHe4"
/// </summary>
RecycleHeatPumps,
/// <summary>
/// Warm up entry point
/// </summary>
WarmupStart,
/// <summary>
/// Warming up stuff
/// </summary>
WarmupHeating,
/// <summary>
/// The warm up is finished
/// </summary>
WarmupFinished,
/// <summary>
/// Cancel the current action and go back to standby.
/// </summary>
Cancel,
/// <summary>
/// Stop all devices / complete shutdown.
/// </summary>
Stop
}
}<file_sep>/CryostatControlClient/ViewModels/MessageBoxViewModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MessageBoxViewModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels
{
using System.Collections.ObjectModel;
using CryostatControlClient.Models;
/// <summary>
/// The message box view model.
/// </summary>
public class MessageBoxViewModel : AbstractViewModel
{
/// <summary>
/// The max amount of notifications showing in the GUI.
/// </summary>
private const int MaxAmountNotifications = 100;
/// <summary>
/// The message box model.
/// </summary>
private MessageBoxModel messageBoxModel;
/// <summary>
/// Initializes a new instance of the <see cref="MessageBoxViewModel"/> class.
/// </summary>
public MessageBoxViewModel()
{
this.messageBoxModel = new MessageBoxModel();
}
/// <summary>
/// Gets or sets the message.
/// </summary>
public string[] Message
{
get
{
return this.messageBoxModel.Message;
}
set
{
this.messageBoxModel.Message = value;
this.AddToNotificationList(this.CreateNotification(value));
this.RaisePropertyChanged("Message");
this.RaisePropertyChanged("Notifications");
}
}
/// <summary>
/// Gets or sets the notifications.
/// </summary>
/// <value>
/// The notifications.
/// </value>
public ObservableCollection<Notification> Notifications
{
get
{
return this.messageBoxModel.Notifications ?? new ObservableCollection<Notification>();
}
set
{
this.messageBoxModel.Notifications = value;
}
}
/// <summary>
/// Creates a notification.
/// </summary>
/// <param name="data">
/// The data.
/// </param>
/// <returns>
/// The <see cref="Notification"/>.
/// </returns>
public Notification CreateNotification(string[] data)
{
Notification notification = new Notification(data[0], data[1], data[2]);
return notification;
}
/// <summary>
/// Adds notification to notification list and removes last item if size reached its max.
/// </summary>
/// <param name="notification">The notification.</param>
private void AddToNotificationList(Notification notification)
{
ObservableCollection<Notification> notifications = this.Notifications;
notifications.Insert(0, notification);
if (notifications.Count > MaxAmountNotifications)
{
notifications.RemoveAt(notifications.Count - 1);
}
this.Notifications = notifications;
}
}
}
<file_sep>/CryostatControlServer/HostService/Enumerators/HeaterEnumerator.cs
//-----------------------------------------------------------------------
// <copyright file="HeaterEnumerator.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.HostService.Enumerators
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Enumerator for the heater places
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1602:EnumerationItemsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.")]
public enum HeaterEnumerator
{
He3Pump = 0,
He4Pump = 1,
He3Switch = 2,
He4Switch = 3,
HeaterAmount = 4
}
}<file_sep>/CryostatControlServer/Logging/GeneralDataLogger.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GeneralDataLogger.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Logging
{
using System;
using System.IO;
using CryostatControlServer.Data;
/// <summary>
/// The log all data.
/// </summary>
public class GeneralDataLogger : AbstractDataLogger
{
/// <summary>
/// Write general data to log.
/// </summary>
/// <param name="pathToFile">
/// The path To File.
/// </param>
/// <param name="data">
/// The data.
/// </param>
/// <param name="time">
/// The time.
/// </param>
public void WriteGeneralData(string pathToFile, double[] data, string time)
{
string dataLine = time;
for (int i = 0; i < data.Length; i++)
{
dataLine += AbstractDataLogger.Delimiter + Math.Round(data[i], AbstractDataLogger.Amountdigits);
}
try
{
using (FileStream fileStream =
new FileStream(pathToFile, FileMode.Append, FileAccess.Write, FileShare.None))
{
using (StreamWriter sw = new StreamWriter(fileStream))
{
sw.WriteLine(dataLine);
}
}
}
catch (IOException)
{
DebugLogger.Warning(this.GetType().Name, "The general log file is opened by another process. Please close this first.");
}
}
/// <summary>
/// The create array with only true.
/// </summary>
/// <returns>
/// The <see cref="bool[]"/> containing a list with only true.
/// </returns>
public bool[] CreateArrayWithOnlyTrue()
{
bool[] devices = new bool[(int)DataEnumerator.DataLength];
for (int i = 0; i < devices.Length; i++)
{
devices[i] = true;
}
return devices;
}
}
}
<file_sep>/CryostatControlServerTests/Logging/AbstractDataLoggingTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CryostatControlServerTests.Logging
{
using System.IO;
using System.Linq;
using CryostatControlServer.Data;
using CryostatControlServer.Logging;
[TestClass]
public class AbstractDataLoggingTest
{
[TestMethod]
public void WriteInitialLineTest()
{
GeneralDataLogger generalDataLogger = new GeneralDataLogger();
bool[] toBeLogged = generalDataLogger.CreateArrayWithOnlyTrue();
string filePath = "SpecificDataLoggerTest.csv";
if (File.Exists(filePath))
{
File.Delete(filePath);
}
File.Create(filePath).Close();
generalDataLogger.WriteInitialLine(filePath,toBeLogged);
string line = File.ReadLines(filePath).First();
string[] elements = line.Split(';');
Assert.AreEqual("Time", elements[0]);
Assert.AreEqual("Compressor helium", elements[(int)DataEnumerator.ComHelium + 1]);
Assert.AreEqual("He3 Switch Temperature", elements[(int)DataEnumerator.He3SwitchTemp + 1]);
}
}
}
<file_sep>/CryostatControlServerTests/Lakeshore/LakeShoreTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CryostatControlServerTests.Lakeshore
{
using System;
using System.Globalization;
using System.Threading;
using CryostatControlServer.Data;
using CryostatControlServer.LakeShore;
using CryostatControlServer.Streams;
using Moq;
[TestClass]
public class LakeShoreTests
{
#region Methods
[TestMethod]
public void TestStartAndRead()
{
var lakeshore = new LakeShore();
//Set up mock
var mockLS = new Mock<IManagedStream>();
mockLS.Setup(stream => stream.Open());
mockLS.Setup(stream => stream.WriteString(It.IsAny<string>()));
mockLS.Setup(stream => stream.ReadString()).Returns(() => "5.0");
mockLS.Setup(stream => stream.IsConnected()).Returns(true);
lakeshore.Init(mockLS.Object);
//wait for the thread to run
Thread.Sleep(500);
ISensor lssensor = new Sensor(SensorEnum.Plate50K, lakeshore);
Assert.AreEqual(5.0, lssensor.Value);
lakeshore.Close();
Thread.Sleep(1);
}
#endregion Methods
}
}<file_sep>/CryostatControlServer/Compressor/Enumerators/StatusEnum.cs
//-----------------------------------------------------------------------
// <copyright file="StatusEnum.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.Compressor
{
/// <summary>
/// Enumerator for status
/// </summary>
public enum StatusEnum
{
/// <summary>
/// The idling state
/// </summary>
Idling = 0,
/// <summary>
/// The starting state
/// </summary>
Starting = 2,
/// <summary>
/// The running state
/// </summary>
Running = 3,
/// <summary>
/// The stopping state
/// </summary>
Stopping = 5,
/// <summary>
/// The error lockout state
/// </summary>
ErrorLockout = 6,
/// <summary>
/// The error state
/// </summary>
Error = 7,
/// <summary>
/// The helium cool down state
/// </summary>
HeliumCoolDown = 8,
/// <summary>
/// The error power related state
/// </summary>
ErrorPowerRelated = 9,
/// <summary>
/// The error recovery state
/// </summary>
ErrorRecovery = 16
}
}<file_sep>/CryostatControlServer/Compressor/Enumerators/AnalogRegistersEnum.cs
//-----------------------------------------------------------------------
// <copyright file="AnalogRegistersEnum.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.Compressor
{
/// <summary>
/// Enumerator for analog input registers
/// </summary>
public enum AnalogRegistersEnum
{
/// <summary>
/// The operating state register
/// </summary>
OperatingState = 1,
/// <summary>
/// The energy state register
/// </summary>
EnergyState = 2,
/// <summary>
/// The warning state register
/// </summary>
WarningState = 3,
/// <summary>
/// The error state register
/// </summary>
ErrorState = 5,
/// <summary>
/// The coolant in temperature register
/// </summary>
CoolantInTemp = 7,
/// <summary>
/// The coolant out temperature register
/// </summary>
CoolantOutTemp = 9,
/// <summary>
/// The oil temperature register
/// </summary>
OilTemp = 11,
/// <summary>
/// The helium temperature register
/// </summary>
HeliumTemp = 13,
/// <summary>
/// The low pressure register
/// </summary>
LowPressure = 15,
/// <summary>
/// The low pressure average register
/// </summary>
LowPressureAvg = 17,
/// <summary>
/// The high pressure register
/// </summary>
HighPressure = 19,
/// <summary>
/// The high pressure average register
/// </summary>
HighPressureAvg = 21,
/// <summary>
/// The delta pressure average register
/// </summary>
DeltaPressureAvg = 23,
/// <summary>
/// The motor current register
/// </summary>
MotorCurrent = 25,
/// <summary>
/// The hours of operation register
/// </summary>
HoursOfOperation = 27,
/// <summary>
/// The pressure scale register
/// </summary>
PressureScale = 29,
/// <summary>
/// The temperature scale register
/// </summary>
TempScale = 30,
/// <summary>
/// The panel serial number register
/// </summary>
PanelSerialNumber = 31,
/// <summary>
/// The model number register
/// </summary>
Model = 32
}
}<file_sep>/CryostatControlClient/ViewModels/LoggingViewModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LoggingViewModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels
{
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using CryostatControlClient.Communication;
using CryostatControlClient.Models;
using CryostatControlClient.ViewModels.LoggingPresets;
using CryostatControlServer.Data;
/// <summary>
/// The logging view model.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1623:PropertySummaryDocumentationMustMatchAccessors", Justification = "Reviewed, is ok here")]
public class LoggingViewModel : AbstractViewModel
{
/// <summary>
/// The logging model.
/// </summary>
private LoggingModel loggingModel;
/// <summary>
/// The logging preset
/// </summary>
private ILoggingPreset loggingPreset;
/// <summary>
/// The start button command
/// </summary>
private ICommand startButtonCommand;
/// <summary>
/// The cancel button command
/// </summary>
private ICommand cancelButtonCommand;
/// <summary>
/// Initializes a new instance of the <see cref="LoggingViewModel"/> class.
/// </summary>
public LoggingViewModel()
{
this.loggingModel = new LoggingModel();
this.StartButtonCommand = new RelayCommand(this.OnClickStart, param => true);
this.CancelButtonCommand = new RelayCommand(this.OnClickCancel, param => true);
}
#region Properties
/// <summary>
/// Gets or sets the he3 pump temperature.
/// </summary>
/// <value>
/// The he3 pump temperature.
/// </value>
public bool He3PumpTemp
{
get
{
return this.loggingModel.He3PumpTemp;
}
set
{
this.loggingModel.He3PumpTemp = value;
this.RaisePropertyChanged("He3PumpTemp");
}
}
/// <summary>
/// Gets or sets the he3 head temperature.
/// </summary>
/// <value>
/// The he3 head temperature.
/// </value>
public bool He3HeadTemp
{
get
{
return this.loggingModel.He3HeadTemp;
}
set
{
this.loggingModel.He3HeadTemp = value;
this.RaisePropertyChanged("He3HeadTemp");
}
}
/// <summary>
/// Gets or sets the he3 switch temperature.
/// </summary>
/// <value>
/// The he3 switch temperature.
/// </value>
public bool He3SwitchTemp
{
get
{
return this.loggingModel.He3SwitchTemp;
}
set
{
this.loggingModel.He3SwitchTemp = value;
this.RaisePropertyChanged("He3SwitchTemp");
}
}
/// <summary>
/// Gets or sets the he4 pump temperature.
/// </summary>
/// <value>
/// The he4 pump temperature.
/// </value>
public bool He4PumpTemp
{
get
{
return this.loggingModel.He4PumpTemp;
}
set
{
this.loggingModel.He4PumpTemp = value;
this.RaisePropertyChanged("He4PumpTemp");
}
}
/// <summary>
/// Gets or sets the he4 head temperature.
/// </summary>
/// <value>
/// The he4 head temperature.
/// </value>
public bool He4HeadTemp
{
get
{
return this.loggingModel.He4HeadTemp;
}
set
{
this.loggingModel.He4HeadTemp = value;
this.RaisePropertyChanged("He4HeadTemp");
}
}
/// <summary>
/// Gets or sets the he4 switch temperature.
/// </summary>
/// <value>
/// The he4 switch temperature.
/// </value>
public bool He4SwitchTemp
{
get
{
return this.loggingModel.He4SwitchTemp;
}
set
{
this.loggingModel.He4SwitchTemp = value;
this.RaisePropertyChanged("He4SwitchTemp");
}
}
/// <summary>
/// Gets or sets the two k plate temperature.
/// </summary>
/// <value>
/// The two k plate temperature.
/// </value>
public bool TwoKPlateTemp
{
get
{
return this.loggingModel.TwoKPlateTemp;
}
set
{
this.loggingModel.TwoKPlateTemp = value;
this.RaisePropertyChanged("TwoKPlateTemp");
}
}
/// <summary>
/// Gets or sets the four k plate temperature.
/// </summary>
/// <value>
/// The four k plate temperature.
/// </value>
public bool FourKPlateTemp
{
get
{
return this.loggingModel.FourKPlateTemp;
}
set
{
this.loggingModel.FourKPlateTemp = value;
this.RaisePropertyChanged("FourKPlateTemp");
}
}
/// <summary>
/// Gets or sets the he3 pump Volt.
/// </summary>
/// <value>
/// The he3 pump Volt.
/// </value>
public bool He3PumpVolt
{
get
{
return this.loggingModel.He3PumpVolt;
}
set
{
this.loggingModel.He3PumpVolt = value;
this.RaisePropertyChanged("He3PumpVolt");
}
}
/// <summary>
/// Gets or sets the he3 switch Volt.
/// </summary>
/// <value>
/// The he3 switch Volt.
/// </value>
public bool He3SwitchVolt
{
get
{
return this.loggingModel.He3SwitchVolt;
}
set
{
this.loggingModel.He3SwitchVolt = value;
this.RaisePropertyChanged("He3SwitchVolt");
}
}
/// <summary>
/// Gets or sets the he4 pump Volt.
/// </summary>
/// <value>
/// The he4 pump Volt.
/// </value>
public bool He4PumpVolt
{
get
{
return this.loggingModel.He4PumpVolt;
}
set
{
this.loggingModel.He4PumpVolt = value;
this.RaisePropertyChanged("He4PumpVolt");
}
}
/// <summary>
/// Gets or sets the he4 switch Volt.
/// </summary>
/// <value>
/// The he4 switch Volt.
/// </value>
public bool He4SwitchVolt
{
get
{
return this.loggingModel.He4SwitchVolt;
}
set
{
this.loggingModel.He4SwitchVolt = value;
this.RaisePropertyChanged("He4SwitchVolt");
}
}
/// <summary>
/// Gets or sets the bluefors50 k shield temperature.
/// </summary>
/// <value>
/// The bluefors50 k shield temperature.
/// </value>
public bool Bluefors50KShieldTemp
{
get
{
return this.loggingModel.Bluefors50KShieldTemp;
}
set
{
this.loggingModel.Bluefors50KShieldTemp = value;
this.RaisePropertyChanged("Bluefors50KShieldTemp");
}
}
/// <summary>
/// Gets or sets the bluefors3 k shield temperature.
/// </summary>
/// <value>
/// The bluefors3 k shield temperature.
/// </value>
public bool Bluefors3KShieldTemp
{
get
{
return this.loggingModel.Bluefors3KShieldTemp;
}
set
{
this.loggingModel.Bluefors3KShieldTemp = value;
this.RaisePropertyChanged("Bluefors3KShieldTemp");
}
}
/// <summary>
/// Gets or sets the compressor water in temperature.
/// </summary>
/// <value>
/// The compressor water in temperature.
/// </value>
public bool CompressorWaterInTemp
{
get
{
return this.loggingModel.CompressorWaterInTemp;
}
set
{
this.loggingModel.CompressorWaterInTemp = value;
this.RaisePropertyChanged("CompressorWaterInTemp");
}
}
/// <summary>
/// Gets or sets the compressor water out temperature.
/// </summary>
/// <value>
/// The compressor water out temperature.
/// </value>
public bool CompressorWaterOutTemp
{
get
{
return this.loggingModel.CompressorWaterOutTemp;
}
set
{
this.loggingModel.CompressorWaterOutTemp = value;
this.RaisePropertyChanged("CompressorWaterOutTemp");
}
}
/// <summary>
/// Gets or sets the compressor helium temperature.
/// </summary>
/// <value>
/// The compressor helium temperature.
/// </value>
public bool CompressorHeliumTemp
{
get
{
return this.loggingModel.CompressorHeliumTemp;
}
set
{
this.loggingModel.CompressorHeliumTemp = value;
this.RaisePropertyChanged("CompressorHeliumTemp");
}
}
/// <summary>
/// Gets or sets the compressor oil temperature.
/// </summary>
/// <value>
/// The compressor oil temperature.
/// </value>
public bool CompressorOilTemp
{
get
{
return this.loggingModel.CompressorOilTemp;
}
set
{
this.loggingModel.CompressorOilTemp = value;
this.RaisePropertyChanged("CompressorOilTemp");
}
}
/// <summary>
/// Gets or sets the compressor low pressure.
/// </summary>
/// <value>
/// The compressor low pressure.
/// </value>
public bool CompressorLowPressure
{
get
{
return this.loggingModel.CompressorLowPressure;
}
set
{
this.loggingModel.CompressorLowPressure = value;
this.RaisePropertyChanged("CompressorLowPressure");
}
}
/// <summary>
/// Gets or sets the compressor low average pressure.
/// </summary>
/// <value>
/// The compressor low average pressure.
/// </value>
public bool CompressorLowAveragePressure
{
get
{
return this.loggingModel.CompressorLowAveragePressure;
}
set
{
this.loggingModel.CompressorLowAveragePressure = value;
this.RaisePropertyChanged("CompressorLowAveragePressure");
}
}
/// <summary>
/// Gets or sets the compressor high pressure.
/// </summary>
/// <value>
/// The compressor high pressure.
/// </value>
public bool CompressorHighPressure
{
get
{
return this.loggingModel.CompressorHighPressure;
}
set
{
this.loggingModel.CompressorHighPressure = value;
this.RaisePropertyChanged("CompressorHighPressure");
}
}
/// <summary>
/// Gets or sets the compressor high average pressure.
/// </summary>
/// <value>
/// The compressor high average pressure.
/// </value>
public bool CompressorHighAveragePressure
{
get
{
return this.loggingModel.CompressorHighAveragePressure;
}
set
{
this.loggingModel.CompressorHighAveragePressure = value;
this.RaisePropertyChanged("CompressorHighAveragePressure");
}
}
/// <summary>
/// Gets or sets the compressor delta average pressure.
/// </summary>
/// <value>
/// The compressor delta average pressure.
/// </value>
public bool CompressorDeltaAveragePressure
{
get
{
return this.loggingModel.CompressorDeltaAveragePressure;
}
set
{
this.loggingModel.CompressorDeltaAveragePressure = value;
this.RaisePropertyChanged("CompressorDeltaAveragePressure");
}
}
/// <summary>
/// Gets or sets the logging interval.
/// </summary>
/// <value>
/// The logging interval.
/// </value>
public double LoggingInterval
{
get
{
return this.loggingModel.LoggingInterval;
}
set
{
this.loggingModel.LoggingInterval = value;
this.RaisePropertyChanged("LoggingInterval");
}
}
/// <summary>
/// Gets or sets a value indicating whether [logging in progress].
/// </summary>
/// <value>
/// <c>true</c> if [logging in progress]; otherwise, <c>false</c>.
/// </value>
public bool LoggingInProgress
{
get
{
return this.loggingModel.LoggingInProgress;
}
set
{
this.loggingModel.LoggingInProgress = value;
this.RaisePropertyChanged("LoggingInProgress");
this.RaisePropertyChanged("LoggingInProgressColor");
this.RaisePropertyChanged("LoggingInProgressReversed");
this.RaisePropertyChanged("LoggingInProgressConverted");
}
}
/// <summary>
/// Gets a value indicating whether [logging in progress reversed].
/// </summary>
/// <value>
/// <c>true</c> if [logging in progress reversed]; otherwise, <c>false</c>.
/// </value>
public bool LoggingInProgressReversed
{
get
{
return !this.LoggingInProgress;
}
}
/// <summary>
/// Gets the logging in progress converted.
/// </summary>
/// <value>
/// The logging in progress converted.
/// </value>
public string LoggingInProgressConverted
{
get
{
return this.loggingModel.LoggingInProgress ? "Currently logging" : "Currently not logging";
}
}
/// <summary>
/// Gets the color of the logging in progress.
/// </summary>
/// <value>
/// The color of the logging in progress.
/// </value>
public SolidColorBrush LoggingInProgressColor
{
get
{
return this.loggingModel.LoggingInProgress ? new SolidColorBrush(Colors.Green) : new SolidColorBrush(Colors.Red);
}
}
/// <summary>
/// Gets or sets the preset ComboBox.
/// </summary>
/// <value>
/// The preset ComboBox.
/// </value>
public int PresetComboBox
{
get
{
return this.loggingModel.PresetComboBox;
}
set
{
this.loggingModel.PresetComboBox = value;
this.ConvertIntToPreset(value);
this.RaisePropertyChanged("PresetComboBox");
}
}
#endregion
/// <summary>
/// Gets or sets the start button command.
/// </summary>
/// <value>
/// The start button command.
/// </value>
public ICommand StartButtonCommand
{
get
{
return this.startButtonCommand;
}
set
{
this.startButtonCommand = value;
}
}
/// <summary>
/// Gets or sets the cancel button command.
/// </summary>
/// <value>
/// The cancel button command.
/// </value>
public ICommand CancelButtonCommand
{
get
{
return this.cancelButtonCommand;
}
set
{
this.cancelButtonCommand = value;
}
}
/// <summary>
/// Converts the integer to preset.
/// </summary>
/// <param name="presetNumber">The preset number.</param>
public void ConvertIntToPreset(int presetNumber)
{
switch (presetNumber)
{
case 0:
this.loggingPreset = new LogNothingPreset(this);
break;
case 1:
this.loggingPreset = new LogAllPreset(this);
break;
case 2:
this.loggingPreset = new LogCompressorPreset(this);
break;
case 3:
this.loggingPreset = new LogHe7Preset(this);
break;
case 4:
this.loggingPreset = new LogBlueforsPreset(this);
break;
}
}
/// <summary>
/// Get the logging array.
/// </summary>
/// <returns>
/// The <see cref="double[]"/>.
/// </returns>
public bool[] GetLoggingArray()
{
bool[] loggingDataArray = new bool[(int)DataEnumerator.DataLength];
loggingDataArray[(int)DataEnumerator.LakePlate50K] = this.Bluefors50KShieldTemp;
loggingDataArray[(int)DataEnumerator.LakePlate3K] = this.Bluefors3KShieldTemp;
loggingDataArray[(int)DataEnumerator.ComWaterIn] = this.CompressorWaterInTemp;
loggingDataArray[(int)DataEnumerator.ComWaterOut] = this.CompressorWaterOutTemp;
loggingDataArray[(int)DataEnumerator.ComHelium] = this.CompressorHeliumTemp;
loggingDataArray[(int)DataEnumerator.ComOil] = this.CompressorOilTemp;
loggingDataArray[(int)DataEnumerator.ComLow] = this.CompressorLowPressure;
loggingDataArray[(int)DataEnumerator.ComLowAvg] = this.CompressorLowAveragePressure;
loggingDataArray[(int)DataEnumerator.ComHigh] = this.CompressorHighPressure;
loggingDataArray[(int)DataEnumerator.ComHighAvg] = this.CompressorHighAveragePressure;
loggingDataArray[(int)DataEnumerator.ComDeltaAvg] = this.CompressorDeltaAveragePressure;
loggingDataArray[(int)DataEnumerator.He3Pump] = this.He3PumpTemp;
loggingDataArray[(int)DataEnumerator.HePlate2K] = this.TwoKPlateTemp;
loggingDataArray[(int)DataEnumerator.HePlate4K] = this.FourKPlateTemp;
loggingDataArray[(int)DataEnumerator.He3Head] = this.He3HeadTemp;
loggingDataArray[(int)DataEnumerator.He4Pump] = this.He4PumpTemp;
loggingDataArray[(int)DataEnumerator.He4SwitchTemp] = this.He4SwitchTemp;
loggingDataArray[(int)DataEnumerator.He3SwitchTemp] = this.He3SwitchTemp;
loggingDataArray[(int)DataEnumerator.He4Head] = this.He4HeadTemp;
loggingDataArray[(int)DataEnumerator.He3VoltActual] = this.He3PumpVolt;
loggingDataArray[(int)DataEnumerator.He4SwitchVoltActual] = this.He4SwitchVolt;
loggingDataArray[(int)DataEnumerator.He3SwitchVoltActual] = this.He3SwitchVolt;
loggingDataArray[(int)DataEnumerator.He4VoltActual] = this.He4PumpVolt;
return loggingDataArray;
}
/// <summary>
/// The on click start.
/// </summary>
/// <param name="obj">
/// The object.
/// </param>
public void OnClickStart(object obj)
{
ServerCheck.SendMessage(new Task(() => { this.StartLogging(); }));
}
/// <summary>
/// The on click cancel.
/// </summary>
/// <param name="obj">
/// The object.
/// </param>
public void OnClickCancel(object obj)
{
ServerCheck.SendMessage(new Task(() => { ServerCheck.CommandClient.CancelLogging(); }));
}
/// <summary>
/// Starts the logging.
/// </summary>
private void StartLogging()
{
bool[] dataToBeLogged = this.GetLoggingArray();
int interval = (int)this.LoggingInterval;
ServerCheck.CommandClient.StartLogging(interval, dataToBeLogged);
}
}
}
<file_sep>/CryostatControlServer/HostService/ICommandService.cs
//-----------------------------------------------------------------------
// <copyright file="ICommandService.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.HostService
{
using System;
using System.ServiceModel;
using System.ServiceModel.Web;
using CryostatControlServer.HostService.DataContracts;
/// <summary>
/// Interface for the available commands
/// </summary>
[ServiceContract]
public interface ICommandService
{
#region Methods
/// <summary>
/// Method to check if the host is running
/// </summary>
/// <returns>The service state</returns>
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "IsAlive")]
[OperationContract]
bool IsAlive();
/// <summary>
/// Start cool down process
/// </summary>
/// <returns>If the cool down process could be started</returns>
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
bool Cooldown();
/// <summary>
/// Start cool down process timed
/// </summary>
/// <param name="time">
/// The time.
/// </param>
/// <returns>
/// If the cool down process could be started
/// </returns>
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool CooldownTime(DateTime time);
/// <summary>
/// Start recycle process
/// </summary>
/// <returns>If the recycle process could be started</returns>
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
bool Recycle();
/// <summary>
/// Start recycle process
/// </summary>
/// <param name="time">The time.</param>
/// <returns>
/// If the recycle process could be started
/// </returns>
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool RecycleTime(DateTime time);
/// <summary>
/// Start warm up process
/// </summary>
/// <returns>If the warm up process could be started</returns>
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool Warmup();
/// <summary>
/// Start warm up process
/// </summary>
/// <param name="time">The time.</param>
/// <returns>
/// If the warm up process could be started
/// </returns>
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool WarmupTime(DateTime time);
/// <summary>
/// Go to manual mode
/// </summary>
/// <returns>If the server could go to manual mode</returns>
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
bool Manual();
/// <summary>
/// Cancel the current operation, such as warm up, cool down, recycle and manual.
/// </summary>
/// <returns>true if canceled</returns>
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
bool Cancel();
/// <summary>
/// Stops the process of the cryostat.
/// Everything will be turned off.
/// </summary>
/// <returns></returns>
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
bool Stop();
/// <summary>
/// Gets the state.
/// </summary>
/// <returns>integer representing the controller state <see cref="Controlstate"/></returns>
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
int GetState();
/// <summary>
/// The get start time of a delayed operation (warm up, cool down etc.)
/// </summary>
/// <returns>
/// The <see cref="DateTime"/>.
/// </returns>
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
DateTime GetStartTime();
/// <summary>
/// Sets the compressor on or off.
/// <c>true</c> to turn the compressor on.
/// <c>false</c> to turn the compressor off.
/// </summary>
/// <param name="status">if set to <c>true</c> [compressor on] if <c>false</c> [compressor off]</param>
/// <returns>
/// <c>true</c> if the status is set
/// <c>false</c> status could not been set either there is no connection or the compressor is controlled by an automatic process.
/// </returns>
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool SetCompressorState(bool status);
/// <summary>
/// Writes values to the helium7 heaters.
/// <seealso cref="HeaterEnumerator"/>
/// for position for each heater.
/// </summary>
/// <param name="heater">
/// The heater.
/// <seealso cref="HeaterEnumerator"/>
/// </param>
/// <param name="value">
/// The value.
/// </param>
/// <returns>
/// <c>true</c> values could be set.
/// <c>false</c> values could not be set, either there is no connection,
/// input values are incorrect or manual control isn't allowed
/// </returns>
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[FaultContract(typeof(CouldNotPerformActionFault))]
bool WriteHelium7(int heater, double value);
/// <summary>
/// Get a sensor value
/// </summary>
/// <param name="sensor">
/// The sensor.
/// <see cref="DataEnumerator"/> for all sensor numbers
/// </param>
/// <returns>
/// The <see cref="double"/>.
/// </returns>
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "value/{sensor}/")]
double GetValue(string sensor);
/// <summary>
/// Reads the compressor temperature scale.
/// </summary>
/// <returns>Temperature scale in double <seealso cref="TemperatureEnum"/></returns>
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
double ReadCompressorTemperatureScale();
/// <summary>
/// Reads the compressor pressure scale.
/// </summary>
/// <returns>Pressure scale in double <seealso cref="PressureEnum"/></returns>
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
double ReadCompressorPressureScale();
/// <summary>
/// Writes the allowed settings to server.
/// </summary>
/// <param name="setting">
/// The setting <see cref="SettingEnumerator"/>.
/// </param>
/// <param name="value">
/// The value.
/// </param>
/// <returns>
/// If the values have been written
/// </returns>
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
bool WriteSettingValue(int setting, double value);
/// <summary>
/// Read all settings, ordered by the SettingEnumerator
/// </summary>
/// <returns>
/// The settings ordered by SettingEnumerator <see cref="double[]"/>.
/// </returns>
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
double[] ReadSettings();
/// <summary>
/// Reads the single sensor.
/// </summary>
/// <param name="sensorId">The sensor identifier.</param>
/// <returns>The value of the sensor or NaN if no value could be read</returns>
[OperationContract]
double ReadSingleSensor(int sensorId);
/// <summary>
/// Starts the logging.
/// </summary>
/// <param name="interval">
/// The interval in milliseconds.
/// </param>
/// <param name="logData">
/// Array which tells which data be logged
/// <seealso cref="DataEnumerator"/>
/// for the places of the sensors
/// </param>
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
void StartLogging(int interval, bool[] logData);
/// <summary>
/// Stops the logging.
/// </summary>
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void CancelLogging();
/// <summary>
/// Determines whether this instance is logging.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is logging; otherwise, <c>false</c>.
/// </returns>
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
bool IsLogging();
/// <summary>
/// Determines whether [is registered for data] [the specified key].
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if [is registered for data] [the specified key]; otherwise, <c>false</c>.
/// </returns>
[OperationContract]
bool IsRegisteredForData(string key);
/// <summary>
/// Determines whether [is registered for updates] [the specified key].
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if [is registered for updates] [the specified key]; otherwise, <c>false</c>.
/// </returns>
[OperationContract]
bool IsRegisteredForUpdates(string key);
#endregion Methods
}
}<file_sep>/CryostatControlServer/Streams/ManagedCOMStream.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ManagedCOMStream.cs" company="SRON">
// blabla copyright.
// </copyright>
// <author><NAME></author>
// <summary>
// ManagedCOMStream
// ManagedCOMStream is an implementation of IManagedStream to communicate to a Serial Port. It tries to handle as many common issues as possible.
// Methods are not re-entrant, since most devices are neither. THe code calling methods in this class should take care to only issue one command at the time.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Streams
{
using System.IO;
using System.IO.Ports;
/// <summary>
/// ManagedCOMStream
/// ManagedCOMStream is an implementation of IManagedStream to communicate to a Serial Port. It tries to handle as many common issues as possible.
/// Methods are not re-entrant, since most devices are neither. THe code calling methods in this class should take care to only issue one command at the time.
/// </summary>
internal class ManagedCOMStream : BaseManagedStream
{
/// <summary>
/// The baud rate of the com port.
/// </summary>
private readonly int baudRate;
/// <summary>
/// The port name.
/// </summary>
private readonly string portname;
/// <summary>
/// The serial port.
/// </summary>
private SerialPort serialPort;
/// <summary>
/// Initializes a new instance of the <see cref="ManagedCOMStream"/> class.
/// </summary>
/// <param name="portname">The port name.</param>
/// <param name="baudRate">The baud rate.</param>
public ManagedCOMStream(string portname, int baudRate)
{
this.portname = portname;
this.baudRate = baudRate;
}
/// <summary>
/// Closes the connection.
/// </summary>
public override void Close()
{
this.ContainedStream.Flush();
this.serialPort.Close();
}
/// <summary>
/// Determines whether this instance is connected.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is connected; otherwise, <c>false</c>.
/// </returns>
public override bool IsConnected()
{
return this.serialPort.IsOpen;
}
/// <summary>
/// Connect to a COM port and setup the stream.
/// Must be called before calling any other method
/// </summary>
public override void Open()
{
this.serialPort =
new SerialPort(this.portname, this.baudRate)
{
DataBits = 7,
StopBits = StopBits.One,
Parity = Parity.Odd,
Handshake = Handshake.None
};
this.serialPort.Open();
this.ContainedStream = this.serialPort.BaseStream;
this.ContainedStream.ReadTimeout = 2000;
this.Init();
}
}
}<file_sep>/CryostatControlServerTests/He7Cooler/SensorTests.cs
namespace CryostatControlServerTests.He7Cooler
{
using System;
using System.Globalization;
using System.Threading;
using CryostatControlServer.He7Cooler;
using CryostatControlServer.Streams;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
/// <summary>
/// The sensor tests.
/// </summary>
[TestClass]
public class SensorTests
{
[TestMethod]
public void TestCalibration()
{
Calibration testSensor = new Calibration();
Assert.AreEqual(100.0, testSensor.ConvertValue(100.0));
testSensor.AddCalibrationDatapoint(new Tuple<double, double>(0, 0));
testSensor.AddCalibrationDatapoint(new Tuple<double, double>(100.0, 100.0));
Assert.AreEqual(10.0, testSensor.ConvertValue(10.0));
Assert.AreEqual(0.0, testSensor.ConvertValue(0.0));
Assert.AreEqual(100.0, testSensor.ConvertValue(100.0));
Assert.AreEqual(100.0, testSensor.ConvertValue(200.0));
Assert.AreEqual(0.0, testSensor.ConvertValue(-1.0));
testSensor.AddCalibrationDatapoint(new Tuple<double, double>(50.0, 80.0));
Assert.AreEqual(40.0, testSensor.ConvertValue(25.0));
Assert.AreEqual(80.0, testSensor.ConvertValue(50.0));
Assert.AreEqual(90.0, testSensor.ConvertValue(75.0));
}
[TestMethod]
public void TestReadingCalibration()
{
var testSensor = Calibration.He4Calibration;
Assert.AreEqual(149, testSensor.CalibrationSize);
Assert.AreEqual(35.0, testSensor.ConvertValue(0.2133), 0.01);
Assert.AreEqual(0.1, testSensor.ConvertValue(3.9229), 0.01);
Assert.AreEqual(0.099, testSensor.ConvertValue(3.99), 0.001);
Calibration testSensor2 = new Calibration();
testSensor2.LoadSensorCalibrationFromFile("..\\..\\DIODE.CAL", 1, 0);
Assert.AreEqual(142, testSensor2.CalibrationSize);
Assert.AreEqual(300.0, testSensor2.ConvertValue(0.57), 0.1);
Assert.AreEqual(17.5, testSensor2.ConvertValue(1.215), 0.1);
Assert.AreEqual(0.8, testSensor2.ConvertValue(1.8), 0.001);
}
}
}
<file_sep>/CryostatControlServer/HostService/DataContracts/ActionFaultReason.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ActionFaultReason.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.HostService.DataContracts
{
/// <summary>
/// The fault reason.
/// </summary>
public enum ActionFaultReason
{
/// <summary>
/// Not connected to device.
/// </summary>
NotConnected,
/// <summary>
/// Not ready to issue command.
/// Device may not be ready yet or server not ready.
/// </summary>
NotReady,
/// <summary>
/// Server is in automatic mode
/// </summary>
NotInManualMode,
/// <summary>
/// value was invalid. More info in reason string.
/// </summary>
InvalidValue,
/// <summary>
/// The unknown value.
/// </summary>
Unknown,
}
}
<file_sep>/CryostatControlServer/Logging/AbstractDataLogger.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AbstractDataLogger.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Logging
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using CryostatControlServer.Data;
/// <summary>
/// The abstract data logger.
/// </summary>
public abstract class AbstractDataLogger
{
/// <summary>
/// The delimiter for csv files.
/// </summary>
protected const string Delimiter = ";";
/// <summary>
/// The csv file format.
/// </summary>
protected const string CsvFileFormat = ".csv";
/// <summary>
/// The amount of digits for logging.
/// </summary>
protected const int Amountdigits = 3;
/// <summary>
/// The device dictionary containing titles for logging.
/// </summary>
[SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1013:ClosingCurlyBracketsMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")]
[SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1012:OpeningCurlyBracketsMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")]
[SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1009:ClosingParenthesisMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")]
private static readonly Dictionary<int, string> DeviceDictionary = new Dictionary<int, string>()
{
{(int) DataEnumerator.LakePlate50K, "50K Plate"},
{(int) DataEnumerator.LakePlate3K, "3K Plate"},
{(int) DataEnumerator.ComWaterIn, "Compressor water in"},
{(int) DataEnumerator.ComWaterOut, "Compressor water out"},
{(int) DataEnumerator.ComHelium, "Compressor helium"},
{(int) DataEnumerator.ComOil, "Compressor oil"},
{(int) DataEnumerator.ComLow, "Compressor low pressure"},
{(int) DataEnumerator.ComLowAvg, "Compressor low avg pressure"},
{(int) DataEnumerator.ComHigh, "Compressor high pressure"},
{(int) DataEnumerator.ComHighAvg, "Compressor high avg pressure"},
{(int) DataEnumerator.ComDeltaAvg, "Compressor delta avg pressure"},
{(int) DataEnumerator.He3Pump, "He3 Pump"},
{(int) DataEnumerator.HePlate2K, "He 2K Plate"},
{(int) DataEnumerator.HePlate4K, "He 4K Plate"},
{(int) DataEnumerator.He3Head, "He3 Head"},
{(int) DataEnumerator.He4Pump, "He4 Pump"},
{(int) DataEnumerator.He4SwitchTemp, "He4 Switch Temperature"},
{(int) DataEnumerator.He3SwitchTemp, "He3 Switch Temperature"},
{(int) DataEnumerator.He4Head, "He4 Head"},
{(int) DataEnumerator.He3VoltActual, "He3 Volt"},
{(int) DataEnumerator.He4SwitchVoltActual, "He4 Switch Volt"},
{(int) DataEnumerator.He3SwitchVoltActual, "He3 Switch Volt"},
{(int) DataEnumerator.He4VoltActual, "He4 Volt"},
{(int) DataEnumerator.HeConnectionState, "He Connection State"},
{(int) DataEnumerator.ComConnectionState, "Compressor Connection State"},
{(int) DataEnumerator.LakeConnectionState, "LakeShore Connection State"},
{(int) DataEnumerator.ComError, "Compressor Error"},
{(int) DataEnumerator.ComWarning, "Compressor Warning"},
{(int) DataEnumerator.ComHoursOfOperation, "Compressor hours of operation"},
{(int) DataEnumerator.ComOperationState, "Compressor Opertating State"},
};
/// <summary>
/// Initializes a new instance of the <see cref="AbstractDataLogger"/> class.
/// </summary>
public AbstractDataLogger()
{
}
/// <summary>
/// Create specific folder.
/// </summary>
/// <param name="currentDateTime">
/// The current Date Time.
/// </param>
/// <param name="mainFolderPath">
/// The main Folder Path.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public virtual string CreateFolder(DateTime currentDateTime, string mainFolderPath)
{
string year = currentDateTime.Year.ToString();
string month = currentDateTime.ToString("MMMM", new CultureInfo("en-US"));
string newFolderName = year + @"\" + month + @"\";
string pathToNewFolder = Path.Combine(mainFolderPath, newFolderName);
try
{
Directory.CreateDirectory(pathToNewFolder);
}
catch (Exception)
{
Console.WriteLine("Creating log folder failed");
}
return pathToNewFolder;
}
/// <summary>
/// Create a file with the current day as name, if it does not exist yet.
/// </summary>
/// <param name="mainFolderPath">
/// The main Folder Path.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public virtual string CreateFile(string mainFolderPath)
{
DateTime currentDateTime = DateTime.Now;
string folderPath = this.CreateFolder(currentDateTime, mainFolderPath);
string day = currentDateTime.Day.ToString();
string fileName = day + CsvFileFormat;
string actualPathToFile = Path.Combine(folderPath, fileName);
try
{
if (!File.Exists(actualPathToFile))
{
File.Create(actualPathToFile).Close();
}
}
catch (Exception)
{
Console.WriteLine("Creating log file failed");
}
return actualPathToFile;
}
/// <summary>
/// Write initial line containing headers.
/// </summary>
/// <param name="pathToFile">
/// The path to file.
/// </param>
/// <param name="devices">
/// The devices.
/// </param>
/// <param name="isGeneralLogging">
/// The general Log.
/// </param>
public void WriteInitialLine(string pathToFile, bool[] devices, bool isGeneralLogging)
{
FileInfo fileInfo = new FileInfo(pathToFile);
if (fileInfo.Length > 0)
{
return;
}
string initialLine = "Time";
for (int i = 0; i < devices.Length; i++)
{
if (devices[i])
{
initialLine += Delimiter + this.GetDeviceName(i);
}
}
if (isGeneralLogging)
{
initialLine += Delimiter + "ControllerState";
}
using (StreamWriter sw = File.AppendText(pathToFile))
{
sw.WriteLine(initialLine);
}
}
/// <summary>
/// The write initial line without control state header.
/// </summary>
/// <param name="pathToFile">
/// The path to file.
/// </param>
/// <param name="devices">
/// The devices.
/// </param>
public void WriteInitialLine(string pathToFile, bool[] devices)
{
this.WriteInitialLine(pathToFile, devices, false);
}
/// <summary>
/// The get device name.
/// </summary>
/// <param name="dataNumber">
/// The data number.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public string GetDeviceName(int dataNumber)
{
if (DeviceDictionary.ContainsKey(dataNumber))
{
return DeviceDictionary[dataNumber];
}
return string.Empty;
}
}
}<file_sep>/CryostatControlClient/ViewModels/ViewModelContainer.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ViewModelContainer.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels
{
using System;
using CryostatControlClient.ViewModels;
using LiveCharts;
using LiveCharts.Configurations;
using LiveCharts.Defaults;
/// <summary>
/// The viewmodel container.
/// </summary>
public class ViewModelContainer
{
/// <summary>
/// Initializes a new instance of the <see cref="ViewModelContainer" /> class.
/// </summary>
public ViewModelContainer()
{
this.BlueforsViewModel = new BlueforsViewModel();
this.CompressorViewModel = new CompressorViewModel();
this.He7ViewModel = new He7ViewModel();
this.LoggingViewModel = new LoggingViewModel();
this.ModusViewModel = new ModusViewModel();
this.SettingsViewModel = new SettingsViewModel();
this.ChartViewModel = new ChartViewModel();
this.MessageBoxViewModel = new MessageBoxViewModel();
this.InitSeriesCollection();
this.InitSeriesCollection2();
}
#region Properties
/// <summary>
/// Gets or sets the series collection.
/// </summary>
/// <value>
/// The series collection.
/// </value>
public SeriesCollection SeriesCollection { get; set; }
/// <summary>
/// Gets or sets the series collection.
/// </summary>
/// <value>
/// The series collection.
/// </value>
public SeriesCollection SeriesCollection2 { get; set; }
/// <summary>
/// Gets or sets the x formatter.
/// </summary>
/// <value>
/// The x formatter.
/// </value>
public Func<double, string> XFormatter { get; set; }
/// <summary>
/// Gets or sets the x formatter.
/// </summary>
/// <value>
/// The x formatter.
/// </value>
public Func<double, string> YFormatter { get; set; }
/// <summary>
/// Gets the BlueforsViewModel.
/// </summary>
/// <value>
/// The BlueforsViewModel.
/// </value>
public BlueforsViewModel BlueforsViewModel { get; }
/// <summary>
/// Gets the CompressorViewModel.
/// </summary>
/// <value>
/// The CompressorViewModel.
/// </value>
public CompressorViewModel CompressorViewModel { get; }
/// <summary>
/// Gets the He7ViewModel.
/// </summary>
/// <value>
/// The He7ViewModel.
/// </value>
public He7ViewModel He7ViewModel { get; }
/// <summary>
/// Gets the LoggingViewmodel.
/// </summary>
/// <value>
/// The logging view model.
/// </value>
public LoggingViewModel LoggingViewModel { get; }
/// <summary>
/// Gets the ModusViewmodel.
/// </summary>
/// <value>
/// The modus view model.
/// </value>
public ModusViewModel ModusViewModel { get; }
/// <summary>
/// Gets or sets the MessageBoxViewmodel.
/// </summary>
public MessageBoxViewModel MessageBoxViewModel { get; set; }
/// <summary>
/// Gets the SettingsViewmodel.
/// </summary>
public SettingsViewModel SettingsViewModel { get; private set; }
/// <summary>
/// Gets the ZoomingViewmodel.
/// </summary>
/// <value>
/// The zooming view model.
/// </value>
public ChartViewModel ChartViewModel { get; }
#endregion Properties
#region Methods
/// <summary>
/// Initializes the series collection for the chart tab chart.
/// </summary>
private void InitSeriesCollection()
{
this.SeriesCollection = new SeriesCollection
{
this.BlueforsViewModel.ColdPlate3KLineSeries,
this.BlueforsViewModel.ColdPlate50KLineSeries,
this.He7ViewModel.FourKPlateLineSeries,
this.He7ViewModel.TwoKPlatLineSeries,
this.He7ViewModel.He3HeadLineSeries,
this.He7ViewModel.He3PumpLineSeries,
this.He7ViewModel.He3SwitchLineSeries,
this.He7ViewModel.He4HeadLineSeries,
this.He7ViewModel.He4PumpLineSeries,
this.He7ViewModel.He4SwitchLineSeries,
};
this.XFormatter = val => this.GetDateTime(val);
}
/// <summary>
/// Initializes the series collection for the bottom chart.
/// </summary>
private void InitSeriesCollection2()
{
var mapper = Mappers.Xy<ObservablePoint>()
.X(point => point.X) //a 10 base log scale in the X axis
.Y(point => Math.Log(point.Y, 10));
this.SeriesCollection2 = new SeriesCollection(mapper)
{
this.BlueforsViewModel.ColdPlate3KLineSeriesBottom,
this.BlueforsViewModel.ColdPlate50KLineSeriesBottom,
this.He7ViewModel.He3HeadLineSeriesBottom,
this.He7ViewModel.He4HeadLineSeriesBottom,
};
this.YFormatter = value => Math.Pow(10, value).ToString("N");
}
/// <summary>
/// Gets the date time.
/// </summary>
/// <param name="val">The value.</param>
/// <returns>Time in hours and minutes.</returns>
private string GetDateTime(double val)
{
try
{
return new DateTime((long)val).ToString("HH:mm");
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.ToString());
return string.Empty;
}
}
#endregion Methods
}
}
<file_sep>/CryostatControlServer/HostService/Enumerators/SettingEnumerator.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SettingEnumerator.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.HostService.Enumerators
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// List of all settings
/// Make sure these names EXACTLY match those in settings property, ordering doesn't matter
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1602:EnumerationItemsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.")]
public enum SettingEnumerator
{
// He3PumpMaxVoltage,
// He4PumpMaxVoltage,
// He4SwitchMaxVoltage,
// He3SwitchMaxVoltage,
ControllerHe3HeaterPower,
ControllerHe4HeaterPower,
ControllerHe3SwitchVoltage,
ControllerHe4SwitchVoltage,
ControllerHe7StartTemperature,
ControllerHeaterTemperatureSetpoint,
ControllerHeatSwitchOnTemperature,
ControllerHeatSwitchSafeValue,
ControllerHeatupTemperature,
ControllerHe4StartTemperature,
ControllerHe3StartTemperature,
ControllerDisableHeaterHeatSwitchTemperature,
ControllerHe3StartMinimalTemperature,
ControllerHe3StartWaitTimeMinutes,
ControllerHeaterLowPowerValue,
}
}
<file_sep>/CryostatControlServerTests/He7Cooler/He7CoolerSmokeTests.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CryostatControlServerTests.He7Cooler
{
using System.Globalization;
using System.Threading;
using CryostatControlServer.He7Cooler;
using CryostatControlServer.Streams;
using Moq;
/// <summary>
/// The he 7 cooler smoke tests.
/// </summary>
[TestClass]
public class He7CoolerSmokeTests
{
#region Methods
[TestMethod]
public void SmokeTestInitialisation()
{
var mockH7 = new Mock<IManagedStream>();
mockH7.Setup(stream => stream.Open());
mockH7.Setup(stream => stream.ReadString()).Returns("1\n");
mockH7.Setup(stream => stream.IsConnected()).Returns(true);
var agilent = new Agilent34972A();
agilent.Init(mockH7.Object);
var cooler = new CryostatControlServer.He7Cooler.He7Cooler();
cooler.Connect(agilent, false);
cooler.Disconnect();
}
[TestMethod]
[ExpectedException(typeof(AgilentException), "Should have thrown invalid state exeption, but didn't.")]
public void SmokeTestFailedInitialisation()
{
var mockH7 = new Mock<IManagedStream>();
mockH7.Setup(stream => stream.Open());
mockH7.Setup(stream => stream.ReadString()).Returns("0\n");
mockH7.Setup(stream => stream.IsConnected()).Returns(true);
var agilent = new Agilent34972A();
agilent.Init(mockH7.Object);
var cooler = new He7Cooler();
cooler.Connect(agilent, false);
cooler.Disconnect();
}
[TestMethod]
public void SmokeTestReadValues()
{
//Set up mock
var mockH7 = new Mock<IManagedStream>();
var fakeresponser = new He7ResponseGenerator();
mockH7.Setup(stream => stream.Open());
mockH7.Setup(stream => stream.WriteString(It.IsAny<string>()))
.Callback((string s) => fakeresponser.ListenToAny(s));
mockH7.Setup(stream => stream.ReadString()).Returns(() => fakeresponser.RespondToRead());
mockH7.Setup(stream => stream.IsConnected()).Returns(true);
var agilent = new Agilent34972A();
agilent.Init(mockH7.Object);
var cooler = new CryostatControlServer.He7Cooler.He7Cooler();
cooler.Connect(agilent, false);
cooler.ReadVoltages();
Assert.AreEqual(0.0, cooler.He3Pump.Voltage);
fakeresponser.responsevalues[(int)Channels.SensHe3Pump] = 5.0;
cooler.ReadVoltages();
Assert.AreEqual(5.0, cooler.He3Pump.Voltage);
fakeresponser.responsevalues[(int)Channels.SensHe3HeadT] = 0.2147;
cooler.ReadVoltages();
Assert.AreEqual(33.0, cooler.He3HeadT.Value, 0.01);
cooler.Disconnect();
}
[TestMethod]
public void SmokeTestReadValuesThreaded()
{
//Set up mock
var mockH7 = new Mock<IManagedStream>();
var fakeresponser = new He7ResponseGenerator();
mockH7.Setup(stream => stream.Open());
mockH7.Setup(stream => stream.WriteString(It.IsAny<string>()))
.Callback((string s) => fakeresponser.ListenToAny(s));
mockH7.Setup(stream => stream.ReadString()).Returns(() => fakeresponser.RespondToRead());
mockH7.Setup(stream => stream.IsConnected()).Returns(true);
var agilent = new Agilent34972A();
agilent.Init(mockH7.Object);
var cooler = new CryostatControlServer.He7Cooler.He7Cooler();
cooler.Connect(agilent, true);
fakeresponser.responsevalues[(int)Channels.SensHe3HeadT] = 0.2147;
fakeresponser.responsevalues[(int)Channels.SensHe3Pump] = 5.0;
Thread.Sleep(5000);
Assert.AreEqual(5.0, cooler.He3Pump.Voltage);
Assert.AreEqual(33.0, cooler.He3HeadT.Value, 0.01);
cooler.Disconnect();
Thread.Sleep(1);
}
#endregion Methods
}
}<file_sep>/CryostatControlClient/ViewModels/SettingsViewModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SettingsViewModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels
{
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows.Input;
using CryostatControlClient.Communication;
using CryostatControlClient.Models;
using CryostatControlServer.HostService.Enumerators;
/// <summary>
/// The settings view model.
/// </summary>
public class SettingsViewModel : AbstractViewModel
{
/// <summary>
/// The is selected.
/// </summary>
private bool isSelected;
/// <summary>
/// The old settings retrieved from the server.
/// </summary>
private double[] oldSettings;
/// <summary>
/// Initializes a new instance of the <see cref="SettingsViewModel" /> class.
/// </summary>
public SettingsViewModel()
{
this.Settings = new ObservableCollection<SettingModel>(new SettingModel[] { });
this.ConfirmSettingsClick = new RelayCommand((obj) => this.SendChanges());
}
/// <summary>
/// Gets the confirm settings click.
/// </summary>
/// <value>
/// The confirm settings click.
/// </value>
public ICommand ConfirmSettingsClick { get; }
/// <summary>
/// Gets or sets a value indicating whether the settings tab is selected.
/// </summary>
/// <value>
/// <c>true</c> if this instance is selected; otherwise, <c>false</c>.
/// </value>
public bool IsSelected
{
get
{
return this.isSelected;
}
set
{
this.isSelected = value;
if (value)
{
this.UpdateSettingsFromServerAsync();
}
}
}
/// <summary>
/// Gets the settings.
/// </summary>
/// <value>
/// The settings.
/// </value>
public ObservableCollection<SettingModel> Settings { get; }
/// <summary>
/// Gets the current values.
/// </summary>
/// <returns>
/// The <see cref="double[]"/>.
/// </returns>
private double[] GetCurrentValues()
{
double[] res = new double[this.Settings.Count];
for (int i = 0; i < this.Settings.Count; i++)
{
res[i] = this.Settings[i].Value;
}
return res;
}
/// <summary>
/// Sends changes in settings to the server
/// </summary>
private void SendChanges()
{
ServerCheck.SendMessage(new Task(() => { this.WriteSettings(); }));
}
/// <summary>
/// Writes the settings to the server.
/// </summary>
private void WriteSettings()
{
var newSettings = this.GetCurrentValues();
for (int i = 0; i < newSettings.Length; i++)
{
if (Math.Abs(newSettings[i] - this.oldSettings[i]) > 0.01)
{
ServerCheck.CommandClient.WriteSettingValue(i, newSettings[i]);
}
}
}
/// <summary>
/// Updates the displayed settings
/// </summary>
/// <param name="settingValues">
/// The setting values.
/// </param>
private void UpdateSettings(double[] settingValues)
{
this.oldSettings = settingValues;
this.Settings.Clear();
for (int i = 0; i < settingValues.Length; i++)
{
this.Settings.Add(
new SettingModel(
i,
settingValues[i],
SettingEnumeratorDescription.DescriptionStrings[i],
SettingEnumeratorDescription.UnitStrings[i]));
}
}
/// <summary>
/// Updates the displayed settings async
/// </summary>
private void UpdateSettingsFromServerAsync()
{
ServerCheck.SendMessage(new Task(() => { ReadSettings(); }));
}
/// <summary>
/// Reads the settings from the server.
/// </summary>
private void ReadSettings()
{
double[] settings = ServerCheck.CommandClient.ReadSettings();
App.Current.Dispatcher.Invoke((Action)delegate
{
this.UpdateSettings(settings);
});
}
}
}<file_sep>/CryostatControlServer/Compressor/Enumerators/WarningsEnum.cs
//-----------------------------------------------------------------------
// <copyright file="WarningsEnum.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.Compressor
{
/// <summary>
/// Enumerator for the warnings
/// </summary>
public enum WarningsEnum
{
/// <summary>
/// No warnings
/// </summary>
NoWarnings = 0,
/// <summary>
/// The coolant in temperature running high
/// </summary>
CoolantInRunningHigh = -1,
/// <summary>
/// The coolant in temperature running low
/// </summary>
CoolantInRunningLow = -2,
/// <summary>
/// The coolant out temperature running high
/// </summary>
CoolantOutRunningHigh = -4,
/// <summary>
/// The coolant out temperature running low
/// </summary>
CoolantOutRunningLow = -8,
/// <summary>
/// The oil temperature running high
/// </summary>
OilRunningHigh = -16,
/// <summary>
/// The oil temperature running low
/// </summary>
OilRunningLow = -32,
/// <summary>
/// The helium temperature running high
/// </summary>
HeliumRunningHigh = -64,
/// <summary>
/// The helium temperature running low
/// </summary>
HeliumRunningLow = -128,
/// <summary>
/// The low pressure running high
/// </summary>
LowPressureRunningHigh = -256,
/// <summary>
/// The low pressure running low
/// </summary>
LowPressureRunningLow = -512,
/// <summary>
/// The high pressure running high
/// </summary>
HighPressureRunningHigh = -1024,
/// <summary>
/// The high pressure running low
/// </summary>
HighPressureRunningLow = -2048,
/// <summary>
/// The delta pressure running high
/// </summary>
DeltaPressureRunningHigh = -4096,
/// <summary>
/// The delta pressure running low
/// </summary>
DeltaPressureRunningLow = -8192,
/// <summary>
/// The static pressure running high
/// </summary>
StaticPressureRunningHigh = -131072,
/// <summary>
/// The static pressure running low
/// </summary>
StaticPressureRunningLow = -262144,
/// <summary>
/// The cold head motor stall
/// </summary>
ColdHeadMotorStall = -524288
}
}<file_sep>/CryostatControlClientTests/ViewModels/CompressorViewModelTests.cs
//-----------------------------------------------------------------------
// <copyright file="CompressorViewModelTests.cs" company="SRON">
// Copyright (c) SRON. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlClient.ViewModels.Tests
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
/// <summary>
/// Tests for compressor view model
/// </summary>
[TestClass]
public class CompressorViewModelTests
{
private CompressorViewModel compressorViewModel;
[TestInitialize]
public void TestInitialize()
{
this.compressorViewModel = new CompressorViewModel();
}
[TestMethod()]
public void OperatingStateTest()
{
this.compressorViewModel.OperatingState = 1;
Assert.AreEqual(this.compressorViewModel.OperatingState, 1);
}
[TestMethod()]
public void OperatingStateConvertedTest()
{
this.compressorViewModel.OperatingState = 1;
Assert.IsFalse(String.IsNullOrEmpty(this.compressorViewModel.OperatingStateConverted));
}
[TestMethod()]
public void WarningStateTest()
{
this.compressorViewModel.WarningState = 1;
Assert.AreEqual(this.compressorViewModel.WarningState, 1);
}
[TestMethod()]
public void WarningStateConvertedTest()
{
this.compressorViewModel.WarningState = 1;
Assert.IsFalse(String.IsNullOrEmpty(this.compressorViewModel.WarningStateConverted));
}
[TestMethod()]
public void ErrorStateTest()
{
this.compressorViewModel.ErrorState = 1;
Assert.AreEqual(this.compressorViewModel.ErrorState, 1);
}
[TestMethod()]
public void ErrorStateConvertedTest()
{
this.compressorViewModel.ErrorState = 1;
Assert.IsFalse(String.IsNullOrEmpty(this.compressorViewModel.ErrorStateConverted));
}
[TestMethod()]
public void WaterInTempTest()
{
this.compressorViewModel.WaterInTemp = 1;
Assert.AreEqual(this.compressorViewModel.WaterInTemp, 1);
}
[TestMethod()]
public void WaterOutTest()
{
this.compressorViewModel.WaterOutTemp = 1;
Assert.AreEqual(this.compressorViewModel.WaterOutTemp, 1);
}
[TestMethod()]
public void OilTempTest()
{
this.compressorViewModel.OilTemp = 1;
Assert.AreEqual(this.compressorViewModel.OilTemp, 1);
}
[TestMethod()]
public void HeliumTempTest()
{
this.compressorViewModel.HeliumTemp = 1;
Assert.AreEqual(this.compressorViewModel.HeliumTemp, 1);
}
[TestMethod()]
public void LowPressureTest()
{
this.compressorViewModel.LowPressure = 1;
Assert.AreEqual(this.compressorViewModel.LowPressure, 1);
}
[TestMethod()]
public void LowPressureAverageTest()
{
this.compressorViewModel.LowPressureAverage = 1;
Assert.AreEqual(this.compressorViewModel.LowPressureAverage, 1);
}
[TestMethod()]
public void HighPressureTest()
{
this.compressorViewModel.HighPressure = 1;
Assert.AreEqual(this.compressorViewModel.HighPressure, 1);
}
[TestMethod()]
public void HighPressureAverageTest()
{
this.compressorViewModel.HighPressureAverage = 1;
Assert.AreEqual(this.compressorViewModel.HighPressureAverage, 1);
}
[TestMethod()]
public void DeltaPressureAverageTest()
{
this.compressorViewModel.DeltaPressureAverage = 1;
Assert.AreEqual(this.compressorViewModel.DeltaPressureAverage, 1);
}
[TestMethod()]
public void HoursOfOperationTest()
{
this.compressorViewModel.HoursOfOperation = 1;
Assert.AreEqual(this.compressorViewModel.HoursOfOperation, 1);
}
[TestMethod()]
public void PressureScaleTest()
{
this.compressorViewModel.PressureScale = 1;
Assert.AreEqual(this.compressorViewModel.PressureScale, 1);
}
[TestMethod()]
public void PressureScaleConvertedTest()
{
this.compressorViewModel.PressureScale = 1;
Assert.IsFalse(String.IsNullOrEmpty(this.compressorViewModel.PressureScaleConverted));
}
[TestMethod()]
public void TempScaleTest()
{
this.compressorViewModel.TempScale = 1;
Assert.AreEqual(this.compressorViewModel.TempScale, 1);
}
[TestMethod()]
public void TempScaleConvertedTest()
{
this.compressorViewModel.TempScale = 1;
Assert.IsFalse(String.IsNullOrEmpty(this.compressorViewModel.TempScaleConverted));
}
[TestMethod()]
public void ConnectionStateTest()
{
this.compressorViewModel.ConnectionState = 1;
Assert.AreEqual(this.compressorViewModel.ConnectionState, 1);
}
[TestMethod()]
public void ConnectionStateConvertedTest()
{
this.compressorViewModel.ConnectionState = 1;
Assert.IsFalse(String.IsNullOrEmpty(this.compressorViewModel.ConnectionStateConverted));
}
[TestMethod()]
public void TurnOnTestTrue()
{
this.compressorViewModel.OperatingState = 0;
Assert.IsTrue(this.compressorViewModel.CanTurnOn);
}
[TestMethod()]
public void TurnOnTestFalse()
{
this.compressorViewModel.OperatingState = 1;
Assert.IsFalse(this.compressorViewModel.CanTurnOn);
}
[TestMethod()]
public void TurnOffTestTrue()
{
this.compressorViewModel.OperatingState = 3;
Assert.IsTrue(this.compressorViewModel.CanTurnOff);
}
[TestMethod()]
public void TurnOffTestFalse()
{
this.compressorViewModel.OperatingState = 1;
Assert.IsFalse(this.compressorViewModel.CanTurnOff);
}
[TestMethod()]
public void ConvertNanToZeroIfNanTest()
{
double nan = Double.NaN;
Assert.AreEqual(0, this.compressorViewModel.ConvertNanToZeroIfNan(nan));
}
[TestMethod()]
public void ConvertNanToZeroIfNanButIsNoNanTest()
{
double nan = 20;
Assert.AreEqual(20, this.compressorViewModel.ConvertNanToZeroIfNan(nan));
}
}
}<file_sep>/CryostatControlServer/CryostatControlServerApplicationContext.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CryostatControlServerApplicationContext.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer
{
using System;
using System.Diagnostics;
using System.Windows.Forms;
using CryostatControlServer.Properties;
/// <summary>
/// The cryostat control server application context.
/// </summary>
public class CryostatControlServerApplicationContext : ApplicationContext
{
/// <summary>
/// The debug form.
/// </summary>
private static DebugForm debugform = new DebugForm();
/// <summary>
/// The tray icon.
/// </summary>
private readonly NotifyIcon trayIcon;
/// <summary>
/// Initializes a new instance of the <see cref="CryostatControlServerApplicationContext"/> class.
/// </summary>
public CryostatControlServerApplicationContext()
{
// Initialize Tray Icon
this.trayIcon = new NotifyIcon()
{
Icon = Resources.trayicon,
ContextMenu =
new ContextMenu(
new[]
{
new MenuItem("Show console", this.ShowConsole),
new MenuItem("Open log folder", ShowLogs),
new MenuItem("Exit", this.Exit)
}),
Visible = true
};
Launcher.Launch();
}
/// <summary>
/// Main method
/// </summary>
/// <param name="args">The arguments.</param>
public static void Main(string[] args)
{
Application.Run(new CryostatControlServerApplicationContext());
}
/// <summary>
/// Show the log screen.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
private static void ShowLogs(object sender, EventArgs e)
{
try
{
Process.Start(@"explorer.exe", Settings.Default.LoggingAddress);
}
catch (Exception)
{
}
}
/// <summary>
/// Close the application
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
private void Exit(object sender, EventArgs e)
{
// Hide tray icon, otherwise it will remain shown until user mouses over it
this.trayIcon.Visible = false;
Launcher.Exit();
Environment.Exit(0);
}
/// <summary>
/// The show console.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
private void ShowConsole(object sender, EventArgs e)
{
debugform.Show();
}
}
}<file_sep>/CryostatControlClient/ViewModels/CompressorViewModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CompressorViewModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels
{
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using CryostatControlClient.Communication;
using CryostatControlClient.Models;
/// <summary>
/// Compressor ViewModel
/// </summary>
public class CompressorViewModel : AbstractViewModel
{
#region Fields
/// <summary>
/// The water in minimum
/// </summary>
private const int WaterInMinimum = 10;
/// <summary>
/// The water in maximum
/// </summary>
private const int WaterInMaximum = 44;
/// <summary>
/// The water out minimum
/// </summary>
private const int WaterOutMinimum = 10;
/// <summary>
/// The water out maximum
/// </summary>
private const int WaterOutMaximum = 51;
/// <summary>
/// The helium minimum
/// </summary>
private const int HeliumMinimum = 10;
/// <summary>
/// The helium maximum
/// </summary>
private const int HeliumMaximum = 87;
/// <summary>
/// The oil minimum
/// </summary>
private const int OilMinimum = 10;
/// <summary>
/// The oil maximum
/// </summary>
private const int OilMaximum = 51;
/// <summary>
/// No information string used when dictionary has no correct data
/// </summary>
private const string NoInformation = "No information";
/// <summary>
/// The compressor model
/// </summary>
private CompressorModel compressorModel;
/// <summary>
/// The switch command
/// </summary>
private ICommand turnOnCommand;
/// <summary>
/// The switch command
/// </summary>
private ICommand turnOffCommand;
/// <summary>
/// The operating state dictionary
/// </summary>
private Dictionary<int, string> operatingStateDictionary =
new Dictionary<int, string>
{
{ -1, "Disconnected" },
{ 0, "Ready to Start" },
{ 2, "Starting" },
{ 3, "Running" },
{ 5, "Stopping" },
{ 6, "Error Lockout" },
{ 7, "Error" },
{ 8, "Helium Cool Down" },
{ 9, "Error Power Related" },
{ 16, "Error Recovery" }
};
/// <summary>
/// The warning state dictionary
/// </summary>
private Dictionary<int, string> warningStateDictionary =
new Dictionary<int, string>
{
{ 0, "No warnings" },
{ -1, "Water IN running High" },
{ -2, "Water IN running Low" },
{ -4, "Water OUT running High" },
{ -8, "Water OUT running Low" },
{ -16, "Oil running High" },
{ -32, "Oil running Low" },
{ -64, "Helium running High" },
{ -128, "Helium running Low" },
{ -256, "Low Pressure running High" },
{ -512, "Low Pressure running Low" },
{ -1024, "High Pressure running High" },
{ -2048, "High Pressure running Low" },
{ -4096, "Delta Pressure running High" },
{ -8192, "Delta Pressure running Low" },
{ -131072, "Static Pressure running High" },
{ -262144, "Static Pressure running Low" },
{ -524288, "Cold head motor Stall" }
};
/// <summary>
/// The error state dictionary
/// </summary>
private Dictionary<int, string> errorStateDictionary =
new Dictionary<int, string>
{
{ 0, "No Errors" },
{ -1, "Water IN High" },
{ -2, "Water IN Low" },
{ -4, "Water OUT High" },
{ -8, "Water OUT Low" },
{ -16, "Oil High" },
{ -32, "Oil Low" },
{ -64, "Helium High" },
{ -128, "Helium Low" },
{ -256, "Low Pressure High" },
{ -512, "Low Pressure Low" },
{ -1024, "High Pressure High" },
{ -2048, "High Pressure Low" },
{ -4096, "Delta Pressure High" },
{ -8192, "Delta Pressure Low" },
{ -16384, "Motor Current Low" },
{ -32768, "Three Phase Error" },
{ -65536, "Power Supply Error" },
{ -131072, "Static Pressure High" },
{ -262144, "Static Pressure Low" },
};
#endregion Fields
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="CompressorViewModel"/> class.
/// </summary>
public CompressorViewModel()
{
this.compressorModel = new CompressorModel();
this.turnOnCommand = new RelayCommand(this.TurnOn, param => true);
this.turnOffCommand = new RelayCommand(this.TurnOff, param => true);
}
#endregion Constructor
#region Properties
/// <summary>
/// Gets the color of the connection state.
/// </summary>
/// <value>
/// The color of the connection state.
/// </value>
public SolidColorBrush ConnectionStateColor
{
get
{
return this.DisplayColor((ColorState)this.ConnectionState);
}
}
/// <summary>
/// Gets the switch command.
/// </summary>
/// <value>
/// The switch command.
/// </value>
public ICommand TurnOnCommand
{
get
{
return this.turnOnCommand;
}
}
/// <summary>
/// Gets the turn off command.
/// </summary>
/// <value>
/// The turn off command.
/// </value>
public ICommand TurnOffCommand
{
get
{
return this.turnOffCommand;
}
}
/// <summary>
/// Gets or sets the state of the operating.
/// </summary>
/// <value>
/// The state of the operating.
/// </value>
public double OperatingState
{
get
{
return this.compressorModel.OperatingState;
}
set
{
this.compressorModel.OperatingState = value;
this.RaisePropertyChanged("OperatingState");
this.RaisePropertyChanged("OperatingStateConverted");
this.RaisePropertyChanged("CanTurnOn");
this.RaisePropertyChanged("CanTurnOff");
}
}
/// <summary>
/// Gets the operating state converted.
/// </summary>
/// <value>
/// The operating state converted.
/// </value>
public string OperatingStateConverted
{
get
{
string state;
return this.operatingStateDictionary.TryGetValue((int)this.compressorModel.OperatingState, out state) ? state : NoInformation;
}
}
/// <summary>
/// Gets or sets the state of the warning.
/// </summary>
/// <value>
/// The state of the warning.
/// </value>
public double WarningState
{
get
{
return this.compressorModel.WarningState;
}
set
{
this.compressorModel.WarningState = value;
this.RaisePropertyChanged("WarningState");
this.RaisePropertyChanged("WarningStateConverted");
}
}
/// <summary>
/// Gets the warning state converted.
/// </summary>
/// <value>
/// The warning state converted.
/// </value>
public string WarningStateConverted
{
get
{
string state;
return this.warningStateDictionary.TryGetValue((int)this.compressorModel.WarningState, out state) ? state : NoInformation;
}
}
/// <summary>
/// Gets or sets the state of the alarm.
/// </summary>
/// <value>
/// The state of the alarm.
/// </value>
public double ErrorState
{
get
{
return this.compressorModel.ErrorState;
}
set
{
this.compressorModel.ErrorState = value;
this.RaisePropertyChanged("ErrorState");
this.RaisePropertyChanged("ErrorStateConverted");
}
}
/// <summary>
/// Gets the alarm state converted.
/// </summary>
/// <value>
/// The error state converted.
/// </value>
public string ErrorStateConverted
{
get
{
string state;
return this.errorStateDictionary.TryGetValue((int)this.compressorModel.ErrorState, out state) ? state : NoInformation;
}
}
/// <summary>
/// Gets or sets the water in temperature.
/// </summary>
/// <value>
/// The water in temperature.
/// </value>
public double WaterInTemp
{
get
{
return this.compressorModel.WaterInTemp;
}
set
{
this.compressorModel.WaterInTemp = value;
this.RaisePropertyChanged("WaterInTemp");
this.RaisePropertyChanged("WaterInTempProgressbar");
this.RaisePropertyChanged("WaterInTempColor");
}
}
/// <summary>
/// Gets the water in temporary progressbar.
/// </summary>
/// <value>
/// The water in temporary progressbar.
/// </value>
public double WaterInTempProgressbar
{
get
{
return this.ConvertNanToZeroIfNan(this.compressorModel.WaterInTemp);
}
}
/// <summary>
/// Gets the color of the water in temporary.
/// </summary>
/// <value>
/// The color of the water in temporary.
/// </value>
public SolidColorBrush WaterInTempColor
{
get
{
if (this.compressorModel.WaterInTemp < WaterInMinimum
|| this.compressorModel.WaterInTemp > WaterInMaximum)
{
return this.DisplayColor(ColorState.Red);
}
return this.DisplayColor(ColorState.Green);
}
}
/// <summary>
/// Gets or sets the Water out temperature.
/// </summary>
/// <value>
/// The Water out temperature.
/// </value>
public double WaterOutTemp
{
get
{
return this.compressorModel.WaterOutTemp;
}
set
{
this.compressorModel.WaterOutTemp = value;
this.RaisePropertyChanged("WaterOutTemp");
this.RaisePropertyChanged("WaterOutTempProgressbar");
this.RaisePropertyChanged("WaterOutTempColor");
}
}
/// <summary>
/// Gets the water out temporary progressbar.
/// </summary>
/// <value>
/// The water out temporary progressbar.
/// </value>
public double WaterOutTempProgressbar
{
get
{
return this.ConvertNanToZeroIfNan(this.compressorModel.WaterOutTemp);
}
}
/// <summary>
/// Gets the color of the water out temperature.
/// </summary>
/// <value>
/// The color of the water out temperature.
/// </value>
public SolidColorBrush WaterOutTempColor
{
get
{
if (this.compressorModel.WaterOutTemp < WaterOutMinimum
|| this.compressorModel.WaterOutTemp > WaterOutMaximum)
{
return this.DisplayColor(ColorState.Red);
}
return this.DisplayColor(ColorState.Green);
}
}
/// <summary>
/// Gets or sets the oil temperature.
/// </summary>
/// <value>
/// The oil temperature.
/// </value>
public double OilTemp
{
get
{
return this.compressorModel.OilTemp;
}
set
{
this.compressorModel.OilTemp = value;
this.RaisePropertyChanged("OilTemp");
this.RaisePropertyChanged("OilTempProgressbar");
this.RaisePropertyChanged("OilTempColor");
}
}
/// <summary>
/// Gets the oil temperature progressbar.
/// </summary>
/// <value>
/// The oil temperature progressbar.
/// </value>
public double OilTempProgressbar
{
get
{
return this.ConvertNanToZeroIfNan(this.compressorModel.OilTemp);
}
}
/// <summary>
/// Gets the color of the oil temperature.
/// </summary>
/// <value>
/// The color of the oil temperature.
/// </value>
public SolidColorBrush OilTempColor
{
get
{
if (this.compressorModel.OilTemp < OilMinimum
|| this.compressorModel.OilTemp > OilMaximum)
{
return this.DisplayColor(ColorState.Red);
}
return this.DisplayColor(ColorState.Green);
}
}
/// <summary>
/// Gets or sets the helium temperature.
/// </summary>
/// <value>
/// The helium temperature.
/// </value>
public double HeliumTemp
{
get
{
return this.compressorModel.HeliumTemp;
}
set
{
this.compressorModel.HeliumTemp = value;
this.RaisePropertyChanged("HeliumTemp");
this.RaisePropertyChanged("HeliumTempProgressbar");
this.RaisePropertyChanged("HeliumTempColor");
}
}
/// <summary>
/// Gets the helium temperature progressbar.
/// </summary>
/// <value>
/// The helium temperature progressbar.
/// </value>
public double HeliumTempProgressbar
{
get
{
return this.ConvertNanToZeroIfNan(this.compressorModel.HeliumTemp);
}
}
/// <summary>
/// Gets the color of the helium temperature.
/// </summary>
/// <value>
/// The color of the helium temperature.
/// </value>
public SolidColorBrush HeliumTempColor
{
get
{
if (this.compressorModel.HeliumTemp < HeliumMinimum || this.compressorModel.HeliumTemp > HeliumMaximum)
{
return this.DisplayColor(ColorState.Red);
}
return this.DisplayColor(ColorState.Green);
}
}
/// <summary>
/// Gets or sets the low pressure.
/// </summary>
/// <value>
/// The low pressure.
/// </value>
public double LowPressure
{
get
{
return this.compressorModel.LowPressure;
}
set
{
this.compressorModel.LowPressure = value;
this.RaisePropertyChanged("LowPressure");
this.RaisePropertyChanged("LowPressureGauge");
}
}
/// <summary>
/// Gets the low pressure gauge.
/// </summary>
/// <value>
/// The low pressure gauge.
/// </value>
public double LowPressureGauge
{
get
{
return this.ConvertNanToZeroIfNan(this.compressorModel.LowPressure);
}
}
/// <summary>
/// Gets or sets the low pressure average.
/// </summary>
/// <value>
/// The low pressure average.
/// </value>
public double LowPressureAverage
{
get
{
return this.compressorModel.LowPressureAverage;
}
set
{
this.compressorModel.LowPressureAverage = value;
this.RaisePropertyChanged("LowPressureAverage");
}
}
/// <summary>
/// Gets or sets the high pressure.
/// </summary>
/// <value>
/// The high pressure.
/// </value>
public double HighPressure
{
get
{
return this.compressorModel.HighPressure;
}
set
{
this.compressorModel.HighPressure = value;
this.RaisePropertyChanged("HighPressure");
this.RaisePropertyChanged("HighPressureGauge");
}
}
/// <summary>
/// Gets the high pressure gauge.
/// </summary>
/// <value>
/// The high pressure gauge.
/// </value>
public double HighPressureGauge
{
get
{
return this.ConvertNanToZeroIfNan(this.compressorModel.HighPressure);
}
}
/// <summary>
/// Gets or sets the high pressure average.
/// </summary>
/// <value>
/// The high pressure average.
/// </value>
public double HighPressureAverage
{
get
{
return this.compressorModel.HighPressureAverage;
}
set
{
this.compressorModel.HighPressureAverage = value;
this.RaisePropertyChanged("HighPressureAverage");
}
}
/// <summary>
/// Gets or sets the delta pressure average.
/// </summary>
/// <value>
/// The delta pressure average.
/// </value>
public double DeltaPressureAverage
{
get
{
return this.compressorModel.DeltaPressureAverage;
}
set
{
this.compressorModel.DeltaPressureAverage = value;
this.RaisePropertyChanged("DeltaPressureAverage");
}
}
/// <summary>
/// Gets or sets the hours of operation.
/// </summary>
/// <value>
/// The hours of operation.
/// </value>
public double HoursOfOperation
{
get
{
return this.compressorModel.HoursOfOperation;
}
set
{
this.compressorModel.HoursOfOperation = value;
this.RaisePropertyChanged("HoursOfOperation");
}
}
/// <summary>
/// Gets or sets the pressure scale.
/// </summary>
/// <value>
/// The pressure scale.
/// </value>
public double PressureScale
{
get
{
return this.compressorModel.PressureScale;
}
set
{
this.compressorModel.PressureScale = value;
this.RaisePropertyChanged("PressureScale");
this.RaisePropertyChanged("PressureScaleConverted");
}
}
/// <summary>
/// Gets the pressure scale converted.
/// </summary>
/// <value>
/// The pressure scale converted.
/// </value>
public string PressureScaleConverted
{
get
{
return this.ConvertPressureScaleToString((int)this.compressorModel.PressureScale);
}
}
/// <summary>
/// Gets or sets the temperature scale.
/// </summary>
/// <value>
/// The temperature scale.
/// </value>
public double TempScale
{
get
{
return this.compressorModel.TempScale;
}
set
{
this.compressorModel.TempScale = value;
this.RaisePropertyChanged("TempScale");
this.RaisePropertyChanged("TempScaleConverted");
}
}
/// <summary>
/// Gets the temperature scale converted.
/// </summary>
/// <value>
/// The temporary scale converted.
/// </value>
public string TempScaleConverted
{
get
{
return this.ConvertTempScaleToString((int)this.compressorModel.TempScale);
}
}
/// <summary>
/// Gets or sets a value indicating whether [power on].
/// </summary>
/// <value>
/// <c>true</c> if [power on]; otherwise, <c>false</c>.
/// </value>
public double ConnectionState
{
get
{
return this.compressorModel.ConnectionState;
}
set
{
this.compressorModel.ConnectionState = value;
this.RaisePropertyChanged("ConnectionState");
this.RaisePropertyChanged("ConnectionStateConverted");
this.RaisePropertyChanged("ConnectionStateColor");
}
}
/// <summary>
/// Gets the connection state converted.
/// </summary>
public string ConnectionStateConverted
{
get
{
return this.ConvertConnectionStateNumberToString(this.compressorModel.ConnectionState);
}
}
/// <summary>
/// Gets a value indicating whether this instance can turn on.
/// </summary>
/// <value>
/// <c>true</c> if this instance can turn on; otherwise, <c>false</c>.
/// </value>
public bool CanTurnOn
{
get
{
return this.CheckTurnOn();
}
}
/// <summary>
/// Gets a value indicating whether this instance can turn off.
/// </summary>
/// <value>
/// <c>true</c> if this instance can turn off; otherwise, <c>false</c>.
/// </value>
public bool CanTurnOff
{
get
{
return this.CheckTurnOff();
}
}
#endregion Properties
#region Methods
/// <summary>
/// Converts the nan to zero if nan.
/// </summary>
/// <param name="possibleNan">The possible nan.</param>
/// <returns>0 if Nan; Normal value otherwise</returns>
public double ConvertNanToZeroIfNan(double possibleNan)
{
if (double.IsNaN(possibleNan))
{
return 0;
}
return possibleNan;
}
/// <summary>
/// Turns the compressor on.
/// </summary>
/// <param name="obj">The object.</param>
private void TurnOn(object obj)
{
ServerCheck.SendMessage(new Task(() => { ServerCheck.CommandClient.SetCompressorState(true); }));
}
/// <summary>
/// Turns the compressor off.
/// </summary>
/// <param name="obj">The object.</param>
private void TurnOff(object obj)
{
ServerCheck.SendMessage(new Task(() => { ServerCheck.CommandClient.SetCompressorState(false); }));
}
/// <summary>
/// Checks the turn on.
/// </summary>
/// <returns>
/// True if the compressor is ready to start, false otherwise.
/// </returns>
private bool CheckTurnOn()
{
switch ((int)this.OperatingState)
{
case 0: return true;
default: return false;
}
}
/// <summary>
/// Checks the turn off.
/// </summary>
/// <returns>
/// True if the compressor is running, false otherwise.
/// </returns>
private bool CheckTurnOff()
{
switch ((int)this.OperatingState)
{
case 3: return true;
default: return false;
}
}
/// <summary>
/// Converts the temperature scale to string.
/// </summary>
/// <param name="scale">The scale.</param>
/// <returns>Converted scale</returns>
private string ConvertTempScaleToString(int scale)
{
switch (scale)
{
case 0: return "F";
case 1: return "C";
case 2: return "K";
}
return string.Empty;
}
/// <summary>
/// Converts the pressure scale to string.
/// </summary>
/// <param name="scale">The scale.</param>
/// <returns>Converted string</returns>
private string ConvertPressureScaleToString(int scale)
{
switch (scale)
{
case 0: return "PSI";
case 1: return "Bar";
case 2: return "KPA";
}
return string.Empty;
}
#endregion Methods
}
}<file_sep>/CryostatControlClient/Views/Tabs/OverviewFrame.xaml.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OverviewFrame.xaml.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Views.Tabs
{
/// <summary>
/// Interaction logic for OverviewFrame.xaml
/// </summary>
public partial class OverviewFrame
{
}
}
<file_sep>/CryostatControlServer/Logging/SpecificDataLogger.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SpecificDataLogger.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Logging
{
using System;
using System.Globalization;
using System.IO;
/// <summary>
/// Log specific data.
/// </summary>
public class SpecificDataLogger : AbstractDataLogger
{
/// <summary>
/// The to be logged or not to be logged.
/// </summary>
private readonly bool[] toBeLoggedOrNotToBeLogged;
/// <summary>
/// The interval
/// </summary>
private readonly int interval;
/// <summary>
/// Initializes a new instance of the <see cref="SpecificDataLogger"/> class.
/// </summary>
/// <param name="toBeLoggedOrNotToBeLogged">
/// The to Be Logged Or Not To Be Logged.
/// </param>
/// <param name="interval">
/// The interval.
/// </param>
public SpecificDataLogger(bool[] toBeLoggedOrNotToBeLogged, int interval)
{
this.toBeLoggedOrNotToBeLogged = toBeLoggedOrNotToBeLogged;
this.interval = interval;
}
/// <summary>
/// Write specific data.
/// </summary>
/// <param name="pathToFile">
/// The path To File.
/// </param>
/// <param name="logData">
/// The log Data.
/// </param>
/// <param name="time">
/// The time.
/// </param>
public void WriteSpecificData(string pathToFile, double[] logData, string time)
{
string dataLine = time;
for (int i = 0; i < this.toBeLoggedOrNotToBeLogged.Length; i++)
{
if (this.toBeLoggedOrNotToBeLogged[i])
{
dataLine += AbstractDataLogger.Delimiter + Math.Round(logData[i], AbstractDataLogger.Amountdigits);
}
}
try
{
using (FileStream fileStream =
new FileStream(pathToFile, FileMode.Append, FileAccess.Write, FileShare.None))
{
using (StreamWriter sw = new StreamWriter(fileStream))
{
sw.WriteLine(dataLine);
}
}
}
catch (IOException)
{
DebugLogger.Warning(this.GetType().Name, "The specific log file is opened by another process. Please close this first.");
}
}
/// <summary>
/// The get to be logged or not to be logged.
/// </summary>
/// <returns>
/// The <see cref="bool[]"/>.
/// </returns>
public bool[] GetToBeLoggedOrNotToBeLogged()
{
return this.toBeLoggedOrNotToBeLogged;
}
/// <summary>
/// The get interval.
/// </summary>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public int GetInterval()
{
return this.interval;
}
/// <summary>
/// Create specific folder.
/// </summary>
/// <param name="currentDateTime">
/// The current Date Time.
/// </param>
/// <param name="mainFolderPath">
/// The main Folder Path.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public override string CreateFolder(DateTime currentDateTime, string mainFolderPath)
{
string year = currentDateTime.Year.ToString();
string month = currentDateTime.ToString("MMMM", new CultureInfo("en-US"));
string day = currentDateTime.Day.ToString();
string newFolderName = year + @"\" + month + @"\" + day + @"\";
string pathToNewFolder = Path.Combine(mainFolderPath, newFolderName);
try
{
Directory.CreateDirectory(pathToNewFolder);
}
catch (Exception)
{
Console.WriteLine("Creating log folder failed");
}
return pathToNewFolder;
}
/// <summary>
/// Create a file with the current day as name, if it does not exist yet.
/// </summary>
/// <param name="mainFolderPath">
/// The main Folder Path.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public override string CreateFile(string mainFolderPath)
{
DateTime currentDateTime = DateTime.Now;
string folderPath = this.CreateFolder(currentDateTime, mainFolderPath);
string time = currentDateTime.ToString("HH_mm_ss");
string fileName = time + AbstractDataLogger.CsvFileFormat;
string actualPathToFile = Path.Combine(folderPath, fileName);
try
{
if (!File.Exists(actualPathToFile))
{
File.Create(actualPathToFile).Close();
}
}
catch (Exception)
{
Console.WriteLine("Creating log file failed");
}
return actualPathToFile;
}
}
}
<file_sep>/CryostatControlClient/Models/CompressorModel.cs
//-----------------------------------------------------------------------
// <copyright file="CompressorModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlClient.Models
{
using System;
using System.Collections.Generic;
using Dragablz.Dockablz;
/// <summary>
/// The compressor model.
/// </summary>
public class CompressorModel
{
#region Fields
#endregion Fields
#region Properties
/// <summary>
/// Gets or sets the state of operation.
/// </summary>
/// <value>
/// The state of operiation.
/// </value>
public double OperatingState { get; set; } = -1;
/// <summary>
/// Gets or sets the state of the warning.
/// </summary>
/// <value>
/// The state of the warning.
/// </value>
public double WarningState { get; set; }
/// <summary>
/// Gets or sets the state of the error.
/// </summary>
/// <value>
/// The state of the error.
/// </value>
public double ErrorState { get; set; }
/// <summary>
/// Gets or sets the water in temperature.
/// </summary>
/// <value>
/// The water in temperature.
/// </value>
public double WaterInTemp { get; set; }
/// <summary>
/// Gets or sets the water out temperature.
/// </summary>
/// <value>
/// The water out temperature.
/// </value>
public double WaterOutTemp { get; set; }
/// <summary>
/// Gets or sets the oil temperature.
/// </summary>
/// <value>
/// The oil temperature.
/// </value>
public double OilTemp { get; set; }
/// <summary>
/// Gets or sets the helium temperature.
/// </summary>
/// <value>
/// The helium temperature.
/// </value>
public double HeliumTemp { get; set; }
/// <summary>
/// Gets or sets the low pressure.
/// </summary>
/// <value>
/// The low pressure.
/// </value>
public double LowPressure { get; set; }
/// <summary>
/// Gets or sets the low pressure average.
/// </summary>
/// <value>
/// The low pressure average.
/// </value>
public double LowPressureAverage { get; set; }
/// <summary>
/// Gets or sets the high pressure.
/// </summary>
/// <value>
/// The high pressure.
/// </value>
public double HighPressure { get; set; }
/// <summary>
/// Gets or sets the high pressure average.
/// </summary>
/// <value>
/// The high pressure average.
/// </value>
public double HighPressureAverage { get; set; }
/// <summary>
/// Gets or sets the delta pressure average.
/// </summary>
/// <value>
/// The delta pressure average.
/// </value>
public double DeltaPressureAverage { get; set; }
/// <summary>
/// Gets or sets the hours of operation.
/// </summary>
/// <value>
/// The hours of operation.
/// </value>
public double HoursOfOperation { get; set; }
/// <summary>
/// Gets or sets the pressure scale.
/// </summary>
/// <value>
/// The pressure scale.
/// </value>
public double PressureScale { get; set; } = -1;
/// <summary>
/// Gets or sets the temperature scale.
/// </summary>
/// <value>
/// The temperature scale.
/// </value>
public double TempScale { get; set; } = -1;
/// <summary>
/// Gets or sets the connection state.
/// </summary>
/// <value>
/// The connection state.
/// </value>
public double ConnectionState { get; set; }
#endregion Properties
}
}<file_sep>/CryostatControlServerTests/CryostatControlTests.cs
namespace CryostatControlServerTests
{
using System;
using System.Collections.Generic;
using System.Threading;
using CryostatControlServer;
using CryostatControlServer.Compressor;
using CryostatControlServer.He7Cooler;
using CryostatControlServer.HostService;
using CryostatControlServer.HostService.Enumerators;
using CryostatControlServer.LakeShore;
using CryostatControlServer.Streams;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
[TestClass]
public class CryostatControlTests
{
private Dictionary<Channels, double> outvalues = new Dictionary<Channels, double>();
private Dictionary<Channels, double> values = new Dictionary<Channels, double>();
[TestMethod]
public void TestReadingSettings()
{
CommandService cs = new CommandService(new Mock<CryostatControl>().Object, null);
var result = cs.ReadSettings();
Assert.AreEqual(Enum.GetNames(typeof(SettingEnumerator)).Length, result.Length);
}
[TestMethod]
public void TestWritingSettings()
{
CommandService cs = new CommandService(new Mock<CryostatControl>().Object, null);
cs.WriteSettingValue((int)SettingEnumerator.ControllerHeatupTemperature, 20);
var readvals = cs.ReadSettings();
Assert.AreEqual(readvals[(int)SettingEnumerator.ControllerHeatupTemperature], 20);
cs.WriteSettingValue((int)SettingEnumerator.ControllerHeatupTemperature, 50);
readvals = cs.ReadSettings();
Assert.AreEqual(readvals[(int)SettingEnumerator.ControllerHeatupTemperature], 50);
}
[TestMethod]
public void TestControllerControl()
{
var cooler = this.getCoolerMock();
var lakeshore = new LakeShore();
var mockLS = new Mock<IManagedStream>();
mockLS.Setup(stream => stream.Open());
mockLS.Setup(stream => stream.WriteString(It.IsAny<string>()));
mockLS.Setup(stream => stream.ReadString()).Returns(() => "5.0");
mockLS.Setup(stream => stream.IsConnected()).Returns(true);
lakeshore.Init(mockLS.Object);
var compressor = new Mock<Compressor>();
Controller controller = new Controller(cooler, lakeshore, compressor.Object);
CryostatControl cryostatControl = new CryostatControl(compressor.Object, lakeshore, cooler, controller);
Assert.AreEqual(Controlstate.Setup, cryostatControl.ControllerState);
Thread.Sleep(5000);
Assert.AreEqual(Controlstate.Standby, cryostatControl.ControllerState);
Assert.AreEqual(true,cryostatControl.StartCooldown());
Assert.AreEqual(Controlstate.CooldownStart, cryostatControl.ControllerState);
Assert.AreEqual(false,cryostatControl.StartHeatup());
Assert.AreEqual(Controlstate.CooldownStart, cryostatControl.ControllerState);
cryostatControl.CancelCommand();
Assert.AreEqual(Controlstate.Cancel, cryostatControl.ControllerState);
Thread.Sleep(8000);
Assert.AreEqual(Controlstate.Standby, cryostatControl.ControllerState);
Assert.AreEqual(true, cryostatControl.StartHeatup());
Assert.AreEqual(Controlstate.WarmupStart, cryostatControl.ControllerState);
Assert.AreEqual(false, cryostatControl.StartCooldown());
Assert.AreEqual(Controlstate.WarmupStart, cryostatControl.ControllerState);
cryostatControl.CancelCommand();
Assert.AreEqual(Controlstate.Cancel, cryostatControl.ControllerState);
Thread.Sleep(8000);
Assert.AreEqual(Controlstate.Standby, cryostatControl.ControllerState);
Assert.AreEqual(true, cryostatControl.StartRecycle());
Assert.AreEqual(Controlstate.RecycleStart, cryostatControl.ControllerState);
Assert.AreEqual(false, cryostatControl.StartCooldown());
Assert.AreEqual(Controlstate.RecycleStart, cryostatControl.ControllerState);
cryostatControl.CancelCommand();
Assert.AreEqual(Controlstate.Cancel, cryostatControl.ControllerState);
Thread.Sleep(8000);
Assert.AreEqual(Controlstate.Standby, cryostatControl.ControllerState);
Assert.AreEqual(true, cryostatControl.StartManualControl());
Assert.AreEqual(Controlstate.Manual, cryostatControl.ControllerState);
Assert.AreEqual(false, cryostatControl.StartCooldown());
Assert.AreEqual(Controlstate.Manual, cryostatControl.ControllerState);
cryostatControl.CancelCommand();
Assert.AreEqual(Controlstate.Cancel, cryostatControl.ControllerState);
}
private CryostatControlServer.He7Cooler.He7Cooler getCoolerMock()
{
var AgilentMock = new Mock<Agilent34972A>();
AgilentMock.Setup<double[]>((obj) => obj.GetVoltages(It.IsAny<Channels[]>())).Returns<Channels[]>(
(channels) =>
{
var res = new double[channels.Length];
for (int i = 0; i < channels.Length; i++)
{
if (!this.values.TryGetValue(channels[i], out res[i]))
{
res[i] = 0.0;
}
}
return res;
});
AgilentMock.Setup(obj => obj.SetHeaterVoltage(It.IsAny<Channels>(), It.IsAny<double>()))
.Callback<Channels, double>(
(channel, value) =>
{
if (this.outvalues.ContainsKey(channel))
{
this.outvalues[channel] = value;
}
else
{
this.outvalues.Add(channel, value);
}
});
AgilentMock.Setup(obj => obj.IsConnected()).Returns(true);
var cooler = new CryostatControlServer.He7Cooler.He7Cooler();
cooler.Connect(AgilentMock.Object, false);
return cooler;
}
}
}<file_sep>/CryostatControlClient/ColorState.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ColorState.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// The color state.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1602:EnumerationItemsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.")]
public enum ColorState
{
Red = 0,
Green = 1
}
}<file_sep>/CryostatControlServer/Data/SensorArray.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SensorArray.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Data
{
using CryostatControlServer.Compressor;
using CryostatControlServer.He7Cooler;
using CryostatControlServer.LakeShore;
/// <summary>
/// class which consists of an array of all sensors.
/// </summary>
public class SensorArray
{
#region Fields
/// <summary>
/// The compressor
/// </summary>
private readonly Compressor compressor;
/// <summary>
/// The he7 cooler
/// </summary>
private readonly He7Cooler he7Cooler;
/// <summary>
/// The lake shore
/// </summary>
private readonly LakeShore lakeShore;
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SensorArray"/> class.
/// </summary>
/// <param name="compressor">The compressor.</param>
/// <param name="he7Cooler">The he7 cooler.</param>
/// <param name="lakeShore">The lake shore.</param>
public SensorArray(
Compressor compressor,
He7Cooler he7Cooler,
LakeShore lakeShore)
{
this.compressor = compressor;
this.he7Cooler = he7Cooler;
this.lakeShore = lakeShore;
}
#endregion Constructors
#region Methods
/// <summary>
/// Fills the sensors initially with empty sensors than fills it for each component.
/// <seealso cref="DataEnumerator" /> for the position of each sensor
/// </summary>
/// <returns>
/// Array filled with new sensors
/// </returns>
public ISensor[] GetSensorArray()
{
ISensor[] sensors = new ISensor[(int)DataEnumerator.DataLength];
for (int i = 0; i < sensors.Length; i++)
{
sensors[i] = new EmptySensor();
}
this.FillLakeShoreSensors(sensors);
this.FillCompressorSensors(sensors);
this.FillHe7Sensors(sensors);
return sensors;
}
/// <summary>
/// Fills the lake shore sensors.
/// </summary>
/// <param name="sensors">The sensors array to be filled.</param>
private void FillLakeShoreSensors(ISensor[] sensors)
{
sensors[(int)DataEnumerator.LakePlate50K] =
new CryostatControlServer.LakeShore.Sensor(SensorEnum.Plate50K, this.lakeShore);
sensors[(int)DataEnumerator.LakePlate3K] =
new CryostatControlServer.LakeShore.Sensor(SensorEnum.Plate3K, this.lakeShore);
}
/// <summary>
/// Fills the compressor sensors.
/// </summary>
/// <param name="sensors">The sensors array to be filled.</param>
private void FillCompressorSensors(ISensor[] sensors)
{
sensors[(int)DataEnumerator.ComWaterIn] =
new CryostatControlServer.Compressor.Sensor(AnalogRegistersEnum.CoolantInTemp, this.compressor);
sensors[(int)DataEnumerator.ComWaterOut] =
new CryostatControlServer.Compressor.Sensor(AnalogRegistersEnum.CoolantOutTemp, this.compressor);
sensors[(int)DataEnumerator.ComHelium] =
new CryostatControlServer.Compressor.Sensor(AnalogRegistersEnum.HeliumTemp, this.compressor);
sensors[(int)DataEnumerator.ComOil] =
new CryostatControlServer.Compressor.Sensor(AnalogRegistersEnum.OilTemp, this.compressor);
sensors[(int)DataEnumerator.ComLow] =
new CryostatControlServer.Compressor.Sensor(AnalogRegistersEnum.LowPressure, this.compressor);
sensors[(int)DataEnumerator.ComLowAvg] =
new CryostatControlServer.Compressor.Sensor(AnalogRegistersEnum.LowPressureAvg, this.compressor);
sensors[(int)DataEnumerator.ComHigh] =
new CryostatControlServer.Compressor.Sensor(AnalogRegistersEnum.HighPressure, this.compressor);
sensors[(int)DataEnumerator.ComHighAvg] =
new CryostatControlServer.Compressor.Sensor(AnalogRegistersEnum.HighPressureAvg, this.compressor);
sensors[(int)DataEnumerator.ComDeltaAvg] =
new CryostatControlServer.Compressor.Sensor(AnalogRegistersEnum.DeltaPressureAvg, this.compressor);
}
/// <summary>
/// Fills the he7 sensors.
/// </summary>
/// <param name="sensors">The sensors array to be filled.</param>
private void FillHe7Sensors(ISensor[] sensors)
{
Calibration he3Calibration = Calibration.He3Calibration;
Calibration he4Calibration = Calibration.He4Calibration;
Calibration diodeCalibration = Calibration.DiodeCalibration;
Calibration emptyCalibration = Calibration.EmptyCalibration;
sensors[(int)DataEnumerator.He3Pump] =
new He7Cooler.Sensor(Channels.SensHe3PumpT, this.he7Cooler, diodeCalibration);
sensors[(int)DataEnumerator.HePlate2K] =
new He7Cooler.Sensor(Channels.Sens2KplateT, this.he7Cooler, diodeCalibration);
sensors[(int)DataEnumerator.HePlate4K] =
new He7Cooler.Sensor(Channels.Sens4KplateT, this.he7Cooler, diodeCalibration);
sensors[(int)DataEnumerator.He3Head] =
new He7Cooler.Sensor(Channels.SensHe3HeadT, this.he7Cooler, he3Calibration);
sensors[(int)DataEnumerator.He4Pump] =
new He7Cooler.Sensor(Channels.SensHe4PumpT, this.he7Cooler, diodeCalibration);
sensors[(int)DataEnumerator.He4SwitchTemp] = new He7Cooler.Sensor(
Channels.SensHe4SwitchT,
this.he7Cooler,
diodeCalibration);
sensors[(int)DataEnumerator.He3SwitchTemp] = new He7Cooler.Sensor(
Channels.SensHe3SwitchT,
this.he7Cooler,
diodeCalibration);
sensors[(int)DataEnumerator.He4Head] =
new He7Cooler.Sensor(Channels.SensHe4HeadT, this.he7Cooler, he4Calibration);
sensors[(int)DataEnumerator.He3VoltActual] =
new He7Cooler.Sensor(Channels.SensHe3Pump, this.he7Cooler, emptyCalibration);
sensors[(int)DataEnumerator.He4SwitchVoltActual] = new He7Cooler.Sensor(
Channels.SensHe4Switch,
this.he7Cooler,
emptyCalibration);
sensors[(int)DataEnumerator.He3SwitchVoltActual] = new He7Cooler.Sensor(
Channels.SensHe3Switch,
this.he7Cooler,
emptyCalibration);
sensors[(int)DataEnumerator.He4VoltActual] =
new He7Cooler.Sensor(Channels.SensHe4Pump, this.he7Cooler, emptyCalibration);
}
#endregion Methods
}
}<file_sep>/CryostatControlServer/HostService/DataContracts/CouldNotPerformActionFault.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CouldNotPerformActionFault.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.HostService.DataContracts
{
using System;
using System.Runtime.Serialization;
using CryostatControlServer.Logging;
/// <summary>
/// The could not perform action fault.
/// </summary>
[DataContract]
[Serializable]
public class CouldNotPerformActionFault
{
/// <summary>
/// Initializes a new instance of the <see cref="CouldNotPerformActionFault"/> class.
/// </summary>
/// <param name="reason">
/// The reason.
/// </param>
/// <param name="message">
/// The message.
/// </param>
public CouldNotPerformActionFault(ActionFaultReason reason, string message)
{
this.Message = message;
this.Operation = "not set";
this.Reason = reason;
DebugLogger.Error(this.GetType().Name, reason + " => " + message);
}
/// <summary>
/// Initializes a new instance of the <see cref="CouldNotPerformActionFault"/> class.
/// </summary>
/// <param name="reason">
/// The reason.
/// </param>
/// <param name="message">
/// The message.
/// </param>
/// <param name="operation">
/// The operation.
/// </param>
public CouldNotPerformActionFault(ActionFaultReason reason, string message, string operation)
{
this.Message = message;
this.Operation = operation;
this.Reason = reason;
DebugLogger.Error(this.GetType().Name, reason + " => " + message);
}
/// <summary>
/// Gets or sets the reason.
/// </summary>
/// <value>
/// The reason.
/// </value>
[DataMember]
public ActionFaultReason Reason { get; set; }
/// <summary>
/// Gets or sets the operation.
/// </summary>
/// <value>
/// The operation.
/// </value>
[DataMember]
public string Operation { get; set; }
/// <summary>
/// Gets or sets the message.
/// </summary>
/// <value>
/// The message.
/// </value>
[DataMember]
public string Message { get; set; }
}
}<file_sep>/CryostatControlServer/He7Cooler/DigitalSwitch.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DigitalSwitch.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.He7Cooler
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// The digital switches.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1602:EnumerationItemsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.")]
public enum DigitalSwitch
{
SensHe3HeadT = 0,
SensHe4HeadT = 1,
PumpHe3 = 2,
PumpHe4 = 3,
}
}
<file_sep>/CryostatControlServer/CryostatControl.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CryostatControl.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer
{
using System;
using CryostatControlServer.Compressor;
using CryostatControlServer.Data;
using CryostatControlServer.HostService.Enumerators;
using CryostatControlServer.Logging;
/// <summary>
/// Class which handles all the request by the client.
/// </summary>
public class CryostatControl
{
#region Fields
/// <summary>
/// The data read out
/// </summary>
private readonly DataReader dataReader;
/// <summary>
/// The compressor
/// </summary>
private readonly Compressor.Compressor compressor;
/// <summary>
/// The lake shore
/// </summary>
private readonly LakeShore.LakeShore lakeShore;
/// <summary>
/// The he7 cooler
/// </summary>
private readonly He7Cooler.He7Cooler he7Cooler;
/// <summary>
/// The controller.
/// </summary>
private readonly Controller controller;
/// <summary>
/// The heaters
/// </summary>
private readonly He7Cooler.He7Cooler.Heater[] heaters = new He7Cooler.He7Cooler.Heater[(int)HeaterEnumerator.HeaterAmount];
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CryostatControl"/> class.
/// </summary>
/// <param name="compressor">
/// The compressor.
/// </param>
/// <param name="lakeShore">
/// The lake shore.
/// </param>
/// <param name="he7Cooler">
/// The he7 cooler.
/// </param>
/// <param name="controller">
/// The controller.
/// </param>
public CryostatControl(
Compressor.Compressor compressor,
LakeShore.LakeShore lakeShore,
He7Cooler.He7Cooler he7Cooler,
Controller controller)
{
this.compressor = compressor;
this.lakeShore = lakeShore;
this.he7Cooler = he7Cooler;
this.controller = controller;
this.dataReader = new DataReader(this.compressor, this.he7Cooler, this.lakeShore);
this.FillHeaters();
}
#endregion Constructors
#region Properties
/// <summary>
/// Initializes a new instance of the <see cref="CryostatControl"/> class.
/// </summary>
public CryostatControl()
{
}
/// <summary>
/// Gets the start time of scheduled process.
/// </summary>
/// <value>
/// The start time scheduled process.
/// </value>
public DateTime StartTime
{
get
{
return this.controller.StartTime;
}
}
/// <summary>
/// Gets the state of the controller.
/// </summary>
/// <returns>The controller state <see cref="Controlstate"/></returns>
public Controlstate ControllerState
{
get
{
return this.controller.State;
}
}
/// <summary>
/// Gets a value indicating whether Manual control is allowed or not
/// </summary>
private bool ManualControl
{
get
{
return this.ControllerState == Controlstate.Manual;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Cancels the current command safely.
/// </summary>
public void CancelCommand()
{
this.controller.CancelCommand();
}
/// <summary>
/// Starts the cool down.
/// </summary>
/// <returns>true if cool down is started, false otherwise</returns>
public bool StartCooldown()
{
return this.controller.StartCooldown(DateTime.Now);
}
/// <summary>
/// Stop command for the controller. Which stops the current process of the controller and turns everything off.
/// </summary>
public void StopCommand()
{
this.controller.StopCommand();
}
/// <summary>
/// Starts the cool down.
/// </summary>
/// <param name="time">
/// The time.
/// </param>
/// <returns>
/// true if cool down is started, false otherwise
/// </returns>
public bool StartCooldown(DateTime time)
{
return this.controller.StartCooldown(time);
}
/// <summary>
/// Starts the heat up.
/// </summary>
/// <returns>true if heat up is started, false otherwise</returns>
public bool StartHeatup()
{
return this.controller.StartHeatup(DateTime.Now);
}
/// <summary>
/// Starts the heat up.
/// </summary>
/// <param name="time">The time.</param>
/// <returns>
/// true if heat up is started, false otherwise
/// </returns>
public bool StartHeatup(DateTime time)
{
return this.controller.StartHeatup(time);
}
/// <summary>
/// Switch to manual control. Can only be started from Standby.
/// </summary>
/// <returns>
/// true if switched to manual control, false otherwise <see cref="bool"/>.
/// </returns>
public bool StartManualControl()
{
return this.controller.StartManualControl();
}
/// <summary>
/// Starts a recycle.
/// </summary>
/// <returns>true if recycle is started, false otherwise</returns>
public bool StartRecycle()
{
return this.controller.StartRecycle(DateTime.Now);
}
/// <summary>
/// Starts a recycle.
/// </summary>
/// <param name="time">The time.</param>
/// <returns>
/// true if recycle is started, false otherwise
/// </returns>
public bool StartRecycle(DateTime time)
{
return this.controller.StartRecycle(time);
}
/// <summary>
/// Reads the data.
/// </summary>
/// <returns>data array with sensor values</returns>
public double[] ReadData()
{
return this.dataReader.GetDataArray();
}
/// <summary>
/// Turns the compressor on or off.
/// </summary>
/// <param name="status">if set to <c>true</c> [on].</param>
/// <returns>
/// <c>true</c> if the status is set.
/// <c>false</c> status could not been set, either is has no connection or manual control isn't allowed.
/// </returns>
public bool SetCompressorState(bool status)
{
if (!this.ManualControl)
{
return false;
}
try
{
if (status)
{
this.compressor.TurnOn();
}
else
{
this.compressor.TurnOff();
}
}
catch (Exception e)
{
DebugLogger.Error(this.GetType().Name, "Something went wrong setting compressor state");
#if DEBUG
Console.WriteLine("Exception thrown: {0}", e);
#endif
return false;
}
return true;
}
/// <summary>
/// Writes values to the helium7 heaters.
/// <seealso cref="HeaterEnumerator" />
/// for position for each heater.
/// </summary>
/// <param name="heater">The heater.</param>
/// <param name="value">The value.</param>
/// <returns>True if succeeded false otherwise</returns>
public bool WriteHelium7Heater(HeaterEnumerator heater, double value)
{
if (this.ManualControl)
{
this.heaters[(int)heater].Voltage = value;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Reads the compressor temperature scale.
/// </summary>
/// <returns>Temperature scale in double <seealso cref="TemperatureEnum"/></returns>
public double ReadCompressorTemperatureScale()
{
return (double)this.compressor.ReadTemperatureScale();
}
/// <summary>
/// Reads the compressor pressure scale.
/// </summary>
/// <returns>Pressure scale in double <seealso cref="PressureEnum"/></returns>
public double ReadCompressorPressureScale()
{
return (double)this.compressor.ReadPressureScale();
}
/// <summary>
/// Reads the single sensor.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>Data of the sensor or NaN if sensor could not be read, or out of sensor range</returns>
public double ReadSingleSensor(int id)
{
return this.dataReader.ReadSingleSensor(id);
}
/// <summary>
/// Fills the heaters.
/// <seealso cref="HeaterEnumerator"/> for the position of each heater
/// </summary>
private void FillHeaters()
{
this.heaters[(int)HeaterEnumerator.He3Pump] = this.he7Cooler.He3Pump;
this.heaters[(int)HeaterEnumerator.He4Pump] = this.he7Cooler.He4Pump;
this.heaters[(int)HeaterEnumerator.He3Switch] = this.he7Cooler.He3Switch;
this.heaters[(int)HeaterEnumerator.He4Switch] = this.he7Cooler.He4Switch;
}
#endregion Methods
}
}<file_sep>/CryostatControlClient/Views/MainGraphFrame.xaml.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainGraphFrame.xaml.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Views
{
using System.Windows;
/// <summary>
/// Interaction logic for MainGraphFrame.xaml
/// </summary>
public partial class MainGraphFrame : Window
{
}
}
<file_sep>/README.md
# Cryostat Control
This project consists of software to control a cryostat. The software is written in C# and is divided in two components, a server and a client.
The server contains all the logic of the system. The client is the GUI that controls and reads out the server.
Both server and client run on Windows.
CryostatControlClient
---
This project represents the GUI client as can be seen below. It is build as MVVM in WPF. It connects to the server automatically with WCF.

CryostatControlServer
---
This project represents the server that comunicates with the cryostat devices and sends this data to connected clients.
The server is also accessible with Phyton scripts.
Running the program
----
Running the program is as easy as just starting up the server and a client. The server should run on the PC which is connected to the cryostat components in order to retrieve data or execute actions from the client.
<file_sep>/CryostatControlServerTests/Logging/SpecificDataLoggingTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CryostatControlServerTests.Logging
{
using System.IO;
using System.Linq;
using CryostatControlServer.Data;
using CryostatControlServer.Logging;
[TestClass]
public class SpecificDataLoggingTest
{
[TestMethod]
public void WriteSpecificDataToBeLoggedIsTrueTest()
{
int interval = 5;
bool[] toBeLogged = new bool[(int)DataEnumerator.DataLength];
toBeLogged[(int)DataEnumerator.ComHelium] = true;
toBeLogged[(int)DataEnumerator.He3SwitchTemp] = true;
SpecificDataLogger specificDataLogging = new SpecificDataLogger(toBeLogged, interval);
string filePath = "SpecificDataLoggerTest.csv";
double[] logData = new double[(int)DataEnumerator.DataLength];
logData[(int)DataEnumerator.ComHelium] = 20;
logData[(int)DataEnumerator.He3SwitchTemp] = 40;
string time = DateTime.Now.ToString("HH:mm:ss");
if (File.Exists(filePath))
{
File.Delete(filePath);
}
File.Create(filePath).Close();
specificDataLogging.WriteSpecificData(filePath, logData, time);
string line = File.ReadLines(filePath).First();
string[] elements = line.Split(';');
Assert.AreEqual("20", elements[(int)DataEnumerator.ComHelium > (int)DataEnumerator.He3SwitchTemp ? 2 :1]);
Assert.AreEqual("40", elements[(int)DataEnumerator.ComHelium < (int)DataEnumerator.He3SwitchTemp ? 2 : 1]);
}
[TestMethod]
public void WriteSpecificDataToBeLoggedIsFalseTest()
{
int interval = 5;
bool[] toBeLogged = new bool[(int)DataEnumerator.DataLength];
toBeLogged[(int)DataEnumerator.ComHelium] = false;
toBeLogged[(int)DataEnumerator.He3SwitchTemp] = false;
toBeLogged[(int)DataEnumerator.LakePlate50K] = false;
SpecificDataLogger specificDataLogging = new SpecificDataLogger(toBeLogged, interval);
string filePath = "SpecificDataLoggerTest.csv";
double[] logData = new double[(int)DataEnumerator.DataLength];
logData[(int)DataEnumerator.ComHelium] = 20;
logData[(int)DataEnumerator.He3SwitchTemp] = 40;
logData[(int)DataEnumerator.LakePlate50K] = 1;
string time = DateTime.Now.ToString("HH:mm:ss");
if (File.Exists(filePath))
{
File.Delete(filePath);
}
File.Create(filePath).Close();
specificDataLogging.WriteSpecificData(filePath, logData, time);
string line = File.ReadLines(filePath).First();
string[] elements = line.Split(';');
Assert.AreEqual(1, elements.Length);
Assert.AreEqual(time, elements[0]);
}
}
}
<file_sep>/CryostatControlClient/Models/BlueforsModel.cs
//-----------------------------------------------------------------------
// <copyright file="BlueforsModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlClient.Models
{
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Geared;
using LiveCharts.Wpf;
/// <summary>
/// The Bluefors model
/// </summary>
public class BlueforsModel : AbstractModel
{
#region Fields
/// <summary>
/// The cold plate 3 K temperature
/// </summary>
private double coldPlate3KTemp;
/// <summary>
/// The cold plate 50 K temperature
/// </summary>
private double coldPlate50KTemp;
/// <summary>
/// The cold plate 3 k temporary list
/// </summary>
private double[] coldPlate3KTemporaryList;
/// <summary>
/// The cold plate 50 k temporary list
/// </summary>
private double[] coldPlate50KTemporaryList;
/// <summary>
/// The cold plate 3 k temporary list
/// </summary>
private double[] coldPlate3KTemporaryListBottom;
/// <summary>
/// The cold plate 50 k temporary list
/// </summary>
private double[] coldPlate50KTemporaryListBottom;
#endregion Fields
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="BlueforsModel"/> class.
/// </summary>
public BlueforsModel()
{
this.coldPlate3KTemporaryList = new double[this.TemporaryListSize];
this.coldPlate50KTemporaryList = new double[this.TemporaryListSize];
this.coldPlate3KTemporaryListBottom = new double[this.TemporaryListSize];
this.coldPlate50KTemporaryListBottom = new double[this.TemporaryListSize];
this.ColdPlate3KLineSeries = new GLineSeries { Title = "Bluefors - 3K Plate", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
this.ColdPlate50KLineSeries = new GLineSeries { Title = "Bluefors - 50K Plate", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
this.ColdPlate3KLineSeriesBottom = new GLineSeries { Title = "Bluefors - 3K Plate", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
this.ColdPlate50KLineSeriesBottom = new GLineSeries { Title = "Bluefors - 50K Plate", Values = new GearedValues<DateTimePoint>(), Fill = Brushes.Transparent };
}
#endregion Constructor
#region Properties
/// <summary>
/// Gets or sets the cold plate 3 k visibility.
/// </summary>
/// <value>
/// The cold plate 3 k visibility.
/// </value>
public Visibility ColdPlate3KVisibility
{
get
{
return this.ColdPlate3KLineSeries.Visibility;
}
set
{
this.ColdPlate3KLineSeries.Visibility = value;
}
}
/// <summary>
/// Gets or sets the cold plate 50 k visibility.
/// </summary>
/// <value>
/// The cold plate 50 k visibility.
/// </value>
public Visibility ColdPlate50KVisibility
{
get
{
return this.ColdPlate50KLineSeries.Visibility;
}
set
{
this.ColdPlate50KLineSeries.Visibility = value;
}
}
/// <summary>
/// Gets the cold plate 3 k line series.
/// </summary>
/// <value>
/// The cold plate 3 k line series.
/// </value>
public GLineSeries ColdPlate3KLineSeriesBottom { get; }
/// <summary>
/// Gets the cold plate 50 k line series.
/// </summary>
/// <value>
/// The cold plate 50 k line series.
/// </value>
public GLineSeries ColdPlate50KLineSeriesBottom { get; }
/// <summary>
/// Gets the cold plate 3 k line series.
/// </summary>
/// <value>
/// The cold plate 3 k line series.
/// </value>
public GLineSeries ColdPlate3KLineSeries { get; }
/// <summary>
/// Gets the cold plate 50 k line series.
/// </summary>
/// <value>
/// The cold plate 50 k line series.
/// </value>
public GLineSeries ColdPlate50KLineSeries { get; }
/// <summary>
/// Gets or sets the cold plate 3 K temperature.
/// </summary>
/// <value>
/// The cold plate 3K temperature.
/// </value>
public double ColdPlate3KTemp
{
get
{
return this.coldPlate3KTemp;
}
set
{
this.coldPlate3KTemp = value;
this.coldPlate3KTemporaryList = this.AddToGraph(this.coldPlate3KTemporaryList, this.ColdPlate3KLineSeries, value);
this.coldPlate3KTemporaryListBottom = this.AddToGraph(this.coldPlate3KTemporaryListBottom, this.ColdPlate3KLineSeriesBottom, Math.Log(value, 10));
}
}
/// <summary>
/// Gets or sets the cold plate 50 K temperature.
/// </summary>
/// <value>
/// The cold plate 50 K temperature.
/// </value>
public double ColdPlate50KTemp
{
get
{
return this.coldPlate50KTemp;
}
set
{
this.coldPlate50KTemp = value;
this.coldPlate50KTemporaryList = this.AddToGraph(this.coldPlate50KTemporaryList, this.ColdPlate50KLineSeries, value);
this.coldPlate50KTemporaryListBottom = this.AddToGraph(this.coldPlate50KTemporaryListBottom, this.ColdPlate50KLineSeriesBottom, Math.Log(value, 10));
}
}
/// <summary>
/// Gets or sets the connection state.
/// </summary>
public double ConnectionState { get; set; }
#endregion Properties
}
}
<file_sep>/CryostatControlServer/Data/EmptySensor.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EmptySensor.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Data
{
/// <summary>
/// Empty sensor class, as placeholder when a sensor cannot be initialized.
/// </summary>
/// <seealso cref="ISensor" />
public class EmptySensor : ISensor
{
#region Properties
/// <summary>
/// Gets or sets the interval data is read at.
/// This should not change anything
/// </summary>
public int Interval
{
get
{
return int.MinValue;
}
set
{
////do nothing
}
}
/// <summary>
/// Gets the value, min value is returned as error value.
/// </summary>
public double Value { get; } = double.NaN;
#endregion Properties
}
}<file_sep>/CryostatControlServer/HostService/IDataGetCallback.cs
//-----------------------------------------------------------------------
// <copyright file="IDataGetCallback.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.HostService
{
using System;
using System.ServiceModel;
/// <summary>
/// Methods which can be used for callbacks.
/// </summary>
public interface IDataGetCallback
{
#region Methods
/// <summary>
/// Sends the data readout.
/// </summary>
/// <param name="data">The data.</param>
[OperationContract(IsOneWay = true)]
void SendData(double[] data);
/// <summary>
/// Sends the data readout.
/// </summary>
/// <param name="modus">The modus.</param>
[OperationContract(IsOneWay = true)]
void SendModus(int modus);
/// <summary>
/// Sets the state of the logging.
/// </summary>
/// <param name="status">if set to <c>true</c> logging is active.</param>
[OperationContract(IsOneWay = true)]
void SetLoggingState(bool status);
/// <summary>
/// The send log notification.
/// </summary>
/// <param name="notification">
/// The notification.
/// </param>
[OperationContract(IsOneWay = true)]
void UpdateNotification(string[] notification);
/// <summary>
/// Updates the countdown.
/// </summary>
/// <param name="time">The time.</param>
[OperationContract(IsOneWay = true)]
void UpdateCountdown(DateTime time);
#endregion Methods
}
}<file_sep>/CryostatControlClient/Notification.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Notification.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient
{
using System;
using System.Globalization;
using System.Windows.Media;
/// <summary>
/// The notification.
/// </summary>
public class Notification
{
/// <summary>
/// The unknown type.
/// </summary>
private const string UnknownType = "Unknown";
/// <summary>
/// The time.
/// </summary>
private string time;
/// <summary>
/// The level indicating Info, Warning or Error.
/// </summary>
private string level;
/// <summary>
/// Initializes a new instance of the <see cref="Notification"/> class.
/// </summary>
/// <param name="time">
/// The time.
/// </param>
/// <param name="level">
/// The level.
/// </param>
/// <param name="data">
/// The data.
/// </param>
public Notification(string time, string level, string data)
{
this.Time = time;
this.Level = level;
this.Data = data;
}
/// <summary>
/// Gets or sets the time.
/// </summary>
/// <value>
/// The time.
/// </value>
public string Time
{
get
{
return this.time;
}
set
{
if (this.IsATime(value))
{
this.time = value;
}
else
{
this.time = UnknownType;
}
}
}
/// <summary>
/// Gets or sets the level.
/// </summary>
/// <value>
/// The level.
/// </value>
public string Level
{
get
{
return this.level;
}
set
{
if (this.IsALevel(value))
{
this.level = value;
}
else
{
this.level = UnknownType;
}
}
}
/// <summary>
/// Gets or sets the data.
/// </summary>
/// <value>
/// The data.
/// </value>
public string Data { get; set; }
/// <summary>
/// Gets the color.
/// </summary>
/// <value>
/// The color.
/// </value>
public SolidColorBrush Color
{
get
{
switch (this.level)
{
case "Error": return new SolidColorBrush(Colors.Red);
case "Warning": return new SolidColorBrush(Colors.Orange);
default: return new SolidColorBrush(Colors.Black);
}
}
}
/// <summary>
/// Determines whether [time] is [the specified time].
/// </summary>
/// <param name="time">The time.</param>
/// <returns>
/// <c>true</c> if [time] is [the specified time]; otherwise, <c>false</c>.
/// </returns>
private bool IsATime(string time)
{
DateTime dateTime;
return DateTime.TryParseExact(time, "HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
}
/// <summary>
/// Determines whether [level] is [the specified level].
/// </summary>
/// <param name="level">The level.</param>
/// <returns>
/// <c>true</c> if [level] is [the specified level]; otherwise, <c>false</c>.
/// </returns>
private bool IsALevel(string level)
{
switch (level)
{
case "Info": return true;
case "Warning": return true;
case "Error": return true;
default: return false;
}
}
}
}
<file_sep>/CryostatControlServer/He7Cooler/Agilent34972A.cs
//-----------------------------------------------------------------------
// <copyright file="Agilent34972A.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.He7Cooler
{
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using CryostatControlServer.Streams;
/// <summary>
/// Agilent34972 class
/// </summary>
public class Agilent34972A
{
#region Fields
/// <summary>
/// The TCP port.
/// </summary>
private const int TcpPort = 5025;
/// <summary>
/// The connection.
/// </summary>
private IManagedStream connection;
/// <summary>
/// The internet protocol address
/// </summary>
private string ipAddress;
#endregion Fields
#region Methods
/// <summary>
/// Gets voltages from the device
/// </summary>
/// <param name="channelIds">Sensor ID's to measure.</param>
/// <returns>array of voltages in the same ordering as channelIds</returns>
public virtual double[] GetVoltages(Channels[] channelIds)
{
try
{
Monitor.Enter(this.connection);
var numSensors = channelIds.Length;
var returnedChannels = new int[numSensors];
var returnedVolts = new double[numSensors];
var readVolt = new double[numSensors];
// construct a command to read all specified voltages
var cmdStr = "ROUT:SCAN (@";
for (var k = 0; k < numSensors - 1; k++)
{
cmdStr += $"{(int)channelIds[k]},";
}
cmdStr += $"{(int)channelIds[numSensors - 1]})\n";
cmdStr += "READ?\n";
this.connection.WriteString(cmdStr);
var res = this.connection.ReadString();
var values = GetDataFromString(res);
if (values.Length != 2 * channelIds.Length)
{
throw new AgilentException("Amount of values returned by the device did not match request.");
}
// split into voltages and channels
for (var k = 0; k < numSensors; k++)
{
returnedVolts[k] = values[2 * k];
returnedChannels[k] = (int)values[(2 * k) + 1];
}
// Order temperature in order of sens_IDs
for (var k = 0; k < numSensors; k++)
{
for (var i = 0; i < numSensors; i++)
{
if ((int)channelIds[i] == returnedChannels[k])
{
readVolt[i] = returnedVolts[k];
}
}
}
// Write ABOR command to return
this.connection.WriteString("ABOR\n");
this.CheckState();
return readVolt;
}
finally
{
Monitor.Exit(this.connection);
}
}
/// <summary>
/// Determines whether this instance is connected.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is connected; otherwise, <c>false</c>.
/// </returns>
public virtual bool IsConnected()
{
return this.connection?.IsConnected() ?? false;
}
/// <summary>
/// Initializes the specified IP address.
/// </summary>
/// <param name="ipAddress">The IP address.</param>
public void Init(string ipAddress)
{
this.ipAddress = ipAddress;
this.connection = new ManagedTcpStream(ipAddress, TcpPort);
this.connection.Open();
this.connection.WriteString("FORM:READ:CHAN ON\n");
this.CheckState();
}
/// <summary>
/// Initializes using a provided managedStream
/// </summary>
/// <param name="managedStream">
/// The managed Stream.
/// </param>
public void Init(IManagedStream managedStream)
{
this.connection = managedStream;
this.connection.Open();
this.connection.WriteString("FORM:READ:CHAN ON\n");
this.CheckState();
}
/// <summary>
/// Disconnect the device.
/// </summary>
public void Disconnect()
{
this.connection.Close();
}
/// <summary>
/// Try to reopen a disconnected connection.
/// Throws all sorts of exceptions
/// </summary>
public void Reopen()
{
if (this.ipAddress != null && !this.connection.IsConnected())
{
var conn = new ManagedTcpStream(this.ipAddress, TcpPort);
this.connection = conn;
}
this.connection.Open();
this.connection.WriteString("FORM:READ:CHAN ON\n");
this.CheckState();
}
/// <summary>
/// Set digital output.
/// </summary>
/// <param name="bit">
/// The bit index.
/// </param>
/// <param name="b_set">
/// The b_set.
/// </param>
public void SetDigitalOutput(int bit, bool b_set)
{
try
{
Monitor.Enter(this.connection);
// Get current digital output values
this.connection.WriteString($"SOUR:DIG:DATA:BYTE? (@{(int)Channels.CtrlDigOut})\n");
var resString = this.connection.ReadString();
var getByte = int.Parse(resString); // TODO: Catch error
var bitVal = 1 << bit;
if (bit < 2)
{
b_set = !b_set;
}
// set or clear the bit in the old values
var setByte = 0;
if (b_set)
{
setByte = getByte | bitVal;
}
else
{
setByte = getByte - (getByte & bitVal);
}
this.connection.WriteString($"SOUR:DIG:DATA:BYTE {setByte}, (@{(int)Channels.CtrlDigOut})\n");
}
finally
{
Monitor.Exit(this.connection);
}
}
/// <summary>
/// Sets the heater voltage.
/// </summary>
/// <param name="heatId">The heater identifier.</param>
/// <param name="setVoltage">The set voltage.</param>
public virtual void SetHeaterVoltage(Channels heatId, double setVoltage)
{
try
{
Monitor.Enter(this.connection);
this.connection.WriteString($"SOUR:VOLT {setVoltage:F3}, (@{(int)heatId})\n");
}
finally
{
Monitor.Exit(this.connection);
}
}
/// <summary>
/// Get returned data from string.
/// </summary>
/// <param name="dataString">
/// The data string.
/// </param>
/// <returns>
/// The <see cref="double[]"/>.
/// </returns>
private static double[] GetDataFromString(string dataString)
{
var split = dataString.Split(',');
var results = new double[split.Length];
for (var i = 0; i < split.Length; i++)
{
results[i] = double.Parse(split[i]);
}
return results;
}
/// <summary>
/// Checks if the device is in a consistent state and all commands are performed. used for synchronisation.
/// </summary>
/// <exception cref="System.Exception">invalid agilent state</exception>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")]
private void CheckState()
{
try
{
Monitor.Enter(this.connection);
this.connection.WriteString("*OPC?\n");
var res = int.Parse(this.connection.ReadString());
if (res < 1)
{
throw new AgilentException("invalid agilent state");
}
}
finally
{
Monitor.Exit(this.connection);
}
}
#endregion Methods
}
}<file_sep>/CryostatControlServer/Compressor/Enumerators/HoldingRegistersEnum.cs
//-----------------------------------------------------------------------
// <copyright file="HoldingRegistersEnum.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.Compressor
{
/// <summary>
/// Enumerator for the holding registers
/// </summary>
public enum HoldingRegistersEnum
{
/// <summary>
/// The control register
/// </summary>
Control = 1
}
}<file_sep>/CryostatControlServer/Data/DataEnumerator.cs
//-----------------------------------------------------------------------
// <copyright file="DataEnumerator.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.Data
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Enumerator for the Compressor values
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1602:EnumerationItemsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.")]
public enum DataEnumerator
{
LakePlate50K,
LakePlate3K,
ComWaterIn,
ComWaterOut,
ComHelium,
ComOil,
ComLow,
ComLowAvg,
ComHigh,
ComHighAvg,
ComDeltaAvg,
He3Pump,
He3Head,
He3SwitchTemp,
He4Pump,
He4Head,
He4SwitchTemp,
HePlate2K,
HePlate4K,
He3VoltActual,
He3SwitchVoltActual,
He4VoltActual,
He4SwitchVoltActual,
SensorAmount,
HeConnectionState = SensorAmount,
ComConnectionState,
LakeConnectionState,
ComError,
ComWarning,
ComHoursOfOperation,
ComOperationState,
DataLength
}
}<file_sep>/CryostatControlClient/ViewModels/BlueforsViewModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BlueforsViewModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels
{
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using CryostatControlClient.Models;
using LiveCharts.Geared;
/// <summary>
/// Bluefors ViewModel
/// </summary>
public class BlueforsViewModel : AbstractViewModel
{
#region Fields
/// <summary>
/// The bluefors model
/// </summary>
private BlueforsModel blueforsModel;
/// <summary>
/// The cold plate 3 k visibility command
/// </summary>
private ICommand coldPlate3KVisibilityCommand;
/// <summary>
/// The cold plate 50 k visibility command
/// </summary>
private ICommand coldPlate50KVisibilityCommand;
#endregion Fields
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="BlueforsViewModel"/> class.
/// </summary>
public BlueforsViewModel()
{
this.blueforsModel = new BlueforsModel();
this.coldPlate3KVisibilityCommand = new RelayCommand(this.OnColdPlate3KVisibility, param => true);
this.coldPlate50KVisibilityCommand = new RelayCommand(this.OnColdPlate50KVisibility, param => true);
}
#endregion Constructor
#region Properties
/// <summary>
/// Gets the color of the connection state.
/// </summary>
/// <value>
/// The color of the connection state.
/// </value>
public SolidColorBrush ConnectionStateColor
{
get
{
return this.DisplayColor((ColorState)this.ConnectionState);
}
}
/// <summary>
/// Gets the cold plate 3 k visibility command.
/// </summary>
/// <value>
/// The cold plate 3 k visibility command.
/// </value>
public ICommand ColdPlate3KVisibilityCommand
{
get
{
return this.coldPlate3KVisibilityCommand;
}
}
/// <summary>
/// Gets the cold plate 50 k visibility command.
/// </summary>
/// <value>
/// The cold plate 50 k visibility command.
/// </value>
public ICommand ColdPlate50KVisibilityCommand
{
get
{
return this.coldPlate50KVisibilityCommand;
}
}
/// <summary>
/// Gets or sets the cold plate 3 k visibility.
/// </summary>
/// <value>
/// The cold plate 3 k visibility.
/// </value>
public Visibility ColdPlate3KVisibility
{
get
{
return this.blueforsModel.ColdPlate3KVisibility;
}
set
{
this.blueforsModel.ColdPlate3KVisibility = value;
}
}
/// <summary>
/// Gets or sets the cold plate 50 k visibility.
/// </summary>
/// <value>
/// The cold plate 50 k visibility.
/// </value>
public Visibility ColdPlate50KVisibility
{
get
{
return this.blueforsModel.ColdPlate50KVisibility;
}
set
{
this.blueforsModel.ColdPlate50KVisibility = value;
}
}
/// <summary>
/// Gets the cold plate 3 k line series.
/// </summary>
/// <value>
/// The cold plate 3 k line series.
/// </value>
public GLineSeries ColdPlate3KLineSeriesBottom
{
get
{
return this.blueforsModel.ColdPlate3KLineSeriesBottom;
}
}
/// <summary>
/// Gets the cold plate 3 k line series.
/// </summary>
/// <value>
/// The cold plate 3 k line series.
/// </value>
public GLineSeries ColdPlate50KLineSeriesBottom
{
get
{
return this.blueforsModel.ColdPlate50KLineSeriesBottom;
}
}
/// <summary>
/// Gets the cold plate 3 k line series.
/// </summary>
/// <value>
/// The cold plate 3 k line series.
/// </value>
public GLineSeries ColdPlate3KLineSeries
{
get
{
return this.blueforsModel.ColdPlate3KLineSeries;
}
}
/// <summary>
/// Gets the cold plate 3 k line series.
/// </summary>
/// <value>
/// The cold plate 3 k line series.
/// </value>
public GLineSeries ColdPlate50KLineSeries
{
get
{
return this.blueforsModel.ColdPlate50KLineSeries;
}
}
/// <summary>
/// Gets or sets the cold plate 3 K temperature.
/// </summary>
/// <value>
/// The cold plate 3 K temperature.
/// </value>
public double ColdPlate3KTemp
{
get
{
return this.blueforsModel.ColdPlate3KTemp;
}
set
{
this.blueforsModel.ColdPlate3KTemp = value;
this.RaisePropertyChanged("ColdPlate3KTemp");
}
}
/// <summary>
/// Gets or sets the cold plate 50 K temperature.
/// </summary>
/// <value>
/// The cold plate 50 K temperature.
/// </value>
public double ColdPlate50KTemp
{
get
{
return this.blueforsModel.ColdPlate50KTemp;
}
set
{
this.blueforsModel.ColdPlate50KTemp = value;
this.RaisePropertyChanged("ColdPlate50KTemp");
}
}
/// <summary>
/// Gets or sets the connection state.
/// </summary>
/// <value>
/// The state of the connection.
/// </value>
public double ConnectionState
{
get
{
return this.blueforsModel.ConnectionState;
}
set
{
this.blueforsModel.ConnectionState = value;
this.RaisePropertyChanged("ConnectionState");
this.RaisePropertyChanged("ConnectionStateConverted");
this.RaisePropertyChanged("ConnectionStateColor");
}
}
/// <summary>
/// Gets the connection state converted.
/// </summary>
/// <value>
/// The connection state converted.
/// </value>
public string ConnectionStateConverted
{
get
{
return this.ConvertConnectionStateNumberToString(this.blueforsModel.ConnectionState);
}
}
#endregion Properties
#region Methods
/// <summary>
/// Called when [cold plate50 k visibility].
/// </summary>
/// <param name="sender">The sender.</param>
private void OnColdPlate50KVisibility(object sender)
{
if (this.ColdPlate50KVisibility == Visibility.Hidden)
{
this.ColdPlate50KVisibility = Visibility.Visible;
}
else
{
this.ColdPlate50KVisibility = Visibility.Hidden;
}
}
/// <summary>
/// Called when [cold plate3 k visibility].
/// </summary>
/// <param name="sender">The sender.</param>
private void OnColdPlate3KVisibility(object sender)
{
if (this.ColdPlate3KVisibility == Visibility.Hidden)
{
this.ColdPlate3KVisibility = Visibility.Visible;
}
else
{
this.ColdPlate3KVisibility = Visibility.Hidden;
}
}
#endregion Methods
}
}
<file_sep>/CryostatControlClientTests/Models/AbstractModelTests.cs
namespace CryostatControlClient.Models.Tests
{
using LiveCharts.Defaults;
using LiveCharts.Geared;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Windows;
using System;
using System.Linq;
[TestClass()]
public class AbstractModelTests
{
private He7Model he7Model;
[TestInitialize]
public void TestInitialize()
{
this.he7Model = new He7Model();
}
[TestMethod()]
public void AddToGraphTestNoDecimal()
{
double value = 5;
for (int i = 0; i < 31; i++)
{
this.he7Model.He3PumpTemp = value;
}
Assert.AreEqual(value, ((DateTimePoint)this.he7Model.He3PumpLineSeries.Values[0]).Value);
Assert.AreEqual(value, ((DateTimePoint)this.he7Model.He3PumpLineSeries.Values[1]).Value);
}
[TestMethod()]
public void AddToGraphTestDecimal()
{
double value = 10.5;
for (int i = 0; i < 31; i++)
{
this.he7Model.He3PumpTemp = value;
}
Assert.AreEqual(value, ((DateTimePoint)this.he7Model.He3PumpLineSeries.Values[0]).Value);
Assert.AreEqual(value, ((DateTimePoint)this.he7Model.He3PumpLineSeries.Values[1]).Value);
}
[TestMethod()]
public void AddToGraphTestNaN()
{
double value = 5;
for (int i = 0; i < 100; i++)
{
this.he7Model.He3PumpTemp = double.NaN;
}
for (int i = 0; i < 31; i++)
{
this.he7Model.He3PumpTemp = value;
}
Assert.AreEqual(value, ((DateTimePoint)this.he7Model.He3PumpLineSeries.Values[0]).Value);
Assert.AreEqual(value, ((DateTimePoint)this.he7Model.He3PumpLineSeries.Values[1]).Value);
}
}
}<file_sep>/CryostatControlServer/Data/ISensor.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ISensor.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Data
{
/// <summary>
/// The Sensor interface.
/// </summary>
public interface ISensor
{
#region Properties
/// <summary>
/// Gets or sets the interval data is read at.
/// </summary>
int Interval { get; set; }
/// <summary>
/// Gets the value.
/// </summary>
double Value { get; }
#endregion Properties
}
}<file_sep>/CryostatControlServer/Logging/DebugLogger.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DebugLogger.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Logging
{
using System;
using System.Globalization;
using System.IO;
using CryostatControlServer.Properties;
/// <summary>
/// The debug logger.
/// </summary>
public static class DebugLogger
{
/// <summary>
/// The txt file format.
/// </summary>
private const string TxtFileFormat = ".txt";
/// <summary>
/// The debug information
/// </summary>
private const string DebugInfo = "SystemLog";
/// <summary>
/// The file path
/// </summary>
private static string filePath;
/// <summary>
/// Gets the general main folder.
/// </summary>
private static string GeneralMainFolder { get; } = Settings.Default.LoggingAddress + @"\General";
/// <summary>
/// Log the error in file and client notifications.
/// </summary>
/// <param name="tag">
/// The tag.
/// </param>
/// <param name="data">
/// The data.
/// </param>
public static void Error(string tag, string data)
{
Error(tag, data, true);
}
/// <summary>
/// Log the error.
/// </summary>
/// <param name="tag">
/// The tag.
/// </param>
/// <param name="data">
/// The data.
/// </param>
/// <param name="sendAsNotification">
/// Send as notification.
/// </param>
public static void Error(string tag, string data, bool sendAsNotification)
{
string error = "ERROR";
string time = DateTime.Now.ToString("HH:mm:ss");
if (sendAsNotification)
{
try
{
NotificationSender.Error(time, data);
}
catch (NullReferenceException)
{
}
}
WriteToFile(time, error, tag, data);
}
/// <summary>
/// Log the warning in file and client notifications.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="data">The data.</param>
public static void Warning(string tag, string data)
{
Warning(tag, data, true);
}
/// <summary>
/// Log the warning.
/// </summary>
/// <param name="tag">
/// The tag.
/// </param>
/// <param name="data">
/// The data.
/// </param>
/// <param name="sendAsNotification">
/// Send as notification.
/// </param>
public static void Warning(string tag, string data, bool sendAsNotification)
{
string warning = "Warning";
string time = DateTime.Now.ToString("HH:mm:ss");
if (sendAsNotification)
{
try
{
NotificationSender.Warning(time, data);
}
catch (NullReferenceException)
{
}
}
WriteToFile(time, warning, tag, data);
}
/// <summary>
/// Log information in file and client notifications
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="data">The data.</param>
public static void Info(string tag, string data)
{
Info(tag, data, true);
}
/// <summary>
/// Log the information.
/// </summary>
/// <param name="tag">
/// The tag.
/// </param>
/// <param name="data">
/// The data.
/// </param>
/// <param name="sendAsNotification">
/// Send as notification.
/// </param>
public static void Info(string tag, string data, bool sendAsNotification)
{
string info = "Info";
string time = DateTime.Now.ToString("HH:mm:ss");
if (sendAsNotification)
{
try
{
NotificationSender.Info(time, data);
}
catch (NullReferenceException)
{
}
}
WriteToFile(time, info, tag, data);
}
/// <summary>
/// Writes to file.
/// </summary>
/// <param name="time">
/// The time.
/// </param>
/// <param name="level">
/// The level.
/// </param>
/// <param name="tag">
/// The tag.
/// </param>
/// <param name="data">
/// The data.
/// </param>
public static void WriteToFile(string time, string level, string tag, string data)
{
string dataLine = time + "," + tag + "," + level + ": " + data;
#if DEBUG
Console.WriteLine(dataLine);
#endif
if (filePath == null)
{
CreateFile();
}
try
{
using (FileStream fileStream =
new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None))
{
using (StreamWriter sw = new StreamWriter(fileStream))
{
sw.WriteLine(dataLine);
}
}
}
catch (IOException)
{
try
{
NotificationSender.Warning(time, "The debug log file is opened by another process. Please close this first.");
}
catch (NullReferenceException)
{
}
Console.WriteLine("The debug log file is opened by another process. Please close this first.");
}
}
/// <summary>
/// Create folder.
/// </summary>
/// <param name="mainFolderPath">
/// The main folder path.
/// </param>
/// <returns>
/// The <see cref="string"/> of the folderpath.
/// </returns>
private static string CreateFolder(string mainFolderPath)
{
DateTime currentDateTime = DateTime.Now;
string year = currentDateTime.Year.ToString();
string month = currentDateTime.ToString("MMMM", new CultureInfo("en-US"));
string newFolderName = year + @"\" + month + @"\";
string pathToNewFolder = Path.Combine(mainFolderPath, newFolderName);
try
{
Directory.CreateDirectory(pathToNewFolder);
}
catch (Exception)
{
Console.WriteLine("Creating log folder failed");
}
return pathToNewFolder;
}
/// <summary>
/// Create debug logger file.
/// </summary>
private static void CreateFile()
{
DateTime currentDateTime = DateTime.Now;
string folderPath = CreateFolder(GeneralMainFolder);
string day = currentDateTime.Day.ToString();
string fileName = day + "_" + DebugInfo + TxtFileFormat;
string actualPathToFile = System.IO.Path.Combine(folderPath, fileName);
Console.WriteLine(actualPathToFile);
try
{
if (!File.Exists(actualPathToFile))
{
File.Create(actualPathToFile).Close();
}
}
catch (Exception)
{
Console.WriteLine("Creating debug log file failed");
}
filePath = actualPathToFile;
}
}
}
<file_sep>/CryostatControlClient/ViewModels/ModusViewModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ModusViewModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels
{
using System;
using System.ServiceModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using CryostatControlClient.Communication;
using CryostatControlClient.Models;
using CryostatControlServer;
/// <summary>
/// The modus viewmodel
/// </summary>
/// <seealso cref="CryostatControlClient.ViewModels.AbstractViewModel" />
public class ModusViewModel : AbstractViewModel
{
#region Fields
/// <summary>
/// The start button command
/// </summary>
private ICommand startButtonCommand;
/// <summary>
/// The cancel button command
/// </summary>
private ICommand cancelButtonCommand;
/// <summary>
/// The manual button command
/// </summary>
private ICommand manualButtonCommand;
/// <summary>
/// The stop button command
/// </summary>
private ICommand stopButtonCommand;
/// <summary>
/// The radio button command
/// </summary>
private ICommand radioButtonCommand;
/// <summary>
/// The modus model
/// </summary>
private ModusModel modusModel;
#endregion Fields
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ModusViewModel"/> class.
/// </summary>
public ModusViewModel()
{
this.modusModel = new ModusModel();
this.StartButtonCommand = new RelayCommand(this.OnClickStart, param => true);
this.RadioButtonCommand = new RelayCommand(this.OnChangeRadio, param => true);
this.cancelButtonCommand = new RelayCommand(this.OnClickCancel, param => true);
this.manualButtonCommand = new RelayCommand(this.OnClickManual, param => true);
this.stopButtonCommand = new RelayCommand(this.onClickStop, param => true);
this.ToggleTime();
}
#endregion Constructor
#region Properties
/// <summary>
/// Gets a value indicating whether this instance is manual.
/// </summary>
/// <value>
/// <c>true</c> if this instance is manual; otherwise, <c>false</c>.
/// </value>
public bool IsManual
{
get
{
return this.Modus == (int)Controlstate.Manual;
}
}
/// <summary>
/// Gets a value indicating whether [show tool tip start].
/// </summary>
/// <value>
/// <c>true</c> if [show tool tip start]; otherwise, <c>false</c>.
/// </value>
public bool ShowToolTipStart
{
get
{
return this.ToolTipStart != string.Empty;
}
}
/// <summary>
/// Gets a value indicating whether [show tool tip stop].
/// </summary>
/// <value>
/// <c>true</c> if [show tool tip stop]; otherwise, <c>false</c>.
/// </value>
public bool ShowToolTipStop
{
get
{
return this.ToolTipStop != string.Empty;
}
}
/// <summary>
/// Gets a value indicating whether [show tool tip manual].
/// </summary>
/// <value>
/// <c>true</c> if [show tool tip manual]; otherwise, <c>false</c>.
/// </value>
public bool ShowToolTipManual
{
get
{
return this.ToolTipManual != string.Empty;
}
}
/// <summary>
/// Gets the tool tip start.
/// </summary>
/// <value>
/// The tool tip start.
/// </value>
public string ToolTipStart
{
get
{
switch (this.Modus)
{
case (int)Controlstate.Standby: return string.Empty;
default:
return "Only available if system is in standby mode";
}
}
}
/// <summary>
/// Gets the tool tip stop.
/// </summary>
/// <value>
/// The tool tip stop.
/// </value>
public string ToolTipStop
{
get
{
switch (this.Modus)
{
case (int)Controlstate.Standby:
return "Only available if a process is running";
case (int)Controlstate.Setup:
return "Only available if a process is running";
default: return string.Empty;
}
}
}
/// <summary>
/// Gets the tool tip manual.
/// </summary>
/// <value>
/// The tool tip manual.
/// </value>
public string ToolTipManual
{
get
{
switch (this.Modus)
{
case (int)Controlstate.Standby: return string.Empty;
default:
return "Only available if system is in standby mode";
}
}
}
/// <summary>
/// Gets the color of the connection state.
/// </summary>
/// <value>
/// The color of the connection state.
/// </value>
public SolidColorBrush ConnectionStateColor
{
get
{
return this.DisplayColor((ColorState)Convert.ToInt32(this.ServerConnection));
}
}
/// <summary>
/// Gets the planned modus.
/// </summary>
/// <value>
/// The planned modus.
/// </value>
public string PlannedModus
{
get
{
switch (this.modusModel.Modus)
{
case (int)Controlstate.CooldownStart: return "Cool down";
case (int)Controlstate.WarmupStart: return "Warm up";
case (int)Controlstate.RecycleStart: return "Recycle";
default: return string.Empty;
}
}
}
/// <summary>
/// Gets or sets the planned time.
/// </summary>
/// <value>
/// The planned time.
/// </value>
public DateTime PlannedTime
{
get
{
return this.modusModel.PlannedTime;
}
set
{
this.modusModel.PlannedTime = value;
this.RaisePropertyChanged("PlannedTime");
this.RaisePropertyChanged("PlannedTimeConverted");
}
}
/// <summary>
/// Gets the planned time converted.
/// </summary>
/// <value>
/// The planned time converted.
/// </value>
public string PlannedTimeConverted
{
get
{
return DateTime.Now.Subtract(this.PlannedTime).ToString(@"dd\ \d\a\y\s\ hh\:mm\:ss");
}
}
/// <summary>
/// Gets the show countdown.
/// </summary>
/// <value>
/// The show countdown.
/// </value>
public Visibility ShowCountdown
{
get
{
if (string.IsNullOrEmpty(this.PlannedModus))
{
return Visibility.Hidden;
}
else
{
return Visibility.Visible;
}
}
}
/// <summary>
/// Gets a value indicating whether [start mode].
/// </summary>
/// <value>
/// <c>true</c> if [start mode]; otherwise, <c>false</c>.
/// </value>
public bool StartMode
{
get
{
return this.Modus == (int)Controlstate.Standby;
}
}
/// <summary>
/// Gets a value indicating whether [cancel mode].
/// </summary>
/// <value>
/// <c>true</c> if [cancel mode]; otherwise, <c>false</c>.
/// </value>
public bool CancelMode
{
get
{
return this.Modus != (int)Controlstate.Standby && this.Modus != (int)Controlstate.Setup;
}
}
/// <summary>
/// Gets or sets the selected time.
/// </summary>
/// <value>
/// The selected date.
/// </value>
public DateTime SelectedTime
{
get
{
return this.modusModel.SelectedTime;
}
set
{
this.modusModel.SelectedTime = value;
this.RaisePropertyChanged("SelectedTime");
}
}
/// <summary>
/// Gets or sets the selected date.
/// </summary>
/// <value>
/// The selected date.
/// </value>
public DateTime SelectedDate
{
get
{
return this.modusModel.SelectedDate;
}
set
{
this.modusModel.SelectedDate = value;
this.RaisePropertyChanged("SelectedDate");
}
}
/// <summary>
/// Gets or sets the show date time.
/// </summary>
/// <value>
/// The show date time.
/// </value>
public string ShowDateTime
{
get
{
return this.modusModel.ShowDateTime;
}
set
{
this.modusModel.ShowDateTime = value;
this.RaisePropertyChanged("ShowDateTime");
}
}
/// <summary>
/// Gets or sets the modus.
/// </summary>
/// <value>
/// The modus.
/// </value>
public int Modus
{
get
{
return this.modusModel.Modus;
}
set
{
this.modusModel.Modus = value;
this.RaisePropertyChanged("Modus");
this.RaisePropertyChanged("StartMode");
this.RaisePropertyChanged("CancelMode");
this.RaisePropertyChanged("ModusConverted");
this.RaisePropertyChanged("ShowCountdown");
this.RaisePropertyChanged("ShowToolTipStart");
this.RaisePropertyChanged("ShowToolTipStop");
this.RaisePropertyChanged("ShowToolTipManual");
this.RaisePropertyChanged("IsManual");
}
}
/// <summary>
/// Gets the modus converted.
/// </summary>
/// <value>
/// The modus converted.
/// </value>
public string ModusConverted
{
get
{
return this.ConvertModusNumberToString(this.modusModel.Modus);
}
}
/// <summary>
/// Gets or sets a value indicating whether the server is connected.
/// </summary>
/// <value>
/// <c>true</c> if server connected; otherwise, <c>false</c>.
/// </value>
public bool ServerConnection
{
get
{
return this.modusModel.ServerConnection;
}
set
{
this.modusModel.ServerConnection = value;
this.RaisePropertyChanged("Server");
this.RaisePropertyChanged("ServerConverted");
this.RaisePropertyChanged("ConnectionStateColor");
}
}
/// <summary>
/// Gets the server connection converted.
/// </summary>
/// <value>
/// The server converted.
/// </value>
public string ServerConverted
{
get
{
if (this.ServerConnection)
{
return "Connected";
}
return "Disconnected";
}
}
/// <summary>
/// Gets or sets the time.
/// </summary>
/// <value>
/// The time.
/// </value>
public string Time
{
get
{
return this.modusModel.Time;
}
set
{
this.modusModel.Time = value;
}
}
/// <summary>
/// Gets or sets the index of the selected combo.
/// </summary>
/// <value>
/// The index of the selected combo.
/// </value>
public int SelectedComboIndex
{
get
{
return this.modusModel.SelectedComboIndex;
}
set
{
this.modusModel.SelectedComboIndex = value;
}
}
#endregion Properties
#region Commands
/// <summary>
/// Gets or sets the start button command.
/// </summary>
/// <value>
/// The hi button command.
/// </value>
public ICommand StartButtonCommand
{
get
{
return this.startButtonCommand;
}
set
{
this.startButtonCommand = value;
}
}
/// <summary>
/// Gets or sets the cancel button command.
/// </summary>
/// <value>
/// The cancel button command.
/// </value>
public ICommand CancelButtonCommand
{
get
{
return this.cancelButtonCommand;
}
set
{
this.cancelButtonCommand = value;
}
}
/// <summary>
/// Gets or sets the manual mode button command.
/// </summary>
/// <value>
/// The cancel button command.
/// </value>
public ICommand ManualButtonCommand
{
get
{
return this.manualButtonCommand;
}
set
{
this.manualButtonCommand = value;
}
}
/// <summary>
/// Gets or sets the stop button command.
/// </summary>
/// <value>
/// The stop button command.
/// </value>
public ICommand StopButtonCommand
{
get
{
return this.stopButtonCommand;
}
set
{
this.stopButtonCommand = value;
}
}
/// <summary>
/// Gets or sets the radio button command.
/// </summary>
/// <value>
/// The radio button command.
/// </value>
public ICommand RadioButtonCommand
{
get
{
return this.radioButtonCommand;
}
set
{
this.radioButtonCommand = value;
}
}
#endregion Commands
#region Methods
/// <summary>
/// Convert operating state number to string.
/// </summary>
/// <param name="modusNumber">The modus number.</param>
/// <returns>
/// The <see cref="string" />.
/// </returns>
public string ConvertModusNumberToString(double modusNumber)
{
return ((Controlstate)modusNumber).ToString();
}
/// <summary>
/// Handles radio change.
/// </summary>
/// <param name="obj">The object.</param>
public void OnChangeRadio(object obj)
{
this.Time = obj.ToString();
this.ToggleTime();
}
/// <summary>
/// Handles start click.
/// </summary>
/// <param name="obj">The object.</param>
public void OnClickStart(object obj)
{
ServerCheck.SendMessage(new Task(() => { this.StartControlProcess(); }));
}
/// <summary>
/// Handles cancel click.
/// </summary>
/// <param name="obj">The object.</param>
public void OnClickCancel(object obj)
{
ServerCheck.SendMessage(new Task(() => { ServerCheck.CommandClient.Cancel(); }));
}
/// <summary>
/// Handles manual click.
/// </summary>
/// <param name="obj">The object.</param>
public void OnClickManual(object obj)
{
ServerCheck.SendMessage(new Task(() => { ServerCheck.CommandClient.Manual(); }));
}
/// <summary>
/// Handles stop click.
/// </summary>
/// <param name="obj">The object.</param>
public void onClickStop(object obj)
{
ServerCheck.SendMessage(new Task(() => { ServerCheck.CommandClient.Stop(); }));
}
/// <summary>
/// Task method to start the control process.
/// </summary>
private void StartControlProcess()
{
if (ServerCheck.CommandClient.State == CommunicationState.Opened)
{
int radio = this.SelectedComboIndex;
string postpone = this.Time;
DateTime startTime = DateTime.Now;
if (postpone == "Scheduled")
{
startTime = this.SelectedDate;
TimeSpan time = this.SelectedTime.TimeOfDay;
startTime = startTime.Date.Add(time);
}
switch (radio)
{
case (int)ModusEnumerator.Cooldown:
ServerCheck.CommandClient.CooldownTime(startTime);
break;
case (int)ModusEnumerator.Recycle:
ServerCheck.CommandClient.RecycleTime(startTime);
break;
case (int)ModusEnumerator.Warmup:
ServerCheck.CommandClient.WarmupTime(startTime);
break;
}
}
}
/// <summary>
/// Toggles the time.
/// </summary>
private void ToggleTime()
{
if (this.Time == "Now" || this.ShowCountdown == Visibility.Visible)
{
this.ShowDateTime = "Hidden";
}
else
{
this.ShowDateTime = "Visible";
}
}
#endregion Methods
}
}<file_sep>/CryostatControlServer/Compressor/Compressor.cs
//-----------------------------------------------------------------------
// <copyright file="Compressor.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.Compressor
{
using System;
using System.Net.Sockets;
using CryostatControlServer.Logging;
using Modbus.Device;
/// <summary>
/// Compressor class, which contains the functions for the compressor.
/// </summary>
public class Compressor
{
#region Fields
/// <summary>
/// The Slave number, needed for identification.
/// </summary>
private const byte Slave = 1;
/// <summary>
/// The standard port for MODBUS communication.
/// </summary>
private const ushort Port = 502;
/// <summary>
/// SingleRegister for limiting number of registers.
/// </summary>
private const ushort SingleRegister = 1;
/// <summary>
/// DoubleRegister for limiting number of registers.
/// </summary>
private const ushort DoubleRegister = 2;
/// <summary>
/// Master instance where MODBUS calls can be called on.
/// </summary>
private ModbusIpMaster master;
#endregion Fields
#region Methods
/// <summary>
/// Connects the specified address.
/// </summary>
/// <param name="address">The address.</param>
public void Connect(string address)
{
TcpClient client = new TcpClient(address, Port);
this.master = ModbusIpMaster.CreateIp(client);
}
/// <summary>
/// Disconnects this instance.
/// </summary>
public void Disconnect()
{
this.master.Dispose();
}
/// <summary>
/// Turns the compressor on.
/// </summary>
public void TurnOn()
{
const ushort On = 0x001;
this.master.WriteSingleRegister(Slave, (ushort)HoldingRegistersEnum.Control, On);
DebugLogger.Info(this.GetType().Name, "Compressor turned on");
}
/// <summary>
/// Determines whether this instance is connected.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is connected; otherwise, <c>false</c>.
/// </returns>
public bool IsConnected()
{
if (this.master == null)
{
return false;
}
try
{
this.ReadOperatingState();
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Turns the compressor off.
/// </summary>
public void TurnOff()
{
const ushort Off = 0x00FF;
this.master.WriteSingleRegister(Slave, (ushort)HoldingRegistersEnum.Control, Off);
DebugLogger.Info(this.GetType().Name, "Compressor turned off");
}
/// <summary>
/// Reads if the compressor is set on or off.
/// </summary>
/// <returns>
/// 0 if no value is set.
/// 1 if the compressor is set on.
/// 255 if the compressor is set off.
/// </returns>
public ushort ReadOnOff()
{
ushort[] status = this.master.ReadHoldingRegisters((ushort)HoldingRegistersEnum.Control, SingleRegister);
return status[0];
}
/// <summary>
/// Reads the operating state of the compressor.
/// </summary>
/// <returns>Returns the enumerator <see cref="StatusEnum"/> </returns>
public StatusEnum ReadOperatingState()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.OperatingState, SingleRegister);
return (StatusEnum)status[0];
}
/// <summary>
/// Reads the energy state of the compressor.
/// </summary>
/// <returns>Returns the enumerator <see cref="EnergizedEnum"/> </returns>
public EnergizedEnum ReadEnergyState()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.EnergyState, SingleRegister);
return (EnergizedEnum)status[0];
}
/// <summary>
/// Reads the warning state of the compressor.
/// </summary>
/// <returns>Returns the enumerator <see cref="WarningsEnum"/> </returns>
public WarningsEnum ReadWarningState()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.WarningState, DoubleRegister);
return (WarningsEnum)this.ParseFloat(status);
}
/// <summary>
/// Reads the error state of the compressor.
/// </summary>
/// <returns>Returns the enumerator <see cref="ErrorEnum"/> </returns>
public ErrorEnum ReadErrorState()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.ErrorState, DoubleRegister);
return (ErrorEnum)this.ParseFloat(status);
}
/// <summary>
/// Reads the incoming cooling water temperature of the compressor.
/// </summary>
/// <returns>Returns incoming cooling water temperature.</returns>
public float ReadCoolInTemp()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.CoolantInTemp, DoubleRegister);
return this.ParseFloat(status);
}
/// <summary>
/// Reads the outgoing cooling water temperature of the compressor.
/// </summary>
/// <returns>Returns outgoing cooling water temperature.</returns>
public float ReadCoolOutTemp()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.CoolantOutTemp, DoubleRegister);
return this.ParseFloat(status);
}
/// <summary>
/// Reads the oil temperature of the compressor.
/// </summary>
/// <returns>Returns oil temperature.</returns>
public float ReadOilTemp()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.OilTemp, DoubleRegister);
return this.ParseFloat(status);
}
/// <summary>
/// Reads the helium temperature of the compressor.
/// </summary>
/// <returns>Returns helium temperature.</returns>
public float ReadHeliumTemp()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.HeliumTemp, DoubleRegister);
return this.ParseFloat(status);
}
/// <summary>
/// Reads the low pressure of the compressor.
/// </summary>
/// <returns>Returns low pressure.</returns>
public float ReadLowPressure()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.LowPressure, DoubleRegister);
return this.ParseFloat(status);
}
/// <summary>
/// Reads the low pressure average of the compressor.
/// </summary>
/// <returns>Returns low pressure average.</returns>
public float ReadLowPressureAverage()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.LowPressureAvg, DoubleRegister);
return this.ParseFloat(status);
}
/// <summary>
/// Reads the high pressure of the compressor.
/// </summary>
/// <returns>Returns high pressure.</returns>
public float ReadHighPressure()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.HighPressure, DoubleRegister);
return this.ParseFloat(status);
}
/// <summary>
/// Reads the high average pressure of the compressor.
/// </summary>
/// <returns>Returns high average pressure.</returns>
public float ReadHighPressureAverage()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.HighPressureAvg, DoubleRegister);
return this.ParseFloat(status);
}
/// <summary>
/// Reads the delta average pressure of the compressor.
/// </summary>
/// <returns>Returns delta average pressure.</returns>
public float ReadDeltaPressureAverage()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.DeltaPressureAvg, DoubleRegister);
return this.ParseFloat(status);
}
/// <summary>
/// Reads the motor current of the compressor.
/// </summary>
/// <returns>Returns motor current.</returns>
public float ReadMotorCurrent()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.MotorCurrent, DoubleRegister);
return this.ParseFloat(status);
}
/// <summary>
/// Reads the hours of operation of the compressor.
/// </summary>
/// <returns>Hours of operation</returns>
public float ReadHoursOfOperation()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.HoursOfOperation, DoubleRegister);
return this.ParseFloat(status);
}
/// <summary>
/// Reads two analog register which follow each other.
/// This can be called on the most sensors.
/// <seealso cref="AnalogRegistersEnum"/> for the available register.
/// </summary>
/// <param name="register">
/// The register.
/// </param>
/// <returns>
/// The <see cref="float"/>.
/// </returns>
public float ReadDoubleAnalogRegister(AnalogRegistersEnum register)
{
ushort[] status = this.master.ReadInputRegisters((ushort)register, DoubleRegister);
return this.ParseFloat(status);
}
/// <summary>
/// Reads the pressure scale of the compressor.
/// </summary>
/// <returns>Pressure scale.</returns>
public PressureEnum ReadPressureScale()
{
try
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.PressureScale, SingleRegister);
return (PressureEnum)status[0];
}
catch
{
return (PressureEnum)(-1);
}
}
/// <summary>
/// Reads the temperature scale of the compressor.
/// </summary>
/// <returns>Temperature scale.</returns>
public TemperatureEnum ReadTemperatureScale()
{
try
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.TempScale, SingleRegister);
return (TemperatureEnum)status[0];
}
catch
{
return (TemperatureEnum)(-1);
}
}
/// <summary>
/// Reads the panel serial number.
/// </summary>
/// <returns>Panel Serial number.</returns>
public ushort ReadPanelSerialNumber()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.PanelSerialNumber, SingleRegister);
return status[0];
}
/// <summary>
/// Reads the model number.
/// </summary>
/// <returns>Model number.</returns>
public byte[] ReadModel()
{
ushort[] status = this.master.ReadInputRegisters((ushort)AnalogRegistersEnum.Model, SingleRegister);
byte[] bytes = BitConverter.GetBytes(status[0]);
return bytes;
}
/// <summary>
/// Helper method for converting the incoming two <see cref="ushort"/> into <see cref="float"/>. By shifting the bytes.
/// </summary>
/// <param name="input">array with two <see cref="ushort"/> variables</param>
/// <returns>float number from the two<see cref="ushort"/></returns>
private float ParseFloat(ushort[] input)
{
return this.ParseFloat(input[0], input[1]);
}
/// <summary>
/// Helper method for converting the incoming two <see cref="ushort"/> into <see cref="float"/>. By shifting the bytes.
/// </summary>
/// <param name="data1">First <see cref="ushort"/> input</param>
/// <param name="data2">Second <see cref="ushort"/> input</param>
/// <returns>float number from the two<see cref="ushort"/></returns>
private float ParseFloat(ushort data1, ushort data2)
{
byte[] bytes1 = BitConverter.GetBytes(data1);
byte[] bytes2 = BitConverter.GetBytes(data2);
byte[] arbyWorker = new byte[4];
arbyWorker[3] = bytes2[1];
arbyWorker[2] = bytes2[0];
arbyWorker[1] = bytes1[1];
arbyWorker[0] = bytes1[0];
return BitConverter.ToSingle(arbyWorker, 0);
}
#endregion Methods
}
}<file_sep>/CryostatControlClient/Models/AbstractModel.cs
//-----------------------------------------------------------------------
// <copyright file="AbstractModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlClient.Models
{
using System;
using System.Linq;
using LiveCharts.Defaults;
using LiveCharts.Geared;
/// <summary>
/// The abstract model
/// </summary>
public abstract class AbstractModel
{
#region Fields
/// <summary>
/// The amount of data averaged in 1 point
/// </summary>
private const int DataPerPoint = 30;
/// <summary>
/// The maximum amount of chart values
/// </summary>
private const int MaxChartValues = 3000;
#endregion Fields
#region Properties
/// <summary>
/// Gets the update interval.
/// </summary>
/// <value>
/// The update interval.
/// </value>
protected int TemporaryListSize
{
get
{
return DataPerPoint + 1;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Add a value to the graph.
/// </summary>
/// <param name="temporaryList">The temporary list.</param>
/// <param name="lineSeries">The line series.</param>
/// <param name="value">The value.</param>
/// <returns>
/// The updated temporary list.
/// </returns>
public double[] AddToGraph(double[] temporaryList, GLineSeries lineSeries, double value)
{
if (!double.IsNaN(value))
{
temporaryList[(int)temporaryList[DataPerPoint]] = value;
temporaryList[DataPerPoint]++;
if (lineSeries.Values.Count < 1)
{
lineSeries.Values.Add(new DateTimePoint(DateTime.Now, Math.Round(value, 3)));
temporaryList = new double[this.TemporaryListSize];
temporaryList[DataPerPoint] = 0;
}
else if (temporaryList[DataPerPoint] > this.TemporaryListSize - 2)
{
lineSeries.Values.Add(new DateTimePoint(DateTime.Now, Math.Round((temporaryList.Sum() - DataPerPoint) / DataPerPoint, 3)));
if (lineSeries.Values.Count > MaxChartValues)
{
lineSeries.Values.RemoveAt(0);
}
temporaryList = new double[this.TemporaryListSize];
temporaryList[this.TemporaryListSize - 1] = 0;
}
}
return temporaryList;
}
#endregion Methods
}
}
<file_sep>/CryostatControlClient/Models/LoggingModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LoggingModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Models
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// The logging model.
/// </summary>
public class LoggingModel
{
/// <summary>
/// Gets or sets a value indicating whether [he3 pump temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [he3 pump temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool He3PumpTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [he3 head temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [he3 head temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool He3HeadTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [he3 switch temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [he3 switch temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool He3SwitchTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [he4 pump temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [he4 pump temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool He4PumpTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [he4 head temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [he4 head temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool He4HeadTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [he4 switch temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [he4 switch temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool He4SwitchTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [two k plate temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [two k plate temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool TwoKPlateTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [four k plate temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [four k plate temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool FourKPlateTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [he3 pump volt] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [he3 pump volt] will be logged; otherwise, <c>false</c>.
/// </value>
public bool He3PumpVolt { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [he3 switch volt] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [he3 switch volt] will be logged; otherwise, <c>false</c>.
/// </value>
public bool He3SwitchVolt { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [he4 pump volt] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [he4 pump volt] will be logged; otherwise, <c>false</c>.
/// </value>
public bool He4PumpVolt { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [he4 switch volt] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [he4 switch volt] will be logged; otherwise, <c>false</c>.
/// </value>
public bool He4SwitchVolt { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [bluefors50 k shield temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [bluefors50 k shield temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool Bluefors50KShieldTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [bluefors3 k shield temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [bluefors3 k shield temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool Bluefors3KShieldTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [compressor water in temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [compressor water in temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool CompressorWaterInTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [compressor water out temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [compressor water out temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool CompressorWaterOutTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [compressor helium temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [compressor helium temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool CompressorHeliumTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [compressor oil temperature] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [compressor oil temperature] will be logged; otherwise, <c>false</c>.
/// </value>
public bool CompressorOilTemp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [compressor low pressure] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [compressor low pressure] will be logged; otherwise, <c>false</c>.
/// </value>
public bool CompressorLowPressure { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [compressor low average pressure] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [compressor low average pressure] will be logged; otherwise, <c>false</c>.
/// </value>
public bool CompressorLowAveragePressure { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [compressor high pressure] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [compressor high pressure] will be logged; otherwise, <c>false</c>.
/// </value>
public bool CompressorHighPressure { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [compressor high average pressure] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [compressor high average pressure] will be logged; otherwise, <c>false</c>.
/// </value>
public bool CompressorHighAveragePressure { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [compressor delta average pressure] will be logged.
/// </summary>
/// <value>
/// <c>true</c> if [compressor delta average pressure] will be logged; otherwise, <c>false</c>.
/// </value>
public bool CompressorDeltaAveragePressure { get; set; }
/// <summary>
/// Gets or sets the logging interval.
/// </summary>
/// <value>
/// The logging interval.
/// </value>
public double LoggingInterval { get; set; }
/// <summary>
/// Gets or sets the preset ComboBox.
/// </summary>
/// <value>
/// The preset ComboBox.
/// </value>
public int PresetComboBox { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [logging in progress].
/// </summary>
/// <value>
/// <c>true</c> if [logging in progress]; otherwise, <c>false</c>.
/// </value>
public bool LoggingInProgress { get; set; }
}
}
<file_sep>/CryostatControlServer/He7Cooler/Sensor.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Sensor.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.He7Cooler
{
using CryostatControlServer.Data;
/// <summary>
/// The he 7 cooler.
/// </summary>
public partial class He7Cooler
{
#region Classes
/// <summary>
/// Representation of a sensor on the H7 cooler.
/// </summary>
public class Sensor : ISensor
{
#region Fields
/// <summary>
/// The sensor calibration.
/// </summary>
private Calibration calibration;
/// <summary>
/// The Agilent data channel.
/// </summary>
private Channels channel;
/// <summary>
/// The He7 cooler.
/// </summary>
private He7Cooler device;
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Sensor"/> class.
/// </summary>
/// <param name="channel">
/// The agilent channel of the sensor.
/// </param>
/// <param name="device">
/// The He7 cooler device.
/// </param>
/// <param name="calibration">
/// The calibration.
/// </param>
public Sensor(Channels channel, He7Cooler device, Calibration calibration)
{
this.channel = channel;
this.calibration = calibration;
this.device = device;
device.AddChannel(channel);
}
#endregion Constructors
#region Destructors
/// <summary>
/// Finalizes an instance of the <see cref="Sensor"/> class. Removes it from the list of channels to read.
/// </summary>
~Sensor()
{
this.device.RemoveChannel(this.channel);
}
#endregion Destructors
#region Properties
/// <summary>
/// Gets or sets the interval.
/// This is ignored for now, sensors are always read as fast as possible.
/// </summary>
public int Interval { get; set; }
/// <summary>
/// Gets the current calibrated value of the sensor.
/// </summary>
public double Value => this.calibration.ConvertValue(this.device.values[this.channel]);
#endregion Properties
}
#endregion Classes
}
}<file_sep>/CryostatControlServer/HostService/PasswordValidator.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PasswordValidator.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.HostService
{
using System;
using System.IdentityModel.Selectors;
using System.ServiceModel;
using Properties;
/// <summary>
/// The password validator.
/// </summary>
public class PasswordValidator : UserNamePasswordValidator
{
/// <summary>
/// The user name.
/// </summary>
private string userName = "cooler";
/// <summary>
/// Validate the username and password against the password token
/// </summary>
/// <param name="userName">
/// The user name.
/// </param>
/// <param name="password">
/// The password.
/// </param>
/// <exception cref="ArgumentNullException">
/// thrown when an argument is null
/// </exception>
/// <exception cref="FaultException">
/// Thrown when the username and password are invalid
/// </exception>
public override void Validate(string userName, string password)
{
if (userName == null || password == null)
{
throw new ArgumentNullException();
}
if (!(userName == this.userName && password == Settings.Default.PasswordToken))
{
// This throws an informative fault to the client.
throw new FaultException("Unknown Username or Incorrect Password");
}
}
}
}
<file_sep>/CryostatControlClient/Communication/ServerCheck.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ServerCheck.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Communication
{
using System;
using System.Net;
using System.Net.Sockets;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CryostatControlClient.Properties;
using CryostatControlClient.ServiceReference1;
using CryostatControlClient.ViewModels;
using CryostatControlClient.Views;
/// <summary>
/// Class which continuously checks the connection with the server
/// </summary>
public class ServerCheck
{
/// <summary>
/// The wait time
/// </summary>
private const int WaitTime = 500;
/// <summary>
/// The check interval
/// </summary>
private const int CheckInterval = 1000;
/// <summary>
/// The subscribe interval
/// </summary>
private const int SubscribeInterval = 1000;
/// <summary>
/// The callback client
/// </summary>
private DataGetClient callbackClient;
/// <summary>
/// The first time connected
/// </summary>
private bool firstTimeConnected = false;
/// <summary>
/// The main application
/// </summary>
private App mainApp;
/// <summary>
/// The main window
/// </summary>
private MainWindow mainWindow;
/// <summary>
/// The timer
/// </summary>
private System.Threading.Timer timer;
/// <summary>
/// The ip address
/// </summary>
private string ipAddress = string.Empty;
/// <summary>
/// The key
/// </summary>
private string key;
/// <summary>
/// Initializes a new instance of the <see cref="ServerCheck" /> class.
/// </summary>
/// <param name="app">The application.</param>
public ServerCheck(App app)
{
this.mainApp = app;
this.mainWindow = this.mainApp.MainWindow as MainWindow;
this.Connect();
this.timer = new System.Threading.Timer(this.CheckStatus, null, WaitTime, Timeout.Infinite);
}
/// <summary>
/// Gets the command client.
/// </summary>
/// <value>
/// The command client.
/// </value>
public static CommandServiceClient CommandClient
{
get; private set;
}
/// <summary>
/// Sends the message to the server.
/// </summary>
/// <param name="task">The task.</param>
public static void SendMessage(Task task)
{
try
{
if (CommandClient.State == CommunicationState.Opened)
{
task.Start();
}
else
{
System.Windows.Forms.MessageBox.Show("No connection", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch
{
System.Windows.Forms.MessageBox.Show("Something went wrong with the server, check connection and try again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Gets the local ip address.
/// </summary>
/// <returns>Combination of the clients internet address and current time</returns>
private string GetRegisterKey()
{
if (this.ipAddress != string.Empty)
{
return this.ipAddress + this.key;
}
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
this.ipAddress = ip.ToString();
return ip.ToString() + this.key;
}
}
}
return this.key;
}
/// <summary>
/// Checks the status with the server.
/// Firstly it calls the server to see if it is alive.
/// If the server is alive nothing happens else an exception is thrown and the connections are aborted and a reconnect is started.
/// If the client is for the first time connect to the client it updates some GUI elements.
/// Further it checks if it subscribed for data and updates, if not it subscribes for data.
/// Finally the timer is reactivated for a new execution.
/// </summary>
/// <param name="state">The state.</param>
private void CheckStatus(object state)
{
try
{
CommandClient.IsAlive();
this.SetConnected(true);
if (this.firstTimeConnected)
{
this.UpdateGUI();
}
if (!CommandClient.IsRegisteredForData(this.GetRegisterKey()))
{
this.callbackClient.SubscribeForData(SubscribeInterval, this.GetRegisterKey());
}
if (!CommandClient.IsRegisteredForUpdates(this.GetRegisterKey()))
{
this.callbackClient.SubscribeForUpdates(this.GetRegisterKey());
}
this.firstTimeConnected = false;
}
catch (Exception e)
{
if (e is CommunicationException || e is TimeoutException) {
this.SetConnected(false);
CommandClient.Abort();
this.callbackClient.Abort();
this.Connect();
}
}
finally
{
this.timer.Change(CheckInterval, Timeout.Infinite);
}
}
/// <summary>
/// Connects the client to the server.
/// </summary>
private void Connect()
{
this.key = DateTime.Now.ToString();
CommandClient = new CommandServiceClient();
CommandClient.ClientCredentials.UserName.UserName = Settings.Default.UserName;
CommandClient.ClientCredentials.UserName.Password = <PASSWORD>;
CommandClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
X509CertificateValidationMode.None;
DataClientCallback callback = new DataClientCallback(this.mainApp);
InstanceContext instanceContext = new InstanceContext(callback);
this.callbackClient = new DataGetClient(instanceContext);
this.callbackClient.ClientCredentials.UserName.UserName = Settings.Default.UserName;
this.callbackClient.ClientCredentials.UserName.Password = <PASSWORD>;
this.callbackClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
X509CertificateValidationMode.None;
this.firstTimeConnected = true;
}
/// <summary>
/// Sets the connected property.
/// </summary>
/// <param name="state">if set to <c>true</c> [state].</param>
private void SetConnected(bool state)
{
if (this.mainApp != null)
{
this.mainApp.Dispatcher.Invoke(
() =>
{
if ((MainWindow)this.mainApp.MainWindow != null)
{
ViewModelContainer container = ((MainWindow)this.mainApp.MainWindow).Container;
if (container != null)
{
container.ModusViewModel.ServerConnection = state;
}
}
});
}
}
/// <summary>
/// Updates the GUI components
/// </summary>
private void UpdateGUI()
{
if (this.mainApp != null)
{
this.mainApp.Dispatcher.Invoke(() =>
{
if ((MainWindow)this.mainApp.MainWindow != null)
{
ViewModelContainer viewModelContainer = ((MainWindow)this.mainApp.MainWindow).Container;
try
{
CommandServiceClient commandClient = ServerCheck.CommandClient;
if (commandClient.State == CommunicationState.Opened && viewModelContainer != null)
{
viewModelContainer.CompressorViewModel.TempScale =
commandClient.ReadCompressorTemperatureScale();
viewModelContainer.CompressorViewModel.PressureScale =
commandClient.ReadCompressorPressureScale();
viewModelContainer.LoggingViewModel.LoggingInProgress =
commandClient.IsLogging();
}
}
catch (Exception)
{
//// Do nothing and continue
}
}
});
}
}
}
}<file_sep>/CryostatControlServer/HostService/CommandService.cs
//-----------------------------------------------------------------------
// <copyright file="CommandService.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.HostService
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.Threading;
using CryostatControlServer.HostService.DataContracts;
using CryostatControlServer.HostService.Enumerators;
using CryostatControlServer.Logging;
/// <summary>
/// Service class which handles the incoming methods calls.
/// </summary>
/// <seealso cref="CryostatControlServer.HostService.ICommandService" />
public class CommandService : ICommandService, IDataGet
{
#region Fields
/// <summary>
/// The cryostat control
/// </summary>
private readonly CryostatControl cryostatControl;
/// <summary>
/// The logger
/// </summary>
private readonly LogThreader logger;
/// <summary>
/// The callback list
/// </summary>
private readonly Dictionary<string, Timer> dataListeners = new Dictionary<string, Timer>();
/// <summary>
/// The update listeners
/// </summary>
private readonly Dictionary<string, IDataGetCallback> updateListeners = new Dictionary<string, IDataGetCallback>();
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CommandService" /> class.
/// </summary>
/// <param name="cryostatControl">The cryostat Control.</param>
/// <param name="logger">The logger.</param>
public CommandService(CryostatControl cryostatControl, LogThreader logger)
{
this.cryostatControl = cryostatControl;
this.logger = logger;
}
#endregion Constructors
#region Methods
/// <inheritdoc cref="ICommandService.IsAlive"/>
public bool IsAlive()
{
return true;
}
/// <inheritdoc cref="ICommandService.Cooldown"/>>
public bool Cooldown()
{
return this.cryostatControl.StartCooldown();
}
/// <inheritdoc cref="ICommandService.Cooldown"/>>
public bool CooldownTime(DateTime time)
{
return this.cryostatControl.StartCooldown(time);
}
/// <inheritdoc cref="ICommandService.Recycle"/>>
public bool Recycle()
{
return this.cryostatControl.StartRecycle();
}
/// <inheritdoc cref="ICommandService.Recycle"/>>
public bool RecycleTime(DateTime time)
{
return this.cryostatControl.StartRecycle(time);
}
/// <inheritdoc cref="ICommandService.Warmup"/>>
public bool Warmup()
{
return this.cryostatControl.StartHeatup();
}
/// <inheritdoc cref="ICommandService.Warmup"/>>
public bool WarmupTime(DateTime time)
{
return this.cryostatControl.StartHeatup(time);
}
/// <inheritdoc cref="ICommandService.Manual"/>
public bool Manual()
{
return this.cryostatControl.StartManualControl();
}
/// <summary>
/// Cancel the controller action
/// </summary>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
public bool Cancel()
{
this.cryostatControl.CancelCommand();
return true;
}
/// <inheritdoc cref="ICommandService.Stop"/>
public bool Stop()
{
this.cryostatControl.StopCommand();
return true;
}
/// <summary>
/// Get the controller state
/// </summary>
/// <returns>
/// The controller state <see cref="int"/>.
/// </returns>
public int GetState()
{
return (int)this.cryostatControl.ControllerState;
}
/// <inheritdoc cref="ICommandService.GetStartTime"/>
public DateTime GetStartTime()
{
return this.cryostatControl.StartTime;
}
/// <inheritdoc cref="ICommandService.GetValue"/>
public double GetValue(string sensor)
{
try
{
int sensorId = int.Parse(sensor);
return this.cryostatControl.ReadSingleSensor(sensorId);
}
catch (Exception e)
{
throw new FaultException(e.GetType().ToString());
}
}
/// <inheritdoc cref="ICommandService.SetCompressorState"/>
public bool SetCompressorState(bool status)
{
return this.cryostatControl.SetCompressorState(status);
}
/// <inheritdoc cref="ICommandService.WriteHelium7"/>
public bool WriteHelium7(int heater, double value)
{
try
{
if (this.cryostatControl.WriteHelium7Heater((HeaterEnumerator)heater, value))
{
return true;
}
else
{
throw new FaultException<CouldNotPerformActionFault>(
new CouldNotPerformActionFault(ActionFaultReason.NotInManualMode, "Not in manual mode"));
}
}
catch (ArgumentOutOfRangeException ex)
{
throw new FaultException<CouldNotPerformActionFault>(
new CouldNotPerformActionFault(ActionFaultReason.InvalidValue, ex.Message));
}
catch (Exception e)
{
throw new FaultException<CouldNotPerformActionFault>(
new CouldNotPerformActionFault(ActionFaultReason.Unknown, e.GetType().ToString()));
}
}
/// <inheritdoc cref="ICommandService.ReadCompressorTemperatureScale"/>>
public double ReadCompressorTemperatureScale()
{
return this.cryostatControl.ReadCompressorTemperatureScale();
}
/// <inheritdoc cref="ICommandService.ReadCompressorPressureScale"/>>
public double ReadCompressorPressureScale()
{
return this.cryostatControl.ReadCompressorPressureScale();
}
/// <inheritdoc cref="ICommandService.ReadSingleSensor"/>>
public double ReadSingleSensor(int sensorId)
{
return this.cryostatControl.ReadSingleSensor(sensorId);
}
/// <inheritdoc cref="ICommandService.WriteSettingValues"/>>
public bool WriteSettingValue(int setting, double value)
{
SettingEnumerator settingEnum = (SettingEnumerator)setting;
foreach (SettingsProperty prop in Properties.Settings.Default.Properties)
{
if (prop.Name == settingEnum.ToString())
{
Properties.Settings.Default[prop.Name] = value;
return true;
}
}
return false;
}
/// <inheritdoc cref="ICommandService.ReadSettings"/>
public double[] ReadSettings()
{
var settings = Enum.GetValues(typeof(SettingEnumerator)).Cast<SettingEnumerator>();
var values = new double[settings.ToArray().Length];
foreach (SettingEnumerator setting in settings)
{
foreach (SettingsProperty prop in Properties.Settings.Default.Properties)
{
if (prop.Name == setting.ToString())
{
values[(int)setting] = (double)Properties.Settings.Default[setting.ToString()];
}
}
}
return values;
}
/// <inheritdoc cref="ICommandService.StartLogging"/>
public void StartLogging(int interval, bool[] logData)
{
this.logger.StartSpecificDataLogging(interval, logData);
this.SetLoggingState(true);
}
/// <inheritdoc cref="ICommandService.CancelLogging"/>
public void CancelLogging()
{
this.logger.StopSpecificDataLogging();
this.SetLoggingState(false);
}
/// <inheritdoc cref="IDataGet.SubscribeForData"/>>
public void SubscribeForData(int interval, string key)
{
if (!this.dataListeners.ContainsKey(key))
{
IDataGetCallback client =
OperationContext.Current.GetCallbackChannel<IDataGetCallback>();
TimerPackage package = new TimerPackage(key, client, interval);
this.dataListeners.Add(key, new Timer(this.TimerMethod, package, 0, Timeout.Infinite));
}
}
/// <inheritdoc cref="IDataGet.UnsubscribeForData"/>>
public void UnsubscribeForData(string key)
{
if (this.dataListeners.ContainsKey(key))
{
Timer timer = this.dataListeners[key];
timer.Dispose();
this.dataListeners.Remove(key);
}
}
/// <inheritdoc cref="IDataGet.SubscribeForUpdates"/>>
public void SubscribeForUpdates(string key)
{
IDataGetCallback client =
OperationContext.Current.GetCallbackChannel<IDataGetCallback>();
if (!this.updateListeners.ContainsKey(key))
{
this.updateListeners.Add(key, client);
}
}
/// <inheritdoc cref="IDataGet.UnsubscribeForUpdates"/>>
public void UnsubscribeForUpdates(string key)
{
this.updateListeners.Remove(key);
}
/// <inheritdoc cref="ICommandService.IsLogging"/>>
public bool IsLogging()
{
return this.logger.GetSpecificLoggingInProgress();
}
/// <summary>
/// The send log notification.
/// </summary>
/// <param name="message">
/// The message.
/// </param>
public void UpdateNotification(string[] message)
{
foreach (KeyValuePair<string, IDataGetCallback> callback in this.updateListeners)
{
Thread thread = new Thread(() => this.UpdateNotification(callback.Key, callback.Value, message));
thread.Start();
}
}
/// <summary>
/// Determines whether [is registered for data] [the specified key].
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if [is registered for data] [the specified key]; otherwise, <c>false</c>.
/// </returns>
public bool IsRegisteredForData(string key)
{
return this.dataListeners.ContainsKey(key);
}
/// <summary>
/// Determines whether [is registered for updates] [the specified key].
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if [is registered for updates] [the specified key]; otherwise, <c>false</c>.
/// </returns>
public bool IsRegisteredForUpdates(string key)
{
return this.updateListeners.ContainsKey(key);
}
/// <summary>
/// Sets the state of the logging to all clients.
/// </summary>
/// <param name="status">if set to <c>true</c> [status].</param>
private void SetLoggingState(bool status)
{
foreach (KeyValuePair<string, IDataGetCallback> callback in this.updateListeners)
{
Thread thread = new Thread(() => this.SendLoggingState(callback.Key, callback.Value, status));
thread.Start();
}
}
/// <summary>
/// Sends the state of the logging.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="callback">The callback.</param>
/// <param name="status">if set to <c>true</c> [status].</param>
private void SendLoggingState(string key, IDataGetCallback callback, bool status)
{
try
{
callback.SetLoggingState(status);
}
catch
{
this.updateListeners.Remove(key);
}
}
/// <summary>
/// The send log notification.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="callback">The callback.</param>
/// <param name="message">The message.</param>
private void UpdateNotification(string key, IDataGetCallback callback, string[] message)
{
try
{
callback.UpdateNotification(message);
}
catch
{
this.updateListeners.Remove(key);
}
}
/// <summary>
/// Timer method to sent update data to the clients
/// </summary>
/// <param name="state">State should contain TimerPackage</param>
private void TimerMethod(object state)
{
TimerPackage package = (TimerPackage)state;
IDataGetCallback client = package.Callback;
double[] data = this.cryostatControl.ReadData();
try
{
Timer timer = this.dataListeners[package.Key];
client.SendData(data);
client.SendModus(this.GetState());
client.UpdateCountdown(this.cryostatControl.StartTime);
timer.Change(package.WaitTime, Timeout.Infinite);
}
catch
{
if (this.dataListeners.ContainsKey(package.Key))
{
Timer timer = this.dataListeners[package.Key];
this.dataListeners.Remove(package.Key);
timer.Dispose();
}
}
}
#endregion Methods
}
}<file_sep>/CryostatControlServer/HostService/TimerPackage.cs
//-----------------------------------------------------------------------
// <copyright file="TimerPackage.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.HostService
{
/// <summary>
/// Data class to hold the data needed in the Timer, as only one parameter can be sent,
/// the required data needs to be wrapped into a single class.
/// </summary>
public class TimerPackage
{
/// <summary>
/// Initializes a new instance of the <see cref="TimerPackage"/> class.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="callback">The callback.</param>
/// <param name="waitTime">The wait time.</param>
public TimerPackage(string key, IDataGetCallback callback, int waitTime)
{
this.Key = key;
this.Callback = callback;
this.WaitTime = waitTime;
}
/// <summary>
/// Gets or sets the key.
/// </summary>
/// <value>
/// The key.
/// </value>
public string Key { get; set; }
/// <summary>
/// Gets or sets the callback.
/// </summary>
/// <value>
/// The callback.
/// </value>
public IDataGetCallback Callback { get; set; }
/// <summary>
/// Gets or sets the wait time.
/// </summary>
/// <value>
/// The wait time.
/// </value>
public int WaitTime { get; set; }
}
}<file_sep>/CryostatControlServer/HostService/Enumerators/SettingEnumeratorDescription.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SettingEnumeratorDescription.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.HostService.Enumerators
{
/// <summary>
/// The setting descriptions.
/// </summary>
public static class SettingEnumeratorDescription
{
/// <summary>
/// Gets description strings of each setting, matches with settingEnumerator
/// </summary>
/// <value>
/// The description strings.
/// </value>
public static string[] DescriptionStrings
{
get;
}
=
{
//// "He3 pump heater max voltage",
//// "He4 pump heater max voltage",
//// "He4 Switch max voltage",
//// "He3 Switch max voltage",
"He3 heater max power used",
"He4 heater max power used",
"He3 switch voltage used",
"He4 switch voltage used",
"Pump heating start temperature",
"Pump heating temperature setpoint",
"Heatswitch ON temperature",
"Heatswitch safety temperature",
"Heatup cycle heater temperature setpoint",
"He4 adsorption start temperature",
"He3 adsorption start target temperature",
"Disable heater when switches are above",
"He3 adsorption start minimal temperature",
"He3 adsorption maximum wait time",
"Heater power while waiting for switches"
};
/// <summary>
/// Gets a string with the unit of each setting.
/// </summary>
/// <value>
/// The unit strings.
/// </value>
public static string[] UnitStrings
{
get;
}
=
{ "W", "W", "V", "V", "K", "K", "K", "K", "K", "K", "K", "K", "K", "min.", "W" };
}
}
<file_sep>/CryostatControlServer/Controller.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Controller.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer
{
using System;
using System.Threading;
using CryostatControlServer.Logging;
using CryostatControlServer.Properties;
/// <summary>
/// Control class, controls the cryostat using a state machine.
/// </summary>
public partial class Controller
{
/// <summary>
/// The timer period.
/// </summary>
private readonly int timerPeriod = 5000;
/// <summary>
/// The compressor
/// </summary>
private Compressor.Compressor compressor;
/// <summary>
/// The control timer.
/// </summary>
private Timer controlTimer;
/// <summary>
/// The He7 cooler
/// </summary>
private He7Cooler.He7Cooler cooler;
/// <summary>
/// The lakeshore.
/// </summary>
private LakeShore.LakeShore lakeshore;
/// <summary>
/// The start time.
/// </summary>
private DateTime startTime = DateTime.Now;
/// <summary>
/// The state.
/// </summary>
private Controlstate state = Controlstate.Setup;
/// <summary>
/// The time when the current state was entered
/// </summary>
private DateTime stateEnteredTime = DateTime.Now;
/// <summary>
/// Initializes a new instance of the <see cref="Controller"/> class.
/// </summary>
/// <param name="cooler">
/// The cooler.
/// </param>
/// <param name="ls">
/// The Lake Shore instance.
/// </param>
/// <param name="compressor">
/// The compressor.
/// </param>
public Controller(He7Cooler.He7Cooler cooler, LakeShore.LakeShore ls, Compressor.Compressor compressor)
{
this.cooler = cooler;
this.lakeshore = ls;
this.compressor = compressor;
this.StartStateMachine();
}
/// <summary>
/// Finalizes an instance of the <see cref="Controller"/> class.
/// </summary>
~Controller()
{
this.StopStateMachine();
}
/// <summary>
/// Gets or sets the he 3 heater voltage.
/// </summary>
/// <value>
/// The he3 heater power.
/// </value>
public double He3HeaterPower
{
get
{
return Settings.Default.ControllerHe3HeaterPower;
}
set
{
Settings.Default.ControllerHe3HeaterPower = value;
}
}
/// <summary>
/// Gets or sets the he 3 switch voltage.
/// </summary>
/// <value>
/// The he3 switch voltage.
/// </value>
public double He3SwitchVoltage
{
get
{
return Settings.Default.ControllerHe3SwitchVoltage;
}
set
{
Settings.Default.ControllerHe3SwitchVoltage = value;
}
}
/// <summary>
/// Gets or sets the he 4 heater voltage.
/// </summary>
/// <value>
/// The he4 heater power.
/// </value>
public double He4HeaterPower
{
get
{
return Settings.Default.ControllerHe4HeaterPower;
}
set
{
Settings.Default.ControllerHe4HeaterPower = value;
}
}
/// <summary>
/// Gets or sets the he 4 start temperature.
/// </summary>
/// <value>
/// The he4 start temperature.
/// </value>
public double He4StartTemperature
{
get
{
return Settings.Default.ControllerHe4StartTemperature;
}
set
{
Settings.Default.ControllerHe4StartTemperature = value;
}
}
/// <summary>
/// Gets or sets the he 4 switch voltage.
/// </summary>
/// <value>
/// The he4 switch voltage.
/// </value>
public double He4SwitchVoltage
{
get
{
return Settings.Default.ControllerHe4SwitchVoltage;
}
set
{
Settings.Default.ControllerHe4SwitchVoltage = value;
}
}
/// <summary>
/// Gets or sets the he 7 start temperature.
/// </summary>
/// <value>
/// The he7 start temperature.
/// </value>
public double He7StartTemperature
{
get
{
return Settings.Default.ControllerHe7StartTemperature;
}
set
{
Settings.Default.ControllerHe7StartTemperature = value;
}
}
/// <summary>
/// Gets or sets the heater temperature set point.
/// </summary>
/// <value>
/// The heater temperature setpoint.
/// </value>
public double HeaterTemperatureSetpoint
{
get
{
return Settings.Default.ControllerHeaterTemperatureSetpoint;
}
set
{
Settings.Default.ControllerHeaterTemperatureSetpoint = value;
}
}
/// <summary>
/// Gets or sets the heat switch on temperature.
/// </summary>
/// <value>
/// The heat switch on temperature.
/// </value>
public double HeatSwitchOnTemperature
{
get
{
return Settings.Default.ControllerHeatSwitchOnTemperature;
}
set
{
Settings.Default.ControllerHeatSwitchOnTemperature = value;
}
}
/// <summary>
/// Gets or sets the heat switch safe value.
/// </summary>
/// <value>
/// The heat switch safe value.
/// </value>
public double HeatSwitchSafeValue
{
get
{
return Settings.Default.ControllerHeatSwitchSafeValue;
}
set
{
Settings.Default.ControllerHeatSwitchSafeValue = value;
}
}
/// <summary>
/// Gets or sets the heat up temperature.
/// </summary>
/// <value>
/// The heatup temperature.
/// </value>
public double HeatupTemperature
{
get
{
return Settings.Default.ControllerHeatupTemperature;
}
set
{
Settings.Default.ControllerHeatupTemperature = value;
}
}
/// <summary>
/// Gets the start time.
/// </summary>
/// <value>
/// The start time.
/// </value>
public DateTime StartTime
{
get
{
return this.startTime;
}
}
/// <summary>
/// Gets the state.
/// </summary>
/// <value>
/// The state.
/// </value>
public Controlstate State
{
get
{
return this.state;
}
private set
{
string message = "[Control] Switched from state " + this.state + " to " + value;
DebugLogger.Info(this.GetType().Name, message);
this.stateEnteredTime = DateTime.Now;
this.state = value;
}
}
/// <summary>
/// Gets or sets the disable heater heat switch temperature.
/// </summary>
/// <value>
/// The disable heater heat switch temperature.
/// </value>
private double DisableHeaterHeatSwitchTemperature
{
get
{
return Settings.Default.ControllerDisableHeaterHeatSwitchTemperature;
}
set
{
Settings.Default.ControllerDisableHeaterHeatSwitchTemperature = value;
}
}
/// <summary>
/// Gets or sets the he 3 start temperature.
/// </summary>
/// <value>
/// The he3 start minimal temperature.
/// </value>
private double He3StartMinimalTemperature
{
get
{
return Settings.Default.ControllerHe3StartMinimalTemperature;
}
set
{
Settings.Default.ControllerHe3StartMinimalTemperature = value;
}
}
/// <summary>
/// Gets or sets the he 3 start temperature.
/// </summary>
/// <value>
/// The he3 start temperature.
/// </value>
private double He3StartTemperature
{
get
{
return Settings.Default.ControllerHe3StartTemperature;
}
set
{
Settings.Default.ControllerHe3StartTemperature = value;
}
}
/// <summary>
/// Gets or sets the he 3 start temperature.
/// </summary>
/// <value>
/// The he3 start wait time minutes.
/// </value>
private double He3StartWaitTimeMinutes
{
get
{
return Settings.Default.ControllerHe3StartWaitTimeMinutes;
}
set
{
Settings.Default.ControllerHe3StartWaitTimeMinutes = value;
}
}
/// <summary>
/// Cancels the current command safely.
/// </summary>
public void CancelCommand()
{
this.State = Controlstate.Cancel;
}
/// <summary>
/// The stop command.
/// </summary>
public void StopCommand()
{
this.state = Controlstate.Stop;
}
/// <summary>
/// Starts the cool down id possible.
/// </summary>
/// <param name="time">The time.</param>
/// <returns>
/// true if cool down is started, false otherwise
/// </returns>
public bool StartCooldown(DateTime time)
{
if (this.State == Controlstate.Standby)
{
this.startTime = time;
this.State = Controlstate.CooldownStart;
Console.WriteLine($"Starting cooldown at: {time}");
return true;
}
return false;
}
/// <summary>
/// Starts the heat up.
/// </summary>
/// <param name="time">The time.</param>
/// <returns>
/// true if heat up is started, false otherwise
/// </returns>
public bool StartHeatup(DateTime time)
{
if (this.State == Controlstate.Standby)
{
this.startTime = time;
this.State = Controlstate.WarmupStart;
return true;
}
return false;
}
/// <summary>
/// Switch to manual control. Can only be started from Standby.
/// </summary>
/// <returns>
/// true if switched to manual control, false otherwise <see cref="bool"/>.
/// </returns>
public bool StartManualControl()
{
if (this.State == Controlstate.Standby)
{
this.State = Controlstate.Manual;
return true;
}
return false;
}
/// <summary>
/// Starts a recycle.
/// </summary>
/// <param name="time">The time.</param>
/// <returns>
/// true if recycle is started, false otherwise
/// </returns>
public bool StartRecycle(DateTime time)
{
if (this.State == Controlstate.Standby)
{
this.startTime = time;
this.State = Controlstate.RecycleStart;
return true;
}
return false;
}
/// <summary>
/// Controls the he3 pump heater.
/// </summary>
private void ControlHe3PumpHeater()
{
if (this.cooler.He3SwitchT.Value < this.DisableHeaterHeatSwitchTemperature)
{
this.SetHeaterTemperature(this.cooler.He3Pump, this.HeaterTemperatureSetpoint, this.He3HeaterPower);
}
else
{
this.SetHeaterVoltage(this.cooler.He3Pump, 0.0);
}
}
/// <summary>
/// Controls the he4 pump heater.
/// </summary>
private void ControlHe4PumpHeater()
{
if (this.cooler.He4SwitchT.Value < this.DisableHeaterHeatSwitchTemperature)
{
this.SetHeaterTemperature(this.cooler.He4Pump, this.HeaterTemperatureSetpoint, this.He4HeaterPower);
}
else
{
this.SetHeaterVoltage(this.cooler.He4Pump, 0.0);
}
}
/// <summary>
/// The reset all values.
/// </summary>
private void ResetAllValues()
{
this.SetHeaterVoltage(this.cooler.He3Pump, 0.0);
this.SetHeaterVoltage(this.cooler.He4Pump, 0.0);
// Keep switches and compressor on if cold, turn off otherwise.
if (this.cooler.Plate4KT.Value < this.HeatSwitchSafeValue)
{
this.cooler.He3Switch.Voltage = this.He3SwitchVoltage;
this.cooler.He4Switch.Voltage = this.He4SwitchVoltage;
}
else
{
this.SetHeaterVoltage(this.cooler.He3Switch, 0.0);
this.SetHeaterVoltage(this.cooler.He4Switch, 0.0);
}
}
/// <summary>
/// Checks if the heat switches are allowed to be turned on.
/// If the cooler temperature is too high, the heaters are turned off.
/// </summary>
private void SafetyCheckHeatSwitch()
{
if (this.cooler.Plate4KT.Value > this.HeatSwitchSafeValue && this.cooler.He4Switch.Voltage > 0.2)
{
this.SetHeaterVoltage(this.cooler.He4Switch, 0.0);
}
if (this.cooler.Plate4KT.Value > this.HeatSwitchSafeValue && this.cooler.He3Switch.Voltage > 0.2)
{
this.SetHeaterVoltage(this.cooler.He3Switch, 0.0);
}
}
/// <summary>
/// Safety check of the pump heaters.
/// If the cooler is to warm, the heaters are turned off
/// </summary>
private void SafetyCheckPumps()
{
if ((this.cooler.Plate4KT.Value > 100.0 || this.cooler.He3PumpT.Value > 150.0)
&& this.cooler.He3Pump.Voltage > 0.1)
{
this.SetHeaterVoltage(this.cooler.He3Pump, 0.0);
}
if ((this.cooler.Plate4KT.Value > 100.0 || this.cooler.He4PumpT.Value > 150.0)
&& this.cooler.He4Pump.Voltage > 0.1)
{
this.SetHeaterVoltage(this.cooler.He4Pump, 0.0);
}
}
/// <summary>
/// Set a heater to temperature control with temperature and power settings.
/// </summary>
/// <param name="heater">
/// The heater.
/// </param>
/// <param name="temperature">
/// The temperature.
/// </param>
/// <param name="maxpower">
/// The maximum power.
/// </param>
private void SetHeaterTemperature(He7Cooler.He7Cooler.Heater heater, double temperature, double maxpower)
{
heater.TemperatureSetpoint = temperature;
try
{
heater.PowerLimit = maxpower;
heater.TemperatureControlEnabled = true;
}
catch (ArgumentOutOfRangeException e)
{
DebugLogger.Error("heater", e.Message, true);
DebugLogger.Error("Controller", "Tried to set too high power setting to heater!, not heating!", true);
}
}
/// <summary>
/// The set heater voltage capturing any errors.
/// </summary>
/// <param name="heater">
/// The heater.
/// </param>
/// <param name="voltage">
/// The voltage.
/// </param>
private void SetHeaterVoltage(He7Cooler.He7Cooler.Heater heater, double voltage)
{
try
{
heater.TemperatureControlEnabled = false;
heater.Voltage = voltage;
}
catch (Exception ex)
{
DebugLogger.Error(this.GetType().Name, "Error while setting heater: " + ex.Message);
}
}
/// <summary>
/// Start the thread running the state machine.
/// </summary>
private void StartStateMachine()
{
this.controlTimer = new Timer(timerState => this.StateMachine(), null, 0, this.timerPeriod);
}
/// <summary>
/// Stop the thread running the state machine.
/// </summary>
private void StopStateMachine()
{
this.controlTimer.Dispose();
}
}
}<file_sep>/CryostatControlServer/Streams/ManagedTcpStream.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ManagedTcpStream.cs" company="SRON">
// blabla copyright.
// </copyright>
// <author><NAME></author>
// <summary>
// ManagedStream
// ManagedStream is a standerdized class to communicate to a TCP or Serial Port. It tries to handle as many common issues as possible.
// Methods are not re-entrant, since most devices are neither. THe code calling methods in this class should take care to only issue one command at the time.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Streams
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Sockets;
/// <summary>
/// ManagedStream
/// ManagedStream is a standardized class to communicate to a TCP or Serial Port. It tries to handle as many common issues as possible.
/// Methods are not re-entrant, since most devices are neither. THe code calling methods in this class should take care to only issue one command at the time.
/// </summary>
public class ManagedTcpStream : BaseManagedStream
{
/// <summary>
/// The port.
/// </summary>
private readonly int port;
/// <summary>
/// The TCP client.
/// </summary>
private readonly TcpClient tcpClient = new TcpClient();
/// <summary>
/// The TCP timeout.
/// </summary>
private readonly TimeSpan tcpTimeout = TimeSpan.FromMilliseconds(5000);
/// <summary>
/// The IP.
/// </summary>
private string ip;
/// <summary>
/// Initializes a new instance of the <see cref="ManagedTcpStream"/> class.
/// </summary>
/// <param name="ip">
/// The IP.
/// </param>
/// <param name="port">
/// The port.
/// </param>
public ManagedTcpStream(string ip, int port)
{
this.ip = ip;
this.port = port;
}
/// <summary>
/// Closes the connection.
/// </summary>
public override void Close()
{
this.ContainedStream.Flush();
this.tcpClient.Close();
return;
}
/// <summary>
/// Determines whether this instance is connected.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is connected; otherwise, <c>false</c>.
/// </returns>
public override bool IsConnected()
{
return this.tcpClient.Connected;
}
/// <summary>
/// Connect to a (remote) TCP port.
/// Must be called before calling any other method.
/// </summary>
/// <exception cref="System.TimeoutException">TCP Connection timed out</exception>
[SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1650:ElementDocumentationMustBeSpelledCorrectly",
Justification = "Reviewed. Suppression is OK here.")]
public override void Open()
{
var connectTask = this.tcpClient.ConnectAsync(IPAddress.Parse(this.ip), this.port);
Console.WriteLine("Connecting to port...");
if (!connectTask.Wait(this.tcpTimeout))
{
throw new TimeoutException("TCP Connection timed out");
}
this.tcpClient.SendTimeout = (int)this.tcpTimeout.TotalMilliseconds;
this.tcpClient.ReceiveTimeout = (int)this.tcpTimeout.TotalMilliseconds;
this.ContainedStream = this.tcpClient.GetStream();
this.Init();
}
}
}<file_sep>/CryostatControlServer/He7Cooler/Heater.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Heater.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.He7Cooler
{
using System;
using System.Diagnostics.CodeAnalysis;
using CryostatControlServer.Logging;
/// <summary>
/// The he 7 cooler.
/// </summary>
public partial class He7Cooler
{
/// <summary>
/// Representation a heater element on the H7 cooler.
/// </summary>
public class Heater
{
/// <summary>
/// The default safe range high.
/// </summary>
private const double DefaultSafeRangeHigh = 10.0;
/// <summary>
/// The default safe range low.
/// </summary>
private const double DefaultSafeRangeLow = 0.0;
/// <summary>
/// The max value of the integrator.
/// </summary>
private const double IntegratorMax = 0.15 / Ki;
/// <summary>
/// The derivative gain.
/// </summary>
private const double Kd = 0.5;
/// <summary>
/// The integral gain.
/// </summary>
private const double Ki = 0.004;
/// <summary>
/// The proportional gain.
/// </summary>
private const double Kp = 0.18;
/// <summary>
/// The resistance of the heater resistor.
/// </summary>
private readonly double resistance = 1;
/// <summary>
/// The amplifier calibration. converts from post amplification to pre-amplification.
/// </summary>
private Calibration calibration;
/// <summary>
/// The H7 cooler device.
/// </summary>
private He7Cooler device;
/// <summary>
/// The filter factor.
/// </summary>
private double filterFactor = 0.50;
/// <summary>
/// The channel where current voltage is read.
/// </summary>
private Channels inchannel;
/// <summary>
/// The PID controller integrator.
/// </summary>
private double integrator = 0;
/// <summary>
/// The channel where to output the voltage set point.
/// </summary>
private Channels outchannel;
/// <summary>
/// The power limit
/// </summary>
private double powerLimit;
/// <summary>
/// The previous error used for the PID controller.
/// </summary>
private double previousError = 0.0;
/// <summary>
/// The previous derivative
/// </summary>
private double previousDerivative = 0.0;
/// <summary>
/// The previous loop time.
/// </summary>
private DateTime previousLoopTime = DateTime.MinValue;
/// <summary>
/// The temperature feedback sensor
/// </summary>
private Sensor temperatureFeedback;
/// <summary>
/// The temperature setpoint
/// </summary>
private double temperatureSetpoint;
private bool temperatureControlEnabled = false;
/// <summary>
/// Initializes a new instance of the <see cref="Heater"/> class.
/// </summary>
/// <param name="outputChannel">
/// The voltage output channel.
/// </param>
/// <param name="inputChannel">
/// The voltage input channel.
/// </param>
/// <param name="device">
/// The He7 cooler device the heater is connected to.
/// </param>
public Heater(Channels outputChannel, Channels inputChannel, He7Cooler device)
{
this.inchannel = inputChannel;
this.outchannel = outputChannel;
this.device = device;
device.AddChannel(inputChannel);
this.SafeRangeHigh = DefaultSafeRangeHigh;
this.SafeRangeLow = DefaultSafeRangeLow;
this.calibration = new Calibration();
}
/// <summary>
/// Initializes a new instance of the <see cref="Heater"/> class.
/// </summary>
/// <param name="outputChannel">
/// The voltage output channel.
/// </param>
/// <param name="inputChannel">
/// The voltage input channel.
/// </param>
/// <param name="temperatureFeedbackSensor">
/// Temperature sensor used for feedback
/// </param>
/// <param name="resistance">
/// The resistance.
/// </param>
/// <param name="outputCalibration">
/// The output Calibration.
/// </param>
/// <param name="device">
/// The He7 cooler device the heater is connected to.
/// </param>
public Heater(
Channels outputChannel,
Channels inputChannel,
Sensor temperatureFeedbackSensor,
double resistance,
Calibration outputCalibration,
He7Cooler device)
{
this.inchannel = inputChannel;
this.outchannel = outputChannel;
this.device = device;
device.AddChannel(inputChannel);
this.SafeRangeHigh = DefaultSafeRangeHigh;
this.SafeRangeLow = DefaultSafeRangeLow;
this.temperatureFeedback = temperatureFeedbackSensor;
this.resistance = resistance;
this.calibration = outputCalibration;
device.AddHeater(this);
}
/// <summary>
/// Finalizes an instance of the <see cref="Heater" /> class.
/// </summary>
~Heater()
{
this.device.RemoveChannel(this.inchannel);
}
/// <summary>
/// Gets or sets the current.
/// </summary>
/// <value>
/// The current.
/// </value>
public double Current
{
get
{
return this.Voltage / this.resistance;
}
set
{
this.Voltage = value * this.resistance;
}
}
/// <summary>
/// Gets or sets the power.
/// </summary>
/// <value>
/// The power.
/// </value>
public double Power
{
get
{
return this.VoltageToPower(this.Voltage);
}
set
{
this.Voltage = this.PowerToVoltage(value);
}
}
/// <summary>
/// Gets or sets the power limit in Watt.
/// </summary>
/// <value>
/// The power limit.
/// </value>
/// <exception cref="System.ArgumentOutOfRangeException">Argument out of range exception</exception>
public double PowerLimit
{
get
{
return this.powerLimit;
}
set
{
if (this.SafeRangeHigh < this.calibration.ConvertValue(this.PowerToVoltage(value)))
{
throw new ArgumentOutOfRangeException(
$"maxPower {value} -> voltage {this.calibration.ConvertValue(this.PowerToVoltage(value))} exeeds the safety limit {this.SafeRangeHigh} of this heater.");
}
this.powerLimit = value;
}
}
/// <summary>
/// Gets or sets the voltage safe range high side.
/// </summary>
/// <value>
/// The safe range high.
/// </value>
public double SafeRangeHigh { get; set; }
/// <summary>
/// Gets or sets the voltage safe range low side.
/// </summary>
/// <value>
/// The safe range low.
/// </value>
public double SafeRangeLow { get; set; }
/// <summary>
/// Gets or sets a value indicating whether temperature control enabled.
/// </summary>
public bool TemperatureControlEnabled
{
get
{
return this.temperatureControlEnabled;
}
set
{
if (this.temperatureControlEnabled == false && value == true)
{
this.integrator = 0;
this.previousError = double.NaN;
this.previousDerivative = double.NaN;
}
this.temperatureControlEnabled = value;
}
}
/// <summary>
/// Gets or sets the temperature setpoint in Kelvin.
/// </summary>
/// <value>
/// The temperature setpoint.
/// </value>
public double TemperatureSetpoint
{
get
{
return this.temperatureSetpoint;
}
set
{
this.temperatureSetpoint = value;
}
}
/// <summary>
/// Gets or sets the voltage of the heater.
/// </summary>
/// <value>
/// The voltage.
/// </value>
public double Voltage
{
get
{
return this.device.values[this.inchannel];
}
set
{
if (!this.TemperatureControlEnabled)
{
this.SetOutput(this.calibration.ConvertValue(value));
}
}
}
/// <summary>
/// The control temperature loop function.
/// </summary>
/// <param name="TSet">
/// The t set.
/// </param>
/// <param name="maxPower">
/// The maxPower.
/// </param>
[SuppressMessage(
"StyleCop.CSharp.NamingRules",
"SA1306:FieldNamesMustBeginWithLowerCaseLetter",
Justification = "Reviewed. Suppression is OK here.")]
public void ControlTemperature(double TSet, double maxPower)
{
double error = TSet - this.temperatureFeedback.Value; // Positive if too cold
var deltaError = this.CalculateDerivative(error);
var P = error * Heater.Kp;
var I = this.integrator * Heater.Ki;
var D = this.CalculateDerivative(error) * Heater.Kd;
double output = P + I + D;
try
{
if (output > maxPower)
{
this.SetOutput(this.calibration.ConvertValue(this.PowerToVoltage(maxPower)));
this.integrator = 0;
}
else if (output < 0)
{
this.SetOutput(0);
this.integrator = Math.Max(error + this.integrator, 0);
}
else
{
this.SetOutput(this.calibration.ConvertValue(this.PowerToVoltage(output)));
this.integrator = Math.Min(error + this.integrator, Heater.IntegratorMax);
}
}
catch (Exception e)
{
DebugLogger.Error("Heater", e.ToString(), false);
}
}
/// <summary>
/// Calculate the filtered derivative
/// </summary>
/// <param name="error">The error.</param>
/// <returns>The filtered value</returns>
private double CalculateDerivative(double error)
{
if (double.IsNaN(this.previousError))
{
this.previousError = error;
}
var dt = Math.Max((DateTime.Now - this.previousLoopTime).TotalSeconds, 1.0);
var dedt = ((error - this.previousError) / dt);
if (double.IsNaN(this.previousDerivative))
{
this.previousDerivative = dedt;
}
this.previousDerivative = (this.filterFactor * this.previousDerivative) + ((1 - this.filterFactor) * dedt);
this.previousError = error;
this.previousLoopTime = DateTime.Now;
return this.previousDerivative;
}
/// <summary>
/// Notify the heater it has received new measurements.
/// </summary>
public void Notify()
{
if (this.TemperatureControlEnabled)
{
this.ControlTemperature(this.TemperatureSetpoint, this.PowerLimit);
}
}
/// <summary>
/// Convert power to voltage using the heater resistance.
/// </summary>
/// <param name="power">
/// The power.
/// </param>
/// <returns>
/// The <see cref="double"/>.
/// </returns>
private double PowerToVoltage(double power)
{
return Math.Sqrt(power * this.resistance);
}
/// <summary>
/// The set output.
/// </summary>
/// <param name="volts">
/// The volts.
/// </param>
private void SetOutput(double volts)
{
if (volts > this.SafeRangeHigh || volts < this.SafeRangeLow)
{
DebugLogger.Error(
this.GetType().Name,
$"Voltage setpoint of {volts} is out of the safe range from {this.SafeRangeLow} to {this.SafeRangeHigh}");
throw new ArgumentOutOfRangeException(
$"Voltage setpoint of {volts} is out of the safe range from {this.SafeRangeLow} to {this.SafeRangeHigh}");
}
this.device.SetVoltage(this.outchannel, volts);
}
/// <summary>
/// Convert voltage to power using the heater resistance.
/// </summary>
/// <param name="voltage">
/// The voltage.
/// </param>
/// <returns>
/// The <see cref="double"/>.
/// </returns>
private double VoltageToPower(double voltage)
{
return voltage * voltage / this.resistance;
}
}
}
}<file_sep>/CryostatControlServer/He7Cooler/AgilentException.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AgilentException.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.He7Cooler
{
using CryostatControlServer.Logging;
/// <summary>
/// The agilent exception.
/// Thrown when there is an error in communication with the Agilent, or an internal error in the device occurred
/// </summary>
public class AgilentException : System.Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="AgilentException"/> class.
/// </summary>
public AgilentException() : base("generic agilent error")
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AgilentException"/> class.
/// </summary>
/// <param name="description">
/// The description.
/// </param>
public AgilentException(string description)
: base(description)
{
DebugLogger.Error(this.GetType().Name, this.GetType().Name + ": " + description);
}
/// <summary>
/// Initializes a new instance of the <see cref="AgilentException"/> class.
/// </summary>
/// <param name="description">
/// The description.
/// </param>
/// <param name="innerException">
/// The inner exception.
/// </param>
public AgilentException(string description, System.Exception innerException)
: base(description, innerException)
{
}
}
}
<file_sep>/CryostatControlClient/Models/MessageBoxModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MessageBoxModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Models
{
using System.Collections.ObjectModel;
/// <summary>
/// The message box model.
/// </summary>
public class MessageBoxModel
{
/// <summary>
/// Gets or sets the message.
/// </summary>
/// <value>
/// The message.
/// </value>
public string[] Message { get; set; }
/// <summary>
/// Gets or sets the notifications.
/// </summary>
/// <value>
/// The notifications.
/// </value>
public ObservableCollection<Notification> Notifications { get; set; }
}
}
<file_sep>/CryostatControlServer/DebugForm.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DebugForm.cs" company="SRON">
// All rights reserved
// </copyright>
// <summary>
// Defines the DebugForm type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer
{
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
/// <summary>
/// The debug form.
/// </summary>
public partial class DebugForm : Form
{
/// <summary>
/// Initializes a new instance of the <see cref="DebugForm"/> class.
/// </summary>
public DebugForm()
{
this.InitializeComponent();
}
/// <summary>
/// Override on form closing to prevent disposing of the form.
/// </summary>
/// <param name="e">
/// The e.
/// </param>
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown)
{
return;
}
this.Hide();
e.Cancel = true;
}
/// <summary>
/// The debug form load.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
private void DebugFormLoad(object sender, EventArgs e)
{
Console.SetOut(new ControlWriter(this.textBox1));
}
/// <summary>
/// The control writer.
/// </summary>
private class ControlWriter : TextWriter
{
/// <summary>
/// The buffer.
/// </summary>
private string buffer = string.Empty;
/// <summary>
/// The textbox.
/// </summary>
private Control textbox;
/// <summary>
/// Initializes a new instance of the <see cref="ControlWriter"/> class.
/// </summary>
/// <param name="textbox">
/// The textbox.
/// </param>
public ControlWriter(Control textbox)
{
this.textbox = textbox;
}
/// <summary>
/// Gets the encoding.
/// </summary>
public override Encoding Encoding
{
get
{
return Encoding.ASCII;
}
}
/// <summary>
/// Write a char to the textbox.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
public override void Write(char value)
{
this.buffer += value;
if (value == '\n' || value == '\r')
{
var buffercopy = this.buffer.Clone();
this.textbox.BeginInvoke(new Action(() => { this.textbox.Text = buffercopy + this.textbox.Text; }));
this.buffer = string.Empty;
}
}
/// <summary>
/// Write a string to the textbox
/// </summary>
/// <param name="value">
/// The value.
/// </param>
public override void Write(string value)
{
this.textbox.BeginInvoke(new Action(() => { this.textbox.Text = value + this.textbox.Text; }));
}
}
}
}<file_sep>/CryostatControlServerTests/Logging/LogThreaderTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CryostatControlServerTests.Logging
{
using CryostatControlServer.Data;
using CryostatControlServer.Logging;
using Moq;
[TestClass]
public class LogThreaderTest
{
[TestMethod]
public void ConvertSecondsToMsTest()
{
LogThreader logThreader = new LogThreader(null, null);
Assert.AreEqual(1000, logThreader.ConvertSecondsToMs(1));
}
[TestMethod]
public void NewFileIsNeededFalseTest()
{
LogThreader logThreader = new LogThreader(null, null);
DateTime today = DateTime.Now;
string filePath = @"c\CryostatLogging\General\" + today.Year + @"\" + today.Month + @"\"
+ today.Day + ".csv";
Assert.IsFalse(logThreader.NewFileIsNeeded(filePath));
}
[TestMethod]
public void NewFileIsNeededTrueTest()
{
LogThreader logThreader = new LogThreader(null, null);
DateTime tomorrow = DateTime.Now.AddDays(1);
string filePath = @"c\CryostatLogging\General\" + tomorrow.Year + @"\" + tomorrow.Month + @"\"
+ tomorrow.Day + ".csv";
Assert.IsTrue(logThreader.NewFileIsNeeded(filePath));
}
[TestMethod]
public void NewFileIsNeededNoExtensionTest()
{
LogThreader logThreader = new LogThreader(null, null);
DateTime tomorrow = DateTime.Now.AddDays(1);
string filePath = @"c\CryostatLogging\General\" + tomorrow.Year + @"\" + tomorrow.Month + @"\"
+ tomorrow.Day;
Assert.IsFalse(logThreader.NewFileIsNeeded(filePath));
}
[TestMethod]
public void NewFileIsNeededNullFileTest()
{
LogThreader logThreader = new LogThreader(null, null);
string filePath = null;
Assert.IsFalse(logThreader.NewFileIsNeeded(filePath));
}
}
}
<file_sep>/CryostatControlServer/Compressor/Enumerators/ErrorEnum.cs
//-----------------------------------------------------------------------
// <copyright file="ErrorEnum.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.Compressor
{
/// <summary>
/// Enumerator for Error states.
/// </summary>
public enum ErrorEnum
{
/// <summary>
/// No errors
/// </summary>
NoErrors = 0,
/// <summary>
/// Coolant in has a too high temperature
/// </summary>
CoolantInHigh = -1,
/// <summary>
/// The coolant in has a too low temperature
/// </summary>
CoolantInLow = -2,
/// <summary>
/// The coolant out has a too high temperature
/// </summary>
CoolantOutHigh = -4,
/// <summary>
/// The coolant out has a too low to temperature
/// </summary>
CoolantOutLow = -8,
/// <summary>
/// The oil temperature is too high
/// </summary>
OilHigh = -16,
/// <summary>
/// The oil temperature is too low
/// </summary>
OilLow = -32,
/// <summary>
/// The helium temperature is too high
/// </summary>
HeliumHigh = -64,
/// <summary>
/// The helium temperature is too low
/// </summary>
HeliumLow = -128,
/// <summary>
/// The low pressure is too high
/// </summary>
LowPressureHigh = -256,
/// <summary>
/// The low pressure it too low
/// </summary>
LowPressureLow = -512,
/// <summary>
/// The high pressure is too high
/// </summary>
HighPressureHigh = -1024,
/// <summary>
/// The high pressure is too low
/// </summary>
HighPressureLow = -2048,
/// <summary>
/// The delta pressure is too high
/// </summary>
DeltaPressureHigh = -4096,
/// <summary>
/// The delta pressure is too low
/// </summary>
DeltaPressureLow = -8192,
/// <summary>
/// The motor current is too low
/// </summary>
MotorCurrentLow = -16384,
/// <summary>
/// The three phase error
/// </summary>
ThreePhaseError = -32768,
/// <summary>
/// The power supply error
/// </summary>
PowerSupplyError = -65536,
/// <summary>
/// The static pressure is too high
/// </summary>
StaticPressureHigh = -131072,
/// <summary>
/// The static pressure is too low
/// </summary>
StaticPressureLow = -262144
}
}<file_sep>/CryostatControlServer/He7Cooler/Channels.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Channels.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.He7Cooler
{
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// used DAQ channels.
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1602:EnumerationItemsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.")]
public enum Channels
{
// Temperature sensors
SensHe3PumpT = 101,
Sens2KplateT = 104,
Sens4KplateT = 105,
SensHe3HeadT = 107,
SensHe4PumpT = 106,
SensHe4SwitchT = 102,
SensHe3SwitchT = 103,
SensHe4HeadT = 108,
// Heater sensors
SensHe3Pump = 110,
SensHe4Switch = 111,
SensHe3Switch = 112,
SensHe4Pump = 109,
// Digital Channel
CtrlDigOut = 201,
// Heaters
PumpHe3 = 204,
PumpHe4 = 205,
SwitchHe3 = 305,
SwitchHe4 = 304,
}
}<file_sep>/CryostatControlServer/He7Cooler/He7Cooler.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="He7Cooler.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.He7Cooler
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using CryostatControlServer.Logging;
using CryostatControlServer.Properties;
/// <summary>
/// He7 Cooler class.
/// Represents the He7 cooler controls. Read and set voltages and digital bits.
/// </summary>
public partial class He7Cooler
{
/// <summary>
/// The interval between voltage samples
/// </summary>
private const int ReadInterval = 1000;
/// <summary>
/// The connected device.
/// </summary>
private Agilent34972A device = new Agilent34972A();
/// <summary>
/// The internet protocol
/// </summary>
private string ip = string.Empty;
/// <summary>
/// Is the sampling of voltages started.
/// </summary>
private bool isStarted = false;
/// <summary>
/// The amount of sensor readers per channel.
/// </summary>
private Dictionary<Channels, int> readersPerChannel = new Dictionary<Channels, int>();
/// <summary>
/// The thread reading voltages.
/// </summary>
private Thread readThread;
/// <summary>
/// The current voltage of each channel.
/// </summary>
private Dictionary<Channels, double> values = new Dictionary<Channels, double>();
/// <summary>
/// The heaters.
/// </summary>
private List<Heater> heaters = new List<Heater>();
/// <summary>
/// Initializes a new instance of the <see cref="He7Cooler"/> class.
/// </summary>
public He7Cooler()
{
Calibration he3Calibration = Calibration.He3Calibration;
Calibration he4Calibration = Calibration.He4Calibration;
Calibration diodeCalibration = Calibration.DiodeCalibration;
this.He3PumpT = new Sensor(Channels.SensHe3PumpT, this, diodeCalibration);
this.He4PumpT = new Sensor(Channels.SensHe4PumpT, this, diodeCalibration);
this.He4SwitchT = new Sensor(Channels.SensHe4SwitchT, this, diodeCalibration);
this.He3SwitchT = new Sensor(Channels.SensHe3SwitchT, this, diodeCalibration);
this.Plate4KT = new Sensor(Channels.Sens4KplateT, this, diodeCalibration);
this.Plate2KT = new Sensor(Channels.Sens2KplateT, this, diodeCalibration);
this.He4HeadT = new Sensor(Channels.SensHe4HeadT, this, he4Calibration);
this.He3HeadT = new Sensor(Channels.SensHe3HeadT, this, he3Calibration);
this.He3Pump = new Heater(Channels.PumpHe3, Channels.SensHe3Pump, this.He3PumpT, 400, Calibration.He3AmplifierCalibration, this);
this.He4Pump = new Heater(Channels.PumpHe4, Channels.SensHe4Pump, this.He4PumpT, 200, Calibration.He4AmplifierCalibration, this);
this.He3Switch = new Heater(Channels.SwitchHe3, Channels.SensHe3Switch, this);
this.He4Switch = new Heater(Channels.SwitchHe4, Channels.SensHe4Switch, this);
this.He3Pump.SafeRangeHigh = Settings.Default.He3PumpMaxVoltage;
this.He4Pump.SafeRangeHigh = Settings.Default.He4PumpMaxVoltage;
this.He4Switch.SafeRangeHigh = Settings.Default.He4SwitchMaxVoltage;
this.He3Switch.SafeRangeHigh = Settings.Default.He3SwitchMaxVoltage;
}
/// <summary>
/// Gets the he 3 head temperature sensor.
/// </summary>
public Sensor He3HeadT { get; private set; }
/// <summary>
/// Gets the he 3 pump.
/// </summary>
public Heater He3Pump { get; private set; }
/// <summary>
/// Gets the he 3 pump temperature sensor.
/// </summary>
public Sensor He3PumpT { get; private set; }
/// <summary>
/// Gets the he 3 switch.
/// </summary>
public Heater He3Switch { get; private set; }
/// <summary>
/// Gets the he 3 switch temperature sensor.
/// </summary>
public Sensor He3SwitchT { get; private set; }
/// <summary>
/// Gets the he 4 head temperature sensor.
/// </summary>
public Sensor He4HeadT { get; private set; }
/// <summary>
/// Gets the he 4 pump.
/// </summary>
public Heater He4Pump { get; private set; }
/// <summary>
/// Gets the he 4 pump temperature sensor.
/// </summary>
public Sensor He4PumpT { get; private set; }
/// <summary>
/// Gets the he 4 switch.
/// </summary>
public Heater He4Switch { get; private set; }
/// <summary>
/// Gets the he 4 switch temperature sensor.
/// </summary>
public Sensor He4SwitchT { get; private set; }
/// <summary>
/// Gets the plate 2k temperature sensor.
/// </summary>
public Sensor Plate2KT { get; private set; }
/// <summary>
/// Gets the plate 4k temperature sensor.
/// </summary>
public Sensor Plate4KT { get; private set; }
/// <summary>
/// Connect to the Agilent device.
/// </summary>
/// <param name="ip">
/// The IP to connect to.
/// </param>
public void Connect(string ip)
{
this.ip = ip;
this.device.Init(ip);
this.isStarted = true;
this.readThread = new Thread(this.MainLoop);
this.readThread.Start();
}
/// <summary>
/// Connect using an already initialized Agilent device.
/// Used for testing.
/// </summary>
/// <param name="device">
/// The initialized device.
/// </param>
/// <param name="startReading">
/// The start Reading.
/// </param>
public void Connect(Agilent34972A device, bool startReading)
{
this.device = device;
this.isStarted = startReading;
this.readThread = new Thread(this.MainLoop);
this.readThread.Start();
}
/// <summary>
/// Stop the reading thread and disconnect from the device.
/// </summary>
public void Disconnect()
{
this.isStarted = false;
this.device.Disconnect();
}
/// <summary>
/// Determines whether this instance is connected.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is connected; otherwise, <c>false</c>.
/// </returns>
public bool IsConnected()
{
return this.device.IsConnected();
}
/// <summary>
/// Read the voltages of all registered channels
/// </summary>
public void ReadVoltages()
{
Channels[] channels;
Monitor.Enter(this.readersPerChannel);
try
{
channels = this.readersPerChannel.Where((pair) => pair.Value > 0).Select(pair => pair.Key).ToArray();
}
finally
{
Monitor.Exit(this.readersPerChannel);
}
try
{
double[] voltages = this.device.GetVoltages(channels);
for (int i = 0; i < channels.Length; i++)
{
this.values[channels[i]] = voltages[i];
}
}
catch (AgilentException ex)
{
DebugLogger.Error(this.GetType().Name, "Reading values failed: " + ex.ToString());
}
catch (Exception)
{
DebugLogger.Error(this.GetType().Name, "He7 cooler connection error.");
}
}
/// <summary>
/// The set digital switch.
/// </summary>
/// <param name="theSwitch">
/// The switch.
/// </param>
/// <param name="value">
/// The value.
/// </param>
public void SetDigitalSwitch(DigitalSwitch theSwitch, bool value)
{
this.device.SetDigitalOutput((int)theSwitch, value);
}
/// <summary>
/// The add channel.
/// </summary>
/// <param name="channel">
/// The channel.
/// </param>
protected void AddChannel(Channels channel)
{
Monitor.Enter(this.readersPerChannel);
try
{
if (!this.readersPerChannel.ContainsKey(channel))
{
this.values.Add(channel, 0.0);
this.readersPerChannel[channel] = 0;
}
this.readersPerChannel[channel]++;
}
finally
{
Monitor.Exit(this.readersPerChannel);
}
}
/// <summary>
/// Add a heater to the heaters list
/// </summary>
/// <param name="heater">
/// The heater.
/// </param>
protected void AddHeater(Heater heater)
{
this.heaters.Add(heater);
}
/// <summary>
/// The remove channel.
/// </summary>
/// <param name="channel">
/// The channel.
/// </param>
protected void RemoveChannel(Channels channel)
{
Monitor.Enter(this.readersPerChannel);
try
{
if (this.readersPerChannel.ContainsKey(channel))
{
if (this.readersPerChannel[channel] > 0)
{
this.readersPerChannel[channel]--;
}
}
}
finally
{
Monitor.Exit(this.readersPerChannel);
}
}
/// <summary>
/// Set the voltage of a channel
/// </summary>
/// <param name="channel">
/// The channel.
/// </param>
/// <param name="volts">
/// The voltage
/// </param>
protected void SetVoltage(Channels channel, double volts)
{
this.device.SetHeaterVoltage(channel, volts);
}
/// <summary>
/// Notify heaters that a new reading has been done
/// </summary>
private void NotifyHeaters()
{
foreach (var heater in this.heaters)
{
heater?.Notify();
}
}
/// <summary>
/// The main loop of the thread that reads voltages from the He7 cooler.
/// </summary>
private void MainLoop()
{
while (this.isStarted)
{
if (!this.device.IsConnected())
{
DebugLogger.Info(this.GetType().Name, "H7 cooler disconnected, trying to reconnect...");
try
{
this.device.Disconnect();
}
catch (Exception e)
{
DebugLogger.Error(this.GetType().Name, "Can not dissconnect He7Cooler: " + e.GetType() + e.Message);
}
try
{
this.device.Reopen();
}
catch (Exception e)
{
DebugLogger.Error(this.GetType().Name, "Reconnecting failed: " + e.GetType() + e.Message);
}
}
else
{
this.ReadVoltages();
this.NotifyHeaters();
}
Thread.Sleep(ReadInterval);
}
}
}
}<file_sep>/CryostatControlServer/Logging/LoggerDataObject.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LoggerDataObject.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Logging
{
/// <summary>
/// The logger data object.
/// </summary>
public class LoggerDataObject
{
/// <summary>
/// The abstract log data.
/// </summary>
private AbstractDataLogger abstractDataLogger;
/// <summary>
/// The file path.
/// </summary>
private string filePath;
/// <summary>
/// Initializes a new instance of the <see cref="LoggerDataObject"/> class.
/// </summary>
/// <param name="abstractDataLogger">
/// The abstract log data.
/// </param>
/// <param name="filePath">
/// The file path.
/// </param>
public LoggerDataObject(AbstractDataLogger abstractDataLogger, string filePath)
{
this.abstractDataLogger = abstractDataLogger;
this.filePath = filePath;
}
/// <summary>
/// The get abstract log data.
/// </summary>
/// <returns>
/// The <see cref="AbstractDataLogger" />.
/// </returns>
public AbstractDataLogger GetAbstractLogData()
{
return this.abstractDataLogger;
}
/// <summary>
/// Get file path.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public string GetFilePath()
{
return this.filePath;
}
}
}
<file_sep>/CryostatControlServer/Data/DataReader.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataReader.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.Data
{
using System;
using CryostatControlServer.Logging;
/// <summary>
/// Class which returns a array filled with data according to <seealso cref="DataEnumerator"/>
/// </summary>
public class DataReader
{
#region Fields
/// <summary>
/// The sensors
/// </summary>
private readonly ISensor[] sensors;
/// <summary>
/// The compressor
/// </summary>
private readonly Compressor.Compressor compressor;
/// <summary>
/// The he7 cooler
/// </summary>
private readonly He7Cooler.He7Cooler he7Cooler;
/// <summary>
/// The lake shore
/// </summary>
private readonly LakeShore.LakeShore lakeShore;
#endregion Fields
#region Methods
/// <summary>
/// Initializes a new instance of the <see cref="DataReader" /> class.
/// </summary>
/// <param name="compressor">The compressor.</param>
/// <param name="he7Cooler">The he7 cooler.</param>
/// <param name="lakeShore">The lake shore.</param>
public DataReader(
Compressor.Compressor compressor,
He7Cooler.He7Cooler he7Cooler,
LakeShore.LakeShore lakeShore)
{
this.compressor = compressor;
this.he7Cooler = he7Cooler;
this.lakeShore = lakeShore;
this.sensors = new SensorArray(this.compressor, he7Cooler, lakeShore).GetSensorArray();
}
/// <summary>
/// Fills data array with mock values, then it calls the methods which actually fill the array with data.
/// </summary>
/// <returns>array filled with available data</returns>
public double[] GetDataArray()
{
double[] data = new double[(int)DataEnumerator.DataLength];
for (int i = 0; i < data.Length; i++)
{
data[i] = double.MinValue;
}
this.FillConnectionData(data);
this.FillDataWithSensor(data);
this.FillCompressorData(data);
if (!this.he7Cooler.IsConnected())
{
for (int i = (int)DataEnumerator.He3Pump; i < (int)DataEnumerator.SensorAmount; i++)
{
data[i] = float.NaN;
}
}
if (!this.lakeShore.IsConnected())
{
data[(int)DataEnumerator.LakePlate3K] = float.NaN;
data[(int)DataEnumerator.LakePlate50K] = float.NaN;
}
return data;
}
/// <summary>
/// Reads the single sensor.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>Value of the sensor, if something went wrong NaN</returns>
public double ReadSingleSensor(int id)
{
if (id < 0 && id >= (int)DataEnumerator.DataLength)
{
return double.NaN;
}
if (id < (int)DataEnumerator.SensorAmount)
{
return this.ReadSensor(id);
}
return this.ReadFromSwitch(id);
}
/// <summary>
/// Reads from switch.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>Value of the sensor, if something went wrong NaN</returns>
private double ReadFromSwitch(int id)
{
try
{
switch (id)
{
case (int)DataEnumerator.HeConnectionState: return Convert.ToDouble(this.he7Cooler.IsConnected());
case (int)DataEnumerator.ComConnectionState: return Convert.ToDouble(this.compressor.IsConnected());
case (int)DataEnumerator.LakeConnectionState:
return Convert.ToDouble(this.lakeShore?.IsConnected() ?? false);
case (int)DataEnumerator.ComError: return (double)this.compressor.ReadErrorState();
case (int)DataEnumerator.ComWarning: return (double)this.compressor.ReadWarningState();
case (int)DataEnumerator.ComHoursOfOperation: return (double)this.compressor.ReadHoursOfOperation();
case (int)DataEnumerator.ComOperationState: return (double)this.compressor.ReadOperatingState();
default: return double.NaN;
}
}
catch
{
return double.NaN;
}
}
/// <summary>
/// Fills the data array with sensor data.
/// </summary>
/// <param name="data">The data.</param>
private void FillDataWithSensor(double[] data)
{
for (int i = 0; i < (int)DataEnumerator.SensorAmount; i++)
{
try
{
data[i] = this.sensors[i].Value;
}
catch (Exception)
{
data[i] = float.NaN;
}
}
}
/// <summary>
/// Fills the data array with compressor data which cannot be read with the sensor interface.
/// </summary>
/// <param name="data">The data.</param>
private void FillCompressorData(double[] data)
{
try
{
data[(int)DataEnumerator.ComError] = (double)this.compressor.ReadErrorState();
data[(int)DataEnumerator.ComWarning] = (double)this.compressor.ReadWarningState();
data[(int)DataEnumerator.ComHoursOfOperation] = (double)this.compressor.ReadHoursOfOperation();
data[(int)DataEnumerator.ComOperationState] = (double)this.compressor.ReadOperatingState();
}
catch (Exception)
{
data[(int)DataEnumerator.ComError] = float.NaN;
data[(int)DataEnumerator.ComWarning] = float.NaN;
data[(int)DataEnumerator.ComHoursOfOperation] = float.NaN;
data[(int)DataEnumerator.ComOperationState] = float.NaN;
}
}
/// <summary>
/// Fills the data array with mock data.
/// </summary>
/// <param name="data">The data.</param>
private void FillWithMockData(double[] data)
{
Random random = new Random();
for (int i = 0; i < data.Length; i++)
{
data[i] = random.NextDouble();
}
}
/// <summary>
/// Reads the sensor.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>Value of the sensor, if something went wrong NaN is returned</returns>
private double ReadSensor(int id)
{
try
{
return this.sensors[id].Value;
}
catch
{
return double.NaN;
}
}
/// <summary>
/// Fills the connection data.
/// </summary>
/// <param name="data">The data.</param>
private void FillConnectionData(double[] data)
{
data[(int)DataEnumerator.ComConnectionState] = Convert.ToDouble(this.compressor.IsConnected());
data[(int)DataEnumerator.HeConnectionState] = Convert.ToDouble(this.he7Cooler.IsConnected());
if (this.lakeShore != null)
{
data[(int)DataEnumerator.LakeConnectionState] = Convert.ToDouble(this.lakeShore.IsConnected());
}
else
{
data[(int)DataEnumerator.LakeConnectionState] = 0;
}
}
#endregion Methods
}
}<file_sep>/CryostatControlServer/Launcher.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Launcher.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer
{
using System;
using System.ServiceModel;
using System.Threading.Tasks;
using CryostatControlServer.Data;
using CryostatControlServer.HostService;
using CryostatControlServer.Logging;
/// <summary>
/// Launcher for the server application
/// </summary>
public class Launcher
{
/// <summary>
/// The host address for the compressor
/// </summary>
private const string CompressorHost = "169.254.16.68";
/// <summary>
/// Host address of the helium 7 cooler
/// </summary>
private const string CoolerHost = "192.168.1.100";
/// <summary>
/// The logger
/// </summary>
private static LogThreader logger;
/// <summary>
/// The compressor
/// </summary>
private static Compressor.Compressor compressor = new Compressor.Compressor();
/// <summary>
/// The controller.
/// </summary>
private static Controller controller;
/// <summary>
/// The cryostat control.
/// </summary>
private static CryostatControl cryostatControl;
/// <summary>
/// The he7 cooler
/// </summary>
private static He7Cooler.He7Cooler he7Cooler = new He7Cooler.He7Cooler();
/// <summary>
/// The host.
/// </summary>
private static ServiceHost host;
/// <summary>
/// The lake shore
/// </summary>
private static LakeShore.LakeShore lakeShore = new LakeShore.LakeShore();
/// <summary>
/// Initializes the components.
/// </summary>
public static void InitComponents()
{
var lakeShorePort = LakeShore.LakeShore.FindPort();
if (lakeShorePort != null)
{
new Task(() => { lakeShore.Init(lakeShorePort); }).Start();
}
else
{
DebugLogger.Error("Launcher", "No connection with LakeShore");
}
new Task(
() =>
{
try
{
he7Cooler.Connect(CoolerHost);
}
catch (Exception)
{
DebugLogger.Error("Launcher", "No connection with He7 cooler");
}
}).Start();
new Task(
() =>
{
try
{
compressor.Connect(CompressorHost);
}
catch (Exception)
{
DebugLogger.Error("Launcher", "No connection with Compressor");
}
}).Start();
controller = new Controller(he7Cooler, lakeShore, compressor);
cryostatControl = new CryostatControl(compressor, lakeShore, he7Cooler, controller);
}
/// <summary>
/// Close the server and all connections.
/// </summary>
public static void Exit()
{
try
{
host.Close();
lakeShore.Close();
compressor.Disconnect();
he7Cooler.Disconnect();
}
catch (Exception)
{
}
}
/// <summary>
/// Launch the server
/// </summary>
public static void Launch()
{
InitComponents();
logger = new LogThreader(new DataReader(compressor, he7Cooler, lakeShore), cryostatControl);
logger.StartGeneralDataLogging();
StartHost();
}
/// <summary>
/// Starts the web service.
/// </summary>
public static void StartHost()
{
CommandService hostService = new CommandService(cryostatControl, logger);
NotificationSender.Init(hostService);
host = new ServiceHost(hostService);
((ServiceBehaviorAttribute)host.Description.Behaviors[typeof(ServiceBehaviorAttribute)])
.InstanceContextMode = InstanceContextMode.Single;
host.Open();
DebugLogger.Info("Launcher", "The service is ready");
}
}
}<file_sep>/CryostatControlClient/Views/Tabs/GraphFrame.xaml.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GraphFrame.xaml.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Views.Tabs
{
/// <summary>
/// Interaction logic for OverviewFrame.xaml
/// </summary>
public partial class GraphFrame
{
}
}
<file_sep>/documents/manuals/README.md
Device documentation
=====
335_manual.pdf
---
The model 335 Lake Shore temperature controller manual.
The device is controlled over a COM-over-USB interface.
Chapter 6.3.4 describes the communication protocol.
34970A-34972A_Command_Reference
---
Agilent 34970A/34972A Command Reference
The device connects over an ethernet connection using a TCP socket on port 5025 or Telnet over port 5024.
The file descibes the command protocol.<file_sep>/CryostatControlClient/ViewModels/LoggingPresets/LogHe7Preset.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LogHe7Preset.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels.LoggingPresets
{
/// <summary>
/// The log he 7 preset.
/// </summary>
public class LogHe7Preset : ILoggingPreset
{
/// <summary>
/// Initializes a new instance of the <see cref="LogHe7Preset"/> class.
/// </summary>
/// <param name="loggingViewModel">
/// The logging view model.
/// </param>
public LogHe7Preset(LoggingViewModel loggingViewModel)
{
this.SetLoggingValues(loggingViewModel);
}
/// <summary>
/// Sets the logging values.
/// </summary>
/// <param name="loggingViewModel">The logging view model.</param>
public void SetLoggingValues(LoggingViewModel loggingViewModel)
{
loggingViewModel.LoggingInterval = 10.0;
loggingViewModel.He3PumpVolt = true;
loggingViewModel.He3SwitchVolt = true;
loggingViewModel.He4PumpVolt = true;
loggingViewModel.He4SwitchVolt = true;
loggingViewModel.FourKPlateTemp = true;
loggingViewModel.TwoKPlateTemp = true;
loggingViewModel.Bluefors3KShieldTemp = false;
loggingViewModel.Bluefors50KShieldTemp = false;
loggingViewModel.CompressorHeliumTemp = false;
loggingViewModel.CompressorOilTemp = false;
loggingViewModel.CompressorWaterInTemp = false;
loggingViewModel.CompressorWaterOutTemp = false;
loggingViewModel.He3HeadTemp = true;
loggingViewModel.He4SwitchTemp = true;
loggingViewModel.He4HeadTemp = true;
loggingViewModel.He3SwitchTemp = true;
loggingViewModel.He3PumpTemp = true;
loggingViewModel.He4PumpTemp = true;
loggingViewModel.CompressorDeltaAveragePressure = false;
loggingViewModel.CompressorDeltaAveragePressure = false;
loggingViewModel.CompressorHighPressure = false;
loggingViewModel.CompressorHighAveragePressure = false;
loggingViewModel.CompressorLowPressure = false;
loggingViewModel.CompressorLowAveragePressure = false;
}
}
}
<file_sep>/CryostatControlClient/Views/Tabs/CompressorFrame.xaml.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CompressorFrame.xaml.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Views
{
/// <summary>
/// Interaction logic for OverviewFrame.xaml
/// </summary>
public partial class CompressorFrame
{
}
}
<file_sep>/CryostatControlServer/LakeShore/Sensor.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Sensor.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.LakeShore
{
using CryostatControlServer.Data;
/// <summary>
/// The sensor.
/// </summary>
public class Sensor : ISensor
{
#region Fields
/// <summary>
/// The sensor id.
/// </summary>
private SensorEnum sensorId;
/// <summary>
/// The device.
/// </summary>
private LakeShore device;
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Sensor"/> class.
/// </summary>
/// <param name="sensorId">
/// The sensor id.
/// </param>
/// <param name="device">
/// The device.
/// </param>
public Sensor(SensorEnum sensorId, LakeShore device)
{
this.sensorId = sensorId;
this.device = device;
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets or sets the interval.
/// This is ignored for now.
/// </summary>
public int Interval { get; set; }
/// <summary>
/// Gets the value.
/// </summary>
public double Value
{
get
{
return this.device.SensorValues[(int)this.sensorId];
}
}
#endregion Properties
}
}<file_sep>/CryostatControlClient/Views/MessageBox.xaml.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MessageBox.xaml.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Views
{
using System.Windows.Controls;
/// <summary>
/// Interaction logic for MessageBox.xaml
/// </summary>
public partial class MessageBox : Page
{
/// <summary>
/// Initializes a new instance of the <see cref="MessageBox"/> class.
/// </summary>
public MessageBox()
{
this.InitializeComponent();
}
}
}
<file_sep>/CryostatControlClient/Communication/DataReceiver.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataReceiver.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Communication
{
using System;
using CryostatControlClient.ViewModels;
using CryostatControlServer.Data;
/// <summary>
/// Handles the received data
/// </summary>
public class DataReceiver
{
#region Methods
/// <summary>
/// Sets the state.
/// </summary>
/// <param name="modus">The modus.</param>
/// <param name="dataContext">The data context.</param>
public void SetState(int modus, ViewModelContainer dataContext)
{
if (dataContext != null)
{
dataContext.ModusViewModel.Modus = modus;
}
}
/// <summary>
/// Sets the is logging.
/// </summary>
/// <param name="state">if set to <c>true</c> [state].</param>
/// <param name="dataContext">The data context.</param>
public void SetIsLogging(bool state, ViewModelContainer dataContext)
{
if (dataContext != null)
{
dataContext.LoggingViewModel.LoggingInProgress = state;
}
}
/// <summary>
/// Updates the compressor viewmodel.
/// </summary>
/// <param name="time">The time.</param>
/// <param name="dataContext">The data context.</param>
public void UpdateCountdown(DateTime time, ViewModelContainer dataContext)
{
if (dataContext != null)
{
dataContext.ModusViewModel.PlannedTime = time;
}
}
/// <summary>
/// Updates the notification.
/// </summary>
/// <param name="notification">
/// The notification.
/// </param>
/// <param name="dataContext">
/// The viewmodels.
/// </param>
public void UpdateNotification(string[] notification, ViewModelContainer dataContext)
{
if (dataContext != null)
{
dataContext.MessageBoxViewModel.Message = notification;
}
}
/// <summary>
/// Updates the compressor viewmodel.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="dataContext">The data context.</param>
public void UpdateViewModels(double[] data, ViewModelContainer dataContext)
{
if (dataContext != null)
{
this.UpdateHe7ViewModel(data, dataContext);
this.UpdateBlueforsViewModel(data, dataContext);
this.UpdateCompressorViewModel(data, dataContext);
}
}
/// <summary>
/// Updates the he7 view model.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="viewModelContainer">The view model container.</param>
private void UpdateHe7ViewModel(double[] data, ViewModelContainer viewModelContainer)
{
viewModelContainer.He7ViewModel.ConnectionState = data[(int)DataEnumerator.HeConnectionState];
viewModelContainer.He7ViewModel.He3HeadTemp = data[(int)DataEnumerator.He3Head];
viewModelContainer.He7ViewModel.He3PumpTemp = data[(int)DataEnumerator.He3Pump];
viewModelContainer.He7ViewModel.He4HeadTemp = data[(int)DataEnumerator.He4Head];
viewModelContainer.He7ViewModel.He4PumpTemp = data[(int)DataEnumerator.He4Pump];
viewModelContainer.He7ViewModel.He3PumpActualVolt = data[(int)DataEnumerator.He3VoltActual];
viewModelContainer.He7ViewModel.He4PumpActualVolt = data[(int)DataEnumerator.He4VoltActual];
viewModelContainer.He7ViewModel.He3SwitchTemp = data[(int)DataEnumerator.He3SwitchTemp];
viewModelContainer.He7ViewModel.He3SwitchActualVolt = data[(int)DataEnumerator.He3SwitchVoltActual];
viewModelContainer.He7ViewModel.He4SwitchTemp = data[(int)DataEnumerator.He4SwitchTemp];
viewModelContainer.He7ViewModel.He4SwitchActualVolt = data[(int)DataEnumerator.He4SwitchVoltActual];
viewModelContainer.He7ViewModel.TwoKPlateTemp = data[(int)DataEnumerator.HePlate2K];
viewModelContainer.He7ViewModel.FourKPlateTemp = data[(int)DataEnumerator.HePlate4K];
}
/// <summary>
/// Updates the bluefors view model.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="viewModelContainer">The view model container.</param>
private void UpdateCompressorViewModel(double[] data, ViewModelContainer viewModelContainer)
{
viewModelContainer.CompressorViewModel.ConnectionState = data[(int)DataEnumerator.ComConnectionState];
viewModelContainer.CompressorViewModel.WaterInTemp = data[(int)DataEnumerator.ComWaterIn];
viewModelContainer.CompressorViewModel.WaterOutTemp = data[(int)DataEnumerator.ComWaterOut];
viewModelContainer.CompressorViewModel.HeliumTemp = data[(int)DataEnumerator.ComHelium];
viewModelContainer.CompressorViewModel.OilTemp = data[(int)DataEnumerator.ComOil];
viewModelContainer.CompressorViewModel.LowPressure = data[(int)DataEnumerator.ComLow];
viewModelContainer.CompressorViewModel.LowPressureAverage = data[(int)DataEnumerator.ComLowAvg];
viewModelContainer.CompressorViewModel.HighPressure = data[(int)DataEnumerator.ComHigh];
viewModelContainer.CompressorViewModel.HighPressureAverage = data[(int)DataEnumerator.ComHighAvg];
viewModelContainer.CompressorViewModel.DeltaPressureAverage = data[(int)DataEnumerator.ComDeltaAvg];
viewModelContainer.CompressorViewModel.ErrorState = data[(int)DataEnumerator.ComError];
viewModelContainer.CompressorViewModel.WarningState = data[(int)DataEnumerator.ComWarning];
viewModelContainer.CompressorViewModel.HoursOfOperation = data[(int)DataEnumerator.ComHoursOfOperation];
viewModelContainer.CompressorViewModel.OperatingState = data[(int)DataEnumerator.ComOperationState];
}
/// <summary>
/// Updates the compressor view model.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="viewModelContainer">The view model container.</param>
private void UpdateBlueforsViewModel(double[] data, ViewModelContainer viewModelContainer)
{
viewModelContainer.BlueforsViewModel.ConnectionState = data[(int)DataEnumerator.LakeConnectionState];
viewModelContainer.BlueforsViewModel.ColdPlate50KTemp = data[(int)DataEnumerator.LakePlate50K];
viewModelContainer.BlueforsViewModel.ColdPlate3KTemp = data[(int)DataEnumerator.LakePlate3K];
}
#endregion Methods
}
}<file_sep>/CryostatControlClient/ViewModels/AbstractViewModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AbstractViewModel.cs" company="SRON">
// // Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels
{
using System.ComponentModel;
using System.Windows.Media;
/// <summary>
/// The abstract view model.
/// </summary>
public abstract class AbstractViewModel : INotifyPropertyChanged
{
#region Events
/// <summary>
/// The property changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
#endregion Events
#region Methods
/// <summary>
/// Convert connection state number to string.
/// </summary>
/// <param name="connectionState">
/// The connection state.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public string ConvertConnectionStateNumberToString(double connectionState)
{
switch ((int)connectionState)
{
case 0: return "Disconnected";
case 1: return "Connected";
default: return "No information";
}
}
/// <summary>
/// Connections the color.
/// </summary>
/// <param name="state">The state.</param>
/// <returns>Color of connections state.</returns>
public SolidColorBrush DisplayColor(ColorState state)
{
switch (state)
{
case ColorState.Green: return (SolidColorBrush)new BrushConverter().ConvertFrom("#4CAF50");
case ColorState.Red: return (SolidColorBrush)new BrushConverter().ConvertFrom("#F44336");
default: return new SolidColorBrush(Colors.Black);
}
}
/// <summary>
/// The raise property changed.
/// </summary>
/// <param name="propertyName">
/// The property name.
/// </param>
protected void RaisePropertyChanged(string propertyName)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion Methods
}
}<file_sep>/CryostatControlClient/Views/Tabs/BlueforsFrame.xaml.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BlueforsFrame.xaml.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Views
{
/// <summary>
/// Interaction logic for OverviewFrame.xaml
/// </summary>
public partial class BlueforsFrame
{
}
}
<file_sep>/CryostatControlClient/Views/TabFrame.xaml.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TabFrame.xaml.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Views
{
using System.Windows;
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class TabFrame
{
/// <summary>
/// Initializes a new instance of the <see cref="TabFrame"/> class.
/// </summary>
public TabFrame()
{
}
/// <summary>
/// Frames the navigated.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Windows.Navigation.NavigationEventArgs"/> instance containing the event data.</param>
private void FrameNavigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
((FrameworkElement)e.Content).DataContext = this.DataContext;
}
}
}
<file_sep>/CryostatControlServer/LakeShore/LakeShore.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LakeShore.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlServer.LakeShore
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO.Ports;
using System.Threading;
using CryostatControlServer.Logging;
using CryostatControlServer.Streams;
/// <summary>
/// Connection and communication to the LakeShore 355 temperature controller.
/// </summary>
public class LakeShore
{
#region Fields
/// <summary>
/// The 3K cold plate id
/// </summary>
public const string ColdPlate3K = "A";
/// <summary>
/// The 5k cold plate id
/// </summary>
public const string ColdPlate5K = "B";
/// <summary>
/// The baud rate of the COM connection
/// </summary>
private const int BaudRate = 57600;
/// <summary>
/// The read interval.
/// </summary>
private const int ReadInterval = 1000;
/// <summary>
/// The time of the last command. Commands need to be spaced at least 50ms
/// </summary>
[SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1650:ElementDocumentationMustBeSpelledCorrectly",
Justification = "Reviewed. Suppression is OK here.")]
private DateTime lastCommand;
/// <summary>
/// The read thread.
/// </summary>
private Thread readthread;
/// <summary>
/// The connection.
/// </summary>
private IManagedStream stream;
#endregion Fields
#region Properties
/// <summary>
/// Gets or sets the latest sensor values;
/// </summary>
/// <value>
/// The sensor values.
/// </value>
public double[] SensorValues { get; set; } = new double[2] { 0, 0 };
#endregion Properties
#region Methods
/// <summary>
/// Find the lakeshore com port and connect
/// </summary>
/// <returns>
/// The <see cref="CryostatControlServer.LakeShore"/>.
/// </returns>
public static string FindPort()
{
var names = SerialPort.GetPortNames();
foreach (var name in names)
{
ManagedCOMStream stream = null;
try
{
stream = new ManagedCOMStream(name, BaudRate);
stream.Open();
stream.WriteString("MODE 1\n");
Thread.Sleep(35);
stream.WriteString("*IDN?\n");
if (stream.ReadString().Contains("MODEL335"))
{
return name;
}
}
catch (Exception)
{
////ignore this exception and try new port
}
finally
{
stream?.Close();
}
}
return null;
}
/// <summary>
/// Closes this instance.
/// </summary>
public void Close()
{
// Stop the read thread inside a lock to prevent stopping while thread holds the lock.
Monitor.Enter(this.stream);
this.readthread.Abort();
Monitor.Exit(this.stream);
this.stream.Close();
}
/// <summary>
/// Initializes by connecting to the specified port name.
/// </summary>
/// <param name="portname">The port name.</param>
public void Init(string portname)
{
this.stream = new ManagedCOMStream(portname, BaudRate);
this.stream.Open();
this.StartReading();
}
/// <summary>
/// Initializes by connecting to the specified port name.
/// </summary>
/// <param name="managedStream">
/// The managed Stream.
/// </param>
public void Init(IManagedStream managedStream)
{
this.stream = managedStream;
this.stream.Open();
this.StartReading();
}
/// <summary>
/// Is the lakeshore connected.
/// </summary>
/// <returns>
/// Returns whether the lakeshore is connected <see cref="bool" />.
/// </returns>
public bool IsConnected()
{
return this.stream?.IsConnected() ?? false;
}
/// <summary>
/// Sends OPC command to device and waits for response.
/// Used to confirm connection and synchronisation of state of the device.
/// </summary>
/// <returns><c>true</c> if connect, else <c>false</c></returns>
// ReSharper disable once InconsistentNaming
[SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1650:ElementDocumentationMustBeSpelledCorrectly",
Justification = "Reviewed. Suppression is OK here.")]
public bool OPC()
{
try
{
Monitor.Enter(this.stream);
this.WaitCommandInterval();
this.stream.WriteString("OPC?\n");
this.stream.ReadString();
return true;
}
catch (Exception)
{
return false;
}
finally
{
Monitor.Exit(this.stream);
}
}
/// <summary>
/// The read values.
/// </summary>
private void ReadValues()
{
try
{
this.SensorValues[0] = this.ReadTemperature("A");
this.SensorValues[1] = this.ReadTemperature("B");
}
catch (Exception e)
{
DebugLogger.Error(this.GetType().Name, "Error while reading lakeshore: " + e.GetType().ToString());
}
}
/// <summary>
/// The reading loop running in a different thread.
/// </summary>
private void ReadingLoop()
{
while (true)
{
if (this.stream.IsConnected())
{
this.ReadValues();
}
else
{
try
{
this.stream.Open();
}
catch (Exception e)
{
DebugLogger.Error(this.GetType().Name, "Could not reconnect to lakeshore: " + e.GetType().ToString());
}
}
Thread.Sleep(ReadInterval);
}
}
/// <summary>
/// Reads the sensor temperature in Kelvin.
/// </summary>
/// <param name="sensor">The sensor.</param>
/// <returns>sensor temperature in K</returns>
private double ReadTemperature(string sensor)
{
try
{
Monitor.Enter(this.stream);
this.WaitCommandInterval();
this.stream.WriteString($"KRDG? {sensor}\n");
string response = this.stream.ReadString();
return double.Parse(response);
}
finally
{
Monitor.Exit(this.stream);
}
}
/// <summary>
/// Start reading temperatures.
/// </summary>
private void StartReading()
{
this.lastCommand = DateTime.Now;
this.stream.WriteString("MODE 1\n");
this.OPC();
this.readthread = new Thread(this.ReadingLoop);
this.readthread.Start();
}
/// <summary>
/// Wait until the specified minimum time between commands is passed.
/// The lakeshore355 manual specifies a minimum time of 50ms between commands.
/// </summary>
[SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1650:ElementDocumentationMustBeSpelledCorrectly",
Justification = "Reviewed. Suppression is OK here.")]
private void WaitCommandInterval()
{
while (DateTime.Now - this.lastCommand < TimeSpan.FromMilliseconds(50))
{
Thread.Sleep(DateTime.Now - this.lastCommand);
}
this.lastCommand = DateTime.Now;
}
#endregion Methods
}
}<file_sep>/CryostatControlServerTests/Logging/GeneralDataLoggerTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CryostatControlServerTests.Logging
{
using System.IO;
using System.Linq;
using CryostatControlServer.Data;
using CryostatControlServer.Logging;
using Moq;
[TestClass]
public class GeneralDataLoggerTest
{
[TestMethod]
public void CreateArrayWithOnlyTrueTest()
{
GeneralDataLogger generalDataLogger = new GeneralDataLogger();
bool[] devices = generalDataLogger.CreateArrayWithOnlyTrue();
for (int i = 0; i < devices.Length; i++)
{
Assert.IsTrue(devices[i]);
}
}
[TestMethod]
public void WriteGeneralDataTest()
{
GeneralDataLogger generalDataLogger = new GeneralDataLogger();
string filePath = "GeneralDataLoggerTest.csv";
double[] logData = new double[(int)DataEnumerator.DataLength];
logData[(int)DataEnumerator.ComHelium] = 20;
logData[(int)DataEnumerator.He3SwitchTemp] = 40;
logData[(int)DataEnumerator.LakePlate50K] = 1;
string time = DateTime.Now.ToString("HH:mm:ss");
if (File.Exists(filePath))
{
File.Delete(filePath);
}
File.Create(filePath).Close();
generalDataLogger.WriteGeneralData(filePath, logData, time);
string line = File.ReadLines(filePath).First();
string[] elements = line.Split(';');
Assert.AreEqual("20", elements[(int)DataEnumerator.ComHelium + 1]);
Assert.AreEqual("40", elements[(int)DataEnumerator.He3SwitchTemp + 1]);
Assert.AreEqual("1", elements[(int)DataEnumerator.LakePlate50K + 1]);
}
[TestMethod]
[ExpectedException(typeof(IOException))]
public void WriteGeneralDataExceptionTest()
{
GeneralDataLogger generalDataLogger = new GeneralDataLogger();
string filePath = "GeneralDataLoggerTest.csv";
double[] logData = new double[(int)DataEnumerator.DataLength];
logData[(int)DataEnumerator.ComHelium] = 20;
logData[(int)DataEnumerator.He3SwitchTemp] = 40;
logData[(int)DataEnumerator.LakePlate50K] = 1;
string time = DateTime.Now.ToString("HH:mm:ss");
if (File.Exists(filePath))
{
File.Delete(filePath);
}
File.Create(filePath);
generalDataLogger.WriteGeneralData(filePath, logData, time);
string line = File.ReadLines(filePath).First();
string[] elements = line.Split(';');
Assert.AreEqual("20", elements[(int)DataEnumerator.ComHelium + 1]);
Assert.AreEqual("40", elements[(int)DataEnumerator.He3SwitchTemp + 1]);
Assert.AreEqual("1", elements[(int)DataEnumerator.LakePlate50K + 1]);
}
}
}
<file_sep>/CryostatControlClient/ViewModels/ZoomingModeConverter.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ZoomingModeConverter.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels
{
using System;
using System.Globalization;
using System.Windows.Data;
using LiveCharts;
/// <summary>
/// Converter for the zooming mode
/// </summary>
/// <seealso cref="System.Windows.Data.IValueConverter" />
public class ZoomingModeConverter : IValueConverter
{
/// <summary>
/// Converts the zoomingoption to a string.
/// </summary>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
switch ((ZoomingOptions)value)
{
case ZoomingOptions.None:
return "is off";
case ZoomingOptions.X:
return "the X-axis";
case ZoomingOptions.Y:
return "the Y-axis";
case ZoomingOptions.Xy:
return "the X- and Y-axis";
default:
return "is off";
}
}
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
/// <exception cref="System.NotImplementedException">Indicates not implemented.</exception>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
<file_sep>/CryostatControlClient/ViewModels/He7ViewModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="He7ViewModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels
{
using System.ServiceModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using CryostatControlClient.Communication;
using CryostatControlClient.Models;
using CryostatControlServer.HostService.DataContracts;
using CryostatControlServer.HostService.Enumerators;
using LiveCharts.Geared;
/// <summary>
/// The he7 view model.
/// </summary>
public class He7ViewModel : AbstractViewModel
{
#region Fields
/// <summary>
/// The he7 model.
/// </summary>
private He7Model he7Model;
/// <summary>
/// The update button command
/// </summary>
private ICommand updateCommand;
/// <summary>
/// The two k plate visibility command
/// </summary>
private ICommand twoKPlateVisibilityCommand;
/// <summary>
/// The four k plate visibility command
/// </summary>
private ICommand fourKPlateVisibilityCommand;
/// <summary>
/// The he3 head visibility command
/// </summary>
private ICommand he3HeadVisibilityCommand;
/// <summary>
/// The he3 switch visibility command
/// </summary>
private ICommand he3SwitchVisibilityCommand;
/// <summary>
/// The he3 pump visibility command
/// </summary>
private ICommand he3PumpVisibilityCommand;
/// <summary>
/// The he4 head visibility command
/// </summary>
private ICommand he4HeadVisibilityCommand;
/// <summary>
/// The he4 switch visibility command
/// </summary>
private ICommand he4SwitchVisibilityCommand;
/// <summary>
/// The he4 pump visibility command
/// </summary>
private ICommand he4PumpVisibilityCommand;
#endregion Fields
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="He7ViewModel"/> class.
/// </summary>
public He7ViewModel()
{
this.he7Model = new He7Model();
this.updateCommand = new RelayCommand(this.OnClickUpdate, param => true);
this.twoKPlateVisibilityCommand = new RelayCommand(this.OnTwoKPlateVisibility, param => true);
this.fourKPlateVisibilityCommand = new RelayCommand(this.OnFourKPlateVisibility, param => true);
this.he3HeadVisibilityCommand = new RelayCommand(this.OnHe3HeadVisibility, param => true);
this.he3SwitchVisibilityCommand = new RelayCommand(this.OnHe3SwitchVisibility, param => true);
this.he3PumpVisibilityCommand = new RelayCommand(this.OnHe3PumpVisibility, param => true);
this.he4HeadVisibilityCommand = new RelayCommand(this.OnHe4HeadVisibility, param => true);
this.he4SwitchVisibilityCommand = new RelayCommand(this.OnHe4SwitchVisibility, param => true);
this.he4PumpVisibilityCommand = new RelayCommand(this.OnHe4PumpVisibility, param => true);
}
#endregion Constructor
#region Properties
/// <summary>
/// Gets the two k plate visibility command.
/// </summary>
/// <value>
/// The two k plate visibility command.
/// </value>
public ICommand TwoKPlateVisibilityCommand
{
get
{
return this.twoKPlateVisibilityCommand;
}
}
/// <summary>
/// Gets the four k plate visibility command.
/// </summary>
/// <value>
/// The four k plate visibility command.
/// </value>
public ICommand FourKPlateVisibilityCommand
{
get
{
return this.fourKPlateVisibilityCommand;
}
}
/// <summary>
/// Gets the he3 head visibility command.
/// </summary>
/// <value>
/// The he3 head visibility command.
/// </value>
public ICommand He3HeadVisibilityCommand
{
get
{
return this.he3HeadVisibilityCommand;
}
}
/// <summary>
/// Gets the he3 pump visibility command.
/// </summary>
/// <value>
/// The he3 pump visibility command.
/// </value>
public ICommand He3PumpVisibilityCommand
{
get
{
return this.he3PumpVisibilityCommand;
}
}
/// <summary>
/// Gets the he3 switch visibility command.
/// </summary>
/// <value>
/// The he3 switch visibility command.
/// </value>
public ICommand He3SwitchVisibilityCommand
{
get
{
return this.he3SwitchVisibilityCommand;
}
}
/// <summary>
/// Gets the he4 head visibility command.
/// </summary>
/// <value>
/// The he4 head visibility command.
/// </value>
public ICommand He4HeadVisibilityCommand
{
get
{
return this.he4HeadVisibilityCommand;
}
}
/// <summary>
/// Gets the he4 switch visibility command.
/// </summary>
/// <value>
/// The he4 switch visibility command.
/// </value>
public ICommand He4SwitchVisibilityCommand
{
get
{
return this.he4SwitchVisibilityCommand;
}
}
/// <summary>
/// Gets the he4 pump visibility command.
/// </summary>
/// <value>
/// The he4 pump visibility command.
/// </value>
public ICommand He4PumpVisibilityCommand
{
get
{
return this.he4PumpVisibilityCommand;
}
}
/// <summary>
/// Gets or sets the two k plate visibility.
/// </summary>
/// <value>
/// The two k plate visibility.
/// </value>
public Visibility TwoKPlateVisibility
{
get
{
return this.he7Model.TwoKPlateVisibility;
}
set
{
this.he7Model.TwoKPlateVisibility = value;
}
}
/// <summary>
/// Gets or sets the four k plate visibility.
/// </summary>
/// <value>
/// The four k plate visibility.
/// </value>
public Visibility FourKPlateVisibility
{
get
{
return this.he7Model.FourKPlateVisibility;
}
set
{
this.he7Model.FourKPlateVisibility = value;
}
}
/// <summary>
/// Gets or sets the he3 head visibility.
/// </summary>
/// <value>
/// The he3 head visibility.
/// </value>
public Visibility He3HeadVisibility
{
get
{
return this.he7Model.He3HeadVisibility;
}
set
{
this.he7Model.He3HeadVisibility = value;
}
}
/// <summary>
/// Gets or sets the he3 switch visibility.
/// </summary>
/// <value>
/// The he3 switch visibility.
/// </value>
public Visibility He3SwitchVisibility
{
get
{
return this.he7Model.He3SwitchVisibility;
}
set
{
this.he7Model.He3SwitchVisibility = value;
}
}
/// <summary>
/// Gets or sets the he3 pump visibility.
/// </summary>
/// <value>
/// The he3 pump visibility.
/// </value>
public Visibility He3PumpVisibility
{
get
{
return this.he7Model.He3PumpVisibility;
}
set
{
this.he7Model.He3PumpVisibility = value;
}
}
/// <summary>
/// Gets or sets the he4 head visibility.
/// </summary>
/// <value>
/// The he4 head visibility.
/// </value>
public Visibility He4HeadVisibility
{
get
{
return this.he7Model.He4HeadVisibility;
}
set
{
this.he7Model.He4HeadVisibility = value;
}
}
/// <summary>
/// Gets or sets the he4 switch visibility.
/// </summary>
/// <value>
/// The he4 switch visibility.
/// </value>
public Visibility He4SwitchVisibility
{
get
{
return this.he7Model.He4SwitchVisibility;
}
set
{
this.he7Model.He4SwitchVisibility = value;
}
}
/// <summary>
/// Gets or sets the he4 pump visibility.
/// </summary>
/// <value>
/// The he4 pump visibility.
/// </value>
public Visibility He4PumpVisibility
{
get
{
return this.he7Model.He4PumpVisibility;
}
set
{
this.he7Model.He4PumpVisibility = value;
}
}
/// <summary>
/// Gets the he4 head line series.
/// </summary>
/// <value>
/// The he4 head line series.
/// </value>
public GLineSeries He4HeadLineSeriesBottom
{
get
{
return this.he7Model.He4HeadLineSeriesBottom;
}
}
/// <summary>
/// Gets the he3 head line series.
/// </summary>
/// <value>
/// The he3 head line series.
/// </value>
public GLineSeries He3HeadLineSeriesBottom
{
get
{
return this.he7Model.He3HeadLineSeriesBottom;
}
}
/// <summary>
/// Gets the he4 switch line series.
/// </summary>
/// <value>
/// The he4 switch line series.
/// </value>
public GLineSeries He4SwitchLineSeries
{
get
{
return this.he7Model.He4SwitchLineSeries;
}
}
/// <summary>
/// Gets the he4 pump line series.
/// </summary>
/// <value>
/// The he4 pump line series.
/// </value>
public GLineSeries He4PumpLineSeries
{
get
{
return this.he7Model.He4PumpLineSeries;
}
}
/// <summary>
/// Gets the he4 head line series.
/// </summary>
/// <value>
/// The he4 head line series.
/// </value>
public GLineSeries He4HeadLineSeries
{
get
{
return this.he7Model.He4HeadLineSeries;
}
}
/// <summary>
/// Gets the he3 switch line series.
/// </summary>
/// <value>
/// The he3 switch line series.
/// </value>
public GLineSeries He3SwitchLineSeries
{
get
{
return this.he7Model.He3SwitchLineSeries;
}
}
/// <summary>
/// Gets the he3 pump line series.
/// </summary>
/// <value>
/// The he3 pump line series.
/// </value>
public GLineSeries He3PumpLineSeries
{
get
{
return this.he7Model.He3PumpLineSeries;
}
}
/// <summary>
/// Gets the he3 head line series.
/// </summary>
/// <value>
/// The he3 head line series.
/// </value>
public GLineSeries He3HeadLineSeries
{
get
{
return this.he7Model.He3HeadLineSeries;
}
}
/// <summary>
/// Gets the two k plat line series.
/// </summary>
/// <value>
/// The two k plat line series.
/// </value>
public GLineSeries TwoKPlatLineSeries
{
get
{
return this.he7Model.TwoKPlateLineSeries;
}
}
/// <summary>
/// Gets the four k plate line series.
/// </summary>
/// <value>
/// The four k plate line series.
/// </value>
public GLineSeries FourKPlateLineSeries
{
get
{
return this.he7Model.FourKPlateLineSeries;
}
}
/// <summary>
/// Gets the color of the connection state.
/// </summary>
/// <value>
/// The color of the connection state.
/// </value>
public SolidColorBrush ConnectionStateColor
{
get
{
return this.DisplayColor((ColorState)this.ConnectionState);
}
}
/// <summary>
/// Gets or sets the update button command.
/// </summary>
/// <value>
/// The hi button command.
/// </value>
public ICommand UpdateButtonCommand
{
get
{
return this.updateCommand;
}
set
{
this.updateCommand = value;
}
}
/// <summary>
/// Gets or sets the four k plate temperature.
/// </summary>
/// <value>
/// The four k plate temperature.
/// </value>
public double FourKPlateTemp
{
get
{
return this.he7Model.FourKPlateTemp;
}
set
{
this.he7Model.FourKPlateTemp = value;
this.RaisePropertyChanged("FourKPlateTemp");
}
}
/// <summary>
/// Gets or sets the four k plate max 1.
/// </summary>
/// <value>
/// The four k plate max1.
/// </value>
public double FourKPlateMax1
{
get
{
return this.he7Model.FourKPlateMax1;
}
set
{
this.he7Model.FourKPlateMax1 = value;
this.RaisePropertyChanged("FourKPlateMax1");
}
}
/// <summary>
/// Gets or sets the four k plate max 2.
/// </summary>
/// <value>
/// The four k plate max2.
/// </value>
public double FourKPlateMax2
{
get
{
return this.he7Model.FourKPlateMax2;
}
set
{
this.he7Model.FourKPlateMax2 = value;
this.RaisePropertyChanged("FourKPlateMax2");
}
}
/// <summary>
/// Gets or sets the he3 head temperature.
/// </summary>
/// <value>
/// The he3 head temperature.
/// </value>
public double He3HeadTemp
{
get
{
return this.he7Model.He3HeadTemp;
}
set
{
this.he7Model.He3HeadTemp = value;
this.RaisePropertyChanged("He3HeadTemp");
}
}
/// <summary>
/// Gets or sets the he 3 head max.
/// </summary>
/// <value>
/// The he3 head maximum.
/// </value>
public double He3HeadMax
{
get
{
return this.he7Model.He3HeadMax;
}
set
{
this.he7Model.He3HeadMax = value;
this.RaisePropertyChanged("He3HeadMax");
}
}
/// <summary>
/// Gets or sets the he3 pump temperature.
/// </summary>
/// <value>
/// The he3 pump temperature.
/// </value>
public double He3PumpTemp
{
get
{
return this.he7Model.He3PumpTemp;
}
set
{
this.he7Model.He3PumpTemp = value;
this.RaisePropertyChanged("He3PumpTemp");
}
}
/// <summary>
/// Gets or sets the he 3 pump actual volt.
/// </summary>
/// <value>
/// The he3 pump actual volt.
/// </value>
public double He3PumpActualVolt
{
get
{
return this.he7Model.He3PumpActualVolt;
}
set
{
this.he7Model.He3PumpActualVolt = value;
this.RaisePropertyChanged("He3PumpActualVolt");
}
}
/// <summary>
/// Gets or sets the he 3 pump new volt.
/// </summary>
/// <value>
/// The he3 pump new volt.
/// </value>
public double He3PumpNewVolt
{
get
{
return this.he7Model.He3PumpNewVolt;
}
set
{
this.he7Model.He3PumpNewVolt = value;
this.RaisePropertyChanged("He3PumpNewVolt");
}
}
/// <summary>
/// Gets or sets the he 3 pump max.
/// </summary>
/// <value>
/// The he3 pump maximum.
/// </value>
public double He3PumpMax
{
get
{
return this.he7Model.He3PumpMax;
}
set
{
this.he7Model.He3PumpMax = value;
this.RaisePropertyChanged("He3PumpMax");
}
}
/// <summary>
/// Gets or sets the he3 switch temperature.
/// </summary>
/// <value>
/// The he3 switch temperature.
/// </value>
public double He3SwitchTemp
{
get
{
return this.he7Model.He3SwitchTemp;
}
set
{
this.he7Model.He3SwitchTemp = value;
this.RaisePropertyChanged("He3SwitchTemp");
}
}
/// <summary>
/// Gets or sets the he 3 switch actual volt.
/// </summary>
/// <value>
/// The he3 switch actual volt.
/// </value>
public double He3SwitchActualVolt
{
get
{
return this.he7Model.He3SwitchActualVolt;
}
set
{
this.he7Model.He3SwitchActualVolt = value;
this.RaisePropertyChanged("He3SwitchActualVolt");
}
}
/// <summary>
/// Gets or sets the he 3 switch new volt.
/// </summary>
/// <value>
/// The he3 switch new volt.
/// </value>
public double He3SwitchNewVolt
{
get
{
return this.he7Model.He3SwitchNewVolt;
}
set
{
this.he7Model.He3SwitchNewVolt = value;
this.RaisePropertyChanged("He3SwitchNewVolt");
}
}
/// <summary>
/// Gets or sets the he 3 switch max 1.
/// </summary>
/// <value>
/// The he3 switch max1.
/// </value>
public double He3SwitchMax1
{
get
{
return this.he7Model.He3SwitchMax1;
}
set
{
this.he7Model.He3SwitchMax1 = value;
this.RaisePropertyChanged("He3SwitchMax1");
}
}
/// <summary>
/// Gets or sets the he 3 switch max 2.
/// </summary>
/// <value>
/// The he3 switch max2.
/// </value>
public double He3SwitchMax2
{
get
{
return this.he7Model.He3SwitchMax2;
}
set
{
this.he7Model.He3SwitchMax2 = value;
this.RaisePropertyChanged("He3SwitchMax2");
}
}
/// <summary>
/// Gets or sets the he4 head temperature.
/// </summary>
/// <value>
/// The he4 head temperature.
/// </value>
public double He4HeadTemp
{
get
{
return this.he7Model.He4HeadTemp;
}
set
{
this.he7Model.He4HeadTemp = value;
this.RaisePropertyChanged("He4HeadTemp");
}
}
/// <summary>
/// Gets or sets the he 4 head max.
/// </summary>
/// <value>
/// The he4 head maximum.
/// </value>
public double He4HeadMax
{
get
{
return this.he7Model.He4HeadMax;
}
set
{
this.he7Model.He4HeadMax = value;
this.RaisePropertyChanged("He4HeadMax");
}
}
/// <summary>
/// Gets or sets the he4 pump temperature.
/// </summary>
/// <value>
/// The he4 pump temperature.
/// </value>
public double He4PumpTemp
{
get
{
return this.he7Model.He4PumpTemp;
}
set
{
this.he7Model.He4PumpTemp = value;
this.RaisePropertyChanged("He4PumpTemp");
}
}
/// <summary>
/// Gets or sets the he 4 pump actual volt.
/// </summary>
/// <value>
/// The he4 pump actual volt.
/// </value>
public double He4PumpActualVolt
{
get
{
return this.he7Model.He4PumpActualVolt;
}
set
{
this.he7Model.He4PumpActualVolt = value;
this.RaisePropertyChanged("He4PumpActualVolt");
}
}
/// <summary>
/// Gets or sets the he 4 pump new volt.
/// </summary>
/// <value>
/// The he4 pump new volt.
/// </value>
public double He4PumpNewVolt
{
get
{
return this.he7Model.He4PumpNewVolt;
}
set
{
this.he7Model.He4PumpNewVolt = value;
this.RaisePropertyChanged("He4PumpNewVolt");
}
}
/// <summary>
/// Gets or sets the he 4 pump max.
/// </summary>
/// <value>
/// The he4 pump maximum.
/// </value>
public double He4PumpMax
{
get
{
return this.he7Model.He4PumpMax;
}
set
{
this.he7Model.He4PumpMax = value;
this.RaisePropertyChanged("He4PumpMax");
}
}
/// <summary>
/// Gets or sets the he4 switch temperature.
/// </summary>
/// <value>
/// The he4 switch temperature.
/// </value>
public double He4SwitchTemp
{
get
{
return this.he7Model.He4SwitchTemp;
}
set
{
this.he7Model.He4SwitchTemp = value;
this.RaisePropertyChanged("He4SwitchTemp");
}
}
/// <summary>
/// Gets or sets the he 4 switch actual volt.
/// </summary>
/// <value>
/// The he4 switch actual volt.
/// </value>
public double He4SwitchActualVolt
{
get
{
return this.he7Model.He4SwitchActualVolt;
}
set
{
this.he7Model.He4SwitchActualVolt = value;
this.RaisePropertyChanged("He4SwitchActualVolt");
}
}
/// <summary>
/// Gets or sets the he 4 switch new volt.
/// </summary>
/// <value>
/// The he4 switch new volt.
/// </value>
public double He4SwitchNewVolt
{
get
{
return this.he7Model.He4SwitchNewVolt;
}
set
{
this.he7Model.He4SwitchNewVolt = value;
this.RaisePropertyChanged("He4SwitchNewVolt");
}
}
/// <summary>
/// Gets or sets the he 4 switch max 1.
/// </summary>
/// <value>
/// The he4 switch max1.
/// </value>
public double He4SwitchMax1
{
get
{
return this.he7Model.He4SwitchMax1;
}
set
{
this.he7Model.He4SwitchMax1 = value;
this.RaisePropertyChanged("He4SwitchMax1");
}
}
/// <summary>
/// Gets or sets the he 4 switch max 2.
/// </summary>
/// <value>
/// The he4 switch max2.
/// </value>
public double He4SwitchMax2
{
get
{
return this.he7Model.He4SwitchMax2;
}
set
{
this.he7Model.He4SwitchMax2 = value;
this.RaisePropertyChanged("He4SwitchMax2");
}
}
/// <summary>
/// Gets or sets the two k plate temperature.
/// </summary>
/// <value>
/// The two k plate temperature.
/// </value>
public double TwoKPlateTemp
{
get
{
return this.he7Model.TwoKPlateTemp;
}
set
{
this.he7Model.TwoKPlateTemp = value;
this.RaisePropertyChanged("TwoKPlateTemp");
}
}
/// <summary>
/// Gets or sets the connection state.
/// </summary>
/// <value>
/// The state of the connection.
/// </value>
public double ConnectionState
{
get
{
return this.he7Model.ConnectionState;
}
set
{
this.he7Model.ConnectionState = value;
this.RaisePropertyChanged("ConnectionState");
this.RaisePropertyChanged("ConnectionStateConverted");
this.RaisePropertyChanged("ConnectionStateColor");
}
}
/// <summary>
/// Gets a value indicating whether [update enable].
/// </summary>
/// <value>
/// <c>true</c> if [update enable]; otherwise, <c>false</c>.
/// </value>
public bool UpdateEnable
{
get
{
if (this.ConnectionState == 1)
{
return true;
}
return false;
}
}
/// <summary>
/// Gets the connection state converted.
/// </summary>
/// <value>
/// The connection state converted.
/// </value>
public string ConnectionStateConverted
{
get
{
return this.ConvertConnectionStateNumberToString(this.he7Model.ConnectionState);
}
}
#endregion Properties
#region Methods
/// <summary>
/// Called when [two k plate visibility].
/// </summary>
/// <param name="obj">The object.</param>
private void OnTwoKPlateVisibility(object obj)
{
if (this.TwoKPlateVisibility == Visibility.Hidden)
{
this.TwoKPlateVisibility = Visibility.Visible;
}
else
{
this.TwoKPlateVisibility = Visibility.Hidden;
}
}
/// <summary>
/// Called when [four k plate visibility].
/// </summary>
/// <param name="obj">The object.</param>
private void OnFourKPlateVisibility(object obj)
{
if (this.FourKPlateVisibility == Visibility.Hidden)
{
this.FourKPlateVisibility = Visibility.Visible;
}
else
{
this.FourKPlateVisibility = Visibility.Hidden;
}
}
/// <summary>
/// Called when [he3 head visibility].
/// </summary>
/// <param name="obj">The object.</param>
private void OnHe3HeadVisibility(object obj)
{
if (this.He3HeadVisibility == Visibility.Hidden)
{
this.He3HeadVisibility = Visibility.Visible;
}
else
{
this.He3HeadVisibility = Visibility.Hidden;
}
}
/// <summary>
/// Called when [he3 switch visibility].
/// </summary>
/// <param name="obj">The object.</param>
private void OnHe3SwitchVisibility(object obj)
{
if (this.He3SwitchVisibility == Visibility.Hidden)
{
this.He3SwitchVisibility = Visibility.Visible;
}
else
{
this.He3SwitchVisibility = Visibility.Hidden;
}
}
/// <summary>
/// Called when [he3 pump visibility].
/// </summary>
/// <param name="obj">The object.</param>
private void OnHe3PumpVisibility(object obj)
{
if (this.He3PumpVisibility == Visibility.Hidden)
{
this.He3PumpVisibility = Visibility.Visible;
}
else
{
this.He3PumpVisibility = Visibility.Hidden;
}
}
/// <summary>
/// Called when [he4 head visibility].
/// </summary>
/// <param name="obj">The object.</param>
private void OnHe4HeadVisibility(object obj)
{
if (this.He4HeadVisibility == Visibility.Hidden)
{
this.He4HeadVisibility = Visibility.Visible;
}
else
{
this.He4HeadVisibility = Visibility.Hidden;
}
}
/// <summary>
/// Called when [he4 switch visibility].
/// </summary>
/// <param name="obj">The object.</param>
private void OnHe4SwitchVisibility(object obj)
{
if (this.He4SwitchVisibility == Visibility.Hidden)
{
this.He4SwitchVisibility = Visibility.Visible;
}
else
{
this.He4SwitchVisibility = Visibility.Hidden;
}
}
/// <summary>
/// Called when [he4 pump visibility].
/// </summary>
/// <param name="obj">The object.</param>
private void OnHe4PumpVisibility(object obj)
{
if (this.He4PumpVisibility == Visibility.Hidden)
{
this.He4PumpVisibility = Visibility.Visible;
}
else
{
this.He4PumpVisibility = Visibility.Hidden;
}
}
/// <summary>
/// Shows the message.
/// </summary>
/// <param name="obj">The object.</param>
private void OnClickUpdate(object obj)
{
ServerCheck.SendMessage(new Task(() => { this.HeatersUpdate(); }));
}
/// <summary>
/// Task method for updating the values of the heaters
/// </summary>
private void HeatersUpdate()
{
try
{
ServerCheck.CommandClient.WriteHelium7((int)HeaterEnumerator.He4Pump, this.He4PumpNewVolt);
}
catch (FaultException<CouldNotPerformActionFault> e)
{
MessageBox.Show("Could not set He4 Pump voltage because " + e.Detail.Message);
}
try
{
ServerCheck.CommandClient.WriteHelium7((int)HeaterEnumerator.He3Pump, this.He3PumpNewVolt);
}
catch (FaultException<CouldNotPerformActionFault> e)
{
MessageBox.Show("Could not set He3 Pump voltage because " + e.Detail.Message);
}
try
{
ServerCheck.CommandClient.WriteHelium7((int)HeaterEnumerator.He3Switch, this.He3SwitchNewVolt);
}
catch (FaultException<CouldNotPerformActionFault> e)
{
MessageBox.Show("Could not set He3 Switch voltage because " + e.Detail.Message);
}
try
{
ServerCheck.CommandClient.WriteHelium7((int)HeaterEnumerator.He4Switch, this.He4SwitchNewVolt);
}
catch (FaultException<CouldNotPerformActionFault> e)
{
MessageBox.Show("Could not set He4 Switch voltage because " + e.Detail.Message);
}
}
#endregion Methods
}
}
<file_sep>/CryostatControlClient/App.xaml.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="App.xaml.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient
{
using System;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Threading.Tasks;
using System.Windows;
using CryostatControlClient.Communication;
using CryostatControlClient.ServiceReference1;
using CryostatControlClient.Properties;
/// <summary>
/// Interaction logic for <see cref="App.xaml" /></summary>
/// <seealso cref="System.Windows.Application" />
public partial class App
{
#region Fields
/// <summary>
/// The server check
/// </summary>
private ServerCheck serverCheck;
#endregion Fields
#region Methods
/// <summary>
/// Executes the specified action.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="timeoutInMilliseconds">The timeout in milliseconds.</param>
/// <param name="client">The client.</param>
/// <returns>Returns the task</returns>
public async Task Execute(Action<DataGetClient> action, int timeoutInMilliseconds, DataGetClient client)
{
await Task.Delay(timeoutInMilliseconds);
action(client);
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Application.Startup" /> event.
/// </summary>
/// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param>
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
this.serverCheck = new ServerCheck(this);
}
/// <summary>
/// Raises the <see cref="E:System.Windows.Application.Exit" /> event.
/// </summary>
/// <param name="e">An <see cref="T:System.Windows.ExitEventArgs" /> that contains the event data.</param>
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
Environment.Exit(0);
}
#endregion Methods
}
}<file_sep>/CryostatControlClient/Communication/ModusEnumerator.cs
//-----------------------------------------------------------------------
// <copyright file="ModusEnumerator.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlClient.Communication
{
/// <summary>
/// Enumerator for modi
/// </summary>
public enum ModusEnumerator
{
/// <summary>
/// The cool down
/// </summary>
Cooldown = 0,
/// <summary>
/// The recycle
/// </summary>
Recycle = 1,
/// <summary>
/// The warm up
/// </summary>
Warmup = 2,
/// <summary>
/// The manual
/// </summary>
Manual = 3
}
}
<file_sep>/CryostatControlServer/Compressor/Enumerators/PressureEnum.cs
//-----------------------------------------------------------------------
// <copyright file="PressureEnum.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlServer.Compressor
{
/// <summary>
/// Enumerator for pressure scale
/// </summary>
public enum PressureEnum
{
/// <summary>
/// PSI scale
/// </summary>
PSI = 0,
/// <summary>
/// Bar scale
/// </summary>
Bar = 1,
/// <summary>
/// KPA scale
/// </summary>
KPA = 2
}
}<file_sep>/CryostatControlClientTests/ViewModels/He7ViewModelTests.cs
//-----------------------------------------------------------------------
// <copyright file="CompressorViewModelTests.cs" company="SRON">
// Copyright (c) SRON. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace CryostatControlClient.ViewModels.Tests
{
using System;
using System.Windows;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass()]
public class He7ViewModelTests
{
private He7ViewModel he7ViewModel;
[TestInitialize]
public void TestInitialize()
{
this.he7ViewModel = new He7ViewModel();
}
[TestMethod()]
public void TwoKPlateVisibilityTest()
{
this.he7ViewModel.TwoKPlateVisibility = System.Windows.Visibility.Hidden;
Assert.AreEqual(this.he7ViewModel.TwoKPlateVisibility, Visibility.Hidden);
}
[TestMethod()]
public void FourKPlateVisibilityTest()
{
this.he7ViewModel.FourKPlateVisibility = System.Windows.Visibility.Hidden;
Assert.AreEqual(this.he7ViewModel.FourKPlateVisibility, Visibility.Hidden);
}
[TestMethod()]
public void He3HeadVisibilityTest()
{
this.he7ViewModel.He3HeadVisibility = System.Windows.Visibility.Hidden;
Assert.AreEqual(this.he7ViewModel.He3HeadVisibility, Visibility.Hidden);
}
[TestMethod()]
public void He3SwitchVisibilityTest()
{
this.he7ViewModel.He3SwitchVisibility = System.Windows.Visibility.Hidden;
Assert.AreEqual(this.he7ViewModel.He3SwitchVisibility, Visibility.Hidden);
}
[TestMethod()]
public void He3PumpVisibilityTest()
{
this.he7ViewModel.He3PumpVisibility = System.Windows.Visibility.Hidden;
Assert.AreEqual(this.he7ViewModel.He3PumpVisibility, Visibility.Hidden);
}
[TestMethod()]
public void He4HeadVisibilityTest()
{
this.he7ViewModel.He4HeadVisibility = System.Windows.Visibility.Hidden;
Assert.AreEqual(this.he7ViewModel.He4HeadVisibility, Visibility.Hidden);
}
[TestMethod()]
public void He4SwitchVisibilityTest()
{
this.he7ViewModel.He4SwitchVisibility = System.Windows.Visibility.Hidden;
Assert.AreEqual(this.he7ViewModel.He4SwitchVisibility, Visibility.Hidden);
}
[TestMethod()]
public void He4PumpVisibilityTest()
{
this.he7ViewModel.He4PumpVisibility = System.Windows.Visibility.Hidden;
Assert.AreEqual(this.he7ViewModel.He4PumpVisibility, Visibility.Hidden);
}
[TestMethod()]
public void FourKPlateTempTest()
{
this.he7ViewModel.FourKPlateTemp = 1;
Assert.AreEqual(this.he7ViewModel.FourKPlateTemp, 1);
}
[TestMethod()]
public void FourKPlateMax1Test()
{
this.he7ViewModel.FourKPlateMax1 = 1;
Assert.AreEqual(this.he7ViewModel.FourKPlateMax1, 1);
}
[TestMethod()]
public void FourKPlateMax2Test()
{
this.he7ViewModel.FourKPlateMax2 = 1;
Assert.AreEqual(this.he7ViewModel.FourKPlateMax2, 1);
}
[TestMethod()]
public void He3HeadTempTest()
{
this.he7ViewModel.He3HeadTemp = 1;
Assert.AreEqual(this.he7ViewModel.He3HeadTemp, 1);
}
[TestMethod()]
public void He3HeadMaxTest()
{
this.he7ViewModel.He3HeadMax = 1;
Assert.AreEqual(this.he7ViewModel.He3HeadMax, 1);
}
[TestMethod()]
public void He3PumpTempTest()
{
this.he7ViewModel.He3PumpTemp = 1;
Assert.AreEqual(this.he7ViewModel.He3PumpTemp, 1);
}
[TestMethod()]
public void He3PumpActualVoltTest()
{
this.he7ViewModel.He3PumpActualVolt = 1;
Assert.AreEqual(this.he7ViewModel.He3PumpActualVolt, 1);
}
[TestMethod()]
public void He3PumpNewVoltTest()
{
this.he7ViewModel.He3PumpNewVolt = 1;
Assert.AreEqual(this.he7ViewModel.He3PumpNewVolt, 1);
}
[TestMethod()]
public void He3PumpMaxTest()
{
this.he7ViewModel.He3PumpMax = 1;
Assert.AreEqual(this.he7ViewModel.He3PumpMax, 1);
}
[TestMethod()]
public void He3SwitchTempTest()
{
this.he7ViewModel.He3SwitchTemp = 1;
Assert.AreEqual(this.he7ViewModel.He3SwitchTemp, 1);
}
[TestMethod()]
public void He3SwitchActualVoltTest()
{
this.he7ViewModel.He3SwitchActualVolt = 1;
Assert.AreEqual(this.he7ViewModel.He3SwitchActualVolt, 1);
}
[TestMethod()]
public void He3SwitchNewVoltTest()
{
this.he7ViewModel.He3SwitchNewVolt = 1;
Assert.AreEqual(this.he7ViewModel.He3SwitchNewVolt, 1);
}
[TestMethod()]
public void He3SwitchMax1Test()
{
this.he7ViewModel.He3SwitchMax1 = 1;
Assert.AreEqual(this.he7ViewModel.He3SwitchMax1, 1);
}
[TestMethod()]
public void He3SwitchMax2Test()
{
this.he7ViewModel.He3SwitchMax2 = 1;
Assert.AreEqual(this.he7ViewModel.He3SwitchMax2, 1);
}
[TestMethod()]
public void He4HeadTempTest()
{
this.he7ViewModel.He4HeadTemp = 1;
Assert.AreEqual(this.he7ViewModel.He4HeadTemp, 1);
}
[TestMethod()]
public void He4HeadMaxTest()
{
this.he7ViewModel.He4HeadMax = 1;
Assert.AreEqual(this.he7ViewModel.He4HeadMax, 1);
}
[TestMethod()]
public void He4PumpTempTest()
{
this.he7ViewModel.He4PumpTemp = 1;
Assert.AreEqual(this.he7ViewModel.He4PumpTemp, 1);
}
[TestMethod()]
public void He4PumpActualVoltTest()
{
this.he7ViewModel.He4PumpActualVolt = 1;
Assert.AreEqual(this.he7ViewModel.He4PumpActualVolt, 1);
}
[TestMethod()]
public void He4PumpNewVoltTest()
{
this.he7ViewModel.He4PumpNewVolt = 1;
Assert.AreEqual(this.he7ViewModel.He4PumpNewVolt, 1);
}
[TestMethod()]
public void He4PumpMaxTest()
{
this.he7ViewModel.He4PumpMax = 1;
Assert.AreEqual(this.he7ViewModel.He4PumpMax, 1);
}
[TestMethod()]
public void He4SwitchTempTest()
{
this.he7ViewModel.He4SwitchTemp = 1;
Assert.AreEqual(this.he7ViewModel.He4SwitchTemp, 1);
}
[TestMethod()]
public void He4SwitchActualVoltTest()
{
this.he7ViewModel.He4SwitchActualVolt = 1;
Assert.AreEqual(this.he7ViewModel.He4SwitchActualVolt, 1);
}
[TestMethod()]
public void He4SwitchNewVoltTest()
{
this.he7ViewModel.He4SwitchNewVolt = 1;
Assert.AreEqual(this.he7ViewModel.He4SwitchNewVolt, 1);
}
[TestMethod()]
public void He4SwitchMax1Test()
{
this.he7ViewModel.He4SwitchMax1 = 1;
Assert.AreEqual(this.he7ViewModel.He4SwitchMax1, 1);
}
[TestMethod()]
public void He4SwitchMax2Test()
{
this.he7ViewModel.He4SwitchMax2 = 1;
Assert.AreEqual(this.he7ViewModel.He4SwitchMax2, 1);
}
[TestMethod()]
public void TwoKPlateTemp()
{
this.he7ViewModel.TwoKPlateTemp = 1;
Assert.AreEqual(this.he7ViewModel.TwoKPlateTemp, 1);
}
[TestMethod()]
public void OperatingStateTest()
{
this.he7ViewModel.ConnectionState = 1;
Assert.AreEqual(this.he7ViewModel.ConnectionState, 1);
}
[TestMethod()]
public void OperatingStateConvertedTest()
{
this.he7ViewModel.ConnectionState = 1;
Assert.IsFalse(String.IsNullOrEmpty(this.he7ViewModel.ConnectionStateConverted));
}
[TestMethod()]
public void UpdateEnableTestTrue()
{
this.he7ViewModel.ConnectionState = 1;
Assert.IsTrue(this.he7ViewModel.UpdateEnable);
}
[TestMethod()]
public void UpdateEnableTestFalse()
{
this.he7ViewModel.ConnectionState = 2;
Assert.IsFalse(this.he7ViewModel.UpdateEnable);
}
}
}<file_sep>/CryostatControlClient/ViewModels/RelayCommand.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RelayCommand.cs" company="https://www.codeproject.com/Tips/813345/Basic-MVVM-and-ICommand-Usage-Example">
// Since this class is just a tool to implement commands in MVVM the used class is copied from the source above.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels
{
using System;
using System.Windows.Input;
/// <summary>
/// Command a
/// </summary>
/// <seealso cref="System.Windows.Input.ICommand" />
public class RelayCommand : ICommand
{
/// <summary>
/// The execute
/// </summary>
private Action<object> execute;
/// <summary>
/// The can execute
/// </summary>
private Predicate<object> canExecute;
/// <summary>
/// Initializes a new instance of the <see cref="RelayCommand"/> class.
/// </summary>
/// <param name="execute">The execute.</param>
public RelayCommand(Action<object> execute)
: this(execute, DefaultCanExecute)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RelayCommand"/> class.
/// </summary>
/// <param name="execute">The execute.</param>
/// <param name="canExecute">The can execute.</param>
/// <exception cref="System.ArgumentNullException">
/// execute
/// or
/// canExecute
/// </exception>
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
if (canExecute == null)
{
throw new ArgumentNullException("canExecute");
}
this.execute = execute;
this.canExecute = canExecute;
}
/// <summary>
/// Occurs when changes occur that affect whether or not the command should execute.
/// </summary>
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
this.CanExecuteChangedInternal += value;
}
remove
{
CommandManager.RequerySuggested -= value;
this.CanExecuteChangedInternal -= value;
}
}
/// <summary>
/// Occurs when [can execute changed internal].
/// </summary>
private event EventHandler CanExecuteChangedInternal;
/// <summary>
/// Defines the method that determines whether the command can execute in its current state.
/// </summary>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
/// <returns>
/// true if this command can be executed; otherwise, false.
/// </returns>
public bool CanExecute(object parameter)
{
return this.canExecute != null && this.canExecute(parameter);
}
/// <summary>
/// Defines the method to be called when the command is invoked.
/// </summary>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
public void Execute(object parameter)
{
this.execute(parameter);
}
/// <summary>
/// Called when [can execute changed].
/// </summary>
public void OnCanExecuteChanged()
{
EventHandler handler = this.CanExecuteChangedInternal;
if (handler != null)
{
// DispatcherHelper.BeginInvokeOnUIThread(() => handler.Invoke(this, EventArgs.Empty));
handler.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Destroys this instance.
/// </summary>
public void Destroy()
{
this.canExecute = _ => false;
this.execute = _ => { return; };
}
/// <summary>
/// Defaults the can execute.
/// </summary>
/// <param name="parameter">The parameter.</param>
/// <returns>True a</returns>
private static bool DefaultCanExecute(object parameter)
{
return true;
}
}
}
<file_sep>/CryostatControlClient/Views/CommandPanel.xaml.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CommandPanel.xaml.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.Views
{
using System.Windows;
using System.Windows.Controls;
/// <summary>
/// Interaction logic for CommandPanel.xaml
/// </summary>
public partial class CommandPanel : Grid
{
}
}
<file_sep>/CryostatControlClient/ViewModels/ChartViewModel.cs
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ChartViewModel.cs" company="SRON">
// Copyright (c) 2017 SRON
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CryostatControlClient.ViewModels
{
using System;
using System.Windows.Input;
using CryostatControlClient.Models;
using LiveCharts;
using LiveCharts.Wpf;
/// <summary>
/// The zooming view model.
/// </summary>
/// <seealso cref="CryostatControlClient.ViewModels.AbstractViewModel" />
public class ChartViewModel : AbstractViewModel
{
#region Fields
/// <summary>
/// The zoom command
/// </summary>
private ICommand zoomCommand;
/// <summary>
/// The reset zooming command
/// </summary>
private ICommand resetCommand;
/// <summary>
/// The chart model
/// </summary>
private ChartModel chartModel;
#endregion Fields
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ChartViewModel"/> class.
/// </summary>
public ChartViewModel()
{
this.chartModel = new ChartModel();
this.zoomCommand = new RelayCommand(this.ToggleZoomingMode, param => true);
this.resetCommand = new RelayCommand(this.ResetZooming, param => true);
}
#endregion Constructor
#region Properties
/// <summary>
/// Gets the reset command.
/// </summary>
/// <value>
/// The reset command.
/// </value>
public ICommand ResetCommand
{
get
{
return this.resetCommand;
}
}
/// <summary>
/// Gets the zoom command.
/// </summary>
/// <value>
/// The zoom command.
/// </value>
public ICommand ZoomCommand
{
get
{
return this.zoomCommand;
}
}
/// <summary>
/// Gets or sets the x maximum.
/// </summary>
/// <value>
/// The x maximum.
/// </value>
public DateTime XMax
{
get
{
return this.chartModel.XMax;
}
set
{
this.chartModel.XMax = value;
this.RaisePropertyChanged("XAxisCollection");
}
}
/// <summary>
/// Gets or sets the x minimum.
/// </summary>
/// <value>
/// The x minimum.
/// </value>
public DateTime XMin
{
get
{
return this.chartModel.XMin;
}
set
{
this.chartModel.XMin = value;
this.RaisePropertyChanged("XAxisCollection");
}
}
/// <summary>
/// Gets or sets the y maximum.
/// </summary>
/// <value>
/// The y maximum.
/// </value>
public double YMax
{
get
{
return this.chartModel.YMax;
}
set
{
this.chartModel.YMax = value;
this.RaisePropertyChanged("YAxisCollection");
}
}
/// <summary>
/// Gets or sets the y maximum.
/// </summary>
/// <value>
/// The y maximum.
/// </value>
public double YMin
{
get
{
return this.chartModel.YMin;
}
set
{
this.chartModel.YMin = value;
this.RaisePropertyChanged("YAxisCollection");
}
}
/// <summary>
/// Gets the x axis collection.
/// </summary>
/// <value>
/// The x axis collection.
/// </value>
public AxesCollection XAxisCollection
{
get
{
return this.chartModel.XAxisCollection;
}
}
/// <summary>
/// Gets the y axis collection.
/// </summary>
/// <value>
/// The y axis collection.
/// </value>
public AxesCollection YAxisCollection
{
get
{
return this.chartModel.YAxisCollection;
}
}
/// <summary>
/// Gets or sets the zooming mode.
/// </summary>
/// <value>
/// The zooming mode.
/// </value>
public ZoomingOptions ZoomingMode
{
get
{
return this.chartModel.ZoomingMode;
}
set
{
this.chartModel.ZoomingMode = value;
this.RaisePropertyChanged("ZoomingMode");
}
}
#endregion Properties
#region Methods
/// <summary>
/// Toggles the zooming mode.
/// </summary>
/// <param name="sender">The sender.</param>
private void ToggleZoomingMode(object sender)
{
switch (this.ZoomingMode)
{
case ZoomingOptions.None:
this.ZoomingMode = ZoomingOptions.X;
break;
case ZoomingOptions.X:
this.ZoomingMode = ZoomingOptions.Y;
break;
case ZoomingOptions.Y:
this.ZoomingMode = ZoomingOptions.Xy;
break;
case ZoomingOptions.Xy:
this.ZoomingMode = ZoomingOptions.None;
break;
default:
this.ZoomingMode = ZoomingOptions.None;
break;
}
}
/// <summary>
/// Resets the zooming.
/// </summary>
/// <param name="sender">The sender.</param>
private void ResetZooming(object sender)
{
this.XMin = this.chartModel.GetDateTime(double.NaN);
this.XMax = this.chartModel.GetDateTime(double.NaN);
this.YMax = double.NaN;
this.YMin = 0;
this.RaisePropertyChanged("XAxisCollection");
this.RaisePropertyChanged("YAxisCollection");
}
#endregion Methods
}
}
|
2a8305b711606643a2645a306a85d7b5a0670d1a
|
[
"Markdown",
"C#"
] | 112 |
C#
|
BBekker/CryostatControl
|
98c185e41f8e66d290acb52470f33ad1d178e3cd
|
94bc7c4b201c9e2c8c52ec262b0bb4b2c979d2a0
|
refs/heads/master
|
<file_sep>package net.ultibyte.AutoMobNamer;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
public class CommandHandler implements CommandExecutor {
private AutoMobNamer plugin; // pointer to the main class.
Player p;
public CommandHandler(AutoMobNamer plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender commandsender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("namer")) {
if (args.length == 1) {
if (args[0].equalsIgnoreCase("help")) {
commandsender.sendMessage("*****************" + ChatColor.DARK_RED + "Auto" + ChatColor.BLUE + "Mob" + ChatColor.YELLOW + "Namer " + ChatColor.RESET + "*****************");
commandsender.sendMessage(ChatColor.AQUA + "The Commands are:");
commandsender.sendMessage(ChatColor.GREEN + "/namer add [MobType] [Name (Use _ for spaces!)]");
commandsender.sendMessage(ChatColor.GREEN + "/namer remove [MobType] [Name (Use _ for spaces!)]");
commandsender.sendMessage(ChatColor.GREEN + "/namer ColorOff - Turns colors off for newly spawned mobs");
commandsender.sendMessage(ChatColor.GREEN + "/namer ColorOn - Turns color on for newly spawned mobs");
commandsender.sendMessage(ChatColor.GREEN + "/namer clear [MobType] - Removes all names for this Mob Type (Leaving just the mob type as its name which you can also remove if you wish.)");
commandsender.sendMessage(ChatColor.GREEN + "/namer setvisibility [visible/invisible] - Causes mob names to only be visible when looked at at close proximity");
commandsender.sendMessage("*****************" + ChatColor.YELLOW + "Thats it!" + ChatColor.WHITE + "*****************");
return true;
}
if (args[0].equalsIgnoreCase("add")) {
commandsender.sendMessage(ChatColor.GREEN + "Go on... it's /namer add [MobType] [Name]");
}
if (args[0].equalsIgnoreCase("remove")) {
commandsender.sendMessage(ChatColor.GREEN + "Go on... it's /namer remove [MobType] [Name]");
}
if (args[0].equalsIgnoreCase("ColorOff")) {
VariableStuff.NoColor = true;
commandsender.sendMessage(ChatColor.GREEN + "Mob name colors have been turned off!");
}
if (args[0].equalsIgnoreCase("ColorOn")) {
VariableStuff.NoColor = false;
commandsender.sendMessage(ChatColor.GREEN + "Mob name colors are now on!");
}
if (args[0].equalsIgnoreCase("clear")) {
commandsender.sendMessage(ChatColor.GREEN + "Go on... it's /namer clear [MobType]");
}
}
if (args.length == 2) {
if (args[0].equalsIgnoreCase("add")) {
commandsender.sendMessage(ChatColor.GREEN + "Go on... it's /namer add [MobType] [Name]");
return true;
}
if (args[0].equalsIgnoreCase("setvisibility")) {
if(args[1].equalsIgnoreCase("visible") || args[1].equalsIgnoreCase("invisible")){
if(args[1].equalsIgnoreCase("visible")){
setVisibilityAll(true);
}else{
setVisibilityAll(false);
}
commandsender.sendMessage(ChatColor.GREEN + "Done!");
}else{
commandsender.sendMessage(ChatColor.GREEN + "Go on... it's /namer setvisibility [visible/invisible]");
}
return true;
}
if (args[0].equalsIgnoreCase("remove")) {
commandsender.sendMessage(ChatColor.GREEN + "Go on... it's /namer remove [MobType] [Name]");
return true;
}
if (args[0].equalsIgnoreCase("list")) {
if (args[1].equalsIgnoreCase("Bat")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Bat Names ********************");
for (String SomeName : plugin.BatNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("Chicken")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Chicken Names ********************");
for (String SomeName : plugin.ChickenNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("Cow")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Cow Names ********************");
for (String SomeName : plugin.CowNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if ((args[1].equalsIgnoreCase("IronGolem")) || (args[1].equalsIgnoreCase("Iron_Golem")) || (args[1].equalsIgnoreCase("Villager_Golem")) || (args[1].equalsIgnoreCase("VillagerGolem"))) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Iron Golem Names ********************");
for (String SomeName : plugin.IronGolemNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if ((args[1].equalsIgnoreCase("Mooshroom")) || (args[1].equalsIgnoreCase("MushroomCow")) || (args[1].equalsIgnoreCase("Mushroom_Cow"))) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Mooshroom Names ********************");
for (String SomeName : plugin.MooshroomNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if ((args[1].equalsIgnoreCase("Ocelot")) || (args[1].equalsIgnoreCase("Cat"))) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Ocelot Names ********************");
for (String SomeName : plugin.OcelotNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if ((args[1].equalsIgnoreCase("Pig"))) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Pig Names ********************");
for (String SomeName : plugin.PigNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if ((args[1].equalsIgnoreCase("Sheep"))) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Sheep Names ********************");
for (String SomeName : plugin.SheepNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if ((args[1].equalsIgnoreCase("Squid"))) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Squid Names ********************");
for (String SomeName : plugin.SquidNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if ((args[1].equalsIgnoreCase("Wolf")) || (args[1].equalsIgnoreCase("Dog"))) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Wolf Names ********************");
for (String SomeName : plugin.WolfNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if ((args[1].equalsIgnoreCase("Blaze"))) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Blaze Names ********************");
for (String SomeName : plugin.BlazeNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if ((args[1].equalsIgnoreCase("CaveSpider")) || (args[1].equalsIgnoreCase("Cave_Spider"))) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Cave Spider Names ********************");
for (String SomeName : plugin.CaveSpiderNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if ((args[1].equalsIgnoreCase("Creeper"))) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Creeper Names ********************");
for (String SomeName : plugin.CreeperNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if ((args[1].equalsIgnoreCase("EnderDragon")) || (args[1].equalsIgnoreCase("Ender_Dragon")) || (args[1].equalsIgnoreCase("Dragon"))) {
commandsender.sendMessage(ChatColor.BLUE + "******************** EnderDragon Names ********************");
for (String SomeName : plugin.EnderDragonNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("Enderman")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Enderman Names ********************");
for (String SomeName : plugin.EndermanNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("Ghast")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Ghast Names ********************");
for (String SomeName : plugin.GhastNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("MagmaCube") || args[1].equalsIgnoreCase("LavaCube") || args[1].equalsIgnoreCase("LavaSlime") || args[1].equalsIgnoreCase("MagmaSlime")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Magma Cube Names ********************");
for (String SomeName : plugin.MagmaCubeNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("Silverfish")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Silverfish Names ********************");
for (String SomeName : plugin.SilverfishNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("Skeleton")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Skeleton Names ********************");
for (String SomeName : plugin.SkeletonNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("Slime")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Slime Names ********************");
for (String SomeName : plugin.SlimeNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("SnowGolem") || args[1].equalsIgnoreCase("SnowMan")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Snow Golem Names ********************");
for (String SomeName : plugin.SnowGolemNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("Spider")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Spider Names ********************");
for (String SomeName : plugin.SpiderNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("Witch")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Witch Names ********************");
for (String SomeName : plugin.WitchNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("Wither")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Wither Names ********************");
for (String SomeName : plugin.WitherNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("Zombie")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Zombie Names ********************");
for (String SomeName : plugin.ZombieNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("ZombiePigman") || args[1].equalsIgnoreCase("Pigman")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Zombie Pigman Names ********************");
for (String SomeName : plugin.ZombiePigmanNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
if (args[1].equalsIgnoreCase("Villager")) {
commandsender.sendMessage(ChatColor.BLUE + "******************** Villager Names ********************");
for (String SomeName : plugin.VillagerNames) {
commandsender.sendMessage(ChatColor.AQUA + SomeName);
}
return true;
}
}
if (args[0].equalsIgnoreCase("clear")) {
if (args[1].equalsIgnoreCase("Bat")) {
plugin.BatNames.clear();
plugin.BatNames.add("Bat");
commandsender.sendMessage(ChatColor.GREEN + "Bat names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Chicken")) {
plugin.ChickenNames.clear();
plugin.ChickenNames.add("Chicken");
commandsender.sendMessage(ChatColor.GREEN + "Chicken names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Cow")) {
plugin.CowNames.clear();
plugin.CowNames.add("Cow");
commandsender.sendMessage(ChatColor.GREEN + "Cow names have been cleared!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("IronGolem")) || (args[1].equalsIgnoreCase("Iron_Golem")) || (args[1].equalsIgnoreCase("Villager_Golem")) || (args[1].equalsIgnoreCase("VillagerGolem"))) {
plugin.IronGolemNames.clear();
plugin.IronGolemNames.add("Iron Golem");
commandsender.sendMessage(ChatColor.GREEN + "Iron Golem names have been cleared!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Mooshroom")) || (args[1].equalsIgnoreCase("MushroomCow")) || (args[1].equalsIgnoreCase("Mushroom_Cow"))) {
plugin.MooshroomNames.clear();
plugin.MooshroomNames.add("Mooshroom");
commandsender.sendMessage(ChatColor.GREEN + "Mooshroom names have been cleared!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Ocelot")) || (args[1].equalsIgnoreCase("Cat"))) {
plugin.OcelotNames.clear();
plugin.OcelotNames.add("Ocelot");
commandsender.sendMessage(ChatColor.GREEN + "Mooshroom names have been cleared!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Pig"))) {
plugin.PigNames.clear();
plugin.PigNames.add("Pig");
commandsender.sendMessage(ChatColor.GREEN + "Pig names have been cleared!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Sheep"))) {
plugin.SheepNames.clear();
plugin.SheepNames.add("Sheep");
commandsender.sendMessage(ChatColor.GREEN + "Sheep names have been cleared!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Squid"))) {
plugin.SquidNames.clear();
plugin.SquidNames.add("Squid");
commandsender.sendMessage(ChatColor.GREEN + "Squid names have been cleared!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Wolf")) || (args[1].equalsIgnoreCase("Dog"))) {
plugin.WolfNames.clear();
plugin.WolfNames.add("Wolf");
commandsender.sendMessage(ChatColor.GREEN + "Wolf names have been cleared!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Blaze"))) {
plugin.BlazeNames.clear();
plugin.BlazeNames.add("Blaze");
commandsender.sendMessage(ChatColor.GREEN + "Blaze names have been cleared!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("CaveSpider")) || (args[1].equalsIgnoreCase("Cave_Spider"))) {
plugin.CaveSpiderNames.clear();
plugin.CaveSpiderNames.add("Cave Spider");
commandsender.sendMessage(ChatColor.GREEN + "Cave Spider names have been cleared!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Creeper"))) {
plugin.CreeperNames.clear();
plugin.CreeperNames.add("Creeper");
commandsender.sendMessage(ChatColor.GREEN + "Creeper names have been cleared!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("EnderDragon")) || (args[1].equalsIgnoreCase("Ender_Dragon")) || (args[1].equalsIgnoreCase("Dragon"))) {
plugin.EnderDragonNames.clear();
plugin.EnderDragonNames.add("EnderDragon");
commandsender.sendMessage(ChatColor.GREEN + "EnderDragon names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Enderman")) {
plugin.EndermanNames.clear();
plugin.EndermanNames.add("Enderman");
commandsender.sendMessage(ChatColor.GREEN + "Enderman names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Ghast")) {
plugin.GhastNames.clear();
plugin.GhastNames.add("Ghast");
commandsender.sendMessage(ChatColor.GREEN + "Ghast names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("MagmaCube") || args[1].equalsIgnoreCase("LavaCube") || args[1].equalsIgnoreCase("LavaSlime") || args[1].equalsIgnoreCase("MagmaSlime")) {
plugin.MagmaCubeNames.clear();
plugin.MagmaCubeNames.add("MagmaCube");
commandsender.sendMessage(ChatColor.GREEN + "MagmaCube names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Silverfish")) {
plugin.SilverfishNames.clear();
plugin.SilverfishNames.add("Silverfish");
commandsender.sendMessage(ChatColor.GREEN + "Silverfish names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Skeleton")) {
plugin.SkeletonNames.clear();
plugin.SkeletonNames.add("Skeleton");
commandsender.sendMessage(ChatColor.GREEN + "Skeleton names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Slime")) {
plugin.SlimeNames.clear();
plugin.SlimeNames.add("Slime");
commandsender.sendMessage(ChatColor.GREEN + "Slime names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("SnowGolem") || args[1].equalsIgnoreCase("SnowMan")) {
plugin.SnowGolemNames.clear();
plugin.SnowGolemNames.add("Slime");
commandsender.sendMessage(ChatColor.GREEN + "SnowGolem names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Spider")) {
plugin.SpiderNames.clear();
plugin.SpiderNames.add("Spider");
commandsender.sendMessage(ChatColor.GREEN + "Spider names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Witch")) {
plugin.WitchNames.clear();
plugin.WitchNames.add("Witch");
commandsender.sendMessage(ChatColor.GREEN + "Witch names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Wither")) {
plugin.WitherNames.clear();
plugin.WitherNames.add("Wither");
commandsender.sendMessage(ChatColor.GREEN + "Wither names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Zombie")) {
plugin.ZombieNames.clear();
plugin.ZombieNames.add("Zombie");
commandsender.sendMessage(ChatColor.GREEN + "Zombie names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("ZombiePigman") || args[1].equalsIgnoreCase("Pigman")) {
plugin.ZombiePigmanNames.clear();
plugin.ZombiePigmanNames.add("ZombiePigman");
commandsender.sendMessage(ChatColor.GREEN + "ZombiePigman names have been cleared!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Villager")) {
plugin.VillagerNames.clear();
plugin.VillagerNames.add("Villager");
commandsender.sendMessage(ChatColor.GREEN + "Villager names have been cleared!");
plugin.saveConfig();
return true;
}
}
}
if (args.length == 3) {
if (args[0].equalsIgnoreCase("add")) {
if (args[1].equalsIgnoreCase("Bat")) {
plugin.BatNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Bat Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Chicken")) {
plugin.ChickenNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Chicken Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Cow")) {
plugin.CowNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Cow Names!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("IronGolem")) || (args[1].equalsIgnoreCase("Iron_Golem")) || (args[1].equalsIgnoreCase("Villager_Golem")) || (args[1].equalsIgnoreCase("VillagerGolem"))) {
plugin.IronGolemNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Iron Golem Names!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Mooshroom")) || (args[1].equalsIgnoreCase("MushroomCow")) || (args[1].equalsIgnoreCase("Mushroom_Cow"))) {
plugin.MooshroomNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Mooshroom Names!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Ocelot")) || (args[1].equalsIgnoreCase("Cat"))) {
plugin.OcelotNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Ocelot Names!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Pig"))) {
plugin.PigNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Pig Names!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Sheep"))) {
plugin.SheepNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Sheep Names!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Squid"))) {
plugin.SquidNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Squid Names!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Wolf")) || (args[1].equalsIgnoreCase("Dog"))) {
plugin.WolfNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Wolf Names!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Blaze"))) {
plugin.BlazeNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Blaze Names!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("CaveSpider")) || (args[1].equalsIgnoreCase("Cave_Spider"))) {
plugin.CaveSpiderNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Cave Spider Names!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Creeper"))) {
plugin.CreeperNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Creeper Names!");
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("EnderDragon")) || (args[1].equalsIgnoreCase("Ender_Dragon")) || (args[1].equalsIgnoreCase("Dragon"))) {
plugin.EnderDragonNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Ender Dragon Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Enderman")) {
plugin.EndermanNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Enderman Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Ghast")) {
plugin.GhastNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Ghast Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("MagmaCube") || args[1].equalsIgnoreCase("LavaCube") || args[1].equalsIgnoreCase("LavaSlime") || args[1].equalsIgnoreCase("MagmaSlime")) {
plugin.MagmaCubeNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Magma Cube Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Silverfish")) {
plugin.SilverfishNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Silverfish Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Skeleton")) {
plugin.SkeletonNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Skeleton Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Slime")) {
plugin.SlimeNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Slime Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("SnowGolem") || args[1].equalsIgnoreCase("SnowMan")) {
plugin.SnowGolemNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Snow Golem Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Spider")) {
plugin.SpiderNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Spider Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Witch")) {
plugin.WitchNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Witch Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Wither")) {
plugin.WitherNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Wither Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Zombie")) {
plugin.ZombieNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Zombie Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("ZombiePigman") || args[1].equalsIgnoreCase("Pigman")) {
plugin.ZombiePigmanNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Zombie Pigman Names!");
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Villager")) {
plugin.VillagerNames.add(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been added to Villager Names!");
plugin.saveConfig();
return true;
}
}
if (args[0].equalsIgnoreCase("remove")) {
int ItWasThere = 0;
if (args[1].equalsIgnoreCase("Bat")) {
for (String name : plugin.BatNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.BatNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Bat Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in Bat Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Chicken")) {
for (String name : plugin.ChickenNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.ChickenNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Chicken Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in Chicken Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Cow")) {
for (String name : plugin.CowNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.CowNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Cow Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in Cow Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("IronGolem")) || (args[1].equalsIgnoreCase("Iron_Golem")) || (args[1].equalsIgnoreCase("Villager_Golem")) || (args[1].equalsIgnoreCase("VillagerGolem"))) {
for (String name : plugin.IronGolemNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.IronGolemNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Iron Golem Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in Iron Golem Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Mooshroom")) || (args[1].equalsIgnoreCase("MushroomCow")) || (args[1].equalsIgnoreCase("Mushroom_Cow"))) {
for (String name : plugin.MooshroomNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.MooshroomNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Mooshroom Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in Mooshroom Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Ocelot")) || (args[1].equalsIgnoreCase("Cat"))) {
for (String name : plugin.OcelotNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.OcelotNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Ocelot Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in Ocelot Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Pig"))) {
for (String name : plugin.PigNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.PigNames.remove(args[2]);
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Sheep"))) {
for (String name : plugin.SheepNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.SheepNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Sheep Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Squid"))) {
for (String name : plugin.SquidNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.SquidNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Squid Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Wolf")) || (args[1].equalsIgnoreCase("Dog"))) {
for (String name : plugin.WolfNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.WolfNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Wolf Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Blaze"))) {
for (String name : plugin.BlazeNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.BlazeNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Blaze Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("CaveSpider")) || (args[1].equalsIgnoreCase("Cave_Spider"))) {
for (String name : plugin.CaveSpiderNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.CaveSpiderNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Cave Spider Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("Creeper"))) {
for (String name : plugin.CreeperNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.CreeperNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Creeper Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if ((args[1].equalsIgnoreCase("EnderDragon")) || (args[1].equalsIgnoreCase("Ender_Dragon")) || (args[1].equalsIgnoreCase("Dragon"))) {
for (String name : plugin.EnderDragonNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.EnderDragonNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from EnderDragon Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Enderman")) {
for (String name : plugin.EndermanNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.EndermanNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Enderman Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Ghast")) {
for (String name : plugin.GhastNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.GhastNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Ghast Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("MagmaCube") || args[1].equalsIgnoreCase("LavaCube") || args[1].equalsIgnoreCase("LavaSlime") || args[1].equalsIgnoreCase("MagmaSlime")) {
for (String name : plugin.MagmaCubeNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.MagmaCubeNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Magma Cube Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Silverfish")) {
for (String name : plugin.SilverfishNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.SilverfishNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Silverfish Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Skeleton")) {
for (String name : plugin.SkeletonNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.SkeletonNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Skeleton Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Slime")) {
for (String name : plugin.SlimeNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.SlimeNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Slime Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("SnowGolem") || args[1].equalsIgnoreCase("SnowMan")) {
for (String name : plugin.SnowGolemNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.SnowGolemNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Snow Golem Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Spider")) {
for (String name : plugin.SpiderNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.SpiderNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Spider Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Witch")) {
for (String name : plugin.WitchNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.WitchNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Witch Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Wither")) {
for (String name : plugin.WitherNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.WitherNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Wither Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Zombie")) {
for (String name : plugin.ZombieNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.ZombieNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Zombie Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("ZombiePigman") || args[1].equalsIgnoreCase("Pigman")) {
for (String name : plugin.ZombiePigmanNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.ZombiePigmanNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Zombie Pigman Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
}
if (args[1].equalsIgnoreCase("Villager")) {
for (String name : plugin.VillagerNames) {
if (name.equalsIgnoreCase(args[2])) {
plugin.VillagerNames.remove(args[2]);
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " has been removed from Villager Names!");
ItWasThere = 1;
}
}
if (ItWasThere == 0) {
commandsender.sendMessage(ChatColor.GREEN + "That name isn't in" + args[1] + " Names. (You may have misspelled it)");
}
plugin.saveConfig();
return true;
} else {
commandsender.sendMessage(ChatColor.AQUA + "'" + args[2] + "'" + ChatColor.GREEN + " Is not a valid mob name :/ Try a different variant thereof.");
}
}
}
return false;
}
return false;
}
public void setVisibilityAll(boolean value) {
for (World w : plugin.getServer().getWorlds()) {
for (Entity e : w.getEntities()) {
if (e.getType().isAlive() && !e.getType().equals(EntityType.PLAYER)) {
((LivingEntity) e).setCustomNameVisible(value);
}
}
}
}
}
|
24c7816f1d00a6daa1ab86f43f03cfaa5c435750
|
[
"Java"
] | 1 |
Java
|
woutwoot/AutoMobNamer
|
c1a583ba0f59f8671f70ae1b0bb42418a2544fc4
|
c0d20c5684aa85f46d5b9b837f5e73e508801082
|
refs/heads/main
|
<file_sep>const showBoxes = false;
const looping = false;
const xsize = 1920;
const ysize = 1920;
var xwindow = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var ywindow = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
let y1 = ysize * 3 / 10;
let y2 = ysize - ysize * 3 / 10;
// Create the application helper and add its render target to the page
let app = new PIXI.Application({ backgroundColor: 0xffffff, width: xsize, height:ysize });
document.body.appendChild(app.view);
let scale = xwindow / xsize;
app.stage.scale.x = scale;
app.stage.scale.y = scale;
// vars
var lSpawnRect;
var rSpawnRect;
let lAttractor = null;
let rAttractor = null;
let petals = []; // Petal collection
// create brackground image
function loadBackground() {
let name = "bg.png";
let s = PIXI.Sprite.from(name);
app.stage.addChild(s);
}
// create spawn rectangles (left and right)
function createSpawnRects() {
let xOffset = xsize / 5;
let w = xsize / 100;
let h = ysize / 2;
let yDelta = ysize / 10;
lSpawnRect = new SpawnRectangle(-xOffset, y1 - yDelta, w, h, app.stage);
rSpawnRect = new SpawnRectangle(xsize + xOffset, y2 + yDelta, w,h, app.stage);
}
// create petal attractors (left and right)
function createAttractors() {
lAttractor = new Attractor(xsize / 3, y1, app.stage);
rAttractor = new Attractor(xsize - (xsize / 3), y2, app.stage);
}
// return true whne all petals have stopped
function updatePetals(delta) {
let res = true;
// particle update loop
for (i = 0; i < petals.length; ++i) {
if (!petals[i].update(xsize, delta)) {
res = false;
}
}
return res;
}
function cleanUpPetals() {
while (petals.length > 0) {
petals[0].cleanup(app.stage);
petals.splice(0, 1);
}
}
function createPetals() {
let numPetals = document.getElementById("numPetals").value;
let imageNum = 0;
let delay = 0;
for (let i = 0; i < numPetals; i = i + 2) {
imageNum++;
delay += 2;
petals[petals.length] = new Petal(i, lSpawnRect, lAttractor, (imageNum % 4) + 1, delay, app.stage);
petals[petals.length] = new Petal(i+1, rSpawnRect, rAttractor, (imageNum % 4) + 1, delay, app.stage);
}
}
// button response
function buttonAction() {
cleanUpPetals();
createPetals();
}
////////////////////////////////////////////////////////////////////////////////////////////////
loadBackground();
createSpawnRects();
createAttractors();
// sort
function sortSprites() {
app.stage.children.sort(function (a, b) {
if (a.ident != undefined && b.ident != undefined) {
if (a.ident > b.ident) {
return -1;
} else {
return 1;
}
} else {
return 0;
}
});
}
// Add a ticker callback to move the sprite back and forth
let elapsed = 0.0;
app.ticker.add((delta) => {
elapsed += delta;
if (updatePetals(delta)) {
cleanUpPetals();
}
sortSprites();
});
<file_sep>To run, open command window and localhost - eg
"python -m http.server 8080"
open "localhost:8080" in browser
'ctrl-c' to kill it
<file_sep>class Attractor {
constructor(x, y, container) {
// Initialize the pixi Graphics class
if (showBoxes) {
this.graphics = new PIXI.Graphics();
this.graphics.beginFill(0x0000ff);
this.graphics.drawRect(x - 10, y - 10, 20, 20);
this.graphics.endFill();
container.addChild(this.graphics);
}
this.x = x;
this.y = y;
}
getX() {
return this.x;
}
getY() {
return this.y;
}
}
<file_sep>class Petal {
constructor(id, spawnRect, attractor, imageNum, delay, container) {
let name = "petal0" + imageNum + ".png";
this.sprite = PIXI.Sprite.from(name);
this.sprite.x = 0.5;
this.sprite.y = 0.5;
this.sprite.ident = id;
container.addChild(this.sprite);
spawnRect.assignRandomSpawnPoint(this);
///
this.dx = 0.0;
this.dy = 0.0;
this.delay = parseInt(delay);
this.active = true;
this.lastDist = 999999;
this.updateSpriteCoords();
this.attractor = attractor;
this.pull = document.getElementById("pull").value;
this.sprite.rotation = Math.floor(Math.random() * 360) * Math.PI / 180;
this.rotateDelta = (Math.random() * 6.0) - 3.0;
this.distToAttractor = 0.0;
}
cleanup(container) {
container.removeChild(this.sprite);
}
// updates 1 petal's movement - returns when the journey is complete
update(xsize, delta) {
let res = false;
if (this.active == false) {
res = true;
} else if (this.delay > 0.0) {
this.delay -= delta;
} else {
// make petal grow gradually
let scaleDelta = 0.001 * delta;
this.sprite.scale.x += scaleDelta;
this.sprite.scale.y += scaleDelta;
this.sprite.rotation += (this.rotateDelta * delta) * Math.PI / 180;
let distX = (this.attractor.getX() - this.x);
let distY = (this.attractor.getY() - this.y);
this.distToAttractor = Math.sqrt(distX * distX + distY * distY);
if (this.distToAttractor == 0.0) {
this.distToAttractor = 1.0;
}
let coefficient = this.pull * delta / this.distToAttractor;
this.dx += distX * coefficient;
this.dy += distY * coefficient;
this.x += this.dx;
this.y += this.dy;
this.updateSpriteCoords();
// if petal is heading away from the attract and is outside the screen area, reset it
if (this.distToAttractor > this.lastDist) {
// if looping set scale
if (looping) {
this.sprite.scale.x = 1.0;
this.sprite.scale.y = 1.0;
} else { // disable petal
let xOffset = 2 * this.sprite.width;
if (this.x < - xOffset || this.x > xsize + xOffset) {
this.active = false;
}
}
}
this.lastDist = this.distToAttractor;
}
return res;
}
updateSpriteCoords() {
this.sprite.x = this.x - this.sprite.width / 2;
this.sprite.y = this.y - this.sprite.height / 2;
}
}
|
23fa866bdc141e9c2d7c74ac97b5785f16796310
|
[
"JavaScript",
"Text"
] | 4 |
JavaScript
|
underleg/sakuraParticles
|
821a5710572d35f430b4f1d694a8e27e17448155
|
f788b899dd37d90f790c941d7dd6f4a0f6cdbc9c
|
refs/heads/main
|
<repo_name>LEEbyeonghoon2/delegatePattern<file_sep>/delegatePattern/ViewController.swift
//
// ViewController.swift
// delegatePattern
//
// Created by 이병훈 on 2021/04/13.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var TF: UITextField!
override func viewDidLoad() {
self.TF.delegate = self
self.TF.clearsOnBeginEditing = true
}
/*텍스트 필드의 텍스트가 편집 시작할때 호출*/
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
print("텍스트 필드가 편집 시작!")
return true
}
/*텍스트 필드의 텍스트가 제거될떄 호출*/
func textFieldShouldClear(_ textField: UITextField) -> Bool {
print("텍스트 필드의 텍스트가 제거!")
return true
}
/*리턴키를 눌렀을때 최초응답자를 잃기 */
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
TF.resignFirstResponder()
return true
}
/*텍스트 필드에 문자열을 입력할수 없도록 하기*/
/*텍스트 필드의 글자 범위 8자 이하로 지정*/
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textCount = textField.text?.count else {
return false
}
if textCount > 7 {
let alert = UIAlertController(title: "경고", message: "8글자를 넘었습니다.", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default) { (_) in
self.TF.text = ""
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: false)
return false
}
if Int(string) != nil {
return true
} else {
return false
}
}
}
|
1683bb2a8fa3969604ef60029eab351e87630dd0
|
[
"Swift"
] | 1 |
Swift
|
LEEbyeonghoon2/delegatePattern
|
58d4d0b1afad863e8c1ff01e016741bb462cf8a3
|
09d4e3f679a6cfaa088abc8340f82a871190cce0
|
refs/heads/main
|
<repo_name>silva-rafael/mvc-nodestudio<file_sep>/App/models/Note.php
<?php
use \App\Core\Model;
class Note extends Model {
public function getAll() {
$sql = "SELECT * FROM notes";
$stmt = Model::getConn()->prepare($sql);
$stmt->execute();
if($stmt->rowCount() > 0) {
$resultado = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $resultado;
}else{
return [];
}
}
public function findId($id) {
$sql = "SELECT * FROM notes WHERE id = ?";
$stmt = Model::getConn()->prepare($sql);
$stmt->bindValue(1, $id);
$stmt->execute();
if($stmt->rowCount() > 0) {
$resultado = $stmt->fetch(\PDO::FETCH_ASSOC);
return $resultado;
}else{
return [];
}
}
}<file_sep>/public/index.php
<?php
require_once "../vendor/autoload.php";
$app = new \App\Core\App();
<file_sep>/App/views/template.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">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<title>Curso MVC</title>
</head>
<body>
<header>
<nav class="navbar navbar-nav navbar-expand-lg navbar-dark bg-dark">
<ul class="navbar nav ms-auto">
<li class="nav-item">
<a class="nav-link" href="/home">Inicio</a>
</li>
</ul>
</nav>
</header>
<?php require_once '../App/views/'.$view.'.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep>/App/views/notes/ver.php
<div class="container">
<h1><?php echo $data['titulo']; ?></h1>
<p><?php echo $data['descricao']; ?></p>
</div><file_sep>/App/controllers/home.php
<?php
class Home extends \App\Core\Controller {
public function index($dados = '') {
$note = $this->model('Note');
$dados = $note->getAll();
$this->view('home/index', $dados);
}
}
<file_sep>/README.md
# mvc-nodestudio
Um trabalho de arquitetura mvc<file_sep>/App/views/home/index.php
<?php foreach($data as $note): ?>
<div class="container">
<h2><a href="/notes/ver/<?php echo $note['id']; ?>" ><?php echo $note['titulo']; ?></a></h2>
<p><?php echo $note['descricao']; ?></p>
</div>
<?php endforeach; ?><file_sep>/App/controllers/notes.php
<?php
use \App\Core\Controller;
class Notes extends Controller {
public function ver($id = '') {
$note = $this->model('Note');
$dados = $note->findId($id);
$this->view('notes/ver', $dados);
}
}
|
59066a00542442f8a4e347f94c0c66aa0bf671ed
|
[
"Markdown",
"PHP"
] | 8 |
PHP
|
silva-rafael/mvc-nodestudio
|
3d7777ebbc2a20ea64ed64f7ef112311b216223a
|
eee094c36f63561222c80321093491813084d8db
|
refs/heads/master
|
<repo_name>jjbman52/DiscountStrategy<file_sep>/src/discountstrategy/Store.java
package discountstrategy;
public class Store {
private String storeId;
private String name;
private String address;
private String phoneNumber;
private String emailAddress;
public Store(final String storeId, final String name, final String address, final String phoneNumber, final String emailAddress){
setStoreId(storeId);
setName(name);
setAddress(address);
setPhoneNumber(phoneNumber);
}
public final String getStoreId() {
return storeId;
}
public final void setStoreId(String storeId) {
this.storeId = storeId;
}
public final String getName() {
return name;
}
public final void setName(String name) {
this.name = name;
}
public final String getAddress() {
return address;
}
public final void setAddress(String address) {
this.address = address;
}
public final String getPhoneNumber() {
return phoneNumber;
}
public final void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public final String getEmailAddress() {
return emailAddress;
}
public final void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
<file_sep>/test/discountstrategy/ProductTest.java
package discountstrategy;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class ProductTest {
private Product instance;
private String productId;
private String productName;
private double price;
private Discount discount;
public ProductTest() {
}
@Before
public void setUp() {
instance = new Product(productId, productName, price, discount);
}
@After
public void tearDown() {
}
@Test(expected = IllegalArgumentException.class)
public void testSetProductIdShouldNotAllowNull() {
instance.setProductId(null);
}
@Test(expected = IllegalArgumentException.class)
public void testSetProductIdShouldNotAllowEmpty() {
instance.setProductId("");
}
@Test(expected = IllegalArgumentException.class)
public void testSetProductNameShouldNotAllowNull() {
instance.setProductName(null);
}
@Test(expected = IllegalArgumentException.class)
public void testSetProductNameShouldNotAllowEmpty() {
instance.setProductName("");
}
@Test(expected = IllegalArgumentException.class)
public void testSetPriceShouldNotAllowLessThan0() {
instance.setPrice(-1);
}
@Test(expected = IllegalArgumentException.class)
public void testSetDiscountShouldNotBeNull() {
instance.setDiscount(null);
}
}
<file_sep>/src/discountstrategy/LineItem.java
package discountstrategy;
public class LineItem {
private Product product;
private int quantity;
public LineItem(String productId, int quantity, DataAccessStrategy dataAccessStrategy) {
setProduct(findProduct(productId, dataAccessStrategy));
this.quantity = quantity;
}
private Product findProduct(String productId, DataAccessStrategy dataAccessStrategy){
return dataAccessStrategy.findProduct(productId);
}
public final String getLineItem(){
String line;
line =
getProduct().getProductName() + " " + getProduct().getProductId() + " " + getProduct().getPrice() + " " + getDiscountAmount();
return line;
}
public final Product getProduct() {
return product;
}
public final void setProduct(Product product) throws MandatoryEntryException{
if(product == null){
throw new IllegalArgumentException("Product is not valid.");
}else{
this.product = product;
}
}
public final double getDiscountAmount(){
double discountAmount;
discountAmount = getProduct().getDiscount().calculateDiscount(quantity,product.getPrice());
return discountAmount;
}
public final int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) throws MandatoryEntryException{
if(quantity < 0){
throw new IllegalArgumentException("Input is not valid.");
}else{
this.quantity = quantity;
}
}
}
<file_sep>/src/discountstrategy/Startup.java
package discountstrategy;
public class Startup {
public static void main(String[] args) {
DataAccessStrategy dataAccessStrategy = new InMemoryDataStorage();
OutputStrategy output = new ConsoleOutput();
PosSystem pos = new PosSystem(output);
pos.startTransaction("12", "100", dataAccessStrategy);
pos.addItemToTransaction("A101", 1);
pos.addItemToTransaction("B205", 2);
pos.endTransaction();
}
}
<file_sep>/src/discountstrategy/NoDiscount.java
package discountstrategy;
public class NoDiscount implements Discount{
@Override
public double calculateDiscount(int qty, double price) {
return 0;
}
}
<file_sep>/src/discountstrategy/ConsoleOutput.java
package discountstrategy;
public class ConsoleOutput implements OutputStrategy {
@Override
public final void produceOutput(String line) throws MandatoryEntryException{
if(line == null || line.isEmpty() || line.length() < 2){
throw new IllegalArgumentException("Input is not valid.");
}else{
System.out.println(line);
}
}
}
<file_sep>/src/discountstrategy/PercentOffDiscount.java
package discountstrategy;
public class PercentOffDiscount implements Discount{
private double percent;
PercentOffDiscount(final double percent) {
this.setPercent(percent);
}
@Override
public final double calculateDiscount(int qty, double price) {
if (qty < 0 || price < 0){
throw new IllegalArgumentException("Input is not valid.");
} else {
return price * qty * percent;
}
}
public final double getPercent() {
return percent;
}
public final void setPercent(final double percent) throws MandatoryEntryException{
if(percent < 0){
throw new IllegalArgumentException("Input is not valid.");
}else{
this.percent = percent;
}
}
}
<file_sep>/src/discountstrategy/Receipt.java
package discountstrategy;
public class Receipt {
private DataAccessStrategy dataAccessStrategy;
private Store store;
private Customer customer;
private LineItem[] lineItems;
public Receipt(String storeId, String customerId, DataAccessStrategy dataAccessStrategy) {
this.setDataAccessStrategy(dataAccessStrategy);
lineItems = new LineItem[0];
this.store = findStore(storeId);
this.customer = findCustomer(customerId);
}
private final Store findStore(String storeId) throws MandatoryEntryException{
if(storeId == null || storeId.isEmpty()){
throw new IllegalArgumentException("Store ID is mandatory");
}
return dataAccessStrategy.findStore(storeId);
}
private final Customer findCustomer(String customerId) throws MandatoryEntryException{
if(customerId == null || customerId.isEmpty()) {
throw new IllegalArgumentException("Customer Id is mandatory");
}
return dataAccessStrategy.findCustomer(customerId);
}
public final LineItem addAndGetNewLineItem(final String productId, final int quantity){
LineItem lineItem = new LineItem(productId, quantity, dataAccessStrategy);
addToArray(lineItem);
return lineItem;
}
private final void addToArray(final LineItem lineItem) {
// needs validation
LineItem[] tempItems = new LineItem[lineItems.length + 1];
System.arraycopy(lineItems, 0, tempItems, 0, lineItems.length);
tempItems[lineItems.length] = lineItem;
lineItems = tempItems;
tempItems = null;
}
public final double getTotalDiscountAmount(){
double total = 0.0;
for(LineItem lineItem : lineItems){
total += lineItem.getDiscountAmount();
}
return total;
}
public final DataAccessStrategy getDataAccessStrategy() {
return dataAccessStrategy;
}
public final void setDataAccessStrategy(final DataAccessStrategy dataAccessStrategy) throws MandatoryEntryException{
if(dataAccessStrategy == null){
throw new IllegalArgumentException("DataAccessStrategy is not valid.");
}else{
this.dataAccessStrategy = dataAccessStrategy;
}
}
private final String getColumnHeadings(){
String headings = "ID Item Price Quantity Discount";
return headings;
}
public final String getReceipt(){
String data = "";
data += store.getName();
data += "Sold to: " + customer.getName();
data += "Sold to: " + ((customer.getName() == null) ? "" : customer.getName());
data += getColumnHeadings();
return data;
}
}
<file_sep>/src/discountstrategy/QuantityDiscount.java
package discountstrategy;
public class QuantityDiscount implements Discount {
private double percent;
private int minQty;
public QuantityDiscount(double percent, int minQty) {
setPercent(percent);
setMinQty(minQty);
}
@Override
public final double calculateDiscount(int qty, double price) throws MandatoryEntryException{
double discount = 0;
if(qty >= minQty){
discount = price * qty * percent;
}
return discount;
}
public double getPercent() {
return percent;
}
public void setPercent(double percent) throws MandatoryEntryException{
if(percent < 0){
throw new IllegalArgumentException("Input is not valid.");
}else{
this.percent = percent;
}
}
public int getMinQty() {
return minQty;
}
public void setMinQty(int minQty) {
this.minQty = minQty;
}
}
<file_sep>/src/discountstrategy/InMemoryDataStorage.java
package discountstrategy;
public class InMemoryDataStorage implements DataAccessStrategy{
private Store[] stores = {
new Store("12", "Kohl's", "1215 N West ST Milwaukee WI", "(444)444-4444", "<EMAIL>"),
new Store("13","Walmart","1756 N East ST Milwaukee WI","(555)555-5555","<EMAIL>")
};
private Customer[] customers = {
new Customer("100", "<NAME>"),
new Customer("200", "<NAME>"),
new Customer("300", "<NAME>")
};
// private Product[] products = {
// new Product("A101", "MLB Brewer's Hat ", 19.95, new PercentOffDiscount(0.15)),
// new Product("B205", "Men's Dress Shirt", 35.50, new QtyDiscount(.10,5)),
// new Product("C222", "Women's Socks ", 9.50, new NoDiscount())
// };
private Product[] products = {
new Product("A101", "MLB Brewer's Hat ", 19.95, new PercentOffDiscount(0.15)),
new Product("B205", "Men's Dress Shirt", 35.50, new QuantityDiscount(0.15,5)),
new Product("B300", "Men's Belt", 35.50, new BenchmarkDiscount(5.00,70.00, 1000)),
new Product("C222", "Women's Socks ", 9.50, new NoDiscount())
};
@Override
public final Store findStore(final String storeId) {
// validation is needed for method parameter
if(storeId == null || storeId.length() == 0) {
System.out.println("Sorry, FakeDatabase.findStore method has "
+ "illegal argument");
return null; // end method prematurely after log to console
}
Store store = null;
for(Store s : stores) {
if(storeId.equals(s.getStoreId())) {
store = s;
break;
}
}
return store;
}
/**
* Tries to find a Customer by customer id.
* @param custId - must not be null or empty
* @return found Customer or null if not found or bad argument
*/
@Override
public final Customer findCustomer(final String customerId) {
// validation is needed for method parameter
if(customerId == null || customerId.length() == 0) {
System.out.println("Sorry, FakeDatabase.findCustomer method has "
+ "illegal argument");
return null; // end method prematurely after log to console
}
Customer customer = null;
for(Customer c : customers) {
if(customerId.equals(c.getCustomerId())) {
customer = c;
break;
}
}
return customer;
}
/**
* Tries to find a Proudct by product id.
* @param prodId - must not be null or empty
* @return found Product or null if not found or bad argument
*/
@Override
public final Product findProduct(final String productId) {
// validation is needed for method parameter
if(productId == null || productId.length() == 0) {
System.out.println("Sorry, FakeDatabase.findProduct method has "
+ "illegal argument");
return null; // end method prematurely after log to console
}
Product product = null;
for(Product p : products) {
if(productId.equals(p.getProductId())) {
product = p;
break;
}
}
return product;
}
}<file_sep>/src/discountstrategy/PosSystem.java
package discountstrategy;
public class PosSystem {
private Receipt receipt;
private OutputStrategy output;
public PosSystem(OutputStrategy output){
this.output = new ConsoleOutput();
}
public final void startTransaction(String storeId, String customerId, DataAccessStrategy dataAccessStrategy) {
receipt = new Receipt(storeId, customerId, dataAccessStrategy);
}
/*
Simulating real world display of items being added and output to video monitor
*/
public final void addItemToTransaction(String productId, int productQuantity) {
LineItem lineItem = receipt.addAndGetNewLineItem(productId, productQuantity);
output = new ConsoleOutput();
output.produceOutput(lineItem.getLineItem());
}
public final void endTransaction() {
output.produceOutput(receipt.getReceipt());
}
}
|
797925c64951b75be39a4ed3e67dea34258e70f7
|
[
"Java"
] | 11 |
Java
|
jjbman52/DiscountStrategy
|
30459a799e986920769124f8d8f6f0788412981d
|
095d72f77d5e8d3584e421fed29bf3fc14f0b0b7
|
refs/heads/master
|
<repo_name>michaelmendoza42/vermuino<file_sep>/README.md
# vermuino
An arduboy port of the Game & Watch game titled "Vermin". I took the source code and bitmap assets from here: http://www.instructables.com/id/DIY-Game-Watch/ and ported it.
## Bugs and known issues
There are no lives, no gameovers, and no UI. Missing a mole plays a painfully slow animation.
## Installing
To install, check out the guide and on the arduboy forums: https://community.arduboy.com/t/quick-start-guide/2790
<file_sep>/vermuino/vermuino.ino
#include <Arduboy2.h>
#include "bitmaps.h"
Arduboy2 arduboy;
Sprites sprites;
// Things that make the game work the way it does
#define FRAMES_PER_SECOND 30 // The update and refresh speed
//VERMIN
#define UPTIME 10
#define MTIME 30
#define HUMP_LINE 45
#define HUMP_1_X 21
#define HUMP_2_X 38
#define HUMP_3_X 48
#define HUMP_4_X 80
#define HUMP_5_X 95
#define MAN_1_X 22
#define MAN_2_X 22
#define MAN_3_X 22
// Storage Vars
unsigned char ncount;
unsigned char gamelevel;
unsigned char humplevel;
unsigned char subcount;
unsigned char gametime;
unsigned char ltimer;
unsigned char utimer;
unsigned char mtimer;
unsigned int score;
unsigned char mole;
unsigned char manpos;
unsigned char humpstat[6]; //humpstat[1] - humpstat[5]
unsigned char molemiss;
unsigned char hump;
unsigned char nexthump;
unsigned int tmr3ov; //Timer 3 overflow counter
unsigned char tick;
unsigned int beep1; //mole beep
unsigned int beep2; //hit beep
unsigned int beep3; //miss beep
unsigned int AUTOcount;
unsigned int leftBuffer;
unsigned int rightBuffer;
unsigned int MOLE_1_X = HUMP_1_X + 1;
unsigned int MOLE_2_X = HUMP_2_X + 2;
unsigned int MOLE_3_X = HUMP_3_X + 10;
unsigned int MOLE_4_X = HUMP_4_X - 6;
unsigned int MOLE_5_X = HUMP_5_X - 3;
unsigned int MOLE_LINE = HUMP_LINE - 8;
unsigned int MAN_Y = HUMP_LINE - 33;
unsigned int MAN_POS = 0;
unsigned int MAN_STATE = 0;
// unsigned char mask;
// char string[4];
//pseudo random numbers
unsigned char prand;
///MAN 84,20
//MOLE 12, 8
//LIFE 11, 6
//MOLE_CLEAR 1
unsigned int humpFrame;
void setup() {
arduboy.begin();
arduboy.setFrameRate(FRAMES_PER_SECOND);
arduboy.clear();
arduboy.display();
delay(500);
String title = "VERMUINO";
arduboy.print(title);
//arduboy.drawBitmap(MAN_1_X, MAN_Y, man_1u, 84, 20);
arduboy.drawBitmap(MAN_2_X, MAN_Y, man_2u, 84, 20);
//arduboy.drawBitmap(MAN_3_X, MAN_Y, man_3u, 84, 20);
drawHump(HUMP_1_X, HUMP_LINE, hump_1, 8, 3);
drawHump(HUMP_2_X, HUMP_LINE, hump_2, 11, 3);
drawHump(HUMP_3_X, HUMP_LINE, hump_3, 16, 3);
drawHump(HUMP_4_X, HUMP_LINE, hump_4, 11, 3);
drawHump(HUMP_5_X, HUMP_LINE, hump_5, 8, 3);
arduboy.drawBitmap(MOLE_1_X, MOLE_LINE, mole_1, 12, 8);
arduboy.drawBitmap(MOLE_2_X, MOLE_LINE, mole_1, 12, 8);
arduboy.drawBitmap(MOLE_3_X, MOLE_LINE, mole_2, 12, 8);
arduboy.drawBitmap(MOLE_4_X, MOLE_LINE, mole_3, 12, 8);
arduboy.drawBitmap(MOLE_5_X, MOLE_LINE, mole_3, 12, 8);
arduboy.drawBitmap(MOLE_1_X, MOLE_LINE, mole_1_hit, 12, 8);
arduboy.drawBitmap(MOLE_2_X, MOLE_LINE, mole_1_hit, 12, 8);
arduboy.drawBitmap(MOLE_3_X, MOLE_LINE, mole_2_hit, 12, 8);
arduboy.drawBitmap(MOLE_4_X, MOLE_LINE, mole_3_hit, 12, 8);
arduboy.drawBitmap(MOLE_5_X, MOLE_LINE, mole_3_hit, 12, 8);
drawGround();
arduboy.display();
humpFrame = 2;
gamelevel = 2;
humplevel = 4;
nexthump = 0;
subcount = 0;
ltimer = 0;
utimer = 0;
tmr3ov = 0;
tick = 1;
score = 0;
manpos = 1;
mole = 0;
molemiss = 0;
beep1 = 0;
beep2 = 0;
beep3 = 0;
humpstat[0] = 0xff;
humpstat[1] = 0; //0 = off
humpstat[2] = 0; //0 = off
humpstat[3] = 0; //0 = off
humpstat[4] = 0; //0 = off
humpstat[5] = 0; //0 = off
arduboy.setCursor(58, 48);
while (!arduboy.buttonsState()) { }; // Wait for any key press
}
void loop() {
if (!(arduboy.nextFrame())) { return; }
arduboy.clear();
arduboy.pollButtons();
drawGround();
drawMan(manpos, MAN_STATE);
if ((utimer == 0) && (gamelevel > 0)) {
if (leftPressed())
{
if(manpos > 0)
{
manpos--;
}
}
if (rightPressed())
{
if(manpos < 2)
{
manpos++;
}
}
}
if(tick == 1) {
//tick = 0;
AUTOcount++;
if (AUTOcount > 3000) {
AUTOcount = 0;
}
/*
if (gamelevel == 0)
{
if (SWST_MODE)
{
gamelevel = 1; //Game A
gametime = 35;
subcount = 10;
}
if (SWST_PRO)
{
gamelevel = 2; //Game B
gametime = 25;
subcount = 6;
}
}
else
{
if (SWST_MODE)
{
if (sound) sound = 0;
else sound = 0xff;
}
*/
ltimer++;
if (ltimer >= gametime){
ltimer = 0;
if (!mtimer) //don't auto inc if mole miss sequence in progress
{
//speed 1 1 sec
//1 on 4 10
//speed 2 0.8 sec
//11 on 3 8 7,8,9
//19 on 2 6 4,5,6
//25 on 4 4 3,4,5
//speed 3 0.7
//29 on 3 7
//36 on 2 5
//41 on 4 5
//speed 4 0.6
//46 on 3 8
//54 on 2 5
//59 on 4 3
//speed 5 0.5
//62 on 3 9
//71 on 2 4
//75 on 4 4
//79 on 3 9
//88 on 2 6
//94 on 4 3
//97 on 3 8
//105 on 2 5
//110 on 4 3
//113 on 3
//
if ((humpstat[1] > 0) && (humpstat[1] < 6)) humpstat[1]++; beep1 = 40;
if ((humpstat[2] > 0) && (humpstat[2] < 6)) humpstat[2]++; beep1 = 40;
if ((humpstat[3] > 0) && (humpstat[3] < 6)) humpstat[3]++; beep1 = 40;
if ((humpstat[4] > 0) && (humpstat[4] < 6)) humpstat[4]++; beep1 = 40;
if ((humpstat[5] > 0) && (humpstat[5] < 6)) humpstat[5]++; beep1 = 40;
ncount=0;
if (gamelevel == 1)
{
if (score < 10) gametime = 35; //speed 1 1 sec
else if (score < 25) gametime = 30; //speed 2 0.8 sec
else if (score < 45) gametime = 25; //speed 3 0.7
else if (score < 60) gametime = 20; //speed 4 0.6
else gametime = 15; //speed 5 0.5
if (subcount == 0)
{
if (humplevel == 4)
{
humplevel = 3;
subcount = 4 + random3(); //4,5,6
}
else if(humplevel == 3)
{
humplevel = 2;
subcount = 3 + random3(); //3,4,5
}
else // humplevel == 2
{
humplevel = 4;
subcount = 7 + random3(); //7,8,9
}
}
while((humpstat[nexthump]) && (ncount++<128))
{
nexthump = random1();
}
}
else if (gamelevel == 2)
{
if (score < 25) gametime = 25; //speed 2 0.7 sec
else if (score < 45) gametime = 20; //speed 3 0.6
else if (score < 60) gametime = 15; //speed 4 0.5
else gametime = 10; //speed 5 0.4
if (subcount == 0)
{
if (humplevel == 4)
{
humplevel = 3;
subcount = 4 + random3(); //4,5,6
}
else if(humplevel == 3)
{
humplevel = 2;
subcount = 3 + random3(); //3,4,5
}
else // humplevel == 2
{
humplevel = 4;
subcount = 5 + random3(); //5,6,7
}
}
while((humpstat[nexthump]) && (ncount++<128))
{
nexthump = random2();
}
}
if (ncount<128) //successful random hump selection
{
if ((hump == 0) || ((hump == 1)&&(humpstat[1] == humplevel)) || ((hump == 2)&&(humpstat[2] == humplevel)) || ((hump == 3)&&(humpstat[3] == humplevel)) || ((hump == 4)&&(humpstat[4] == humplevel)) || ((hump == 5)&&(humpstat[5] == humplevel)))
{
hump = nexthump;
if (hump == 1)
humpstat[1] = 1;
else if (hump == 2)
humpstat[2] = 1;
else if (hump == 3)
humpstat[3] = 1;
else if (hump == 4)
humpstat[4] = 1;
else if (hump == 5)
humpstat[5] = 1;
subcount--;
}
}
}
}
if (utimer) utimer--;
if (mtimer) mtimer--;
switch (humpstat[1])
{
case 0: drawHump(HUMP_1_X, HUMP_LINE, hump_1, 8, 0); break;
case 1: drawHump(HUMP_1_X, HUMP_LINE, hump_1, 8, 1); break;
case 2: drawHump(HUMP_1_X, HUMP_LINE, hump_1, 8, 2); break;
case 3: drawHump(HUMP_1_X, HUMP_LINE, hump_1, 8, 3); break;
case 4: arduboy.drawBitmap(MOLE_1_X, MOLE_LINE, mole_1, 12, 8); humpstat[1] = 5; break;
case 5: if ((!molemiss)&&(manpos == 0)){arduboy.drawBitmap(MOLE_1_X, MOLE_LINE, mole_1_hit, 12, 8); MAN_STATE = 1; score++; utimer = UPTIME; humpstat[1] = 7;} break; //hit
case 6: beep2 = 4000; arduboy.drawBitmap(0, 25, mole_clear, 1, 3); mtimer = MTIME; molemiss = 1; humpstat[1] = 8; break; //miss
case 7: if (!utimer) {beep2 = 40; MAN_STATE = 0; arduboy.drawBitmap(HUMP_1_X, MOLE_LINE, mole_clear, 1, 8); drawHump(HUMP_1_X, HUMP_LINE, hump_1, 8, 0); humpstat[1] = 0;} break;
case 8: drawHump(HUMP_1_X, HUMP_LINE, hump_1, 8, 2); if (!mtimer) {beep1 = 40; mtimer = MTIME; humpstat[1] = 9;} break;
case 9: drawHump(HUMP_1_X, HUMP_LINE, hump_1, 8, 1); if (!mtimer) {beep1 = 40; mtimer = MTIME; humpstat[1] = 10;} break;
case 10: drawHump(HUMP_1_X, HUMP_LINE, hump_1, 8, 0); if (!mtimer) {beep1 = 40; mole++; mtimer = MTIME; humpstat[1] = 11;} break;
case 11: if (!mtimer) humpstat[1] = 0; if(humplevel==2) hump = 0; break;
}
switch (humpstat[2])
{
case 0: drawHump(HUMP_2_X, HUMP_LINE, hump_2, 11, 0); break;
case 1: drawHump(HUMP_2_X, HUMP_LINE, hump_2, 11, 1); break;
case 2: drawHump(HUMP_2_X, HUMP_LINE, hump_2, 11, 2); break;
case 3: drawHump(HUMP_2_X, HUMP_LINE, hump_2, 11, 3); break;
case 4: arduboy.drawBitmap(MOLE_2_X, MOLE_LINE, mole_1, 12, 8); humpstat[2] = 5; break;
case 5: if ((!molemiss)&&(manpos == 1)){arduboy.drawBitmap(MOLE_2_X, MOLE_LINE, mole_1_hit, 12, 8); MAN_STATE = 1; score++; utimer = UPTIME; humpstat[2] = 7;} break; //hit
case 6: beep2 = 4000; arduboy.drawBitmap(MOLE_2_X, MOLE_LINE, mole_clear, 1, 6); mtimer = MTIME; molemiss = 1; if (!mtimer) { humpstat[2] = 8;} break; //miss
case 7: if (!utimer) {beep2 = 40; MAN_STATE = 0; arduboy.drawBitmap(MOLE_2_X, MOLE_LINE, mole_clear, 1, 4); drawHump(HUMP_2_X, HUMP_LINE, hump_2, 11, 0); humpstat[2] = 0;} break;
case 8: drawHump(HUMP_2_X, HUMP_LINE, hump_2, 11, 2); if (!mtimer) {beep1 = 40; mtimer = MTIME; humpstat[2] = 9;} break;
case 9: drawHump(HUMP_2_X, HUMP_LINE, hump_2, 11, 1); if (!mtimer) {beep1 = 40; mtimer = MTIME; humpstat[2] = 10;} break;
case 10: drawHump(HUMP_2_X, HUMP_LINE, hump_2, 11, 0); if (!mtimer) {beep1 = 40;mole++; mtimer = MTIME; humpstat[2] = 11;} break;
case 11: if (!mtimer) humpstat[2] = 0; if(humplevel==2) hump = 0; break;
}
switch (humpstat[3])
{
case 0: drawHump(HUMP_3_X, HUMP_LINE, hump_3, 16, 0); break;
case 1: drawHump(HUMP_3_X, HUMP_LINE, hump_3, 16, 1); break;
case 2: drawHump(HUMP_3_X, HUMP_LINE, hump_3, 16, 2); break;
case 3: drawHump(HUMP_3_X, HUMP_LINE, hump_3, 16, 3); break;
case 4: arduboy.drawBitmap(MOLE_3_X, MOLE_LINE, mole_2, 12, 8); humpstat[3] = 5; break;
case 5: if ((!molemiss) && (manpos == 0)){arduboy.drawBitmap(MOLE_3_X, MOLE_LINE, mole_2_hit, 12, 8); MAN_STATE = 2; score++; utimer = UPTIME; humpstat[3] = 7;} //hit
else if ((!mtimer) && (manpos == 2)){arduboy.drawBitmap(MOLE_3_X, MOLE_LINE, mole_2_hit, 12, 8); MAN_STATE = 1; score++; utimer = UPTIME; humpstat[3] = 7;} break;
case 6: beep2 = 4000; arduboy.drawBitmap(MOLE_3_X, MOLE_LINE, mole_clear, 1, 3); mtimer = MTIME; molemiss = 1; humpstat[3] = 8; break;
case 7: if (!utimer) {beep2 = 40; MAN_STATE = 0; arduboy.drawBitmap(MOLE_3_X, MOLE_LINE, mole_clear, 1, 3); drawHump(HUMP_3_X, HUMP_LINE, hump_3, 16, 0); humpstat[3] = 0;} break;
case 8: drawHump(HUMP_3_X, HUMP_LINE, hump_3, 16, 2); if (!mtimer) {beep1 = 40; mtimer = MTIME; humpstat[3] = 9;} break;
case 9: drawHump(HUMP_3_X, HUMP_LINE, hump_3, 16, 1); if (!mtimer) {beep1 = 40; mtimer = MTIME; humpstat[3] = 10;} break;
case 10: drawHump(HUMP_3_X, HUMP_LINE, hump_3, 16, 0); if (!mtimer) {beep1 = 40; mole++; mtimer = MTIME; humpstat[3] = 11;} break;
case 11: if (!mtimer) humpstat[3] = 0; if(humplevel==2) hump = 0; break;
}
switch (humpstat[4])
{
case 0: drawHump(HUMP_4_X, HUMP_LINE, hump_4, 11, 0); break;
case 1: drawHump(HUMP_4_X, HUMP_LINE, hump_4, 11, 1); break;
case 2: drawHump(HUMP_4_X, HUMP_LINE, hump_4, 11, 2); break;
case 3: drawHump(HUMP_4_X, HUMP_LINE, hump_4, 11, 3); break;
case 4: arduboy.drawBitmap(MOLE_4_X, MOLE_LINE, mole_3, 12, 8); humpstat[4] = 5; break;
case 5: if ((!molemiss)&&(manpos == 1)){arduboy.drawBitmap(MOLE_4_X, MOLE_LINE, mole_3_hit, 12, 8); MAN_STATE = 2; score++; utimer = UPTIME; humpstat[4] = 7;} break; //hit
case 6: beep2 = 4000; arduboy.drawBitmap(MOLE_4_X, MOLE_LINE, mole_clear, 52, 3); mtimer = MTIME; molemiss = 1; humpstat[4] = 8; break;
case 7: if (!utimer) {beep2 = 40; MAN_STATE = 0; arduboy.drawBitmap(MOLE_4_X, MOLE_LINE, mole_clear, 1, 3); drawHump(HUMP_4_X, HUMP_LINE, hump_4, 11, 0); humpstat[4] = 0;} break;
case 8: drawHump(HUMP_4_X, HUMP_LINE, hump_4, 11, 2); if (!mtimer) {beep1 = 40; mtimer = MTIME; humpstat[4] = 9;} break;
case 9: drawHump(HUMP_4_X, HUMP_LINE, hump_4, 11, 1); if (!mtimer) {beep1 = 40; mtimer = MTIME; humpstat[4] = 10;} break;
case 10: drawHump(HUMP_4_X, HUMP_LINE, hump_4, 11, 0); if (!mtimer) {beep1 = 40; mole++; mtimer = MTIME; humpstat[4] = 11;} break;
case 11: if (!mtimer) humpstat[4] = 0; if(humplevel==2) hump = 0; break;
}
switch (humpstat[5])
{
case 0: drawHump(HUMP_5_X, HUMP_LINE, hump_5, 8, 0); break;
case 1: drawHump(HUMP_5_X, HUMP_LINE, hump_5, 8, 1); break;
case 2: drawHump(HUMP_5_X, HUMP_LINE, hump_5, 8, 2); break;
case 3: drawHump(HUMP_5_X, HUMP_LINE, hump_5, 8, 3); break;
case 4: arduboy.drawBitmap(MOLE_5_X, MOLE_LINE, mole_3, 12, 8); humpstat[5] = 5; break;
case 5: if ((!molemiss)&&(manpos == 2)){arduboy.drawBitmap(MOLE_5_X, MOLE_LINE, mole_3_hit, 12, 8); MAN_STATE = 2; score++; utimer = UPTIME; humpstat[5] = 7;} break; //hit
case 6: beep2 = 4000; arduboy.drawBitmap(MOLE_5_X, MOLE_LINE, mole_clear, 69, 3); mtimer = MTIME; molemiss = 1; humpstat[5] = 8; break;
case 7: if (!utimer) {beep2 = 40; MAN_STATE = 0; arduboy.drawBitmap(MOLE_5_X, MOLE_LINE, mole_clear, 1, 3); arduboy.drawBitmap(HUMP_5_X, HUMP_LINE, hump_5, 8, 0); humpstat[5] = 0;} break;
case 8: drawHump(HUMP_5_X, HUMP_LINE, hump_5, 8, 2); if (!mtimer) {beep1 = 40; mtimer = MTIME; humpstat[5] = 9;} break;
case 9: drawHump(HUMP_5_X, HUMP_LINE, hump_5, 8, 1); if (!mtimer) {beep1 = 40; mtimer = MTIME; humpstat[5] = 10;} break;
case 10: drawHump(HUMP_5_X, HUMP_LINE, hump_5, 8, 0); if (!mtimer) {beep1 = 40; mole++; mtimer = MTIME; humpstat[5] = 11;} break;
case 11: if (!mtimer) humpstat[5] = 0; if(humplevel==2) hump = 0; break;
}
if (!mtimer) molemiss = 0;
/*
if (mole == 1) arduboy.drawBitmap(0, 50, life, 9, 5);
if (mole == 2) arduboy.drawBitmap(25, 50, life, 9, 5);
if (mole == 3) {arduboy.drawBitmap(50, 50, life, 9, 5); gamelevel = 0; beep3 = 8000;} //end game */
arduboy.print(score);
arduboy.display();
}
}
void drawHump(int16_t x, int16_t y, const uint8_t * bitmap, uint8_t w, unsigned char frame) {
arduboy.drawBitmap(x, y, bitmap, w, 8);
arduboy.fillRect(x, y, w, 9 - frame * 3, BLACK);
}
void drawGround() {
unsigned int line = MOLE_LINE + 6;
arduboy.drawLine(0, line, 22, line);
//GAP 1 = 12
arduboy.drawLine(34, line, 40, line);
//GAP 2 = 12
arduboy.drawLine(52, line, 58, line);
//GAP 3 = 11
arduboy.drawLine(69, line, 75, line);
//GAP 4 = 12
arduboy.drawLine(87, line, 93, line);
//GAP 5 = 12
arduboy.drawLine(105, line, 128, line);
}
void drawMan(int pos, int state) {
switch (pos) {
case 0:
switch (state) {
case 0:
arduboy.drawBitmap(MAN_1_X, MAN_Y, man_1u, 84, 20);
break;
case 1:
arduboy.drawBitmap(MAN_1_X, MAN_Y, man_1l, 84, 20);
break;
case 2:
arduboy.drawBitmap(MAN_1_X, MAN_Y, man_1r, 84, 20);
break;
}
break;
case 1:
switch (state) {
case 0:
arduboy.drawBitmap(MAN_1_X, MAN_Y, man_2u, 84, 20);
break;
case 1:
arduboy.drawBitmap(MAN_1_X, MAN_Y, man_2l, 84, 20);
break;
case 2:
arduboy.drawBitmap(MAN_1_X, MAN_Y, man_2r, 84, 20);
break;
}
break;
case 2:
switch (state) {
case 0:
arduboy.drawBitmap(MAN_1_X, MAN_Y, man_3u, 84, 20);
break;
case 1:
arduboy.drawBitmap(MAN_1_X, MAN_Y, man_3l, 84, 20);
break;
case 2:
arduboy.drawBitmap(MAN_1_X, MAN_Y, man_3r, 84, 20);
break;
}
break;
}
}
boolean leftPressed() {
return (arduboy.justPressed(LEFT_BUTTON) || arduboy.justPressed(A_BUTTON));
}
boolean rightPressed() {
return (arduboy.justPressed(RIGHT_BUTTON) || arduboy.justPressed(B_BUTTON));
}
unsigned char random1() {
return pgm_read_byte_near(randomtable1 + prand++);
}
unsigned char random2() {
return pgm_read_byte_near(randomtable2 + prand++);
}
unsigned char random3() {
return pgm_read_byte_near(randomtable3 + prand++);
}
byte getOffset(unsigned int s) {
if (s > 9999) { return 24; }
if (s > 999) { return 18; }
if (s > 99) { return 12; }
if (s > 9) { return 6; }
return 0;
}
|
d3b000e2b2451b13ecd4369e6b102d38165bdead
|
[
"Markdown",
"C++"
] | 2 |
Markdown
|
michaelmendoza42/vermuino
|
44ab26b9218d0ce4cd51879fc7f81a4072ad4454
|
219d814ffa1c1177e19114d8bfd723b740af364a
|
refs/heads/master
|
<repo_name>xdefrag/image-grabber<file_sep>/README.md
# image-grabber
My first program in Go, don't take it too seriously
## Usages
````
image-grabber -f=<FROM> -t=<TO>
````
For help:
````
image-grabber -h
````
## Example
````
image-grabber -f=http://habrahabr.ru -t=hbrmgs/
````
Will download all images FROM http://habrahabr.ru TO folder hbrmgs/ where binary located.
<file_sep>/image-grabber.go
package main
import (
"log"
"fmt"
"os"
"io"
"strings"
"net/url"
"net/http"
"time"
"flag"
"github.com/PuerkitoBio/goquery"
)
var (
mainLink = flag.String("f", "http://google.com", "")
savePath = flag.String("t", "img/", "")
)
func main() {
start := time.Now()
flag.Parse()
grabber(*mainLink)
elapsed := time.Since(start)
fmt.Printf("f=%s", *mainLink)
fmt.Printf("\nt=%s", *savePath)
fmt.Printf("\nDONE in %s", elapsed)
}
func grabber(link string) {
doc, err := goquery.NewDocument(link)
checkErr(err)
_ = os.Mkdir(*savePath, 0700)
doc.Find("img").Each(func(i int, img *goquery.Selection){
imgLink, _ := img.Attr("src")
checkErr(err)
getImg(imgLink)
})
}
func checkErr(e error) {
if e != nil {
log.Fatal(e)
}
}
func getImg(imgLink string) {
var (
filepath string
)
imgLink = checkImgLink(imgLink)
filename := getFilename(imgLink)
response, err := http.Get(imgLink)
checkErr(err)
filepath += *savePath
filepath += filename
file, err := os.Create(filepath)
checkErr(err)
_, err = io.Copy(file, response.Body)
checkErr(err)
file.Close()
response.Body.Close()
}
func getFilename(link string) (name string) {
i := strings.Split(link, "/")
name = i[len(i)-1]
return name
}
func getDomain(link string) (name string) {
i, _ := url.Parse(link)
name = i.Host
return name
}
func checkImgLink(imgLink string) (outputLink string) {
if strings.HasPrefix(imgLink, "http") {
outputLink = imgLink
} else {
domain := getDomain(*mainLink)
outputLink += "http://"
outputLink += domain
outputLink += imgLink
}
return outputLink
}
|
bd6b7dbaf712931318533fbfbbcc9602ed9e508a
|
[
"Markdown",
"Go"
] | 2 |
Markdown
|
xdefrag/image-grabber
|
671d37399d1f385a7e9b948f28a909d0f9fff317
|
b7dd25100bb3a6ac72b8798bcfb498bcd3805548
|
refs/heads/master
|
<file_sep>def select_books_titles_and_years_in_first_series_order_by_year
"SELECT books.title, books.year FROM books WHERE books.series_id = 1 ORDER BY books.year ASC"
end
def select_name_and_motto_of_char_with_longest_motto
"SELECT characters.name, characters.motto FROM characters ORDER BY LENGTH(characters.motto) DESC LIMIT 1"
end
def select_value_and_count_of_most_prolific_species
"SELECT characters.species, COUNT(characters.species) FROM characters GROUP BY characters.species ORDER BY COUNT(characters.species) DESC LIMIT 1"
end
def select_name_and_series_subgenres_of_authors
"SELECT authors.name, subgenres.name FROM authors LEFT JOIN series ON authors.id = series.author_id LEFT JOIN subgenres ON series.subgenre_id = subgenres.id"
end
def select_series_title_with_most_human_characters
"SELECT series.title FROM series LEFT JOIN characters ON series.id = characters.series_id WHERE characters.species = 'human' GROUP BY series.title ORDER BY COUNT(characters.species) DESC LIMIT 1"
end
def select_character_names_and_number_of_books_they_are_in
"SELECT characters.name, COUNT(books.title) FROM characters LEFT JOIN character_books ON characters.id = character_books.character_id LEFT JOIN books ON books.id = character_books.book_id GROUP BY characters.name ORDER BY COUNT(books.title) DESC"
end
|
6a2dda4114df5488f0dc91b96999a47423c01ed1
|
[
"Ruby"
] | 1 |
Ruby
|
krandles/sql-library-lab-web-121117
|
7a04c03cb5aa4bd1ce6754f975dfcd1b144b44e5
|
fb9723cdf455738f099190896793418cefe7b281
|
refs/heads/master
|
<file_sep>use spinners::{Spinner, Spinners};
use std::thread::sleep;
use std::time::Duration;
fn main() {
let sp = Spinner::new(&Spinners::Dots9, "Waiting for 3 seconds".into());
sleep(Duration::from_secs(3));
sp.stop();
}
<file_sep>use spinners::{Spinner, Spinners};
use std::thread::sleep;
use std::time::Duration;
use strum::IntoEnumIterator;
fn main() {
// loop through each spinner and display them during 2 seconds
for spinner in Spinners::iter() {
print!("{}", ansi_escapes::EraseLines(10000));
let sp = Spinner::new(&spinner, format!("{:?}", spinner));
sleep(Duration::from_secs(2));
sp.stop();
}
}
<file_sep>[package]
name = "spinners"
version = "2.0.1-alpha.0"
edition = "2018"
authors = ["<NAME> <<EMAIL>>"]
homepage = "https://github.com/FGRibreau/spinners"
repository = "https://github.com/FGRibreau/spinners"
readme = "README.md"
documentation = "https://docs.rs/spinners"
description = "🛎 60+ Elegant terminal spinners for Rust"
keywords = ["spinner", "spin", "loader", "term", "terminal"]
categories = ["command-line-interface"]
license = "MIT"
include = ["src/**/*", "README.md"]
[package.metadata.release]
# cargo install cargo-release
# cargo release --dry-run
pre-release-commit-message = "Release {{version}} 🎉🎉"
pre-release-replacements = [ {file="README.md", search="Current release: [a-z0-9\\.-]+", replace="Current release: {{version}}"} , {file ="Cargo.toml", search="branch=\"[a-z0-9\\.-]+\"", replace="branch=\"{{version}}\""} ]
[dependencies]
spinner = "0.5"
lazy_static = "1.4"
strum = "0.21"
strum_macros = "0.21"
maplit = "1.0"
[dev-dependencies]
ansi_term = "0.9"
term = "0.4.6"
ansi-escapes = "0.1.0"
<file_sep>pub mod spinner_data;
pub mod spinner_names;
pub mod spinners_data;
<file_sep>use spinner::{SpinnerBuilder, SpinnerHandle};
use std::time::Duration;
pub mod utils;
pub use crate::utils::spinner_names::SpinnerNames as Spinners;
use crate::utils::spinners_data::SPINNERS as RawSpinners;
pub struct Spinner {
handle: SpinnerHandle,
}
impl Spinner {
/// Create a new spinner along with a message
///
/// Returns a spinner
pub fn new(spinner: &Spinners, message: String) -> Self {
let spinner_name = format!("{:?}", spinner);
let spinner_data = match RawSpinners.get(&spinner_name) {
Some(spinner_data) => spinner_data,
None => panic!("No Spinner found with the given name: {}", spinner_name),
};
// @todo implement my own Spinner thread
let handle = SpinnerBuilder::new(message)
.spinner(spinner_data.frames.clone())
.step(Duration::from_millis(spinner_data.interval.into()))
.start();
Spinner { handle }
}
/// Update spinner's message
///
/// Returns the String that is put in in case the sender could not send.
pub fn message(&self, message: String) -> Option<String> {
self.handle.update(message)
}
/// Stop the spinner
pub fn stop(self) {
self.handle.close();
}
}
|
abb4108a414a7e3653aa2d923fb6975207cff0f9
|
[
"TOML",
"Rust"
] | 5 |
Rust
|
spaghetus/spinners
|
d067b0aa6f1630af4fdb55b8ab91781d30a6c176
|
75f88045e05b8acc5c52dc570273dc59f385a34b
|
refs/heads/master
|
<repo_name>zatcsc/group5.k57ca<file_sep>/app/assets/javascripts/main.js
$(window).load(function() {
$.asm = {};
$.asm.panels = 2;
$.asm.status = 0;
function sidebar(panels) {
$.asm.panels = panels;
if (panels === 1) {
$('#sidebar').hide();
$('#map').removeClass('col-md-9');
$('#map-canvas').width($('#map-canvas').parent().width());
$('#map-canvas').height($(window).height() - 120);
} else if (panels === 2) {
$('#map').addClass('col-md-9');
$('#sidebar').show();
$('#map-canvas').width($('#map-canvas').parent().width());
}
return google.maps.event.trigger(hanoiMap, 'resize');
};
$('#toggleSidebar').click(function() {
if ($.asm.panels === 1) {
$('#toggleSidebar i').addClass('glyphicon-chevron-left');
$('#toggleSidebar i').removeClass('glyphicon-chevron-right');
return sidebar(2);
} else {
$('#toggleSidebar i').removeClass('glyphicon-chevron-left');
$('#toggleSidebar i').addClass('glyphicon-chevron-right');
return sidebar(1);
}
});
$('#traffic-button').click(function() {
if ($.asm.status === 1) {
document.getElementById('traffic-button').childNodes[0].nodeValue = "Show";
$.asm.status = 0;
return hideJam();
} else {
document.getElementById('traffic-button').childNodes[0].nodeValue = "Hide";
$.asm.status = 1;
return showJam();
}
});
});
<file_sep>/db/migrate/20140506171824_add_min_temperature_to_weather.rb
class AddMinTemperatureToWeather < ActiveRecord::Migration
def change
add_column :weathers, :min_temperature, :float
end
end
<file_sep>/app/assets/javascripts/map2.js
var map;
function initialize2() {
var myLatlng = new google.maps.LatLng(21.0382600, 105.7824130);
var mapOptions = {
zoom: 17,
center: myLatlng
};
var map = new google.maps.Map(document.getElementById("map-canvas2"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Đại học Công Nghệ - Đại học Quốc Gia Hà Nội"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}<file_sep>/app/models/weather.rb
class Weather < ActiveRecord::Base
belongs_to :provinces
DAY_REG = /Mon|Tue|Wed|Thu|Fri|Sat|Sun/
validates :day, presence: true, length: { is: 3 }, format: { with: DAY_REG }
validates :status, presence: true
validates :max_temperature, numericality: { less_than_or_equal_to: 50 }
validates :min_temperature, numericality: { greater_than_or_equal_to: -50 }
end
<file_sep>/spec/requests/welcomes_spec.rb
require 'spec_helper'
describe "Welcomes" do
describe "View Page" do
it "should have the right title" do
visit home_path
expect(page).to have_title("Sign in")
end
end
describe "About Us page" do
it "should have right title" do
visit about_path
expect(page).to have_title("About Us")
end
end
end
<file_sep>/spec/factories.rb
FactoryGirl.define do
factory :user do
name "<NAME>"
email "<EMAIL>"
password "<PASSWORD>"
password_confirmation "<PASSWORD>"
end
end<file_sep>/README.md
group5.k57ca
============
* Project: Ha Noi Easy Traffic
* Programming Language: Ruby, HTML/CSS, Javascript
* Framework: Rails
* Overview Description:
This is a web-based application provides user following services:
- View the traffic map of Ha Noi
- Find routes, buses
- Subscribes to the current road, weather condition and also traffic bandwidth
- View the statistic of traffic condition among months
- Provides and shares the traffic data (optional)
- Other features is in planning
<file_sep>/app/assets/javascripts/setting_interface.js
var ready = function() {
var currentClass = '';
var currentIconUrl = '';
for (var i = 0; i < IMPLEMENTED_FEATURE; ++i) {
/*html element*/
currentClass = ".panel-heading." + FEATURES[i];
currentFeatureEl = $(currentClass);
currentIconUrl = "url('../assets/" + FEATURES[i] + ".png')";
currentFeatureEl.css("background-image", currentIconUrl);
currentFeatureEl.css("background-repeat", "no-repeat");
currentFeatureEl.css("background-position", "10% 50%");
currentFeatureEl.css("background-size", "45px 40px");
}
for ( i = 0; i < VEHICLE_TYPES.length; i++) {
currentClass = ".vehicle-type." + VEHICLE_TYPES[i];
var currentVehicleEl = $(currentClass);
currentIconUrl = "url('../assets/" + VEHICLE_TYPES[i] + ".png')";
currentVehicleEl.css("background-image", currentIconUrl);
currentVehicleEl.css("background-size", "50% 100%");
currentVehicleEl.css("background-position", "center");
currentVehicleEl.css("background-repeat", "no-repeat");
currentVehicleEl.css("width", "25%");
currentVehicleEl.css("height", "100%");
}
$('.panel-heading').mouseenter(function(event) {
var oldBackgroundImage = $(this).css('background-image');
var dividerIndex = oldBackgroundImage.lastIndexOf(".");
var newBackgroundImage = oldBackgroundImage.substring(0, dividerIndex) + "-expand.png)";
$(this).css('background-image', newBackgroundImage);
});
$('.panel-heading').mouseleave(function(event) {
var oldBackgroundImage = $(this).css('background-image');
var dividerIndex = oldBackgroundImage.lastIndexOf("-");
var newBackgroundImage = oldBackgroundImage.substring(0, dividerIndex) + ".png)";
$(this).css('background-image', newBackgroundImage);
});
$('.vehicle-type').on('click', function(event) {
var oldChoosenVehicle = $('.' + VEHICLE_TYPES[chosenVehicleType]);
oldChoosenVehicle.css('background-image', "url('../assets/" + VEHICLE_TYPES[chosenVehicleType] + ".png')");
for (var i = 0; i < VEHICLE_TYPES.length; ++i) {
if ($(this).hasClass(VEHICLE_TYPES[i])) {
chosenVehicleType = i;
$(this).css('background-image', "url('../assets/" + VEHICLE_TYPES[i] + "-clicked.png')");
break;
}
}
});
$('.find-route').on('click', function(event) {
initializeRouteDirection();
});
$('.find-btn').on('click', function(event) {
calcRoute();
});
$('.panel-title').css('margin-left', '25%');
};
$(document).ready(ready);
$(document).on('page:load', ready); <file_sep>/spec/models/weather_spec.rb
require 'spec_helper'
describe Weather do
pending "add some examples to (or delete) #{__FILE__}"
before {
@current_date = Date.new(2014,5,9)
@example = Weather.create(day: "Monday",current_date: @current_date ,status: "Kho rao, hoi am",min_temperature: 18,max_temperature: 25)}
subject {@example}
it {should respond_to(:day)}
it {should respond_to(:current_date)}
it {should respond_to(:min_temperature)}
it {should respond_to(:max_temperature)}
describe "when day is not valid" do
describe "when day is blank" do
before{@example.day = '' }
it {should_not be_valid}
end
describe "when day is not a day of week" do
before {@example.day ="not a day"}
it {should_not be_valid}
end
end
describe "when day is valid" do
before {@example.day = "Mon"}
it {should be_valid}
end
describe "when min_temperature is not valid" do
before {@example.min_temperature = -50}
it {should_not be_valid}
end
describe "when max_temperature is not valid" do
before {@example.max_temperature = 100}
it {should_not be_valid}
end
describe "when status is blank " do
before {@example.status = ''}
it {should_not be_valid}
end
end
<file_sep>/spec/models/provinces_spec.rb
require 'spec_helper'
describe Province do
pending "add some examples to (or delete) #{__FILE__}"
before do
@example_coordinates = Coordinates.new(logitude: 14,latitude: 30)
@example_date = Date.new(2014,7,5)
@example_weather = Weather.new(day: "Mon",current_date: @example_date,
status: "Cold, windy",min_temperature: 6,max_temperature: 200)
@example = Province.new(name: "<NAME>")
# @example.coordinates.build(logitude: 14,latitude: 30)
# @example.weather.build()
end
subject{@example}
it {should respond_to(:name)}
describe "when name is blank" do
before {@example.name = ''}
it {should_not be_valid}
end
end
<file_sep>/app/assets/javascripts/map.js
/* Classes declaration*/
function MapIcon(url, size, origin, anchor, scaledSize) {
this.url = url;
this.size = size;
this.origin = origin;
this.anchor = anchor;
this.scaledSize = scaledSize;
}
function MapOption(center, mapTypeId, zoom) {
this.center = center;
this.mapTypeId = mapTypeId;
this.zoom = zoom;
}
function Point(x, y) {
return new google.maps.Point(x, y);
}
function respondToPlaceChange(map, infoWindow, marker, autocomplete) {
infoWindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(GOOD_ZOOM_LEVEL);
console.log(place.geometry.location);
}
var placeIcon = new MapIcon(place.icon, MAP_ICON_SIZE, new Point(0, 0), new Point(17, 34), SCALED_MAP_ICON_SIZE);
marker.setIcon(placeIcon);
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [(place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '')].join(' ');
}
infoWindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infoWindow.open(map, marker);
}
var hanoiMap;
function initializeMap(whereToPlace, searchBox) {
var mapOptions = new MapOption(HANOI_CENTER, ROADMAP, GOOD_ZOOM_LEVEL);
hanoiMap = new google.maps.Map(document.getElementById(whereToPlace), mapOptions);
var input = document.getElementById(searchBox);
// var startInput = document.getElementById("start-place");
// var endInput = document.getElementById("end-place");
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', hanoiMap);
var infoWindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map : hanoiMap,
anchorPoint : GOOD_MARKER_ANCHOR_POINT
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
respondToPlaceChange(hanoiMap, infoWindow, marker, autocomplete);
});
// Autocomplete.
autocomplete.setTypes([]);
}
var jamLat = [];
var jamLgn = [];
var jamReason = [];
var jamMarkerList = [];
function showJam() {
jamMarkerList = [];
for (var i = 0; i < jamLat.length; i++) {
var JamMarker = new google.maps.Marker({
position : new google.maps.LatLng(jamLat[i], jamLgn[i]),
title : jamReason[i],
icon : "/assets/traffic-information.png"
});
jamMarkerList.push(JamMarker);
jamMarkerList[i].setMap(hanoiMap);
}
}
function hideJam() {
for (var i = 0; i < jamLat.length; i++) {
jamMarkerList[i].setMap(null);
}
jamMarkerList = [];
}<file_sep>/spec/models/coordinates_spec.rb
require 'spec_helper'
describe Coordinates do
pending "add some examples to (or delete) #{__FILE__}"
before { @example = Coordinates.new(logitude: -20, latitude: 80)}
subject {@example}
it {should respond_to(:logitude)}
it {should respond_to(:latitude)}
describe "when the coordinates is out of range" do
describe "with logitude is less than -180" do
before { @example.logitude=-200 }
it {should_not be_valid}
end
describe "with logitude is greater than 180" do
before { @example.logitude = 200}
it {should_not be_valid}
end
describe "with latitude is less than -90" do
before {@example.latitude = -100 }
it {should_not be_valid}
end
describe "with latitude is greater than 90" do
before {@example.latitude = 100}
it {should_not be_valid}
end
end
describe "when the coordinates is in rage" do
before do
@example.logitude = 0;
@example.latitude = 0;
end
it "should be valid" do
expect(@example).should be_valid
end
end
end
<file_sep>/app/models/jam.rb
class Jam < ActiveRecord::Base
validates :lat, :lng, numericality: true
validates :reason, presence: true
end
<file_sep>/db/migrate/20140507004800_add_current_date_to_weathers.rb
class AddCurrentDateToWeathers < ActiveRecord::Migration
def change
add_column :weathers, :current_date, :date
end
end
<file_sep>/app/models/province.rb
class Province < ActiveRecord::Base
has_one :coordinates
has_one :weather
validates :name , presence: true
end
<file_sep>/app/models/coordinates.rb
class Coordinates < ActiveRecord::Base
belongs_to :provinces
validates :logitude, numericality: { greater_than_or_equal_to: -180, less_than_or_equal_to: 180 }
validates :latitude, numericality: { greater_than_or_equal_to: -90, less_than_or_equal_to: 90 }
end
<file_sep>/db/migrate/20140506171835_add_max_temperature_to_weather.rb
class AddMaxTemperatureToWeather < ActiveRecord::Migration
def change
add_column :weathers, :max_temperature, :float
end
end
<file_sep>/spec/requests/about_spec.rb
require 'spec_helper'
describe 'AboutProject' do
it "displays the information about the project" do
visit '/'
click_link "About us"
expect(page).to have_content("About Us")
end
end
<file_sep>/db/migrate/20140506153019_add_logitude_to_coordinates.rb
class AddLogitudeToCoordinates < ActiveRecord::Migration
def change
add_column :coordinates, :logitude, :float
end
end
<file_sep>/db/migrate/20140506171855_add_status_to_weather.rb
class AddStatusToWeather < ActiveRecord::Migration
def change
add_column :weathers, :status, :string
end
end
<file_sep>/app/assets/javascripts/contact.js
function setValue(Obj){
Obj.value="";
}
function backupValue(){
var Obj = document.getElementById("msg");
if(Obj.value=="") Obj.value="Bạn vui lòng điền nội dung liên hệ và góp ý bên dưới:";
}<file_sep>/db/migrate/20140506171731_add_day_to_weather.rb
class AddDayToWeather < ActiveRecord::Migration
def change
add_column :weathers, :day, :string
end
end
<file_sep>/app/controllers/welcome_controller.rb
require 'open-uri'
class WelcomeController < ApplicationController
def about
render "about"
end
def contact
render "contact"
end
def submit
if signed_in?
@jam_places = Jam.all
render "submit"
else
redirect_to signin_path
end
end
def add
new_jam = Jam.create(:lat => params[:jam_lat], :lng => params[:jam_lng],
:reason => params[:jam_reason], :place => params[:jam_place])
if !new_jam.valid?
flash[:error] = "There were some input errors. Please input again."
else
flash[:success] = "Added successfully."
end
redirect_to :action => 'submit'
end
def clear
params[:jam_checkbox].each do |check|
target = Jam.find_by_id(check)
target.destroy
end
redirect_to :action => 'submit'
end
def map
if signed_in?
@jam_places = Jam.all
render 'map'
else
redirect_to signin_path
end
end
def weather
@city_id = params[:city_id]
@xml_url = 'http://api.openweathermap.org/data/2.5/weather?id=' + @city_id
@weather_xml = open(@xml_url).read
@data = ActiveSupport::JSON.decode(@weather_xml)
respond_to do |format|
format.html { render 'weather', layout: false }
end
end
end
<file_sep>/app/assets/javascripts/weather.js
var getWeatherInfo = function(event) {
/* Act on the event */
var weather_value = $(".weather-select-box option:selected").val();
// alert(weather_value);
$.ajax({
type:"POST",
url: "/weather",
data: { city_id: weather_value}
})
.done(function( html ){
$('.current-weather').html("");
$('.current-weather').html(html);
});
};
var weatherReady = function(){
$(".weather-select-box").change(getWeatherInfo);
$('.weather').on('click',getWeatherInfo);
};
$(document).ready(weatherReady) ;
$(document).on('page:load',weatherReady);
|
81f11b5b7d0863f653d2d44218fa331ed0c04b4c
|
[
"JavaScript",
"Ruby",
"Markdown"
] | 24 |
JavaScript
|
zatcsc/group5.k57ca
|
e646f030edcd9c859f2bd3ea187587b7442fa111
|
545f3473cb47e6f3bef35ff0b69dc1a2a059327e
|
refs/heads/master
|
<repo_name>diogodutra/borch<file_sep>/metrics.py
import matplotlib.pyplot as plt
from sklearn.metrics import (
mean_squared_error,
precision_score, recall_score, f1_score, accuracy_score,
)
class Metrics:
"""Calculates and stores metrics"""
def __init__(self, scores, str_format = '{:.3f}'):
"""
Args:
scores (list of str): scores to be calculated and stored
str_format (str, optional"): format to print the scores values
"""
self.str_format = str_format
self.score_history = {s: [] for s in scores}
def __call__(self, y_true, y_pred, verbose=False):
"""Calculates and stores the scores results comparing ground truth from predicted targets
Args:
y_true (NumPy array): Ground truth (correct) target values
y_pred (NumPy array): Estimated targets as returned by a classifier
"""
for score, fc in self.score_function.items():
self.score_history[score].append(fc(y_true, y_pred))
if verbose: self.print()
def from_epoch(self, epoch=-1, scores=None):
"""Returns dictionary with scores from a given epoch.
Args:
epoch (int, default -1): epoch related to when the scores will be printed
scores (list of str, optional): scores to be printed, all if ignored
"""
if scores is None: scores = list(self.score_history.keys())
return {s: self.score_history[s][epoch] for s in scores}
def print(self, epoch=-1, scores=None):
"""Prints on console the scores at a certain epoch.
Args:
epoch (int, default -1): epoch related to when the scores will be printed
scores (list of str, optional): scores to be printed, all if ignored
"""
if scores is None: scores = list(self.score_history.keys())
longest_string = max((len(s) for s in scores))
for score in scores:
print(('{}\t' + self.str_format).format(score.rjust(longest_string),
self.score_history[score][epoch]))
def plot(self, scores=None):
"""Plots scores along epochs.
Args:
scores (list of str, optional): scores to be printed, all if ignored
"""
if scores is None: scores = list(self.score_history.keys())
for score in scores:
plt.plot(self.score_history[score], label=score)
plt.ylabel('score')
plt.xlabel('epoch')
plt.grid()
plt.legend()
plt.gcf().patch.set_facecolor('white')
class MetricsClassifier(Metrics):
"""Calculates and stores metrics"""
def __init__(self,
scores = ['precision', 'recall', 'F1', 'accuracy'],
average = 'weighted', zero_division = 0,
str_format = '{:.0%}',
):
"""
Args:
scores (list of str, optional): Which metrics will be calculated and stores
average (str, default "weighter"): "average" argument for some score functions
zero_division (int, default 0): "zero_division" argument for some score functions
str_format (str, default "{:.0%}"): format to print the scores values
"""
super().__init__(scores, str_format)
self.score_function = {
'precision': lambda x, y: precision_score(x, y,
average=average, zero_division=zero_division),
'recall': lambda x, y: recall_score(x, y,
average=average, zero_division=zero_division),
'F1': lambda x, y: f1_score(x, y,
average=average, zero_division=zero_division),
'accuracy': accuracy_score,
}
def plot(self, scores=None):
"""Plots scores along epochs.
Args:
scores (list of str, optional): scores to be printed, all if ignored
"""
super().plot(scores)
plt.gca().set_yticklabels(['{:.0f}%'.format(x*100)
for x in plt.gca().get_yticks()])
class MetricsRegression(Metrics):
"""Calculates and stores metrics for regression"""
def __init__(self,
scores = ['rmse',],
str_format = '{:.3f}',
):
"""
Args:
scores (list of str, optional): Which metrics will be calculated and stored
str_format (str, optional"): format to print the scores values
"""
super().__init__(scores, str_format)
self.score_function = {
'rmse': lambda y_true, y_pred: mean_squared_error(y_true, y_pred, squared=True),
}<file_sep>/models.py
import torch.nn as nn
import torchvision.models as models
class TransferLearning(nn.Module):
"""Wrapper for torch.nn to speed-up downloading and reusing pretrained models."""
def __init__(self, *,
num_target_classes = None,
pretrained_model = models.resnet18(pretrained=True),
freeze_parameters = False,
not_freeze_last_params = 3,
):
"""
Args:
num_target_classes (int, optional): If not ommited, replaces the last layer
pretrained_model (nn.Module, default ResNet18): Base model for Transfer Learning
freeze_parameters (bool, default False): turn off require_gradient from first layers
not_freeze_last_params (int, default 3): let require_gradient on from last layers
"""
super(TransferLearning, self).__init__()
self.model = pretrained_model
if freeze_parameters:
self._freeze_feature_parameters(not_freeze_last_params)
# replace last layer
if num_target_classes is not None:
self.model.fc = nn.Linear(self.model.fc.in_features,
num_target_classes)
def _freeze_feature_parameters(self, not_freeze_last_params):
for child in self.model.children():
n_params = len(list(child.parameters()))
for i, param in enumerate(child.parameters()):
param.requires_grad = False
if i >= n_params - not_freeze_last_params:
break
def forward(self, x):
return self.model(x)<file_sep>/trainer.py
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import numpy as np
import time
from datetime import timedelta
from tqdm.autonotebook import tqdm
import matplotlib.pyplot as plt
import gc
from .utils import PrintFile
from .metrics import MetricsRegression, MetricsClassifier
from borch.utils import PrintFile
from borch.metrics import MetricsRegression, MetricsClassifier
class Trainer:
"""Generic trainer customized for a PyTorch model."""
def __init__(self, model,
optimizer = torch.optim.Adam,
*,
checkpoint_parent_folder = 'drive/MyDrive/pytorch_boilerplate',
checkpoint_model_file = 'model.pth',
verbose = True,
timezone='America/Toronto',
):
"""
Args:
model (nn.Module): PyTorch model, preferebly pretrained (see TransferLearning class)
loss_function (nn.Function, default CrossEntropyLoss): Loss function
optimizer (torch.optim, default Adam): Optimizer for backpropagation
checkpoint_filename (str, default None): .pth file to save state dictionary of best model
verbose (bool, default True): print validation statistics every epoch
"""
self._init_instance_variables()
self.model = model.to(self.device)
self.optimizer = optimizer(self.model.parameters())
self.checkpoint_parent_folder = checkpoint_parent_folder
self.checkpoint_model_file = checkpoint_model_file
self.verbose = verbose
self.elapsed_seconds = 0
self.print_file = PrintFile(parent_folder=checkpoint_parent_folder,
timezone=timezone)
class TrainerClassifier(Trainer):
"""Trainer customized for a PyTorch classifier model."""
def __init__(self, model,
optimizer = torch.optim.Adam,
*,
checkpoint_parent_folder = 'drive/MyDrive/pytorch_boilerplate',
checkpoint_model_file = 'model.pth',
verbose = True,
timezone='America/Toronto',
):
"""
Args:
model (nn.Module): PyTorch model, preferebly pretrained (see TransferLearning class)
loss_function (nn.Function, default CrossEntropyLoss): Loss function
optimizer (torch.optim, default Adam): Optimizer for backpropagation
checkpoint_filename (str, default None): .pth file to save state dictionary of best model
verbose (bool, default True): print validation statistics every epoch
"""
super().__init__(model, optimizer,
checkpoint_parent_folder = checkpoint_parent_folder,
checkpoint_model_file = checkpoint_model_file,
verbose = verbose,
timezone = timezone)
def _init_instance_variables(self):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.losses_log = {key: [] for key in ['train', 'valid', 'saved']}
self.metrics = MetricsClassifier()
self.best_loss = np.Inf
self.epoch = 0
def plot_losses(self):
"""Plots the training and validation loss values across epochs"""
plot_x = range(len(self.losses_log['train']))
for type_data, type_plot, color, marker in [
('train', plt.plot, None, None),
('valid', plt.plot, None, None),
('saved', plt.scatter, 'g', 'x'),
]:
if type_data in self.losses_log.keys():
plot_y = self.losses_log[type_data]
if len(plot_y) > 0:
type_plot(plot_x, plot_y, label=type_data, c=color, marker=marker)
plt.legend()
plt.ylabel('loss')
plt.xlabel('epoch')
plt.grid()
plt.gcf().patch.set_facecolor('white')
def _str_elapsed(self):
elapsed_time = timedelta(seconds=int(self.elapsed_seconds))
return f"Training time (H:MM:SS): {elapsed_time}"
def print_elapsed(self, **kwargs):
print(self._str_elapsed(**kwargs))
def _str_epoch(self, *, scores=None, prefix_dict={},
print_header=False, divider = ' '):
if scores is None: scores = self.metrics.from_epoch()
prefixes = list(prefix_dict.keys())
to_print, header = '', ''
scores_dict = self.metrics.from_epoch()
scores = list(scores_dict.keys())
scores_dict.update(prefix_dict)
lengths = [len(s) + len(divider) for s in prefixes + scores]
header += divider.join([s.rjust(lengths[i])
for i, s in enumerate(prefixes + scores)])
to_print += divider.join([
(self.metrics.str_format if s in scores else '{}')
.format(scores_dict[s])
.rjust(lengths[i])
for i, s in enumerate(prefixes + scores)])
if print_header: to_print = header + '\n' + to_print
return to_print
def _print_epoch(self, **kwargs):
if self.verbose:
print(self._str_epoch(**kwargs))
def _str_epochs(self, epochs=None, **kwargs):
if epochs is None: epochs = range(self.epoch)
to_print = []
for epoch in range(trainer.epoch):
prefix_dict={
'epoch': str(epoch + 1),
'train_loss': '{:.4f}'.format(trainer.losses_log['train'][epoch]),
'valid_loss': '{:.4f}'.format(trainer.losses_log['valid'][epoch]),
'saved': u'\u221A' if trainer.losses_log['saved'] else ' ',
}
to_print.append(self._str_epoch(
prefix_dict=prefix_dict, print_header=epoch==0, **kwargs))
return '\n'.join(to_print)
def print_epochs(self, **kwargs):
print(self._str_epochs, **kwargs)
def load_state_dict(self, state_dict):
self.model.load_state_dict(state_dict)
self.model.eval()
def predict(self, dataset, *,
batch_size = 32, num_workers = 4, shuffle=False,
return_targets=False):
"""
Calculates the classes predictions in the entire DataLoader
Args:
dataset (Dataset): dataset containing images and targets
batch_size (int, default 32): size of each batch
num_workers (int, default 4): number of parallel threads
return_targets (bool, default False): returns list of targets after predictions
"""
self.model.eval()
self.model.to(self.device)
loader = self.create_loader(dataset,
batch_size = batch_size, num_workers = num_workers, shuffle=shuffle)
with torch.no_grad():
all_preds = torch.tensor([])
if return_targets: all_trues = torch.tensor([])
for batch in loader:
images, trues = batch
logits = self.model(images.to(self.device))
# get class prediction from logits
preds = torch.max(logits, 1)[1]
preds = preds.cpu()
all_preds = torch.cat((all_preds, preds), dim=0)
if return_targets: all_trues = torch.cat((all_trues, trues), dim=0)
all_preds = all_preds.cpu().data.numpy().astype('i')
if return_targets: all_trues = all_trues.cpu().data.numpy().astype('i')
if return_targets:
return all_preds, all_trues
else:
return all_preds
def step_train(self, loader):
loss_cumul = 0
batches = len(loader)
# progress bar
progress = tqdm(enumerate(loader), desc="Loss: ",
total=batches, leave=False)
# set model to training
self.model.train()
for i, data in progress:
X, y = data[0].to(self.device), data[1].to(self.device)
# training step for single batch
self.model.zero_grad()
outputs = self.model(X)
loss = self.loss_function(outputs, y)
loss.backward()
self.optimizer.step()
# getting training quality data
current_loss = loss.item()
loss_cumul += current_loss
# updating progress bar
progress.set_description("Loss: {:.4f}".format(loss_cumul/(i+1)))
# releasing unnecessary memory in GPU
if torch.cuda.is_available():
torch.cuda.empty_cache()
loss_train = loss_cumul / batches
return loss_train
def step_valid(self, loader):
loss_cumul = 0
y_true, y_pred = [], []
# set model to evaluating (testing)
self.model.eval()
with torch.no_grad():
for i, data in enumerate(loader):
X, y = data[0].to(self.device), data[1].to(self.device)
outputs = self.model(X)
loss_cumul += self.loss_function(outputs, y)
# predicted classes
predicted_classes = torch.max(outputs, 1)[1]
y_true.extend(y.cpu())
y_pred.extend(predicted_classes.cpu())
loss_valid = float(loss_cumul / len(loader))
return loss_valid, y_true, y_pred
def create_loader(self, dataset, **kwargs):
return DataLoader(dataset, **kwargs)
def default_weights(self, dataset):
# compensate for imbalance in dataset
n_samples = len(dataset)
n_classes = len(dataset.index_to_class.keys())
classes = [dataset.index_to_class[i] for i in range(n_classes)]
index_to_count = dataset.count()
weights = [n_samples / index_to_count[_class] for _class in classes]
weight_avg = sum(weights) / len(weights)
weights = [w / weight_avg for w in weights]
return weights
def run(self, train_dataset, valid_dataset = None, *,
loss_function = nn.CrossEntropyLoss,
batch_size = 32, num_workers = 4, shuffle=True,
weights = None,
max_epochs = 10, early_stop_epochs = 5,
):
"""
Runs the cycle of training and validation along some epochs
Args:
train_dataset (Dataset): train dataset containing images and targets
valid_dataset (Dataset, optional): validation dataset, valid skipped if omitted
batch_size (int, default 32): size of each batch
num_workers (int, default 4): number of parallel threads
shuffle (bool, default True): random sort of train DataLoader batches
weights (torch.tensor, optional): class weigths for loss function to compensate imbalance
max_epochs (int, default 10): maximum number of epochs to run the train and valid cycle
early_stop_epochs (int, default 5): maximum number of epochs to run without improving valid loss
"""
start_ts = time.time()
print_header = True
valid_loss = 0
epochs_without_improvement = 0
self.epoch += 1
train_loader = self.create_loader(train_dataset,
batch_size = batch_size, num_workers = num_workers, shuffle=shuffle)
if valid_dataset is not None:
valid_loader = self.create_loader(valid_dataset,
batch_size = batch_size, num_workers = num_workers, shuffle=False)
self.weights = weights
if self.weights is None: self.weights = self.default_weights(train_dataset)
self.weights = torch.Tensor(self.weights).to(self.device)
self.loss_function = loss_function(weight=self.weights)
for self.epoch in range(self.epoch, self.epoch + max_epochs):
gc.collect()
if epochs_without_improvement >= early_stop_epochs:
break
else:
# ----------------- TRAINING --------------------
train_loss = self.step_train(train_loader)
self.losses_log['train'].append(train_loss)
check_loss = train_loss
# ----------------- VALIDATION -----------------
if valid_dataset is not None:
valid_loss, y_true, y_pred = self.step_valid(valid_loader)
self.metrics(y_true, y_pred)
check_loss = valid_loss
self.losses_log['valid'].append(valid_loss)
# ----------------- CHECKPOINT -----------------
save_checkpoint = (check_loss < self.best_loss)
self.losses_log['saved'].append(check_loss if save_checkpoint else np.nan)
if not save_checkpoint:
epochs_without_improvement += 1
else:
epochs_without_improvement = 0
self.best_loss = check_loss
self.state_dict = self.model.state_dict()
if self.print_file.folder is not None:
torch.save(self.state_dict,
self.print_file.folder + self.checkpoint_model_file)
# ----------------- LOGGING -----------------
to_print = self._str_epoch(print_header=print_header,
prefix_dict={'epoch': str(self.epoch),
'train_loss': '{:.4f}'.format(train_loss),
'valid_loss': '{:.4f}'.format(valid_loss),
'saved': u'\u221A' if save_checkpoint else ' ',
})
self.print_file(to_print)
if self.verbose: print(to_print)
print_header = False
self.elapsed_seconds += time.time() - start_ts
to_print = self._str_elapsed()
self.print_file(to_print)
if self.verbose: print(to_print)
# reload best checkpoint
self.load_state_dict(self.state_dict)
class TrainerRegression:
"""Trainer customized for a PyTorch regression model."""
def __init__(self, model,
optimizer = torch.optim.Adam,
*,
checkpoint_parent_folder = 'drive/MyDrive/pytorch_boilerplate',
checkpoint_model_file = 'model.pth',
verbose = True,
timezone='America/Toronto',
):
"""
Args:
model (nn.Module): PyTorch model, preferebly pretrained (see TransferLearning class)
loss_function (nn.Function, default CrossEntropyLoss): Loss function
optimizer (torch.optim, default Adam): Optimizer for backpropagation
checkpoint_filename (str, default None): .pth file to save state dictionary of best model
verbose (bool, default True): print validation statistics every epoch
"""
self._init_instance_variables()
self.model = model.to(self.device)
self.optimizer = optimizer(self.model.parameters())
self.checkpoint_parent_folder = checkpoint_parent_folder
self.checkpoint_model_file = checkpoint_model_file
self.verbose = verbose
self.elapsed_seconds = 0
self.print_file = PrintFile(parent_folder=checkpoint_parent_folder,
timezone=timezone)
def _init_instance_variables(self):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.losses_log = {key: [] for key in ['train', 'valid', 'saved']}
self.metrics = MetricsRegression()
self.best_loss = np.Inf
self.epoch = 0
def plot_losses(self):
"""Plots the training and validation loss values across epochs"""
plot_x = range(len(self.losses_log['train']))
for type_data, type_plot, color, marker in [
('train', plt.plot, None, None),
('valid', plt.plot, None, None),
('saved', plt.scatter, 'g', 'x'),
]:
if type_data in self.losses_log.keys():
plot_y = self.losses_log[type_data]
if len(plot_y) > 0:
type_plot(plot_x, plot_y, label=type_data, c=color, marker=marker)
plt.legend()
plt.ylabel('loss')
plt.xlabel('epoch')
plt.grid()
plt.gcf().patch.set_facecolor('white')
def _str_elapsed(self):
elapsed_time = timedelta(seconds=int(self.elapsed_seconds))
return f"Training time (H:MM:SS): {elapsed_time}"
def print_elapsed(self, **kwargs):
print(self._str_elapsed(**kwargs))
def _str_epoch(self, *, scores=None, prefix_dict={},
print_header=False, divider = ' '):
if scores is None: scores = self.metrics.from_epoch()
prefixes = list(prefix_dict.keys())
to_print, header = '', ''
scores_dict = self.metrics.from_epoch()
scores = list(scores_dict.keys())
scores_dict.update(prefix_dict)
lengths = [len(s) + len(divider) for s in prefixes + scores]
header += divider.join([s.rjust(lengths[i])
for i, s in enumerate(prefixes + scores)])
to_print += divider.join([
(self.metrics.str_format if s in scores else '{}')
.format(scores_dict[s])
.rjust(lengths[i])
for i, s in enumerate(prefixes + scores)])
if print_header: to_print = header + '\n' + to_print
return to_print
def _print_epoch(self, **kwargs):
if self.verbose:
print(self._str_epoch(**kwargs))
def _str_epochs(self, epochs=None, **kwargs):
if epochs is None: epochs = range(self.epoch)
to_print = []
for epoch in range(trainer.epoch):
prefix_dict={
'epoch': str(epoch + 1),
'train_loss': '{:.4f}'.format(trainer.losses_log['train'][epoch]),
'valid_loss': '{:.4f}'.format(trainer.losses_log['valid'][epoch]),
'saved': u'\u221A' if trainer.losses_log['saved'] else ' ',
}
to_print.append(self._str_epoch(
prefix_dict=prefix_dict, print_header=epoch==0, **kwargs))
return '\n'.join(to_print)
def print_epochs(self, **kwargs):
print(self._str_epochs, **kwargs)
def load_state_dict(self, state_dict):
self.model.load_state_dict(state_dict)
self.model.eval()
def predict(self, dataset, *,
batch_size = 32, num_workers = 4, shuffle=False,
return_targets=False):
"""
Calculates the predicted regression in the entire Dataset
Args:
dataset (Dataset): dataset containing images and targets
batch_size (int, default 32): size of each batch
num_workers (int, default 4): number of parallel threads
return_targets (bool, default False): returns list of targets after predictions
"""
self.model.eval()
self.model.to(self.device)
loader = self.create_loader(dataset,
batch_size = batch_size, num_workers = num_workers, shuffle=shuffle)
with torch.no_grad():
all_preds = torch.tensor([])
if return_targets: all_trues = torch.tensor([])
for batch in loader:
images, trues = batch
logits = self.model(images.to(self.device))
# get class prediction from logits
# preds = torch.max(logits, 1)[1]
preds = preds.cpu()
all_preds = torch.cat((all_preds, preds), dim=0)
if return_targets: all_trues = torch.cat((all_trues, trues), dim=0)
all_preds = all_preds.cpu().data.numpy().astype('i')
if return_targets: all_trues = all_trues.cpu().data.numpy().astype('i')
if return_targets:
return all_preds, all_trues
else:
return all_preds
def step_train(self, loader):
loss_cumul = 0
batches = len(loader)
# progress bar
progress = tqdm(enumerate(loader), desc="Loss: ",
total=batches, leave=False)
# set model to training
self.model.train()
for i, data in progress:
X, y = data[0].float().to(self.device), data[1].float().to(self.device)
# training step for single batch
self.model.zero_grad()
outputs = self.model(X).squeeze()
loss = self.loss_function(outputs, y)
loss.backward()
self.optimizer.step()
# getting training quality data
current_loss = loss.item()
loss_cumul += current_loss
# updating progress bar
progress.set_description("Loss: {:.4f}".format(loss_cumul/(i+1)))
# releasing unnecessary memory in GPU
if torch.cuda.is_available():
torch.cuda.empty_cache()
loss_train = loss_cumul / batches
return loss_train
def step_valid(self, loader):
loss_cumul = 0
y_true, y_pred = [], []
# set model to evaluating (testing)
self.model.eval()
with torch.no_grad():
for i, data in enumerate(loader):
X, y = data[0].float().to(self.device), data[1].float().to(self.device)
outputs = self.model(X).squeeze()
loss_cumul += self.loss_function(outputs, y)
# predicted classes
predicted_classes = outputs.squeeze()#torch.max(outputs, 1)[1]
y_true.extend(y.cpu())
y_pred.extend(predicted_classes.cpu())
loss_valid = float(loss_cumul / len(loader))
return loss_valid, y_true, y_pred
def create_loader(self, dataset, **kwargs):
return DataLoader(dataset, **kwargs)
def run(self, train_dataset, valid_dataset = None, *,
loss_function = nn.MSELoss,
batch_size = 32, num_workers = 4, shuffle=True,
max_epochs = 10, early_stop_epochs = 5,
):
"""
Runs the cycle of training and validation along some epochs
Args:
train_dataset (Dataset): train dataset containing images and targets
valid_dataset (Dataset, optional): validation dataset, valid skipped if omitted
batch_size (int, default 32): size of each batch
num_workers (int, default 4): number of parallel threads
shuffle (bool, default True): random sort of train DataLoader batches
max_epochs (int, default 10): maximum number of epochs to run the train and valid cycle
early_stop_epochs (int, default 5): maximum number of epochs to run without improving valid loss
"""
start_ts = time.time()
print_header = True
valid_loss = 0
epochs_without_improvement = 0
self.epoch += 1
train_loader = self.create_loader(train_dataset,
batch_size = batch_size, num_workers = num_workers, shuffle=shuffle)
if valid_dataset is not None:
valid_loader = self.create_loader(valid_dataset,
batch_size = batch_size, num_workers = num_workers, shuffle=False)
self.loss_function = loss_function
for self.epoch in range(self.epoch, self.epoch + max_epochs):
gc.collect()
if epochs_without_improvement >= early_stop_epochs:
break
else:
# ----------------- TRAINING --------------------
train_loss = self.step_train(train_loader)
self.losses_log['train'].append(train_loss)
check_loss = train_loss
# ----------------- VALIDATION -----------------
if valid_dataset is not None:
valid_loss, y_true, y_pred = self.step_valid(valid_loader)
self.metrics(y_true, y_pred)
check_loss = valid_loss
self.losses_log['valid'].append(valid_loss)
# ----------------- CHECKPOINT -----------------
save_checkpoint = (check_loss < self.best_loss)
self.losses_log['saved'].append(check_loss if save_checkpoint else np.nan)
if not save_checkpoint:
epochs_without_improvement += 1
else:
epochs_without_improvement = 0
self.best_loss = check_loss
self.state_dict = self.model.state_dict()
if self.print_file.folder is not None:
torch.save(self.state_dict,
self.print_file.folder + self.checkpoint_model_file)
# ----------------- LOGGING -----------------
to_print = self._str_epoch(print_header=print_header,
prefix_dict={'epoch': str(self.epoch),
'train_loss': '{:.4f}'.format(train_loss),
'valid_loss': '{:.4f}'.format(valid_loss),
'saved': u'\u221A' if save_checkpoint else ' ',
})
self.print_file(to_print)
if self.verbose: print(to_print)
print_header = False
self.elapsed_seconds += time.time() - start_ts
to_print = self._str_elapsed()
self.print_file(to_print)
if self.verbose: print(to_print)
# reload best checkpoint
self.load_state_dict(self.state_dict)
<file_sep>/dataset.py
from collections import defaultdict
from math import ceil
import copy
import cv2
import os
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import torch
from torch.utils.data import Dataset
class DatasetAnnotated(Dataset):
"""Dataset with list of filepaths and ground truths."""
def __init__(self, dataframe, transform=None):
"""
Args:
dataframe (pandas DataFrame): Table with list files ('filepath') and ground truths ('label').
transform (callable, optional): Optional transform to be applied
on a sample.
include (list of str, optional): only include filepaths that contain
any of these substrings
exclude (list of str, optional): always exclude filepaths that contain
any of these substrings
"""
self.transform = transform
self.filepaths = dataframe.filepath.values
self.labels = dataframe.label.values
def __len__(self):
return len(self.filepaths)
def __getitem__(self, index):
if torch.is_tensor(index): index = index.tolist()
filepath = self.filepaths[int(index)]
image = read_image(filepath)
if self.transform:
image = self.transform(image)
label = self.labels[int(index)]
return image, label
def plot_image(self, index=None):
"""
Plots the image of a church.
Args:
idx (int, default random): index of the church from the dataset.filepaths list
"""
if index is None: index = np.random.choice(range(len(self)))
img, tgt = self[index]
img = to_numpy(img)
_ = plt.imshow(img)
filepath = '/'.join(self.filepaths[index].split('/')[-2:])
height, width, channels = img.shape
title = filepath + f' ({width} x {height})'
plt.gcf().patch.set_facecolor('white')
plt.title(title)
class DatasetClassifier(Dataset):
"""Multi-class classification dataset."""
def __init__(self, root_dir, transform=None, *,
include=None, exclude=None,
):
"""
Args:
root_dir (str): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
include (list of str, optional): only include filepaths that contain
any of these substrings
exclude (list of str, optional): always exclude filepaths that contain
any of these substrings
"""
self._init_instance_variables()
self.root_dir = root_dir
self.transform = transform
self.include = include
self.exclude = exclude
self._list_filepaths()
def _init_instance_variables(self):
self.filepaths = []
self.filepaths_organized = defaultdict(lambda: [])
self.class_to_index = {}
self.index_to_class = {}
self.index_to_count = defaultdict(lambda: 0)
def __len__(self):
return len(self.filepaths)
def __getitem__(self, index):
if torch.is_tensor(index): index = index.tolist()
filepath = self.filepaths[int(index)]
image = read_image(filepath)
if self.transform:
image = self.transform(image)
_class = self._get_class(filepath)
return image, self.class_to_index[_class]
def _list_filepaths(self):
classes = set()
# crawl files in subfolders
for root, dirs, files in os.walk(self.root_dir):
for file in files:
filepath = os.path.join(root, file)
add_filepath = True
if self.include is not None:
add_filepath = any((_inc in filepath for _inc in self.include))
if add_filepath:
if self.exclude is not None:
add_filepath = all((_exc not in filepath for _exc in self.exclude))
if add_filepath:
#append the file name to the list of paths
self.filepaths.append(filepath)
# add country to the set of know countries
_class = self._get_class(filepath)
classes.add(_class)
self.index_to_count[_class] += 1
self.filepaths_organized[_class].append(filepath)
# append the country to the targets dictionary
for i, _class in enumerate(sorted(classes)):
self.index_to_class[i] = _class
self.class_to_index[_class] = i
self.index_to_count = dict(self.index_to_count) # remove defauldict
self.filepaths_organized = dict(self.filepaths_organized) # remove defauldict
def _get_class(self, filepath):
return filepath.split('/')[-2]
def organize(self):
class_to_filepaths = defaultdict(lambda: [])
for filepath in self.filepaths:
_class = self._get_class(filepath)
class_to_filepaths[_class].append(filepath)
return dict(class_to_filepaths)
def count(self):
class_to_filepaths = self.organize()
class_to_count = class_to_filepaths
for _class, filepaths in class_to_count.items():
class_to_count[_class] = len(filepaths)
return class_to_count
def plot_occurrencies(self):
"""
Plots the occurrencies of each label in dataset.
"""
index_to_count = self.count()
n_classes = len(index_to_count)
classes = [self.index_to_class[i] for i in range(n_classes)]
occurrencies = [index_to_count[c] for c in classes]
plt.bar(classes, occurrencies)
plt.gcf().patch.set_facecolor('white')
plt.ylabel('occurrencies')
plt.title('Dataset')
plt.xticks(rotation=90)
plt.gca().set_axisbelow(True)
plt.gca().yaxis.grid(color='gray', linestyle='dashed')
def plot_image(self, index=None):
"""
Plots the image of a church.
Args:
idx (int, default random): index of the church from the dataset.filepaths list
"""
if index is None: index = np.random.choice(range(len(self)))
img, tgt = self[index]
img = to_numpy(img)
_ = plt.imshow(img)
filepath = '/'.join(self.filepaths[index].split('/')[-2:])
height, width, channels = img.shape
title = filepath + f' ({width} x {height})'
plt.gcf().patch.set_facecolor('white')
plt.title(title)
def plot_booth(self, indices=None, predictions=None, *,
cols=4, rows=2):
"""
Plots many small images.
Args:
indices (list of int, default random repeated): indices for
dataset.filepaths for every church to be plotted
predictions (list of int, optional): classifier predictions for
every index in indices, to remark hits and misses
cols (int, default 4): columns of images
rows (int, default 2): rows of images if indices is omitted
"""
prediction_colors = {True: 'g', False: 'r'}
if indices is None:
idx = np.random.choice(range(len(self)))
indices = [idx] * cols * rows # repeat the same index
else:
rows = ceil(len(indices) / cols)
for i, index in enumerate(indices):
plt.subplot(rows, cols, i+1)
img, tgt = self[index]
self.plot_image(index)
plt.gca().axes.get_yaxis().set_visible(False)
plt.gca().axes.get_xaxis().set_visible(False)
if predictions is None:
plt.gca().set_frame_on(False)
plt.title(f'true:{tgt}')
else:
prediction = int(predictions[i])
plt.title(f'true:{tgt} pred:{prediction}')
correct = (prediction == tgt)
plt.setp(plt.gca().spines.values(), linewidth=2,
color=prediction_colors[correct])
def read_image(image_path):
"""Returns NumPy array from image filename, ignoring EXIF orientation."""
r = open(image_path,'rb').read()
img_array = np.asarray(bytearray(r), dtype=np.uint8)
img = cv2.imdecode(img_array, cv2.COLOR_BGR2RGB)[...,::-1]
return img.copy()
def to_numpy(img):
"""
Converts image from torch.Tensor type to NumPy array object for image plot.
"""
if type(img) == torch.Tensor:
img = (img * 255).permute(1, 2, 0).cpu().detach().numpy().astype(np.uint8)
return img
def stratified_split(dataset, k=1, *, shuffle=False):
"""
Splits the dataset ensuring k samples of each country.
Args:
dataset (ChurchesDataset): dataset with all the churches images.
k (int, default 1): occurrencies of each country
Returns:
dataset_split (ChurchesDataset): splitted dataset with k samples for each country
dataset_left (ChurchesDataset): left-over from the input dataset after split
shuffle (bool, default False): randomly selects k images from every country
"""
dataset_split = copy.deepcopy(dataset)
dataset_split.filepaths = []
dataset_leftover = copy.deepcopy(dataset)
dataset_leftover.filepaths = []
for target, filepaths in dataset.organize().items():
indices_all = range(len(filepaths))
if shuffle:
indices_split = random.sample(indices_all, k)
else:
indices_split = range(k)
indices_leftover = [i for i in indices_all if i not in indices_split]
target_filepaths_split = [filepaths[i] for i in indices_split]
target_filepaths_leftover = [filepaths[i] for i in indices_leftover]
dataset_split.filepaths.extend(target_filepaths_split)
dataset_leftover.filepaths.extend(target_filepaths_leftover)
return dataset_split, dataset_leftover
|
2369cd03a02191bf4e0b8709be193b2e42b086ea
|
[
"Python"
] | 4 |
Python
|
diogodutra/borch
|
50352ce26755a6fa8160c2f77171ecd1b0fa6f9f
|
901761c7ab79dc0b9219588a634fa282fb7a8a9f
|
refs/heads/master
|
<repo_name>johannbrehmer/recnn<file_sep>/run_pileup_nogating.s
#!/bin/bash
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=1
#SBATCH --cpus-per-task=4
#SBATCH --time=48:00:00
#SBATCH --mem=32GB
#SBATCH --job-name=recnn
#SBATCH --mail-type=ALL
#SBATCH --mail-user=<EMAIL>
#SBATCH --output=slurm_%j.out
#SBATCH --error=slurm_%j.err
##SBATCH --gres=gpu:1
#SBATCH --array=1-5
module purge
SRCDIR=$HOME/learning_substructure/recnn
cd $SRCDIR
DATA_DIR=$SCRATCH/data/w-vs-qcd/anti-kt
MODEL_DIR=$SCRATCH/models/pileup-nogating/
let 'SEED=SLURM_ARRAY_TASK_ID * 1000'
python train.py $DATA_DIR/antikt-kt-pileup25-new-train.pickle $MODEL_DIR/model-pileup-nogating-$SLURM_ARRAY_TASK_ID.pickle --random_state=$SEED --simple --n_epochs=20
<file_sep>/run_pileup.s
#!/bin/bash
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=1
#SBATCH --cpus-per-task=25
#SBATCH --time=80:00:00
#SBATCH --mem=32GB
#SBATCH --job-name=recnn
#SBATCH --mail-type=ALL
#SBATCH --mail-user=<EMAIL>
#SBATCH --output=slurm_%j.out
#SBATCH --error=slurm_%j.err
##SBATCH --gres=gpu:1
#SBATCH --array=1-10
module purge
SRCDIR=$HOME/learning_substructure/recnn
cd $SRCDIR
DATA_DIR=$SCRATCH/data/w-vs-qcd/anti-kt
MODEL_DIR=$SCRATCH/models/pileup/
let 'SEED=SLURM_ARRAY_TASK_ID * 345'
python train.py $DATA_DIR/antikt-kt-pileup25-new-train.pickle $MODEL_DIR/model-pileup-50epochs-$SLURM_ARRAY_TASK_ID.pickle --random_state=$SEED --n_epochs=50
|
55f40b0b6beccec793a91c082a5c30f601f6c0b7
|
[
"Shell"
] | 2 |
Shell
|
johannbrehmer/recnn
|
f00b9f3c3d3f56cd1fa70752d96f1d52d0eef454
|
1d3acca897239432a275318ce4a813064cf67a29
|
refs/heads/master
|
<file_sep><?php
namespace Vherus\Framework\Time;
use Cake\Chronos\Chronos;
use DateTimeImmutable;
class FixedClock implements Clock
{
private $current;
public function __construct(?DateTimeImmutable $current)
{
$this->current = $current ?: new DateTimeImmutable;
}
public function getCurrentDateTime(): Chronos
{
return Chronos::instance(
new DateTimeImmutable(
$this->current->format(DateTimeImmutable::ATOM)
)
);
}
public function now(): Chronos
{
return $this->getCurrentDateTime();
}
}
<file_sep><?php
namespace Vherus\Framework\IO;
use PHPUnit\Framework\TestCase;
class OutputBufferTest extends TestCase
{
public function test_capture()
{
$output = OutputBuffer::capture(function () {
echo "1\n";
echo "foo";
});
$this->assertEquals("1\nfoo", $output);
}
}
<file_sep><?php
namespace Vherus\Bootstrap;
use Interop\Container\ContainerInterface as IContainer;
use Psr\Container\ContainerExceptionInterface as IContainerException;
class ConfigFactory
{
/**
* @param array $overrides
* Values to override in from the default values, as dot-notation values.
*
* @return Config
*/
public static function create(array $overrides = []): Config
{
return new Config(array_merge([
'app' => [
'host' => getenv('APP_HOST'),
],
'database' => [
'default' => [
'pdo' => [
'dsn' => self::fromEnv('DB_DSN'),
'user' => self::fromEnv('DB_USER'),
'pass' => self::fromEnv('DB_PASS'),
]
]
],
'auth' => [
'ignored-uris' => [
'/healthcheck'
],
'authorized-keys' => [
//
],
],
'session' => [
/**
* The encryption key to use when encrypting session data
*
* This must be overridden in live environments. Run `src/vendor/bin/cryptokey generate` to generate a
* new key, or see https://github.com/AndrewCarterUK/CryptoKey#usage
*/
'crypt-key' => self::fromEnv('SESSION_CRYPT_KEY') ?: '<KEY>',
/**
* Session expiry duration, in seconds
*/
'expiry' => 3600
],
'log' => [
/**
* Which psr/log implementation to use. Options: monolog, null
*/
'logger' => self::fromEnv('LOG_LOGGER') ?: 'monolog'
]
], $overrides));
}
private static function fromEnv(string $key, $default = null)
{
if ($val = getenv($key)) {
return $val;
}
if ($path = getenv("{$key}_FILE")) {
if (file_exists($path)) {
return file_get_contents($path);
}
}
return $default;
}
/** @throws IContainerException */
public static function fromContainer(IContainer $container): Config
{
return $container->get(Config::class);
}
}
<file_sep>#!/bin/bash
bin/docker-dev run --rm web bin/test $@
<file_sep><?php
namespace Vherus\Application\Http\App\Controller;
use Vherus\Framework\IO\OutputBuffer;
use Psr\Http\Message\ResponseInterface as IResponse;
use Psr\Http\Message\ServerRequestInterface as IRequest;
use PSR7Sessions\Storageless\Http\SessionMiddleware;
use Zend\Diactoros\Response\HtmlResponse;
class HomepageController
{
public function __invoke(IRequest $request): IResponse
{
return new HtmlResponse(OutputBuffer::capture(function () use ($request) {
$token = '<KEY>';
require __DIR__ . '/../resources/template/app.php';
}));
}
}
<file_sep>#!/bin/bash
bin/docker-dev run --rm web bin/migrate $@
<file_sep><?php
namespace Vherus\Framework\Exception;
class UndefinedException extends \Exception
{
//
}
<file_sep><?php
namespace Vherus\Application\Http\Healthcheck;
use FastRoute\RouteCollector;
use Vherus\Framework\Http\Router\RouteMapper as IRouteMapper;
class RouteMapper implements IRouteMapper
{
public function map(RouteCollector $router): void
{
$router->addRoute('GET', '/healthcheck', HealthcheckController::class);
}
}
<file_sep><?php
namespace Vherus\Testing\Traits;
use Vherus\Application\Http\HttpServer;
use Psr\Container\ContainerInterface as IContainer;
use Psr\Http\Message\ResponseInterface as IResponse;
use Psr\Http\Message\ServerRequestInterface as IRequest;
trait UsesHttpServer
{
private $authorizedTestUserToken = '<PASSWORD>';
private $authorizedTestUserId = '3495c1ce-b2a9-4be4-938b-9bf56522bc3b';
private $unauthorizedTestUserToken = '<PASSWORD>';
protected function handle(IContainer $container, IRequest $request): IResponse
{
return $container->get(HttpServer::class)->handle($request);
}
}
<file_sep><?php
/**
* This bootstrap file simply loads in any environment config ($_ENV), the creates and returns the ContainerInterface
*/
require __DIR__ . '/vendor/autoload.php';
if (file_exists(__DIR__ . '/.env')) {
(new \josegonzalez\Dotenv\Loader(__DIR__ . '/.env'))
->parse()
->putenv(true);
}
return (new \Vherus\Bootstrap\ContainerFactory)->create(
\Vherus\Bootstrap\ConfigFactory::create()
);
<file_sep><?php
namespace Vherus\Framework\Http\Router;
use FastRoute\Dispatcher as FastRouteDispatcher;
use Vherus\Framework\Exception\NotFoundException;
use Psr\Container\ContainerInterface as IContainer;
use Psr\Http\Message\RequestInterface as IRequest;
use Psr\Http\Message\ResponseInterface as IResponse;
class Dispatcher
{
private $container;
public function __construct(IContainer $container)
{
$this->container = $container;
}
/** @throws NotFoundException */
public function dispatch(IRequest $request, FastRouteDispatcher $dispatcher): IResponse
{
$routeInfo = $dispatcher->dispatch($request->getMethod(), $request->getUri()->getPath());
switch ($routeInfo[0]) {
case FastRouteDispatcher::FOUND:
$target = $routeInfo[1];
$bits = explode('@', $target);
$controller = $bits[0];
$method = $bits[1] ?? '__invoke';
$vars = $routeInfo[2];
$instance = $this->container->get($controller);
$response = $instance->$method($request);
if (!$response instanceof IResponse) {
throw new \RuntimeException("Return value of $controller::$method is not an instance of " . IResponse::class);
}
return $response;
case FastRouteDispatcher::METHOD_NOT_ALLOWED:
case FastRouteDispatcher::NOT_FOUND:
throw new NotFoundException('Page not found');
default:
throw new \RuntimeException("Unexpected dispatcher code returned: {$routeInfo[0]}");
}
}
}
<file_sep><?php
namespace Vherus\Framework\Jsend;
use Zend\Diactoros\Response\JsonResponse;
use InvalidArgumentException;
class JsendResponse extends JsonResponse
{
/** @throws InvalidArgumentException */
public function __construct($data, string $status = 'success', array $headers = [], $encodingOptions = self::DEFAULT_JSON_FLAGS)
{
$data = (object) [
'status' => $status,
'data' => $data
];
switch ($status) {
case 'success':
$statusCode = 200;
break;
case 'fail':
$statusCode = 401;
break;
case 'error':
$statusCode = 500;
break;
default:
throw new InvalidArgumentException("Status '$status' is not a valid Jsend status");
}
parent::__construct($data, $statusCode, $headers, $encodingOptions);
}
/** @throws InvalidArgumentException */
public static function success($data = [], array $headers = [], $encodingOptions = self::DEFAULT_JSON_FLAGS): JsendResponse
{
return new static($data, 'success', $headers, $encodingOptions);
}
/** @throws InvalidArgumentException */
public static function fail($data, array $headers = [], $encodingOptions = self::DEFAULT_JSON_FLAGS): JsendResponse
{
return new static($data, 'fail', $headers, $encodingOptions);
}
/** @throws InvalidArgumentException */
public static function error($data, array $headers = [], $encodingOptions = self::DEFAULT_JSON_FLAGS): JsendResponse
{
return new static($data, 'error', $headers, $encodingOptions);
}
}
<file_sep>#!/bin/bash
#service php-fpm start
service --status-all
nginx -g "daemon off;"
<file_sep><?php
namespace Vherus\Framework\Time;
use Cake\Chronos\Chronos;
interface Clock
{
public function getCurrentDateTime(): Chronos;
/** @alias Clock::getCurrentDateTime() */
public function now(): Chronos;
}
<file_sep><?php
namespace Vherus\Framework\Exception;
class NotFoundException extends \Exception
{
//
}
<file_sep><?php
namespace Vherus\Framework\Middleware\Stratigility\Response;
use Psr\Http\Message\ResponseInterface as IResponse;
use Throwable;
interface ErrorResponseFactory
{
public function create(Throwable $exception): IResponse;
}
<file_sep><?php
namespace Vherus\Bootstrap;
use Depot\Bus\NativeCommandBus;
use Depot\CommandBus;
use Depot\Resolution\NativeNamespaceResolver;
use Monolog\Handler\ErrorLogHandler;
use Monolog\Logger;
use Vherus\Application\Http\ApiV1\RouteMapper as ApiRouteMapper;
use Vherus\Application\Http\App\RouteMapper as HttpRouteMapper;
use Vherus\Application\Http\Healthcheck\RouteMapper as HealthcheckRouteMapper;
use Vherus\Framework\Depot\Container as DepotContainer;
use Vherus\Framework\Middleware\Auth\ArrayAuthoriser;
use Vherus\Framework\Middleware\Auth\Authoriser;
use Vherus\Framework\Middleware\Auth\Stratigility\SessionStore;
use Vherus\Framework\Middleware\Auth\Stratigility\StoragelessSession;
use Vherus\Framework\Http\Router\Router;
use Vherus\Framework\Time\Clock;
use Vherus\Framework\Time\SystemClock;
use DI\ContainerBuilder;
use Doctrine\DBAL\Schema\AbstractSchemaManager;
use Illuminate\Database\Connection;
use Illuminate\Database\MySqlConnection;
use Illuminate\Database\SQLiteConnection;
use Interop\Container\ContainerInterface as IContainer;
use Psr\Log\LoggerInterface as ILogger;
use Psr\Log\NullLogger;
use PSR7Sessions\Storageless\Http\SessionMiddleware;
class ContainerFactory
{
private $config;
public function create(Config $config = null): IContainer
{
$this->config = $config;
return (new ContainerBuilder)
->useAutowiring(true)
->ignorePhpDocErrors(true)
->useAnnotations(false)
->writeProxiesToFile(false)
->addDefinitions($this->getDefinitions())
->build();
}
protected function getDefinitions(): array
{
return array_merge(
$this->defineConfig(),
$this->defineFramework(),
$this->defineDomain(),
$this->defineApplications()
);
}
protected function defineConfig(): array
{
return [
Config::class => \DI\factory(function () {
return $this->config;
}),
];
}
private function defineFramework(): array
{
return array_merge($this->defineDatabase(), [
Clock::class => \DI\object(SystemClock::class),
IContainer::class => \DI\factory(function (IContainer $container) {
return $container;
}),
Router::class => \DI\decorate(function (Router $router, IContainer $container) {
return $router
->addRoutes($container->get(HttpRouteMapper::class))
->addRoutes($container->get(ApiRouteMapper::class))
->addRoutes($container->get(HealthcheckRouteMapper::class));
}),
SessionMiddleware::class => \DI\factory(function (IContainer $container) {
$config = ConfigFactory::fromContainer($container);
return SessionMiddleware::fromSymmetricKeyDefaults(
$config->get('session.crypt-key'),
$config->get('session.expiry')
);
}),
Authoriser::class => \DI\factory(function (IContainer $container) {
$config = $container->get(Config::class);
return new ArrayAuthoriser($config->get('auth.authorized-keys'), []);
}),
SessionStore::class => \DI\factory(function (IContainer $container) {
return $container->get(StoragelessSession::class);
}),
ILogger::class => \DI\factory(function (IContainer $container) {
switch ($logger = $container->get(Config::class)->get('log.logger')) {
case 'monolog':
$logger = new Logger('error');
$logger->pushHandler(new ErrorLogHandler);
return $logger;
case 'null':
return new NullLogger;
default:
throw new \UnexpectedValueException("Logger '$logger' not recognised");
}
}),
CommandBus::class => \DI\factory(function (IContainer $container) {
return new NativeCommandBus(
new NativeNamespaceResolver(
new DepotContainer($container)
)
);
}),
]);
}
/**
* @return array
*/
private function defineDomain(): array
{
return [
//
];
}
/**
* @return array
*/
private function defineApplications(): array
{
return [
//
];
}
/**
* @return array
*/
private function defineDatabase(): array
{
return [
AbstractSchemaManager::class => \DI\factory(function (IContainer $container) {
return $container->get(Connection::class)->getDoctrineSchemaManager();
}),
Connection::class => \DI\factory(function (IContainer $container) {
$config = $container->get(Config::class);
$dsn = $config->get('database.default.pdo.dsn');
if (substr($dsn, 0, 5) === 'mysql') {
return new MySqlConnection($container->get(\PDO::class));
}
if (substr($dsn, 0, 6) === 'sqlite') {
return new SQLiteConnection($container->get(\PDO::class));
}
throw new \RuntimeException("Unrecognised DSN {$dsn}");
}),
\Doctrine\DBAL\Driver\Connection::class => \DI\factory(function (IContainer $container) {
return $container->get(Connection::class)->getDoctrineConnection();
}),
\PDO::class => \DI\factory(function (IContainer $container) {
$config = $container->get(Config::class);
$pdo = new \PDO(
$config->get('database.default.pdo.dsn'),
$config->get('database.default.pdo.user'),
$config->get('database.default.pdo.pass')
);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $pdo;
}),
];
}
}
<file_sep>FROM nginx:1
COPY ./docker/nginx-proxy/certs/selfsign.cert /etc/nginx/ssl/selfsign.crt
COPY ./docker/nginx-proxy/certs/selfsign.key /etc/nginx/ssl/selfsign.key
COPY ./docker/nginx-proxy/nginx.conf /etc/nginx/nginx.conf
COPY ./docker/nginx-proxy/error_pages /etc/nginx/error_pages
<file_sep><?php
namespace Vherus\Application\Console;
use Doctrine\DBAL\Migrations\OutputWriter;
use Doctrine\DBAL\Migrations\Tools\Console\Command\DiffCommand;
use Doctrine\DBAL\Migrations\Tools\Console\Command\ExecuteCommand;
use Doctrine\DBAL\Migrations\Tools\Console\Command\GenerateCommand;
use Doctrine\DBAL\Migrations\Tools\Console\Command\MigrateCommand;
use Doctrine\DBAL\Migrations\Tools\Console\Command\StatusCommand;
use Doctrine\DBAL\Migrations\Tools\Console\Command\VersionCommand;
use Vherus\Application\Console\Command\HelloWorld;
use Doctrine\DBAL\Driver\Connection;
use Doctrine\DBAL\Migrations\Configuration\Configuration;
use Doctrine\DBAL\Migrations\Finder\GlobFinder;
use Doctrine\DBAL\Migrations\Tools\Console\Helper\ConfigurationHelper;
use Interop\Container\ContainerInterface as IContainer;
use Psr\Log\LoggerInterface as ILogger;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputInterface as IInput;
use Symfony\Component\Console\Output\OutputInterface as IOutput;
class Console
{
private $container;
public function __construct(IContainer $container)
{
$this->container = $container;
}
public function run(IInput $input, IOutput $output): int
{
$app = new Application('CLI Application');
$app->setAutoExit(false);
$app->setCatchExceptions(false);
$app->setHelperSet(new HelperSet([
'dialog' => new QuestionHelper,
'configuration' => $this->configureDoctrineHelper($output),
]));
$app->addCommands([
$this->container->get(HelloWorld::class),
new DiffCommand,
new ExecuteCommand,
new GenerateCommand,
new MigrateCommand,
new StatusCommand,
new VersionCommand
]);
try {
return $app->run($input, $output);
} catch (\Throwable $e) {
$message = get_class($e) . " during '{$input->getFirstArgument()}' with message: {$e->getMessage()}";
$output->writeln("<error>$message</error>");
$this->container->get(ILogger::class)->error(
$message,
['exception' => $e]
);
return 1;
}
}
private function configureDoctrineHelper(IOutput $output): ConfigurationHelper
{
$doctrineConfig = new Configuration(
$this->container->get(Connection::class),
null,
new GlobFinder
);
$configHelper = new ConfigurationHelper($this->container->get(Connection::class), $doctrineConfig);
$doctrineConfig->setMigrationsNamespace(__NAMESPACE__ . '\\Command\\Migration');
$doctrineConfig->setMigrationsDirectory(__DIR__ . '/Command/Migration');
$doctrineConfig->setOutputWriter(new OutputWriter(function (string $message) use ($output) {
$output->writeln($message);
}));
return $configHelper;
}
}
<file_sep><?php
namespace Vherus\Application\Http\App;
use GuzzleHttp\Psr7\ServerRequest;
use Vherus\Testing\Traits\UsesContainer;
use Vherus\Testing\Traits\UsesHttpServer;
use PHPUnit\Framework\TestCase;
class AppHomepageIntegrationTest extends TestCase
{
use UsesContainer, UsesHttpServer;
public function test_200_response_returned_when_logged_in()
{
$container = $this->createContainer();
$request = (new ServerRequest('GET', 'https://example.com/app'));
$response = $this->handle($container, $request);
$this->assertEquals(200, $response->getStatusCode());
}
}
<file_sep><?php
namespace Vherus\Framework\Http\Router;
use FastRoute\RouteCollector;
interface RouteMapper
{
public function map(RouteCollector $router): void;
}
<file_sep><?php
namespace Vherus\Framework\Jsend;
use InvalidArgumentException;
class JsendSuccessResponse extends JsendResponse
{
/** @throws InvalidArgumentException */
public function __construct($data = null, array $headers = [], $encodingOptions = self::DEFAULT_JSON_FLAGS)
{
parent::__construct($data, 'success', $headers, $encodingOptions);
}
}
<file_sep>#!/bin/bash
php /opt/src/vendor/bin/phpunit $@
<file_sep><?php
namespace Vherus\Framework\Http\Router;
use FastRoute\RouteCollector;
use Vherus\Framework\Exception\NotFoundException;
use PHPUnit\Framework\TestCase;
use Prophecy\Prophecy\ObjectProphecy;
use Psr\Container\ContainerInterface as IContainer;
use Zend\Diactoros\Response\TextResponse;
use Zend\Diactoros\ServerRequest;
use Zend\Diactoros\Uri;
class RouterIntegrationTest extends TestCase
{
public function test_bound_routes_are_processed()
{
$request = new ServerRequest;
$request = $request->withMethod('get')->withUri(new Uri('/foobar'));
/** @var IContainer|ObjectProphecy $container */
$container = $this->prophesize(IContainer::class);
$container->get('mycontroller')->willReturn(new class () {
public function __invoke()
{
return new TextResponse('hello world', 202);
}
});
$router = new Router(new Dispatcher($container->reveal()));
$router->addRoutes(new class implements RouteMapper {
public function map(RouteCollector $router): void
{
$router->addRoute('get', '/foobar', 'mycontroller');
}
});
$response = $router->process($request);
$this->assertEquals(202, $response->getStatusCode());
}
public function test_notfound_exception_thrown_on_404()
{
$request = new ServerRequest();
$request = $request->withMethod('get')->withUri(new Uri('/no-found'));
/** @var IContainer|ObjectProphecy $container */
$container = $this->prophesize(IContainer::class);
$container->get('mycontroller')->willReturn(new class () {
public function __invoke()
{
return new TextResponse('hello world', 202);
}
});
$router = new Router(new Dispatcher($container->reveal()));
$router->addRoutes(new class implements RouteMapper {
public function map(RouteCollector $router): void
{
$router->addRoute('get', '/foobar', 'mycontroller');
}
});
$this->expectException(NotFoundException::class);
$router->process($request);
}
}
<file_sep><?php
namespace Vherus\Framework\Middleware\Auth\Stratigility;
use Psr\Http\Message\ServerRequestInterface;
use PSR7Sessions\Storageless\Http\SessionMiddleware;
class StoragelessSession implements SessionStore
{
public function get(ServerRequestInterface $request, string $key)
{
return $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE)->get($key);
}
public function set(ServerRequestInterface $request, string $key, $value): void
{
$request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE)->set($key, $value);
}
}
<file_sep><?php
namespace Vherus\Framework\Time;
use Cake\Chronos\Chronos;
use DateTimeZone;
class SystemClock implements Clock
{
private $timeZone;
public function __construct(?DateTimeZone $timeZone)
{
$this->timeZone = $timeZone ?: new DateTimeZone(date_default_timezone_get());
}
public function getCurrentDateTime(): Chronos
{
return new Chronos('now', $this->timeZone);
}
public function now(): Chronos
{
return $this->getCurrentDateTime();
}
}
<file_sep><?php
namespace Vherus\Testing\Traits;
use Vherus\Bootstrap\Config;
use Vherus\Bootstrap\ConfigFactory;
use Vherus\Bootstrap\ContainerFactory;
use Interop\Container\ContainerInterface as IContainer;
trait UsesContainer
{
protected function createContainer(Config $config = null): IContainer
{
return (new ContainerFactory)->create($config ?: ConfigFactory::create());
}
}
<file_sep><?php
namespace Vherus\Framework\Jsend;
use PHPUnit\Framework\TestCase;
class JsendResponseTest extends TestCase
{
public function test_it_can_be_instantiated()
{
$response = new JsendResponse(['foo' => 'bar', 'fizz' => [4, 5]]);
$expectedData = (object) [
'status' => 'success',
'data' => (object) [
'foo' => 'bar',
'fizz' => [4, 5]
]
];
$this->assertEquals($expectedData, json_decode($response->getBody()));
}
public function test_instance_cannot_be_created_with_invalid_status()
{
$this->expectException(\InvalidArgumentException::class);
new JsendResponse([], 'whoops');
}
public function test_success_factory_method()
{
$response = JsendResponse::success('foobar');
$expectedData = (object) [
'status' => 'success',
'data' => 'foobar'
];
$this->assertEquals($expectedData, json_decode($response->getBody()));
}
public function test_fail_factory_method()
{
$response = JsendResponse::fail('foobar');
$expectedData = (object) [
'status' => 'fail',
'data' => 'foobar'
];
$this->assertEquals($expectedData, json_decode($response->getBody()));
}
public function test_error_factory_method()
{
$response = JsendResponse::error('foobar');
$expectedData = (object) [
'status' => 'error',
'data' => 'foobar'
];
$this->assertEquals($expectedData, json_decode($response->getBody()));
}
}
<file_sep><?php
namespace Vherus\Framework\Entity\Helper;
use PHPUnit\Framework\TestCase;
use Vherus\Framework\Exception\UndefinedException;
class UsesPrivateAttributesTest extends TestCase
{
public function test_attributes_are_stored_as_expected()
{
$mock = new class {
use UsesPrivateAttributes;
public function setName(string $name): self
{
return $this->set('name', $name);
}
public function getName(): string
{
return $this->get('name', '');
}
};
$mock->setName('Test');
$this->assertEquals('Test', $mock->getName());
$mock->setName('Changed');
$this->assertEquals('Changed', $mock->getName());
}
public function test_default_is_used_if_property_does_not_exist()
{
$mock = new class {
use UsesPrivateAttributes;
public function setName(string $name): self
{
return $this->set('name', $name);
}
public function getName(): string
{
return $this->get('name', 'Default value');
}
};
$this->assertEquals('Default value', $mock->getName());
$mock->setName('Has been set');
$this->assertEquals('Has been set', $mock->getName());
}
public function test_closures_can_be_supplied_as_default_value()
{
$mock = new class {
use UsesPrivateAttributes;
public function setName(string $name): self
{
return $this->set('name', $name);
}
public function getName(): string
{
return $this->get('name', function () {
return 'Closure';
});
}
};
$this->assertEquals('Closure', $mock->getName());
}
public function test_undefined_exceptions_can_be_thrown()
{
$mock = new class {
use UsesPrivateAttributes;
public function setName(string $name): self
{
return $this->set('name', $name);
}
public function getName(): string
{
return $this->get('name', $this->throwUndefined('name'));
}
};
$this->expectException(UndefinedException::class);
$this->expectExceptionMessage('Property `name` is not defined.');
$mock->getName();
}
}
<file_sep><?php
namespace Vherus\Framework\Jsend;
use PHPUnit\Framework\TestCase;
class JsendSuccessResponseTest extends TestCase
{
public function test_it_can_be_instantiated()
{
$response = new JsendSuccessResponse((object) [
'foo' => 'bar',
'fizz' => [4, 5]
]);
$expectedData = (object) [
'status' => 'success',
'data' => (object) [
'foo' => 'bar',
'fizz' => [4, 5]
]
];
$this->assertEquals($expectedData, json_decode($response->getBody()));
}
public function test_it_can_be_instantiated_with_null_data()
{
$response = new JsendSuccessResponse();
$expectedData = (object) [
'status' => 'success',
'data' => null
];
$this->assertEquals($expectedData, json_decode($response->getBody()));
}
}
<file_sep><?php
namespace Vherus\Framework\Middleware\Auth\Stratigility;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Vherus\Framework\Middleware\Auth\Authoriser;
use Psr\Http\Message\ServerRequestInterface as IRequest;
use Psr\Http\Message\ResponseInterface as IResponse;
use Vherus\Framework\Exception\UnauthorisedException;
class TokenGuard implements MiddlewareInterface
{
private $authoriser;
public function __construct(Authoriser $authoriser)
{
$this->authoriser = $authoriser;
}
/** @throws UnauthorisedException */
public function process(IRequest $request, DelegateInterface $delegate): IResponse
{
if (!$this->authoriser->shouldAuthorise($request)) {
return $delegate->process($request);
}
if (!$token = $this->getToken($request)) {
throw new UnauthorisedException('Missing `AuthorizationToken` HTTP header');
}
if (!$this->authoriser->isAllowed($token, $request)) {
throw new UnauthorisedException("Invalid `AuthorizationToken` HTTP header provided");
}
return $delegate->process($request);
}
private function getToken(IRequest $request): ?string
{
return $request->getHeader('AuthorizationToken')[0] ?? null;
}
}
<file_sep><?php
namespace Vherus\Application\Http\App;
use FastRoute\RouteCollector;
use Vherus\Framework\Http\Router\RouteMapper as IRouteMapper;
class RouteMapper implements IRouteMapper
{
public function map(RouteCollector $router): void
{
$router->addRoute('GET', '/app', Controller\HomepageController::class);
}
}
<file_sep><?php
namespace Vherus\Framework\Middleware\Auth\Stratigility;
use Psr\Http\Message\ServerRequestInterface as IRequest;
interface SessionStore
{
/** @return mixed */
public function get(IRequest $request, string $key);
public function set(IRequest $request, string $key, $value): void;
}
<file_sep><?php
namespace Vherus\Framework\Http\Router;
use FastRoute\RouteCollector;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Psr\Http\Message\ServerRequestInterface as IRequest;
use Psr\Http\Message\ResponseInterface as IResponse;
use Vherus\Framework\Exception\NotFoundException;
class Router implements DelegateInterface
{
private $dispatcher;
/** @var RouteMapper[] */
private $mappers = [];
public function __construct(Dispatcher $dispatcher)
{
$this->dispatcher = $dispatcher;
}
public function addRoutes(RouteMapper $mapper): Router
{
$this->mappers[] = $mapper;
return $this;
}
/** @throws NotFoundException */
public function process(IRequest $request): IResponse
{
$dispatcher = \FastRoute\simpleDispatcher(function(RouteCollector $r) {
foreach ($this->mappers as $mapper) {
$mapper->map($r);
}
});
return $this->dispatcher->dispatch($request, $dispatcher);
}
}
<file_sep><?php
namespace Vherus\Framework\Uuid;
use PHPUnit\Framework\TestCase;
class UuidTest extends TestCase
{
public function test_generate_created_36_byte_uuid()
{
$id = new Uuid(null);
$this->assertNotEmpty((string) $id);
$this->assertEquals(36, strlen($id));
}
public function test_uuid_is_32_hexidecimal_bytes_once_dashes_are_removed()
{
$id = new Uuid(null);
$this->assertNotEmpty((string) $id);
$this->assertEquals(32, strlen(str_replace('-', '', $id)));
}
public function test_uuid_can_be_easily_converted_to_hex()
{
$id = new Uuid(null);
$this->assertNotEmpty((string) $id);
$this->assertEquals(str_replace('-', '', $id), $id->getHex());
}
public function test_uuids_always_unique_and_valid_binary()
{
$ids = [];
foreach (range(1, 1000) as $i) {
$id = new Uuid(null);
$ids[$id->getBinary()] = $id;
}
$this->assertEquals(1000, count($ids));
foreach ($ids as $binary => $id) {
$this->assertEquals($id, Uuid::createFromBinary($binary));
}
}
}
<file_sep>#!/bin/bash
bin/docker-dev up $@
if [[ $@ == *"-d"* ]]
then
# In daemon mode, provide some extra output
PROXY_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(echo ${PWD##*/} | sed s/[-_]//g | tr [:upper:] [:lower:])_nginx-proxy_1)
echo "Running daemon mode:"
echo " proxy: https://"$(bin/docker-dev port nginx-proxy 443)
echo " https://$PROXY_IP"
fi
<file_sep><?php
namespace Vherus\Framework\Exception;
class ValidationException extends \Exception
{
//
}
<file_sep><?php
namespace Vherus\Application\Http\Healthcheck;
use Zend\Diactoros\Response\HtmlResponse;
class HealthcheckController
{
public function __invoke()
{
return new HtmlResponse("Everything is OK!\n");
}
}
<file_sep><?php
namespace Vherus\Application\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface as IInput;
use Symfony\Component\Console\Output\OutputInterface as IOutput;
class HelloWorld extends Command
{
protected function configure()
{
$this->setName("hello")
->setDescription("This test command says hello");
}
protected function execute(IInput $input, IOutput $output)
{
$output->writeln('Hello, world!');
}
}
<file_sep><?php
namespace Vherus\Application\Http\ApiV1\Controller;
use Vherus\Framework\Jsend\JsendSuccessResponse;
class HelloController
{
public function __invoke()
{
return new JsendSuccessResponse([
'message' => 'Hello, world!'
]);
}
}
<file_sep>DB_DSN=sqlite::memory:
DB_USER=root
DB_PASSWORD=<PASSWORD>
SESSION_CRYPT_KEY=
<file_sep><?php
namespace Vherus\Application\Http\ApiV1;
use DI\Container;
use GuzzleHttp\Psr7\ServerRequest;
use Vherus\Framework\Jsend\JsendSuccessResponse;
use Vherus\Bootstrap\ConfigFactory;
use Vherus\Testing\Traits\UsesContainer;
use Vherus\Testing\Traits\UsesHttpServer;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
class ApiV1HelloIntegrationTest extends TestCase
{
use UsesContainer, UsesHttpServer;
public function test_403_returned_when_no_auth_token()
{
$response = $this->handle($this->createContainer(), (new ServerRequest('GET', 'https://example.com/api/v1/hello'))->withHeader('AuthorizationToken', '11111111-2222-3333-4444-555555555555'));
$this->assertEquals(403, $response->getStatusCode());
}
public function test_200_response_returned_when_auth_token_present_and_valid()
{
$config = ConfigFactory::create([
'auth.authorized-keys' => ['<KEY>']
]);
$container = $this->createContainer($config);
$response = $this->handle(
$container,
(new ServerRequest('GET', 'https://example.com/api/v1/hello'))->withHeader('AuthorizationToken', '<KEY>')
);
$this->assertEquals(200, $response->getStatusCode());
}
}
<file_sep>var Vue = require('vue');
var VueRouter = require('vue-router');
var VueResource = require('vue-resource');
Vue.use(VueResource);
Vue.use(VueRouter);
var App = Vue.extend({
ready: function () {
Vue.http.headers.common['AuthorizationToken'] = document.querySelector('#token').getAttribute('value');
},
data: function () {
return {
defaultErrorHandler: function (response) {
if (response.status == 401) {
alert('You don\'t have permission to do that');
return;
}
alert('An unexpected error occurred. Please wait a few moments and try again.');
}
}
},
components: {
'app-layout': require('./components/Layout.vue')
}
});
// Bind routes
var router = new VueRouter();
router.map({
'/': { component: require('./components/Homepage.vue') }
});
// Hit it
router.start(App, '#app');
<file_sep><?php
namespace Vherus\Framework\Time;
use Cake\Chronos\Chronos;
use PHPUnit\Framework\TestCase;
class FixedClockTest extends TestCase
{
public function test_instance_is_of_type_clock()
{
$this->assertInstanceOf(Clock::class, new FixedClock(null));
}
public function test_clock_fixed_at_given_time()
{
$clock = new FixedClock(new \DateTimeImmutable('2018-01-01 01:28:54'));
$this->assertEquals(new Chronos('2018-01-01 01:28:54'), $clock->now());
}
}
<file_sep><?php
namespace Vherus\Framework\Jsend;
use PHPUnit\Framework\TestCase;
class JsendErrorResponseTest extends TestCase
{
public function test_it_can_be_instantiated()
{
$response = new JsendErrorResponse([
new JsendError('Page not found', 4),
new JsendError('User does not exist', 3),
]);
$expectedData = (object) [
'status' => 'error',
'data' => (object) [
'errors' => [
(object) [
'message' => 'Page not found',
'code' => 4,
],
(object) [
'message' => 'User does not exist',
'code' => 3,
],
],
]
];
$this->assertEquals($expectedData, json_decode($response->getBody()));
}
public function test_it_can_be_instantiated_with_no_errors()
{
$response = new JsendFailResponse();
$expectedData = (object) [
'status' => 'fail',
'data' => (object) [
'errors' => []
]
];
$this->assertEquals($expectedData, json_decode($response->getBody()));
}
}
<file_sep><!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">
<title>Vherus - Framework</title>
<link rel="stylesheet" href="/css/app.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div id="app">
<app-layout>
Loading...
</app-layout>
</div>
<input type="hidden" id="token" value="<?= $token ?>" />
<script src="/js/app.js"></script>
</body>
</html>
<file_sep><?php
namespace Vherus\Framework\Middleware\Stratigility\Response;
use Vherus\Framework\Exception\ValidationException;
use Vherus\Framework\Jsend\JsendError;
use Vherus\Framework\Jsend\JsendErrorResponse;
use Vherus\Framework\Jsend\JsendFailResponse;
use Vherus\Framework\Exception\UnauthorisedException;
use Psr\Http\Message\ResponseInterface as IResponse;
use Throwable;
use Vherus\Framework\Exception\UnauthenticatedException;
class JsendErrorResponseFactory implements ErrorResponseFactory
{
public function create(Throwable $exception): IResponse
{
if ($exception instanceof ValidationException) {
return (new JsendFailResponse([
new JsendError($exception->getMessage())
]))->withStatus(400);
}
if ($exception instanceof UnauthenticatedException) {
return (new JsendErrorResponse([
new JsendError($exception->getMessage() ?: 'Unauthenticated', 401)
]))->withStatus(401);
}
if ($exception instanceof UnauthorisedException) {
return (new JsendErrorResponse([
new JsendError($exception->getMessage() ?: 'Forbidden', 403)
]))->withStatus(403);
}
return new JsendErrorResponse;
}
}
<file_sep><?php
namespace Vherus\Application\Http\ApiV1;
use FastRoute\RouteCollector;
use Vherus\Framework\Http\Router\RouteMapper as IRouteMapper;
class RouteMapper implements IRouteMapper
{
public function map(RouteCollector $router): void
{
$router->addRoute('GET', '/api/v1/hello', Controller\HelloController::class);
}
}
<file_sep><?php
namespace Vherus\Bootstrap;
use Illuminate\Database\Connection;
use Vherus\Testing\Traits\RunsMigrations;
use Vherus\Testing\Traits\UsesContainer;
use PHPUnit\Framework\TestCase;
class ContainerTest extends TestCase
{
use UsesContainer, RunsMigrations;
public function test_db_can_be_created()
{
$container = $this->runMigrations($this->createContainer());
$this->assertInstanceOf(Connection::class, $container->get(Connection::class));
}
}
<file_sep><?php
namespace Vherus\Testing\Traits;
use Vherus\Bootstrap\Config;
use Vherus\Bootstrap\ConfigFactory;
trait UsesConfig
{
protected function createConfig(): Config
{
return ConfigFactory::create();
}
}
<file_sep><?php
namespace Vherus\Framework\Middleware\Stratigility;
use Interop\Http\ServerMiddleware\DelegateInterface as IDelegate;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Psr\Http\Message\ResponseInterface as IResponse;
use Throwable;
use Vherus\Framework\Middleware\Stratigility\Logging\ErrorLogger;
use Vherus\Framework\Middleware\Stratigility\Response\ErrorResponseFactory;
use Psr\Http\Message\ServerRequestInterface as IRequest;
class ErrorHandler implements MiddlewareInterface
{
private $presenter;
private $logger;
public function __construct(ErrorResponseFactory $presenter, ErrorLogger $logger)
{
$this->presenter = $presenter;
$this->logger = $logger;
}
public function process(IRequest $request, IDelegate $delegate): IResponse
{
try {
return $delegate->process($request);
} catch (Throwable $e) {
$this->logger->log($e);
return $this->presenter->create($e);
}
}
}
<file_sep><?php
namespace Vherus\Framework\Exception;
class UnauthorisedException extends \Exception
{
//
}
<file_sep><?php
namespace Vherus\Framework\Middleware\Stratigility\Logging;
use Throwable;
interface ErrorLogger
{
public function log(Throwable $exception): void;
}
<file_sep><?php
namespace Vherus\Framework\Middleware\Stratigility\Logging;
use Closure;
use Psr\Log\LoggerInterface as ILogger;
use Throwable;
class PsrLogger implements ErrorLogger
{
private $logger;
private $logLevelCallback;
/**
* @param ILogger $logger
* @param callable $logLevelCallback
* When an exception occurs, this callable will be called and passed a single argument (the
* Throwable). This callable should return a string which is a log level that can be passed
* to the PSR LoggerInterface.
*/
public function __construct(ILogger $logger, Closure $logLevelCallback = null)
{
$this->logger = $logger;
$this->logLevelCallback = $logLevelCallback ?: function () {
return 'error';
};
}
public function log(Throwable $exception): void
{
$class = get_class($exception);
$message = "$class caught with message '{$exception->getMessage()}'";
$context = ['exception' => $exception];
$level = call_user_func($this->logLevelCallback, $exception);
$this->logger->log($level, $message, $context);
}
}
<file_sep><?php
namespace Vherus\Framework\Entity\Helper;
use Vherus\Framework\Exception\UndefinedException;
trait UsesPrivateAttributes
{
private $attributes = [];
private function set(string $property, $value): self
{
$this->attributes[$property] = $value;
return $this;
}
/**
* @param string $property
* @param mixed $default
* The default value to return if the property has not been set. Callbacks may be
* passed here to perform custom logic in the event of an undefined property.
* @return mixed
*/
private function get(string $property, $default)
{
if (!isset($this->attributes[$property])) {
if (is_callable($default)) {
return call_user_func($default);
}
return $default;
}
return $this->attributes[$property];
}
private function throwUndefined(string $property): \Closure
{
return function () use ($property) {
throw new UndefinedException("Property `$property` is not defined.");
};
}
}
<file_sep><?php
namespace Vherus\Bootstrap;
use Adam\Bag\Bag;
class Config extends Bag
{
}
<file_sep># vherus/php-framework
## What it is
A custom bootstrap framework for HTTP, API and Console based PHP applications.
## What's in the box
- *Console*: a starting point for building CLI applications
- *Http/App*: a starting point for building GUIs
- *Http/ApiV1*: a starting point for building APIs
- *Http/Healthcheck*: a starting point for building a healthcheck endpoint for monitoring tools
## Getting started
### Pre-requisites
- [docker-ce](https://www.docker.com/community-edition)
- [docker-compose](https://docs.docker.com/compose)
### Cloning the repository
`git clone <EMAIL>:vherus/php-framework.git <YOUR_APP_NAME>`
Don't delete the whole `.git` folder. Having a shared git history with the framework will make it easy to merge changes from it to your app.
Delete the `origin` remote, and re-add it named `upstream`. This allows you to merge the framework branches into your app by simply doing `git merge upstream <BRANCH>`.
Git remotes for dummies:
`git remote rm origin`
`git remote add upstream https://github.com/vherus/php-framework.git`
Create a new Github repository and add it as remote `origin`.
`git remote add origin https://github.com/<USER>/<APP>`
### Rename the package
Find and replace all occurrences of "Vherus" in this repository with a name suitable for your application - ensuring to preserve case sensitivity.
This will include renaming things such as:
- composer.json name
- Docker image names
- PHP namespaces
### Delete what you don't need
For example, if you never intend to have a GUI, delete the Http/App namespace entirely.
### Easy start mode
Once you've completed the pre-requisite steps above, let's go!
1. Run `bin/setup` from the project root directory
2. Go make a coffee<file_sep><?php
namespace Vherus\Framework\Exception;
class UnauthenticatedException extends \Exception
{
//
}
<file_sep><?php
namespace Vherus\Framework\Middleware\Auth\Stratigility;
use function GuzzleHttp\Psr7\parse_query;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Vherus\Framework\Exception\NotFoundException;
use Vherus\Framework\Exception\UnauthorisedException;
use Vherus\Framework\Middleware\Auth\Authoriser;
use Psr\Http\Message\ResponseInterface as IResponse;
use Psr\Http\Message\ServerRequestInterface as IRequest;
use Zend\Diactoros\Response\RedirectResponse;
class SessionGuard implements MiddlewareInterface
{
private const SESSION_VAR = 'auth_token';
private $authoriser;
private $session;
public function __construct(Authoriser $authoriser, SessionStore $session)
{
$this->authoriser = $authoriser;
$this->session = $session;
}
/**
* @throws NotFoundException when no auth token has been provided in the request
* @throws UnauthorisedException when the provided auth token is invalid
*/
public function process(IRequest $request, DelegateInterface $delegate): IResponse
{
if (!$this->authoriser->shouldAuthorise($request)) {
return $delegate->process($request);
}
if ($token = $this->getQueryStringToken($request)) {
$this->session->set($request, self::SESSION_VAR, $token);
return $this->redirectRemoveTokenFromUri($request);
}
if (!$token = $this->session->get($request, self::SESSION_VAR)) {
throw new NotFoundException("Could not retrieve an authentication token from the request.");
}
if (!$this->authoriser->isAllowed($token, $request)) {
throw new UnauthorisedException("The auth token retrieved from the request is invalid.");
}
return $delegate->process($request);
}
private function getQueryStringToken(IRequest $request): string
{
parse_str($request->getUri()->getQuery(), $args);
return $args[self::SESSION_VAR] ?? '';
}
/**
* @param IRequest $request
* @return mixed|\Psr\Http\Message\UriInterface
*/
private function getUri(IRequest $request)
{
$uri = $request->getUri();
// Stratigility mutates the `Uri` object before passing it to middleware by
// removing the path used to bind the middleware. If the OriginalMessages
// middleware is used we can access the originalUri attribute.
if ($request->getAttribute('originalUri')) {
$uri = $request->getAttribute('originalUri');
}
return $uri;
}
private function redirectRemoveTokenFromUri(IRequest $request): RedirectResponse
{
$uri = $this->getUri($request);
$query = parse_query($uri->getQuery());
unset($query['auth_token']);
$uri = $uri->withQuery(http_build_query($query));
return new RedirectResponse((string) $uri);
}
}
<file_sep><?php
namespace Vherus\Framework\IO;
use Closure;
class OutputBuffer
{
public static function capture(Closure $callback): string
{
ob_start();
$callback();
$content = ob_get_contents();
ob_end_clean();
return $content;
}
}
<file_sep><?php
namespace Vherus\Framework\Middleware\Auth;
use Psr\Http\Message\RequestInterface as IRequest;
interface Authoriser
{
public function shouldAuthorise(IRequest $request): bool;
public function isAllowed(string $token, IRequest $request): bool;
}
<file_sep><?php
namespace Vherus\Framework\Middleware\Auth;
use Psr\Http\Message\RequestInterface as IRequest;
class ArrayAuthoriser implements Authoriser
{
private $allowedTokens;
private $ignoredPaths;
public function __construct(array $allowedTokens, array $ignoredPaths)
{
$this->allowedTokens = $allowedTokens;
$this->ignoredPaths = $ignoredPaths;
}
public function shouldAuthorise(IRequest $request): bool
{
return !in_array($request->getUri()->getPath(), $this->ignoredPaths, true);
}
public function isAllowed(string $token, IRequest $request): bool
{
return in_array($token, $this->allowedTokens, false);
}
}
<file_sep><?php
namespace Vherus\Application\Http\Healthcheck;
use GuzzleHttp\Psr7\ServerRequest;
use Vherus\Testing\Traits\UsesContainer;
use Vherus\Testing\Traits\UsesHttpServer;
use PHPUnit\Framework\TestCase;
class HealthcheckIntegrationTest extends TestCase
{
use UsesContainer, UsesHttpServer;
public function test_200_response_returned()
{
$response = $this->handle($this->createContainer(), new ServerRequest('GET', '/healthcheck'));
$this->assertEquals(200, $response->getStatusCode());
}
}
<file_sep><?php
namespace Vherus\Framework\Jsend;
use JsonSerializable;
class JsendError implements JsonSerializable
{
private $message;
private $code;
public function __construct(string $message, int $code = 1)
{
$this->message = $message;
$this->code = $code;
}
public function getCode(): int
{
return $this->code;
}
public function getMessage(): string
{
return $this->message;
}
public function jsonSerialize(): object
{
return (object) [
'message' => $this->message,
'code' => $this->code
];
}
}
<file_sep><?php
namespace Vherus\Framework\Depot;
use Depot\Container as IContainer;
use Interop\Container\ContainerInterface as InnerContainer;
class Container implements IContainer
{
private $inner;
public function __construct(InnerContainer $inner)
{
$this->inner = $inner;
}
public function make(string $class)
{
return $this->inner->get($class);
}
}
<file_sep><?php
namespace Vherus\Framework\Time;
use PHPUnit\Framework\TestCase;
class SystemClockTest extends TestCase
{
public function test_is_of_type_clock()
{
$this->assertInstanceOf(Clock::class, new SystemClock(null));
}
public function test_expected_timezone_is_used()
{
$clock = new SystemClock(new \DateTimeZone('Africa/Harare'));
$this->assertEquals(new \DateTimeZone('Africa/Harare'), $clock->now()->getTimezone());
}
}
<file_sep><?php
namespace Vherus\Framework\Middleware\Stratigility\Response;
use InvalidArgumentException;
use Vherus\Framework\Exception\NotFoundException;
use Vherus\Framework\Exception\UnauthorisedException;
use Psr\Http\Message\ResponseInterface as IResponse;
use Throwable;
use Vherus\Framework\Exception\UnauthenticatedException;
use Zend\Diactoros\Response\TextResponse;
class HtmlErrorResponseFactory implements ErrorResponseFactory
{
/**
* @throws InvalidArgumentException
* @todo Replace with more user-friendly HTML response
*/
public function create(Throwable $exception): IResponse
{
if ($exception instanceof UnauthenticatedException) {
return new TextResponse(
'You are not authenticated to perform that action',
401
);
}
if ($exception instanceof UnauthorisedException) {
return new TextResponse(
'You are not authorized to perform that action',
403
);
}
if ($exception instanceof NotFoundException) {
return new TextResponse(
'Page not found',
404
);
}
return new TextResponse(
'Server Unavailable',
500
);
}
}
<file_sep><?php
namespace Vherus\Application\Http;
use Vherus\Framework\Middleware\Auth\Stratigility\SessionGuard;
use Vherus\Framework\Http\Router\Router;
use Vherus\Framework\Middleware\Auth\Stratigility\TokenGuard;
use Vherus\Framework\Middleware\Stratigility\ErrorHandler;
use Vherus\Framework\Middleware\Stratigility\Logging\PsrLogger;
use Vherus\Framework\Middleware\Stratigility\Response\HtmlErrorResponseFactory;
use Interop\Container\ContainerInterface as IContainer;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use PSR7Sessions\Storageless\Http\SessionMiddleware;
use Zend\Diactoros\Response;
use Zend\Stratigility\Middleware\DoublePassMiddlewareDecorator;
use Zend\Stratigility\Middleware\OriginalMessages;
use Zend\Stratigility\Middleware\PathMiddlewareDecorator;
use Zend\Stratigility\MiddlewarePipe;
class HttpServer
{
private $container;
public function __construct(IContainer $container)
{
$this->container = $container;
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
$pipe = (new MiddlewarePipe);
return $pipe
->pipe(new PathMiddlewareDecorator('/', new DoublePassMiddlewareDecorator(new OriginalMessages, new Response)))
->pipe(new PathMiddlewareDecorator('/', new ErrorHandler(
$this->container->get(HtmlErrorResponseFactory::class),
$this->container->get(PsrLogger::class)
)))
// Api specific middleware
->pipe(new PathMiddlewareDecorator('/api', $this->container->get(TokenGuard::class)))
->process($request, $this->container->get(Router::class));
}
}
|
09ccfbc8d530be2eaa6457481200b143498f8886
|
[
"JavaScript",
"Markdown",
"PHP",
"Dockerfile",
"Shell"
] | 68 |
PHP
|
vherus/php-framework-decoupling-bootstrap
|
0292b75b5f13df3be96bde4bcfb24b85093e1c11
|
19bf9afd5ff8a3f02d7a2b5eb4c711ff6430b7e2
|
refs/heads/master
|
<file_sep>package com.github.phenegan;
import discord4j.core.event.domain.message.MessageCreateEvent;
import reactor.core.publisher.Mono;
public interface Command {
void execute(MessageCreateEvent event);
}
<file_sep># DiscordTestBot
A test bot that I'm using to learn about how to work with the Discord4J API. I'll likely use this to test commands that will be implemented in other projects
Doesn't really do too much right now. It has a clean command (removes all messages in a channel), a coin flip command, and a basic ping command.
|
04039fdc0793a5e21c7c38bb147eed1ce7bd1363
|
[
"Markdown",
"Java"
] | 2 |
Java
|
PHenegan/DiscordTestBot
|
b4a379fe326d48e7d481314e2a391d36cae01b39
|
8e29550f508953eb0c120918f6f707ac5d0e92c5
|
refs/heads/master
|
<repo_name>j20232/moco_image_pipeline<file_sep>/test/visualize_augmentation.py
import numpy as np
import matplotlib.pyplot as plt
import cv2
from PIL import Image
import pathlib
from pathlib import Path
import os
import sys
sys.path.append(os.path.join("."))
import mcp.augmentation as maug
def show_imgs(img_list, title_list=None,
rows=1, cmap="viridis", size=(16, 8), show_axis=False):
if title_list is not None:
assert len(img_list) == len(title_list)
if type(img_list[0]) == pathlib.PosixPath or type(img_list[0]) == str:
show_list = [Image.open(str(img_path)) for img_path in img_list]
else:
show_list = img_list
plt.figure(figsize=size)
assert len(show_list) % rows == 0
for idx, img in enumerate(show_list):
plt.subplot(rows, int(len(show_list) / rows), idx + 1)
plt.imshow(img, cmap=cmap)
if title_list is not None:
plt.title(title_list[idx])
if not show_axis:
plt.axis("off")
plt.show()
if __name__ == "__main__":
img_nums = 100
rows = 10
TEST_PATH = Path(".").resolve() / "assets" / "test_images"
img = cv2.imread(str(TEST_PATH / "4.png"))
img = cv2.resize(img, (128, 128))
img = (img / 255).astype(np.float64)
# augmentation
imgs = []
for _ in range(img_nums):
out = img
for method_name in maug.modules:
module = getattr(maug, method_name)(prob=0.2)
out = module(out)
tmp = cv2.cvtColor((out * 255).astype(np.uint8), cv2.COLOR_BGR2GRAY)
imgs.append(tmp)
show_imgs(imgs, rows=rows, size=(24, 10))
<file_sep>/competition/Bengali.py
import os
import sys
import gc
import copy
import zipfile
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
import torch
import torch.nn as nn
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
from torch.nn import functional as F
from torch.utils.data import DataLoader
from torchvision import transforms
from tqdm import tqdm
sys.path.append(os.path.join(".."))
import mcp.augmentation as aug
from mcp.datasets import SimpleDataset
from mcp.functions.metrics import accuracy
from mcp.models import PretrainedCNN, FreezedSEResNeXt, KeroSEResNeXt, GhostNet
from mcp.utils import MLflowWriter, show_logs, crop_and_resize_img
GRAPH = 168
VOWEL = 11
CONSO = 7
ALL = 1295
ROOT_PATH = Path(".").resolve()
CONFIG_PATH = ROOT_PATH / "config"
MODEL_PATH = ROOT_PATH / "models"
INPUT_PATH = ROOT_PATH / "input"
OOF_PATH = ROOT_PATH / "logs" / "oof"
TRAIN_ZIPFILES = ["train_image_data_0.parquet.zip",
"train_image_data_1.parquet.zip",
"train_image_data_2.parquet.zip",
"train_image_data_3.parquet.zip"]
# dirty
class Normalizer():
def __init__(self, mode):
self.mode = mode
def __call__(self, img):
if self.mode == "imagenet":
return (img.astype(np.float32) - 0.456) / 0.224
elif self.mode == "nouse":
return img.astype(np.float32)
else:
return (img.astype(np.float32) - 0.0692) / 0.2051
# --------------------------- CutMix --------------------------------
def rand_bbox(size, lam):
W = size[2]
H = size[3]
cut_rat = np.sqrt(1. - lam)
cut_h = np.int(H * cut_rat)
# uniform
cy = np.random.randint(int(H / 5), int(4 * H / 5))
bby1 = np.clip(cy - cut_h // 2, 0, H)
bby2 = np.clip(cy + cut_h // 2, 0, H)
return 0, bby1, W, bby2
def bengali_cutmix_or_mixup(data, targets, is_cutmix=True, use_all=False):
# cutmix if is_cutmix else mixup
indices = torch.randperm(data.size(0))
shuffled_data = data[indices]
shuffled_targets0 = targets[:, 0][indices]
shuffled_targets1 = targets[:, 1][indices]
shuffled_targets2 = targets[:, 2][indices]
lam = np.random.uniform(0, 1.0)
if is_cutmix:
bbx1, bby1, bbx2, bby2 = rand_bbox(data.size(), lam)
data[:, :, bbx1:bbx2, bby1:bby2] = shuffled_data[indices, :, bbx1:bbx2, bby1:bby2]
lam = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (data.size()[-1] * data.size()[-2]))
else:
data = data * lam + shuffled_data * (1 - lam)
out = [targets[:, 0], shuffled_targets0,
targets[:, 1], shuffled_targets1,
targets[:, 2], shuffled_targets2]
if use_all:
shuffled_targets3 = targets[:, 3][indices]
out.append(targets[:, 3])
out.append(shuffled_targets3)
return data, out, lam
# --------------------------- Trainer --------------------------------
class Bengali():
def __init__(self, name, index, cfg):
super(Bengali, self).__init__()
self.competition_name = name
self.index = index
self.cfg = cfg
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
self.use_grapheme = self.cfg["others"]["use_grapheme"]
model_name = self.cfg["model"]["model_name"]
out_dim = GRAPH + VOWEL + CONSO
if self.use_grapheme:
out_dim += ALL
if model_name == "freeze":
self.model = FreezedSEResNeXt(in_channels=3, out_dim=out_dim,
**self.cfg["model"])
elif model_name == "kero_seresnext":
self.model = KeroSEResNeXt(in_channels=1, out_dim=out_dim)
elif model_name == "GhostNet":
self.model = GhostNet(in_channels=1, out_dim=out_dim)
else:
self.model = PretrainedCNN(in_channels=1, out_dim=out_dim,
**self.cfg["model"])
if "loss_weights" in self.cfg["params"].keys():
self.gweight = self.cfg["params"]["loss_weights"]["grapheme"]
self.vweight = self.cfg["params"]["loss_weights"]["vowel"]
self.cweight = self.cfg["params"]["loss_weights"]["conso"]
else:
self.gweight = 1
self.vweight = 1
self.cweight = 1
self.__set_training()
def __set_training(self):
self.model_path = MODEL_PATH / self.competition_name / self.index
self.model_path.mkdir(parents=True, exist_ok=True)
self.check_point_best_weight_path = self.model_path / "check_point_best.pth"
if self.check_point_best_weight_path.exists():
print("Loaded the best check point")
self.model.load_state_dict(torch.load(str(self.check_point_best_weight_path)))
self.optimizer = getattr(optim, self.cfg["optim"]["name"])(
self.model.parameters(), **self.cfg["optim"]["params"][0])
self.scheduler = getattr(lr_scheduler, self.cfg["scheduler"]["name"])(
self.optimizer, **self.cfg["scheduler"]["params"][0])
self.__create_validation_set()
def __create_validation_set(self):
train_df = pd.read_csv(INPUT_PATH / self.competition_name / self.cfg["dataset"]["train"])
self.train_loader = self.__get_train_dataloader(train_df, True)
valid_df = pd.read_csv(INPUT_PATH / self.competition_name / self.cfg["dataset"]["valid"])
self.valid_loader = self.__get_train_dataloader(valid_df, False)
print("Loaded train and validation dataset!")
def __get_train_dataloader(self, df, is_train):
# Train if is_train else Valid
if "dataset" in self.cfg["others"].keys():
train_img_path = INPUT_PATH / self.competition_name / self.cfg["others"]["dataset"]
else:
train_img_path = INPUT_PATH / self.competition_name / "train_images"
print("is_train: {}, dataset:{} ".format(is_train, train_img_path))
paths = [Path(train_img_path / f"{x}.png") for x in df["image_id"].values]
if self.use_grapheme:
labels = df[["grapheme_root", "vowel_diacritic", "consonant_diacritic", "unique_label"]].values
else:
labels = df[["grapheme_root", "vowel_diacritic", "consonant_diacritic"]].values
tfms = []
for tfm_dict in self.cfg["transform"]:
name, params = tfm_dict["name"], tfm_dict["params"]
lib = aug if name in aug.modules else transforms
tfms.append(getattr(lib, name)(**params))
if "normalization" in self.cfg["others"].keys():
normalizer = Normalizer(self.cfg["others"]["normalization"])
else:
normalizer = Normalizer("default")
tfms.append(normalizer)
tfms.append(transforms.ToTensor())
return DataLoader(SimpleDataset(paths, labels, transform=transforms.Compose(tfms)),
batch_size=self.cfg["params"]["batch_size"], shuffle=is_train,
num_workers=self.cfg["params"]["num_workers"])
def fit(self):
self.__initialize_fitting()
for ep in tqdm(range(self.cfg["params"]["epochs"])):
train_log = {"loss": 0,
"loss_grapheme": 0, "loss_vowel": 0, "loss_consonant": 0, "loss_all": 0,
"acc_grapheme": 0, "acc_vowel": 0, "acc_consonant": 0, "acc_all": 0}
valid_log = copy.deepcopy(train_log)
if self.cfg["others"]["name"] is not None:
results_train = self.__train_one_epoch_others(train_log)
else:
results_train = self.__train_one_epoch(train_log)
results_valid = self.__valid_one_epoch(valid_log)
show_logs(self.cfg, ep, results_train, results_valid)
self.__write_training_log(results_train, "Train", ep)
self.__write_training_log(results_valid, "Valid", ep)
if self.__check_early_stopping(results_valid):
print("Early stopping at round {}".format(ep))
break
ep_model_weight = copy.deepcopy(self.model.state_dict())
torch.save(ep_model_weight, str(self.model_path / f"check_point_{ep}.pth"))
if type(self.scheduler) == torch.optim.lr_scheduler.ReduceLROnPlateau:
self.scheduler.step(results_valid["loss"])
else:
self.scheduler.step()
self.model.load_state_dict(self.best_model_weight)
self.__close_fitting()
return self.best_results
def __train_one_epoch(self, log):
self.model.train()
for inputs, labels, _ in tqdm(self.train_loader):
inputs, labels = inputs.to(self.device), labels.to(self.device)
self.optimizer.zero_grad()
preds = self.model(inputs)
if isinstance(preds, tuple) is False:
if self.use_grapheme:
preds = torch.split(preds, [GRAPH, VOWEL, CONSO, ALL], dim=1)
else:
preds = torch.split(preds, [GRAPH, VOWEL, CONSO], dim=1)
loss, log = self.__calc_loss(preds, labels, log, len(self.train_loader))
loss.backward()
self.optimizer.step()
log["acc"] = (log["acc_grapheme"] * 2 + log["acc_vowel"] + log["acc_consonant"]) / 4
return log
def __train_one_epoch_others(self, log):
self.model.train()
for inputs, labels, _ in tqdm(self.train_loader):
inputs, labels = inputs.to(self.device), labels.to(self.device)
inputs, labels, lam = bengali_cutmix_or_mixup(inputs, labels,
is_cutmix=self.cfg["others"]["name"] == "cutmix",
use_all=self.use_grapheme)
self.optimizer.zero_grad()
preds = self.model(inputs)
if isinstance(preds, tuple) is False:
if self.use_grapheme:
preds = torch.split(preds, [GRAPH, VOWEL, CONSO, ALL], dim=1)
else:
preds = torch.split(preds, [GRAPH, VOWEL, CONSO], dim=1)
loss, log = self.__calc_loss_mix(preds, labels, lam, log, len(self.train_loader))
loss.backward()
self.optimizer.step()
log["acc"] = (log["acc_grapheme"] * 2 + log["acc_vowel"] + log["acc_consonant"]) / 4
return log
def __valid_one_epoch(self, log):
self.model.eval()
with torch.no_grad():
for inputs, labels, _ in tqdm(self.valid_loader):
inputs, labels = inputs.to(self.device), labels.to(self.device)
preds = self.model(inputs)
if isinstance(preds, tuple) is False:
if self.use_grapheme:
preds = torch.split(preds, [GRAPH, VOWEL, CONSO, ALL], dim=1)
else:
preds = torch.split(preds, [GRAPH, VOWEL, CONSO], dim=1)
loss, log = self.__calc_loss(preds, labels, log, len(self.valid_loader))
log["acc"] = (log["acc_grapheme"] * 2 + log["acc_vowel"] + log["acc_consonant"]) / 4
return log
def __calc_loss(self, preds, labels, log=None, loader_length=1):
loss_grapheme = F.cross_entropy(preds[0], labels[:, 0])
loss_vowel = F.cross_entropy(preds[1], labels[:, 1])
loss_consonant = F.cross_entropy(preds[2], labels[:, 2])
loss = self.gweight * loss_grapheme + self.vweight * loss_vowel + self.cweight * loss_consonant
log["loss_grapheme"] += (loss_grapheme / loader_length).cpu().detach().numpy()
log["loss_vowel"] += (loss_vowel / loader_length).cpu().detach().numpy()
log["loss_consonant"] += (loss_consonant / loader_length).cpu().detach().numpy()
acc_grapheme = accuracy(preds[0], labels[:, 0])
acc_vowel = accuracy(preds[1], labels[:, 1])
acc_consonant = accuracy(preds[2], labels[:, 2])
log["acc_grapheme"] += (acc_grapheme / loader_length).cpu().detach().numpy()
log["acc_vowel"] += (acc_vowel / loader_length).cpu().detach().numpy()
log["acc_consonant"] += (acc_consonant / loader_length).cpu().detach().numpy()
if self.use_grapheme:
loss_all = F.cross_entropy(preds[3], labels[:, 3])
log["loss_all"] += (loss_all / loader_length).cpu().detach().numpy()
acc_all = accuracy(preds[3], labels[:, 3])
log["acc_all"] += (acc_all / loader_length).cpu().detach().numpy()
loss += loss_all
log["loss"] += (loss / loader_length).cpu().detach().numpy()
return loss, log
def __calc_loss_mix(self, preds, labels, lam, log=None, loader_length=1):
crit = nn.CrossEntropyLoss(reduction='mean')
loss_grapheme = lam * crit(preds[0], labels[0]) + (1 - lam) * crit(preds[0], labels[1])
loss_vowel = lam * crit(preds[1], labels[2]) + (1 - lam) * crit(preds[1], labels[3])
loss_consonant = lam * crit(preds[2], labels[4]) + (1 - lam) * crit(preds[2], labels[5])
loss = self.gweight * loss_grapheme + self.vweight * loss_vowel + self.cweight * loss_consonant
log["loss_grapheme"] += (loss_grapheme / loader_length).cpu().detach().numpy()
log["loss_vowel"] += (loss_vowel / loader_length).cpu().detach().numpy()
log["loss_consonant"] += (loss_consonant / loader_length).cpu().detach().numpy()
log["loss"] += (loss / loader_length).cpu().detach().numpy()
acc_grapheme = lam * accuracy(preds[0], labels[0]) + (1 - lam) * accuracy(preds[0], labels[1])
acc_vowel = lam * accuracy(preds[1], labels[2]) + (1 - lam) * accuracy(preds[1], labels[3])
acc_consonant = lam * accuracy(preds[2], labels[4]) + (1 - lam) * accuracy(preds[2], labels[5])
log["acc_grapheme"] += (acc_grapheme / loader_length).cpu().detach().numpy()
log["acc_vowel"] += (acc_vowel / loader_length).cpu().detach().numpy()
log["acc_consonant"] += (acc_consonant / loader_length).cpu().detach().numpy()
if self.use_grapheme:
loss_all = lam * crit(preds[3], labels[6]) + (1 - lam) * crit(preds[3], labels[7])
log["loss_all"] += (loss_all / loader_length).cpu().detach().numpy()
acc_all = lam * accuracy(preds[3], labels[6]) + (1 - lam) * accuracy(preds[3], labels[7])
log["acc_all"] += (acc_all / loader_length).cpu().detach().numpy()
return loss, log
def __check_early_stopping(self, results_valid):
if results_valid["loss"] < self.best_results["loss"]:
self.best_results["loss_grapheme"] = results_valid["loss_grapheme"]
self.best_results["loss_vowel"] = results_valid["loss_vowel"]
self.best_results["loss_consonant"] = results_valid["loss_consonant"]
self.best_results["loss"] = results_valid["loss"]
self.best_results["acc_grapheme"] = results_valid["acc_grapheme"]
self.best_results["acc_vowel"] = results_valid["acc_vowel"]
self.best_results["acc_consonant"] = results_valid["acc_consonant"]
self.best_results["acc"] = results_valid["acc"]
if self.use_grapheme:
self.best_results["loss_all"] = results_valid["loss_all"]
self.best_results["acc_all"] = results_valid["acc_all"]
self.best_model_weight = copy.deepcopy(self.model.state_dict())
torch.save(self.best_model_weight, str(self.check_point_best_weight_path))
self.early_stopping_count = 0
else:
self.early_stopping_count += 1
return self.early_stopping_count > self.cfg["params"]["es_rounds"]
def __initialize_fitting(self):
self.model = self.model.to(self.device)
self.best_model_weight = copy.deepcopy(self.model.state_dict())
self.best_results = {"loss": 10000000}
self.early_stopping_count = 0
self.writer = MLflowWriter(self.competition_name, self.index)
self.writer.log_param("index", self.index)
self.writer.log_cfg(self.cfg)
print("Initialized the setting of training!")
def __calculate_oof(self):
self.model.eval()
names = []
graph = None
vowel = None
conso = None
graph_label = None
vowel_label = None
conso_label = None
if self.use_grapheme:
uniq = None
uniq_label = None
with torch.no_grad():
for inputs, labels, paths in tqdm(self.valid_loader):
inputs, labels = inputs.to(self.device), labels.to(self.device)
preds = self.model(inputs)
if isinstance(preds, tuple) is False:
if self.use_grapheme:
preds = torch.split(preds, [GRAPH, VOWEL, CONSO, ALL], dim=1)
labels = torch.split(labels, [1, 1, 1, 1], dim=1)
else:
preds = torch.split(preds, [GRAPH, VOWEL, CONSO], dim=1)
labels = torch.split(labels, [1, 1, 1], dim=1)
names.extend([n.split("/")[-1].split(".")[0] for n in list(paths)])
prob_graph = F.softmax(preds[0], dim=1).cpu().detach().numpy()
prob_vowel = F.softmax(preds[1], dim=1).cpu().detach().numpy()
prob_conso = F.softmax(preds[2], dim=1).cpu().detach().numpy()
graph = prob_graph if graph is None else np.append(graph, prob_graph, axis=0)
vowel = prob_vowel if vowel is None else np.append(vowel, prob_vowel, axis=0)
conso = prob_conso if conso is None else np.append(conso, prob_conso, axis=0)
g = labels[0].cpu().detach().numpy()
v = labels[1].cpu().detach().numpy()
c = labels[2].cpu().detach().numpy()
graph_label = g if graph_label is None else np.append(g, graph_label)
vowel_label = v if vowel_label is None else np.append(v, vowel_label)
conso_label = c if conso_label is None else np.append(c, conso_label)
if self.use_grapheme:
prob_uniq = F.softmax(preds[3], dim=1).cpu().detach().numpy()
uniq = prob_uniq if uniq is None else np.append(uniq, prob_uniq, axis=0)
c = labels[3].cpu().detach().numpy()
uniq_label = c if uniq_label is None else np.append(c, uniq_label)
graph_df = pd.DataFrame({"image_id": names, "label": graph_label})
graph_df = pd.concat([graph_df, pd.DataFrame(graph)], axis=1)
vowel_df = pd.DataFrame({"image_id": names, "label": vowel_label})
vowel_df = pd.concat([vowel_df, pd.DataFrame(vowel)], axis=1)
conso_df = pd.DataFrame({"image_id": names, "label": conso_label})
conso_df = pd.concat([conso_df, pd.DataFrame(conso)], axis=1)
oof_dir = OOF_PATH / self.competition_name / self.index
oof_dir.mkdir(parents=True, exist_ok=True)
grapheme_path = oof_dir / "oof_grapheme.csv"
vowel_path = oof_dir / "oof_vowel.csv"
conso_path = oof_dir / "oof_consonant.csv"
graph_df.to_csv(grapheme_path, index=False)
vowel_df.to_csv(vowel_path, index=False)
conso_df.to_csv(conso_path, index=False)
zipfile_name = str(OOF_PATH / self.competition_name / "{}.zip".format(self.index))
if self.use_grapheme:
uniq_df = pd.DataFrame({"image_id": names, "label": uniq_label})
uniq_df = pd.concat([graph_df, pd.DataFrame(uniq)], axis=1)
label_path = oof_dir / "oof_label.csv"
uniq_df.to_csv(label_path, index=False)
with zipfile.ZipFile(zipfile_name, "w") as z:
z.write(str(grapheme_path), arcname="oof_grapheme.csv")
z.write(str(vowel_path), arcname="oof_vowel.csv")
z.write(str(conso_path), arcname="oof_consonant.csv")
if self.use_grapheme:
z.write(str(conso_path), arcname="oof_label.csv")
os.remove(str(label_path))
self.writer.log_artifact(zipfile_name)
os.remove(str(grapheme_path))
os.remove(str(vowel_path))
os.remove(str(conso_path))
os.rmdir(str(oof_dir))
def __close_fitting(self):
self.__calculate_oof()
weight_path = str(self.model_path / f"{self.index}.pth")
torch.save(self.best_model_weight, weight_path)
self.__write_training_log(self.best_results, "CV")
self.writer.log_artifact(weight_path)
self.writer.close()
print("Finished training!")
def __write_training_log(self, results, postfix, ep=None):
self.writer.log_metric(f"loss_{postfix}", results["loss"], ep)
self.writer.log_metric(f"acc_{postfix}", results["acc"], ep)
self.writer.log_metric(f"loss_grapheme_{postfix}", results["loss_grapheme"], ep)
self.writer.log_metric(f"acc_grapheme_{postfix}", results["acc_grapheme"], ep)
self.writer.log_metric(f"loss_vowel_{postfix}", results["loss_vowel"], ep)
self.writer.log_metric(f"acc_vowel_{postfix}", results["acc_vowel"], ep)
self.writer.log_metric(f"loss_consonant_{postfix}", results["loss_consonant"], ep)
self.writer.log_metric(f"acc_consonant_{postfix}", results["acc_consonant"], ep)
if self.use_grapheme:
self.writer.log_metric(f"loss_all_{postfix}", results["loss_all"], ep)
self.writer.log_metric(f"acc_all_{postfix}", results["acc_all"], ep)
def convert_parquet2png(size=(128, 128), save_dir=None, crop_width=13,
crop_height=10, padding=16, line_threshold=80, noise_threshold=20):
WIDTH = 236
HEIGHT = 137
gc.enable()
print("INPUT_PATH: ", INPUT_PATH)
for zipidx, zip_file in tqdm(enumerate(TRAIN_ZIPFILES)):
dir_name = zip_file.split(".")[0]
Path(save_dir).mkdir(parents=True, exist_ok=True)
print("open parquet files...")
with zipfile.ZipFile(INPUT_PATH / "bengaliai-cv19" / zip_file) as existing_zip:
parquet_file = INPUT_PATH / "bengaliai-cv19" / "{}.parquet".format(dir_name)
if os.path.exists(parquet_file) is False:
existing_zip.extractall(INPUT_PATH / "bengaliai-cv19")
img_df = pd.read_parquet(parquet_file)
print("save images...")
for idx in tqdm(range(len(img_df))):
img0 = 255 - img_df.iloc[idx, 1:].values.reshape(HEIGHT, WIDTH).astype(np.uint8)
img = (img0 * (255.0 / img0.max())).astype(np.uint8)
img = crop_and_resize_img(img, size, WIDTH, HEIGHT,
crop_width, crop_height, padding,
line_threshold, noise_threshold)
name = img_df.iloc[idx, 0]
cv2.imwrite(str(save_dir / f"{name}.png"), img)
del img_df
gc.collect()
if __name__ == "__main__":
size = (236, 137)
save_dir = INPUT_PATH / "bengaliai-cv19" / "train_images_{}_{}".format(size[0], size[1])
convert_parquet2png(size, save_dir)
<file_sep>/requirements.txt
albumentations==0.4.3
alembic==1.4.0
appnope==0.1.0
attrs==19.3.0
backcall==0.1.0
bleach==3.1.0
certifi==2019.11.28
chardet==3.0.4
Click==7.0
cloudpickle==1.3.0
configparser==4.0.2
cycler==0.10.0
databricks-cli==0.9.1
decorator==4.4.1
defusedxml==0.6.0
docker==4.2.0
entrypoints==0.3
Flask==1.1.1
gitdb2==3.0.2
GitPython==3.0.8
gorilla==0.3.0
gunicorn==20.0.4
idna==2.8
imageio==2.6.1
imgaug==0.2.6
importlib-metadata==1.5.0
ipykernel==5.1.4
ipython==7.12.0
ipython-genutils==0.2.0
ipywidgets==7.5.1
itsdangerous==1.1.0
jedi==0.16.0
Jinja2==2.11.1
joblib==0.14.1
jsonschema==3.2.0
jupyter==1.0.0
jupyter-client==5.3.4
jupyter-console==6.1.0
jupyter-core==4.6.2
kiwisolver==1.1.0
line-profiler==3.0.2
llvmlite==0.31.0
Mako==1.1.1
MarkupSafe==1.1.1
matplotlib==3.1.3
mistune==0.8.4
mlflow==1.6.0
munch==2.5.0
nbconvert==5.6.1
nbformat==5.0.4
networkx==2.4
notebook==6.0.3
numba==0.48.0
numpy==1.18.1
opencv-python==4.2.0.32
pandas==1.0.1
pandocfilters==1.4.2
parso==0.6.1
pathlib==1.0.1
pexpect==4.8.0
pickleshare==0.7.5
Pillow==6.2.0
pretrainedmodels==0.7.4
prometheus-client==0.7.1
prometheus-flask-exporter==0.12.2
prompt-toolkit==3.0.3
protobuf==3.11.3
ptyprocess==0.6.0
pyarrow==0.16.0
Pygments==2.5.2
pyparsing==2.4.6
pyrsistent==0.15.7
python-dateutil==2.8.1
python-editor==1.0.4
pytz==2019.3
PyWavelets==1.1.1
PyYAML==5.3
pyzmq==18.1.1
qtconsole==4.6.0
querystring-parser==1.2.4
requests==2.22.0
scikit-image==0.16.2
scikit-learn==0.22.1
scipy==1.4.1
Send2Trash==1.5.0
simplejson==3.17.0
six==1.14.0
smmap2==2.0.5
SQLAlchemy==1.3.13
sqlparse==0.3.0
tabulate==0.8.6
terminado==0.8.3
testpath==0.4.4
torch==1.4.0
torchvision==0.5.0
tornado==6.0.3
tqdm==4.42.1
traitlets==4.3.3
urllib3==1.25.8
waitress==1.4.3
wcwidth==0.1.8
webencodings==0.5.1
websocket-client==0.57.0
Werkzeug==1.0.0
widgetsnbextension==3.5.1
zipp==3.0.0
<file_sep>/mcp/datasets/simple_dataset.py
import numpy as np
import cv2
from torch.utils.data.dataset import Dataset
class SimpleDataset(Dataset):
# single channel
def __init__(self, paths, labels=None, transform=None):
self.paths = paths
self.labels = labels
self.is_train = False if self.labels is None else True
self.transform = transform
def __len__(self):
return len(self.paths)
def __getitem__(self, i):
x = cv2.imread(str(self.paths[i]), cv2.IMREAD_GRAYSCALE)
# x = (255 - x).astype(np.float32) / 255.
x = x.astype(np.float32) / 255.
if self.transform:
x = self.transform(x)
return (x, self.labels[i], str(self.paths[i])) if self.is_train else (x, str(self.paths[i]))
class SimpleDatasetNoCache(Dataset):
def __init__(self, imgs, paths, transform=None):
self.imgs = imgs
self.paths = paths
self.transform = transform
def __len__(self):
return len(self.paths)
def __getitem__(self, i):
x = self.imgs[i].astype(np.float32) / 255.
x = self.transform(x)
return (x, str(self.paths[i]))
<file_sep>/test/test_models.py
import unittest
import torch
from mcp.models import PretrainedCNN, get_official_names, get_pretrained_names, get_timm_names
class ModelTest(unittest.TestCase):
def test_official_cnn(self):
t = torch.ones([1, 1, 64, 64])
names = get_official_names()
for name in names:
model = PretrainedCNN(name, in_channels=1, out_dim=10)
model.eval()
out = model(t)
self.assertEqual(out.shape[1], 10)
def test_pretrained_cnn(self):
t = torch.ones([1, 1, 64, 64])
names = get_pretrained_names()
for name in names:
model = PretrainedCNN(name, in_channels=1, out_dim=10)
model.eval()
out = model(t)
self.assertEqual(out.shape[1], 10)
def test_timm_cnn(self):
t = torch.ones([1, 1, 64, 64])
names = get_timm_names()
for name in names:
model = PretrainedCNN(name, in_channels=1, out_dim=10)
model.eval()
out = model(t)
self.assertEqual(out.shape[1], 10)
<file_sep>/mcp/utils/convert.py
import numpy as np
import cv2
# for bengali competition
def calc_bounding_box(img):
cols = np.any(img, axis=0)
xmin, xmax = np.where(cols)[0][[0, -1]]
rows = np.any(img, axis=1)
ymin, ymax = np.where(rows)[0][[0, -1]]
return xmin, xmax, ymin, ymax
def crop_and_resize_img(img, size, max_width, max_height,
crop_width=13, crop_height=10,
padding=16, line_threshold=80, noise_threshold=28):
# crop a box around pixels larger than line_threshold
# NOTE: some images contain line at the sides
xmin, xmax, ymin, ymax = calc_bounding_box(img[5:-5, 5:-5] > line_threshold)
# cropping may cut too much, so we need to add it back
xmin = xmin - crop_width if (xmin > crop_width) else 0
ymin = ymin - crop_height if (ymin > crop_height) else 0
xmax = xmax + crop_width if (xmax < max_width - crop_width) else max_width
ymax = ymax + crop_height if (ymax < max_height - crop_height) else max_height
cropped_img = img[ymin:ymax, xmin:xmax]
# remove low intensity pixels as noise
cropped_img[cropped_img < noise_threshold] = 0
# make sure that aspect ratio is kept in rescaling
len_x, len_y = xmax - xmin, ymax - ymin
length = max(len_x, len_y) + padding
out_img = np.pad(cropped_img, [((length - len_y) // 2,), ((length - len_x) // 2,)], mode="constant")
if type(size) == tuple:
return cv2.resize(out_img, size)
else:
return cv2.resize(out_img, (size, size))
<file_sep>/mcp/augmentation/pil_aug.py
import numpy as np
from PIL import Image
from torchvision.transforms import transforms
# Input: PIL Image or np.ndarray, Output: np.ndarray (0 ~ 1.0)
class CenterOrRandomCrop():
def __init__(self, size, prob=0.8):
self.random_crop = transforms.RandomCrop(size)
self.center_crop = transforms.CenterCrop(size)
self.prob = np.clip(prob, 0.0, 1.0)
def __call__(self, img):
src = img
if type(img) is np.ndarray:
if img.dtype == "float32" or img.dtype == "float64":
src = (img * 255).astype(np.uint8)
src = Image.fromarray(src)
if np.random.uniform() < self.prob:
out = self.center_crop(src)
else:
out = self.random_crop(src)
out = np.asarray(out)
if type(img) is np.ndarray and (img.dtype == "float32" or img.dtype == "float64"):
out = (out / 255).astype(np.float32)
return out
<file_sep>/mcp/utils/mlflow_writer.py
import importlib
class MLflowWriter():
def __init__(self, competition_name, index, **kwargs):
mlflow = importlib.import_module("mlflow")
self.client = mlflow.tracking.MlflowClient(**kwargs)
try:
self.experiment_id = self.client.create_experiment(competition_name)
except:
self.experiment_id = self.client.get_experiment_by_name(competition_name).experiment_id
self.run_id = self.client.create_run(self.experiment_id).info.run_id
def log_cfg(self, cfg):
for key, value in cfg.items():
if type(value) is dict:
for k, v in value.items():
self.client.log_param(self.run_id, "{}/{}".format(key, k), v)
else:
self.client.log_param(self.run_id, key, value)
def log_param(self, key, value):
self.client.log_param(self.run_id, key, value)
def log_metric(self, key, value, step):
self.client.log_metric(self.run_id, key, value, step=step)
def log_artifact(self, local_path):
self.client.log_artifact(self.run_id, local_path)
def close(self):
self.client.set_terminated(self.run_id)
<file_sep>/mcp/kernel.py
import importlib
from . import utils
class Kernel():
def __init__(self, competition, input_path, config_path,
competition_yaml_path, weight_path, output_path):
cfg = utils.read_yaml(config_path)
utils.seed_everything(cfg["seed"])
competition_dict = utils.read_yaml(competition_yaml_path)
module_name = "{}Kernel".format(competition_dict[competition])
modulelib = importlib.import_module("competition.{}".format(module_name))
self.model = getattr(modulelib, module_name)(competition, cfg, input_path,
weight_path, output_path)
def predict(self):
self.model.predict()
<file_sep>/mcp/models/__init__.py
from .pretrained_cnn import PretrainedCNN, get_official_names, get_pretrained_names, get_timm_names
from .freezed_seresnext import FreezedSEResNeXt
from .keroppi import KeroSEResNeXt
from .ghost_net import GhostNet
<file_sep>/kernel_sample.py
from pathlib import Path
from mcp import Kernel
if __name__ == "__main__":
# Please change here
competition_name = "bengaliai-cv19"
index = "0000"
input_path = Path(".").resolve() / "input"
model_weight_path = Path(".").resolve() / "models" / competition_name / index / f"{index}.pth"
config_path = Path(".").resolve() / "config" / competition_name / f"{index}.yaml"
competition_yaml_path = Path(".").resolve() / "competition.yaml"
output_path = input_path / competition_name / "output"
kernel = Kernel(competition_name, input_path, config_path, competition_yaml_path,
model_weight_path, output_path)
kernel.predict()
<file_sep>/mcp/models/keroppi.py
# Reference: https://www.kaggle.com/c/bengaliai-cv19/discussion/123757
import torch
import torch.nn as nn
import torch.nn.functional as F
class KeroSEResNeXt(nn.Module):
def __init__(self, in_channels=1, out_dim=10):
super(KeroSEResNeXt, self).__init__()
self.block0 = nn.Sequential(
nn.Conv2d(in_channels, 64, kernel_size=7, stride=2, padding=3, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True)
)
self.block1 = nn.Sequential(
nn.MaxPool2d(kernel_size=3, padding=0, stride=2, ceil_mode=True),
SENextBottleneckBlock(64, 128, 256, stride=1, is_shortcut=True, excite_size=64),
* [SENextBottleneckBlock(256, 128, 256, stride=1, is_shortcut=False, excite_size=64) for i in range(1, 3)],
)
self.block2 = nn.Sequential(
SENextBottleneckBlock(256, 256, 512, stride=2, is_shortcut=True, excite_size=32),
* [SENextBottleneckBlock(512, 256, 512, stride=1, is_shortcut=False, excite_size=32) for i in range(1, 4)],
)
self.block3 = nn.Sequential(
SENextBottleneckBlock(512, 512, 1024, stride=2, is_shortcut=True, excite_size=16),
* [SENextBottleneckBlock(1024, 512, 1024, stride=1, is_shortcut=False, excite_size=16) for i in range(1, 6)],
)
self.block4 = nn.Sequential(
SENextBottleneckBlock(1024, 1024, 2048, stride=2, is_shortcut=True, excite_size=8),
* [SENextBottleneckBlock(2048, 1024, 2048, stride=1, is_shortcut=False, excite_size=8) for i in range(1, 3)],
)
self.dropout = nn.Dropout(p=0.2)
self.logit = nn.Linear(2048, out_dim)
def forward(self, x):
batch_size = len(x)
x = self.block0(x)
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
x = self.block4(x)
x = F.adaptive_avg_pool2d(x, 1).reshape(batch_size, -1)
x = self.dropout(x)
logit = self.logit(x)
return logit
class SENextBottleneckBlock(nn.Module):
def __init__(self, in_channel, channel, out_channel, stride=1, group=32, reduction=16, excite_size=-1, is_shortcut=False):
super(SENextBottleneckBlock, self).__init__()
self.is_shortcut = is_shortcut
self.conv_bn1 = ConvBn2d(in_channel, channel, kernel_size=1, padding=0, stride=1)
self.conv_bn2 = ConvBn2d(channel, channel, kernel_size=3, padding=1, stride=stride, groups=group)
self.conv_bn3 = ConvBn2d(channel, out_channel, kernel_size=1, padding=0, stride=1)
self.scale = SqueezeExcite(out_channel, reduction, excite_size)
if is_shortcut:
self.shortcut = ConvBn2d(in_channel, out_channel, kernel_size=1, padding=0, stride=stride)
def forward(self, x):
z = F.relu(self.conv_bn1(x), inplace=True)
z = F.relu(self.conv_bn2(z), inplace=True)
z = self.scale(self.conv_bn3(z))
z += self.shortcut(x) if self.is_shortcut else x
z = F.relu(z, inplace=True)
return z
class ConvBn2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, padding=1, dilation=1, stride=1, groups=1, is_bn=True):
super(ConvBn2d, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding, stride=stride, dilation=dilation, groups=groups, bias=False)
self.bn = nn.BatchNorm2d(out_channels, eps=1e-5)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
return x
class SqueezeExcite(nn.Module):
def __init__(self, in_channel, reduction=4, excite_size=-1):
super(SqueezeExcite, self).__init__()
self.excite_size = excite_size
self.fc1 = nn.Conv2d(in_channel, in_channel // reduction, kernel_size=1, padding=0)
self.fc2 = nn.Conv2d(in_channel // reduction, in_channel, kernel_size=1, padding=0)
def forward(self, x):
s = F.adaptive_avg_pool2d(x, 1)
s = self.fc1(s)
s = F.relu(s, inplace=True)
s = self.fc2(s)
x = x * torch.sigmoid(s)
return x
<file_sep>/competition/BengaliKernel.py
import os
import sys
import gc
import numpy as np
import pandas as pd
import cv2
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import transforms
sys.path.append(os.path.join(".."))
from mcp.datasets import SimpleDataset, SimpleDatasetNoCache
from mcp.models import PretrainedCNN, KeroSEResNeXt, GhostNet
from mcp.utils.convert import crop_and_resize_img
GRAPH = 168
VOWEL = 11
CONSO = 7
ALL = 1295
WIDTH = 236
HEIGHT = 137
# dirty
class Normalizer():
def __init__(self, mode):
self.mode = mode
def __call__(self, img):
if self.mode == "imagenet":
return (img.astype(np.float32) - 0.456) / 0.224
elif self.mode == "nouse":
return img.astype(np.float32)
else:
return (img.astype(np.float32) - 0.0692) / 0.2051
class BengaliKernel():
def __init__(self, competition, cfg, input_path, model_weight_path, output_path):
self.cfg = cfg
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
self.use_grapheme = self.cfg["others"]["use_grapheme"]
model_name = self.cfg["model"]["model_name"]
out_dim = GRAPH + VOWEL + CONSO
if self.use_grapheme:
out_dim += ALL
if model_name == "kero_seresnext":
self.model = KeroSEResNeXt(in_channels=1, out_dim=out_dim)
elif model_name == "GhostNet":
self.model = GhostNet(in_channels=1, out_dim=out_dim)
else:
self.model = PretrainedCNN(in_channels=1, out_dim=out_dim,
**self.cfg["model"])
self.model.load_state_dict(torch.load(str(model_weight_path), map_location=self.device))
self.model = self.model.to(self.device)
print("Loaded pretrained model: {}".format(model_weight_path))
self.input_path = input_path / competition
self.output_path = output_path
self.cache_dir = output_path / "cache"
def crop(self, x, size):
x = (x * (255.0 / x.max())).astype(np.uint8)
x = crop_and_resize_img(x, size, WIDTH, HEIGHT)
return x
def predict(self):
size = (128, 128)
if "dataset" in self.cfg["others"].keys():
if self.cfg["others"]["dataset"] == "train_images_236_137":
size = (WIDTH, HEIGHT)
gc.enable()
print("Reading input parquet files...")
test_files = [self.input_path / "test_image_data_0.parquet",
self.input_path / "test_image_data_1.parquet",
self.input_path / "test_image_data_2.parquet",
self.input_path / "test_image_data_3.parquet"]
row_id = None
target = None
bs = self.cfg["params"]["test_batch_size"]
for f in test_files:
img_df = pd.read_parquet(f)
num_rows, num_cols = img_df.shape
imgs = []
paths = []
for idx in range(int(num_rows / bs) + 1):
name = img_df.iloc[idx * bs : (idx + 1) * bs, 0]
img0 = img_df.iloc[idx * bs : (idx + 1) * bs, 1:].values
img0 = np.reshape(img0, (img0.shape[0], HEIGHT, WIDTH))
img0 = 255 - img0.astype(np.uint8)
img = [self.crop(im, size) for im in img0]
imgs.extend(img)
paths.extend(name)
if "normalization" in self.cfg["others"].keys():
normalizer = Normalizer(self.cfg["others"]["normalization"])
else:
normalizer = Normalizer("default")
tfms = [normalizer, transforms.ToTensor()]
loader = DataLoader(SimpleDatasetNoCache(imgs, paths, transform=transforms.Compose(tfms)),
batch_size=bs, shuffle=False, num_workers=self.cfg["params"]["num_workers"])
names, graph, vowel, conso = self.predict_for_ensemble(loader)
g_ids = [f"{s}_grapheme_root" for s in names]
v_ids = [f"{s}_vowel_diacritic" for s in names]
c_ids = [f"{s}_consonant_diacritic" for s in names]
r = np.stack([g_ids, v_ids, c_ids], 1)
row_id = np.append(row_id, r.flatten()) if row_id is not None else r.flatten()
g = np.argmax(graph, axis=1)
v = np.argmax(vowel, axis=1)
c = np.argmax(conso, axis=1)
t = np.stack([g, v, c], 1)
target = np.append(target, t.flatten()) if target is not None else t.flatten()
del graph, vowel, conso
del g_ids, v_ids, c_ids, r
del g, v, c, t
del imgs, paths
gc.collect()
submission_df = pd.DataFrame({'row_id': row_id, 'target': target})
submission_df.to_csv(self.output_path / 'submission.csv', index=False)
print(submission_df.head(10))
print("Submission length: ", len(submission_df))
print("Done")
def predict_for_ensemble(self, test_dataloader):
self.model.eval()
names = []
graph = None
vowel = None
conso = None
with torch.no_grad():
for imgs, paths in test_dataloader:
imgs = imgs.to(self.device)
preds = self.model(imgs)
if isinstance(preds, tuple) is False:
if self.use_grapheme:
preds = torch.split(preds, [GRAPH, VOWEL, CONSO, ALL], dim=1)
else:
preds = torch.split(preds, [GRAPH, VOWEL, CONSO], dim=1)
names.extend([n.split("/")[-1].split(".")[0] for n in list(paths)])
prob_graph = F.softmax(preds[0], dim=1).cpu().detach().numpy()
prob_vowel = F.softmax(preds[1], dim=1).cpu().detach().numpy()
prob_conso = F.softmax(preds[2], dim=1).cpu().detach().numpy()
graph = prob_graph if graph is None else np.append(graph, prob_graph, axis=0)
vowel = prob_vowel if vowel is None else np.append(vowel, prob_vowel, axis=0)
conso = prob_conso if conso is None else np.append(conso, prob_conso, axis=0)
return names, graph, vowel, conso
<file_sep>/mcp/models/freezed_seresnext.py
from torch import nn
import torch.nn.functional as F
import os
import sys
DIR_NAME = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(DIR_NAME + "/local_cnn_finetune/"))
import cnn_finetune
from cnn_finetune.local_pretrainedmodels.pretrainedmodels.models.senet import SEResNeXtBottleneck, SEModule
def initialize_weights(module):
if type(module) == SEModule or type(module) == SEResNeXtBottleneck or type(module) == nn.Sequential:
for child in module.children():
initialize_weights(child)
elif "reset_parameters" in dir(module):
module.reset_parameters()
class FreezedSEResNeXt(nn.Module):
def __init__(self, model_name,
in_channels=3, out_dim=10, hdim=512, activation=F.leaky_relu,
use_bn=True, pretrained=False, kernel_size=3, stride=1, padding=1):
super(FreezedSEResNeXt, self).__init__()
print("Architecture: ", model_name)
is_remote = os.getcwd() != "/kaggle/working"
self.base_model = cnn_finetune.make_model("se_resnext50_32x4d",
num_classes=out_dim,
pretrained=is_remote and pretrained)
self.conv0 = nn.Conv2d(in_channels, 3,
kernel_size=kernel_size, stride=stride, padding=padding,
bias=True)
for child in self.base_model.children():
for cnt, c in enumerate(child.children()):
if cnt == 0:
initialize_weights(c)
else:
for p in c.parameters():
p.requires_grad = False
def forward(self, x):
return self.base_model(self.conv0(x))
<file_sep>/mcp/models/block/linear_block.py
import torch
from torch import nn
import torch.nn.functional as F
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init__()
def forward(self, x):
return x.view(x.size(0), -1)
def residual_add(lhs, rhs):
lhs_ch, rhs_ch = lhs.shape[1], rhs.shape[1]
if lhs_ch < rhs_ch:
out = lhs + rhs[:, :lhs_ch]
elif lhs_ch > rhs_ch:
out = torch.cat([lhs[:, :rhs_ch] + rhs, lhs[:, rhs_ch:]], dim=1)
else:
out = lhs + rhs
return out
class LinearBlock(nn.Module):
def __init__(self, in_features, out_features, bias=True,
use_bn=True, activation=F.relu, dropout_ratio=-1, residual=False):
super(LinearBlock, self).__init__()
self.linear = nn.Linear(in_features, out_features, bias=bias)
self.bn = nn.BatchNorm1d(out_features) if use_bn else (lambda x : x)
self.dropout = nn.Dropout(p=dropout_ratio) if dropout_ratio > 0 else (lambda x : x)
self.activation = activation if activation else (lambda x : x)
self.use_bn = use_bn if use_bn else (lambda x : x)
self.residual = residual if residual else (lambda h, x : h)
def __call__(self, x):
h = self.linear(x)
h = self.bn(h)
h = self.activation(h)
h = residual_add(h, x)
h = self.dropout(h)
return h
<file_sep>/mcp/augmentation/album.py
import numpy as np
from PIL import Image, ImageOps, ImageEnhance
import albumentations as A
# ndarray: H x W x C
def apply_aug(aug, image):
return aug(image=image)["image"]
# ----------------------------------- Blur -------------------------------------------
class RandomBlur():
def __init__(self, prob, blur_limit=9):
self.prob = np.clip(prob, 0.0, 1.0)
self.blur_limit = blur_limit
def __call__(self, img):
if np.random.uniform() < self.prob:
r = np.random.uniform()
if r < 0.4:
img = apply_aug(A.Blur(blur_limit=self.blur_limit, always_apply=True), img)
elif r < 0.6:
img = apply_aug(A.GaussianBlur(blur_limit=self.blur_limit, always_apply=True), img)
else:
img = apply_aug(A.MotionBlur(blur_limit=self.blur_limit, always_apply=True), img)
return img
# ----------------------------------- Noise -------------------------------------------
class GaussNoise():
def __init__(self, prob, var_limit=(0.0, 0.07)):
self.prob = np.clip(prob, 0.0, 1.0)
self.var_limit = var_limit
def __call__(self, img):
return apply_aug(A.GaussNoise(var_limit=self.var_limit, p=self.prob), img)
class MultiplicativeNoise():
def __init__(self, prob, var_limit=(0.6, 1.1)):
self.prob = np.clip(prob, 0.0, 1.0)
self.var_limit = var_limit
def __call__(self, img):
return apply_aug(A.MultiplicativeNoise(multiplier=self.var_limit, p=self.prob), img)
# ---------------------------------- Distortion ---------------------------------------
class GridDistortion():
def __init__(self, prob, num_steps=10, distort_limit=0.7):
self.prob = np.clip(prob, 0.0, 1.0)
self.num_steps = num_steps
self.distort_limit = distort_limit
def __call__(self, img):
return apply_aug(A.GridDistortion(p=self.prob, num_steps=self.num_steps,
distort_limit=self.distort_limit), img)
class ElasticTransform():
def __init__(self, prob, sigma=40, alpha=1, alpha_affine=15):
self.prob = np.clip(prob, 0.0, 1.0)
self.sigma = sigma
self.alpha = alpha
self.alpha_affine = alpha_affine
def __call__(self, img):
return apply_aug(A.ElasticTransform(p=self.prob, sigma=self.sigma,
alpha=self.alpha, alpha_affine=self.alpha_affine), img)
class ShiftScaleRotate():
def __init__(self, prob, shift_limit=0.0625, scale_limit=0.2, rotate_limit=20):
self.prob = prob
self.shift_limit = shift_limit
self.scale_limit = scale_limit
self.rotate_limit = rotate_limit
def __call__(self, img):
return apply_aug(A.ShiftScaleRotate(p=self.prob, shift_limit=self.shift_limit,
scale_limit=self.scale_limit,
rotate_limit=self.rotate_limit), img)
# ----------------------------------- Histogram ----------------------------------------
class HueSaturationValue():
def __init__(self, prob, hue_shift_limit=20, sat_shift_limit=40, val_shift_limit=100):
self.prob = np.clip(prob, 0.0, 1.0)
self.hue_shift_limit = hue_shift_limit
self.sat_shift_limit = sat_shift_limit
self.val_shift_limit = val_shift_limit
def __call__(self, img):
out = img if img.dtype == "uint8" else (img * 255).astype(np.uint8)
out = apply_aug(A.HueSaturationValue(p=self.prob, hue_shift_limit=self.hue_shift_limit,
sat_shift_limit=self.sat_shift_limit,
val_shift_limit=self.val_shift_limit), out)
return out if img.dtype == "uint8" else (out / 255).astype(np.float64)
class RandomBrightnessContrast():
def __init__(self, prob, brightness_limit=2.0, contrast_limit=0.6):
self.prob = np.clip(prob, 0.0, 1.0)
self.brightness_limit = brightness_limit
self.contrast_limit = contrast_limit
def __call__(self, img):
return apply_aug(A.RandomBrightnessContrast(p=self.prob,
brightness_limit=self.brightness_limit,
contrast_limit=self.contrast_limit,
brightness_by_max=False,
), img)
class RandomCLAHE():
def __init__(self, prob, clip_limit=40.0, tile_grid_size=(16, 16)):
self.prob = np.clip(prob, 0.0, 1.0)
self.clip_limit = clip_limit
self.tile_grid_size = tile_grid_size
def __call__(self, img):
out = img if img.dtype == "uint8" else (img * 255).astype(np.uint8)
out = apply_aug(A.CLAHE(p=self.prob, clip_limit=self.clip_limit,
tile_grid_size=self.tile_grid_size), out)
return out if img.dtype == "uint8" else (out / 255).astype(np.float64)
# ------------------------------------- Removal ------------------------------------------
class CoarseDropout():
def __init__(self, prob, max_holes=10, max_height=12, max_width=12):
self.prob = np.clip(prob, 0.0, 1.0)
self.max_holes = max_holes
self.max_height = max_height
self.max_width = max_width
def __call__(self, img):
return apply_aug(A.CoarseDropout(p=self.prob, max_holes=self.max_holes,
max_height=self.max_height, max_width=self.max_width,
fill_value=np.median(img)), img)
# ------------------------------------------- Augmix -------------------------------------------
# Reference: https://www.kaggle.com/haqishen/augmix-based-on-albumentations
def int_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval .
Args:
level: Level of the operation that will be between [0, `PARAMETER_MAX`].
maxval: Maximum value that the operation can have. This will be scaled to
level/PARAMETER_MAX.
Returns:
An int that results from scaling `maxval` according to `level`.
"""
return int(level * maxval / 10)
def float_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval.
Args:
level: Level of the operation that will be between [0, `PARAMETER_MAX`].
maxval: Maximum value that the operation can have. This will be scaled to
level/PARAMETER_MAX.
Returns:
A float that results from scaling `maxval` according to `level`.
"""
return float(level) * maxval / 10.
def sample_level(n):
return np.random.uniform(low=0.1, high=n)
def autocontrast(pil_img, _):
return ImageOps.autocontrast(pil_img)
def equalize(pil_img, _):
return ImageOps.equalize(pil_img)
def posterize(pil_img, level):
level = int_parameter(sample_level(level), 4)
return ImageOps.posterize(pil_img, 4 - level)
def rotate(pil_img, level):
degrees = int_parameter(sample_level(level), 30)
if np.random.uniform() > 0.5:
degrees = -degrees
return pil_img.rotate(degrees, resample=Image.BILINEAR)
def solarize(pil_img, level):
level = int_parameter(sample_level(level), 256)
return ImageOps.solarize(pil_img, 256 - level)
def shear_x(pil_img, level):
level = float_parameter(sample_level(level), 0.3)
if np.random.uniform() > 0.5:
level = -level
return pil_img.transform(pil_img.size,
Image.AFFINE, (1, level, 0, 0, 1, 0),
resample=Image.BILINEAR)
def shear_y(pil_img, level):
level = float_parameter(sample_level(level), 0.3)
if np.random.uniform() > 0.5:
level = -level
return pil_img.transform(pil_img.size,
Image.AFFINE, (1, 0, 0, level, 1, 0),
resample=Image.BILINEAR)
def translate_x(pil_img, level):
level = int_parameter(sample_level(level), pil_img.size[0] / 3)
if np.random.random() > 0.5:
level = -level
return pil_img.transform(pil_img.size,
Image.AFFINE, (1, 0, level, 0, 1, 0),
resample=Image.BILINEAR)
def translate_y(pil_img, level):
level = int_parameter(sample_level(level), pil_img.size[0] / 3)
if np.random.random() > 0.5:
level = -level
return pil_img.transform(pil_img.size,
Image.AFFINE, (1, 0, 0, 0, 1, level),
resample=Image.BILINEAR)
# operation that overlaps with ImageNet-C's test set
def color(pil_img, level):
level = float_parameter(sample_level(level), 1.8) + 0.1
return ImageEnhance.Color(pil_img).enhance(level)
# operation that overlaps with ImageNet-C's test set
def contrast(pil_img, level):
level = float_parameter(sample_level(level), 1.8) + 0.1
return ImageEnhance.Contrast(pil_img).enhance(level)
# operation that overlaps with ImageNet-C's test set
def brightness(pil_img, level):
level = float_parameter(sample_level(level), 1.8) + 0.1
return ImageEnhance.Brightness(pil_img).enhance(level)
# operation that overlaps with ImageNet-C's test set
def sharpness(pil_img, level):
level = float_parameter(sample_level(level), 1.8) + 0.1
return ImageEnhance.Sharpness(pil_img).enhance(level)
def normalize(image):
"""Normalize input image channel-wise to zero mean and unit variance."""
return image - 127
def apply_op(image, op, severity):
# image = np.clip(image, 0, 255)
pil_img = Image.fromarray(image) # Convert to PIL.Image
pil_img = op(pil_img, severity)
return np.asarray(pil_img)
def augment_and_mix(image, severity=3, width=3, depth=-1, alpha=1.):
"""Perform AugMix augmentations and compute mixture.
Args:
image: Raw input image as float32 np.ndarray of shape (h, w, c)
severity: Severity of underlying augmentation operators (between 1 to 10).
width: Width of augmentation chain
depth: Depth of augmentation chain. -1 enables stochastic depth uniformly
from [1, 3]
alpha: Probability coefficient for Beta and Dirichlet distributions.
Returns:
mixed: Augmented and mixed image.
"""
augmentations = [
autocontrast, equalize, posterize, rotate, solarize, shear_x, shear_y,
translate_x, translate_y
]
ws = np.float32(np.random.dirichlet([alpha] * width))
m = np.float32(np.random.beta(alpha, alpha))
mix = np.zeros_like(image).astype(np.float32)
for i in range(width):
image_aug = image.copy()
depth = depth if depth > 0 else np.random.randint(1, 4)
for _ in range(depth):
op = np.random.choice(augmentations)
image_aug = apply_op(image_aug, op, severity)
# Preprocessing commutes since all coefficients are convex
mix += ws[i] * image_aug
# mix += ws[i] * normalize(image_aug)
mixed = (1 - m) * image + m * mix
# mixed = (1 - m) * normalize(image) + m * mix
return mixed
class RandomAugMix():
def __init__(self, prob=0.1, severity=2, width=3, depth=2, alpha=1.):
self.prob = prob
self.severity = severity
self.width = width
self.depth = depth
self.alpha = alpha
def __call__(self, img):
if np.random.uniform() > self.prob:
return img
tmp = (img * 255).astype(np.uint8) if img.dtype != "uint8" else img
out = augment_and_mix(tmp, self.severity, self.width, self.depth, self.alpha)
if type(img) is np.ndarray:
if img.dtype != "uint8":
out = (out / 255).astype(np.float64)
return out
<file_sep>/mcp/augmentation/kero_aug.py
# Reference: https://www.kaggle.com/c/bengaliai-cv19/discussion/123757
import numpy as np
import cv2
# ----------------------------------- Geometric -----------------------------------------
class RandomProjective():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
mag = np.random.uniform(-1, 1) * 0.5 * self.magnitude
height, width = image.shape[:2]
x0, y0 = 0, 0
x1, y1 = 1, 0
x2, y2 = 1, 1
x3, y3 = 0, 1
mode = np.random.choice(['top', 'bottom', 'left', 'right'])
if mode == 'top':
x0 += mag
x1 -= mag
if mode == 'bottom':
x3 += mag
x2 -= mag
if mode == 'left':
y0 += mag
y3 -= mag
if mode == 'right':
y1 += mag
y2 -= mag
s = np.array([[0, 0], [1, 0], [1, 1], [0, 1]]) * [[width, height]]
d = np.array([[x0, y0], [x1, y1], [x2, y2], [x3, y3]]) * [[width, height]]
transform = cv2.getPerspectiveTransform(s.astype(np.float32), d.astype(np.float32))
image = cv2.warpPerspective(image, transform, (width, height), flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT, borderValue=0)
return image
class RandomPerspective():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
mag = np.random.uniform(-1, 1, (4, 2)) * 0.25 * self.magnitude
height, width = image.shape[:2]
s = np.array([[0, 0], [1, 0], [1, 1], [0, 1]])
d = s + mag
s *= [[width, height]]
d *= [[width, height]]
transform = cv2.getPerspectiveTransform(s.astype(np.float32), d.astype(np.float32))
image = cv2.warpPerspective(image, transform, (width, height), flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT, borderValue=0)
return image
class RandomRotate():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
angle = 1 + np.random.uniform(-1, 1) * 30 * self.magnitude
height, width = image.shape[:2]
cx, cy = width // 2, height // 2
transform = cv2.getRotationMatrix2D((cx, cy), -angle, 1.0)
image = cv2.warpAffine(image, transform, (width, height), flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT, borderValue=0)
return image
class RandomScale():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
s = 1 + np.random.uniform(-1, 1) * self.magnitude * 0.5
height, width = image.shape[:2]
transform = np.array([[s, 0, 0], [0, s, 0], ], np.float32)
image = cv2.warpAffine(image, transform, (width, height), flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT, borderValue=0)
return image
class RandomShearX():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
sx = np.random.uniform(-1, 1) * self.magnitude
height, width = image.shape[:2]
transform = np.array([[1, sx, 0], [0, 1, 0]], np.float32)
image = cv2.warpAffine(image, transform, (width, height), flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT, borderValue=0)
return image
class RandomShearY():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
sy = np.random.uniform(-1, 1) * self.magnitude
height, width = image.shape[:2]
transform = np.array([[1, 0, 0], [sy, 1, 0]], np.float32)
image = cv2.warpAffine(image, transform, (width, height), flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT, borderValue=0)
return image
class RandomStretchX():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
sx = 1 + np.random.uniform(-1, 1) * self.magnitude
height, width = image.shape[:2]
transform = np.array([[sx, 0, 0], [0, 1, 0]], np.float32)
image = cv2.warpAffine(image, transform, (width, height), flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT, borderValue=0)
return image
class RandomStretchY():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
sy = 1 + np.random.uniform(-1, 1) * self.magnitude
height, width = image.shape[:2]
transform = np.array([[1, 0, 0], [0, sy, 0]], np.float32)
image = cv2.warpAffine(image, transform, (width, height), flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT, borderValue=0)
return image
# ----------------------------------- GridDistortion -----------------------------------------
class RandomGridDistortion():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
num_step = 5
distort = self.magnitude
distort_x = [1 + np.random.uniform(-distort, distort) for i in range(num_step + 1)]
distort_y = [1 + np.random.uniform(-distort, distort) for i in range(num_step + 1)]
height, width = image.shape[:2]
xx = np.zeros(width, np.float32)
step_x = width // num_step
prev = 0
for i, x in enumerate(range(0, width, step_x)):
start = x
end = x + step_x
if end > width:
end = width
cur = width
else:
cur = prev + step_x * distort_x[i]
xx[start:end] = np.linspace(prev, cur, end - start)
prev = cur
yy = np.zeros(height, np.float32)
step_y = height // num_step
prev = 0
for idx, y in enumerate(range(0, height, step_y)):
start = y
end = y + step_y
if end > height:
end = height
cur = height
else:
cur = prev + step_y * distort_y[idx]
yy[start:end] = np.linspace(prev, cur, end - start)
prev = cur
map_x, map_y = np.meshgrid(xx, yy)
map_x = map_x.astype(np.float32)
map_y = map_y.astype(np.float32)
image = cv2.remap(image, map_x, map_y, interpolation=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT, borderValue=0)
return image
class RandomCustomGridDistortion():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
distort = self.magnitude * 0.3
height = image.shape[0]
width = image.shape[1]
s_x = np.array([0.0, 0.5, 1.0, 0.0, 0.5, 1.0, 0.0, 0.5, 1.0])
s_y = np.array([0.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0])
d_x = s_x.copy()
d_y = s_y.copy()
d_x[[1, 4, 7]] += np.random.uniform(-distort, distort, 3)
d_y[[3, 4, 5]] += np.random.uniform(-distort, distort, 3)
s_x = (s_x * width)
s_y = (s_y * height)
d_x = (d_x * width)
d_y = (d_y * height)
distort = np.zeros_like(image)
for index in ([4, 1, 3], [4, 1, 5], [4, 7, 3], [4, 7, 5]):
point = np.stack([s_x[index], s_y[index]]).T
qoint = np.stack([d_x[index], d_y[index]]).T
src = np.array(point, np.float32)
dst = np.array(qoint, np.float32)
mat = cv2.getAffineTransform(src, dst)
point = np.round(point).astype(np.int32)
x0 = np.min(point[:, 0])
x1 = np.max(point[:, 0])
y0 = np.min(point[:, 1])
y1 = np.max(point[:, 1])
mask = np.zeros_like(image)
mask[y0:y1, x0:x1] = 1
mask = mask * image
warp = cv2.warpAffine(mask, mat, (width, height), borderMode=cv2.BORDER_REPLICATE)
distort = np.maximum(distort, warp)
return distort
# ----------------------------------- Contrast -----------------------------------------
class RandomContrast():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
alpha = 1 + np.random.uniform(-1, 1) * self.magnitude
image = image.astype(np.float32) * alpha
image = np.clip(image, 0, 1)
return image
class RandomBlockFade():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
size = [0.1, self.magnitude]
height = image.shape[0]
width = image.shape[1]
# get bounding box
m = image.copy()
cv2.rectangle(m, (0, 0), (height, width), 1, 5)
m = image < 0.5
if m.sum() == 0:
return image
m = np.where(m)
y0, y1, x0, x1 = np.min(m[0]), np.max(m[0]), np.min(m[1]), np.max(m[1])
w = x1 - x0
h = y1 - y0
if w * h < 10:
return image
ew, eh = np.random.uniform(*size, 2)
ew = int(ew * w)
eh = int(eh * h)
ex = np.random.randint(0, w - ew) + x0
ey = np.random.randint(0, h - eh) + y0
image[ey:ey + eh, ex:ex + ew] *= np.random.uniform(0.1, 0.5)
image = np.clip(image, 0, 1)
return image
# ------------------------------------ Noise ------------------------------------------
class RandomErode():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
s = int(round(1 + np.random.uniform(0, 1) * self.magnitude * 6))
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, tuple((s, s)))
image = cv2.erode(image, kernel, iterations=1)
return image
class RandomDilate():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
s = int(round(1 + np.random.uniform(0, 1) * self.magnitude * 6))
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, tuple((s, s)))
image = cv2.dilate(image, kernel, iterations=1)
return image
class RandomSpinkle():
def __init__(self, prob, magnitude=0.5, size=16):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
self.size = size
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
num_sprinkle = int(round(1 + np.random.randint(10) * self.magnitude))
image = image.copy()
image_small = cv2.resize(image, dsize=None, fx=0.25, fy=0.25)
m = np.where(image_small > 0.25)
num = len(m[0])
if num == 0:
return image
s = self.size // 2
i = np.random.choice(num, num_sprinkle)
for y, x in zip(m[0][i], m[1][i]):
y = y * 4 + 2
x = x * 4 + 2
image[y - s:y + s, x - s:x + s] = 0
return image
class RandomNoise():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
noise = np.random.uniform(-1, 1, image.shape) * self.magnitude * 0.7
image = image + noise
image = np.clip(image, 0, 1)
return image
class RandomLine():
def __init__(self, prob, magnitude=0.5):
self.prob = np.clip(prob, 0.0, 1.0)
self.magnitude = 0.5
def __call__(self, image):
if np.random.uniform() > self.prob:
return image
num_lines = int(round(1 + np.random.randint(8) * self.magnitude))
height = image.shape[0]
width = image.shape[1]
image = image.copy()
def line0():
return (0, 0), (width - 1, 0)
def line1():
return (0, height - 1), (width - 1, height - 1)
def line2():
return (0, 0), (0, height - 1)
def line3():
return (width - 1, 0), (width - 1, height - 1)
def line4():
x0, x1 = np.random.choice(width, 2)
return (x0, 0), (x1, height - 1)
def line5():
y0, y1 = np.random.choice(height, 2)
return (0, y0), (width - 1, y1)
for i in range(num_lines):
p = np.array([1 / 4, 1 / 4 , 1 / 4, 1 / 4, 1, 1])
func = np.random.choice([line0, line1, line2, line3, line4, line5], p=p / p.sum())
(x0, y0), (x1, y1) = func()
color = np.random.uniform(0, 1)
thickness = np.random.randint(1, 5)
line_type = np.random.choice([cv2.LINE_AA, cv2.LINE_4, cv2.LINE_8])
cv2.line(image, (x0, y0), (x1, y1), color, thickness, line_type)
return image
<file_sep>/test/context.py
import unittest
from test_models import ModelTest
from test_augmentation import AugmentationTest
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(ModelTest))
suite.addTest(unittest.makeSuite(AugmentationTest))
return suite
<file_sep>/mcp/utils/__init__.py
from .convert import calc_bounding_box, crop_and_resize_img
from .mlflow_writer import MLflowWriter
from .reader import read_yaml
from .seed import seed_everything
from .train_utils import show_logs
<file_sep>/mcp/augmentation/opencv.py
import numpy as np
import cv2
# ndarray: H x W x C
def get_random_kernel(min_ker, max_ker):
structure = np.random.choice([cv2.MORPH_RECT, cv2.MORPH_ELLIPSE, cv2.MORPH_CROSS])
kernel = cv2.getStructuringElement(structure, tuple(np.random.randint(min_ker, max_ker, 2)))
return kernel
class RandomMorphology():
def __init__(self, prob=0.4, min_ker=1, max_ker=2):
self.prob = np.clip(prob, 0.0, 1.0)
self.min_ker = min_ker
self.max_ker = max_ker
def __call__(self, img):
if np.random.uniform() < self.prob:
r = np.random.uniform()
kernel = get_random_kernel(self.min_ker, self.max_ker)
if r < 0.25:
img = cv2.erode(img, kernel, iterations=1)
elif r < 0.50:
img = cv2.dilate(img, kernel, iterations=1)
elif r < 0.75:
k2 = get_random_kernel(self.min_ker, self.max_ker)
img = cv2.erode(img, kernel, iterations=1)
img = cv2.dilate(img, k2, iterations=1)
else:
k2 = get_random_kernel(self.min_ker, self.max_ker)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, k2, iterations=1)
return img
<file_sep>/mcp/utils/train_utils.py
def show_logs(cfg, epoch, results_train, results_valid):
if cfg["params"]["verbose"] == -1 or (epoch + 1) % cfg["params"]["verbose"] != 0:
return
header = "| train / valid | epoch "
train = "| train | {} ".format(epoch + 1)
valid = "| valid | {} ".format(epoch + 1)
for key in results_train.keys():
header += "| {} ".format(key)
train += "| {} ".format(results_train[key])
valid += "| {} ".format(results_valid[key])
header += "|"
train += "|"
valid += "|"
print(header)
print(train)
print(valid)
print("--------------------")
<file_sep>/mcp/models/block/__init__.py
from .linear_block import Flatten, LinearBlock
from .drop_block import DropBlock2D, DropBlock3D, LinearScheduler
<file_sep>/mcp/augmentation/__init__.py
from .album import RandomBlur
from .album import GaussNoise, MultiplicativeNoise
from .album import GridDistortion, ElasticTransform, ShiftScaleRotate
from .album import HueSaturationValue, RandomBrightnessContrast, RandomCLAHE
from .album import CoarseDropout
from .album import RandomAugMix
from .opencv import RandomMorphology
from .pil_aug import CenterOrRandomCrop
from .mixup import Mixup
from .kero_aug import RandomProjective, RandomPerspective, RandomRotate
from .kero_aug import RandomScale, RandomShearX, RandomShearY, RandomStretchX, RandomStretchY
from .kero_aug import RandomGridDistortion, RandomCustomGridDistortion
from .kero_aug import RandomContrast, RandomBlockFade
from .kero_aug import RandomErode, RandomDilate, RandomSpinkle, RandomNoise, RandomLine
# PIL
pil_modules = [
"CenterOrRandomCrop"
]
# np.ndarray
modules = [
"RandomBlur",
"GaussNoise", "MultiplicativeNoise",
"GridDistortion", "ElasticTransform", "ShiftScaleRotate",
"HueSaturationValue", "RandomBrightnessContrast", "RandomCLAHE",
"CoarseDropout",
"RandomAugMix",
"RandomMorphology",
"RandomProjective", "RandomPerspective", "RandomRotate",
"RandomScale", "RandomShearX", "RandomShearY", "RandomStretchX", "RandomStretchY",
"RandomGridDistortion", "RandomCustomGridDistortion",
"RandomContrast", "RandomBlockFade",
"RandomErode", "RandomDilate", "RandomSpinkle", "RandomNoise", "RandomLine"
]
<file_sep>/test/test_augmentation.py
import unittest
import numpy as np
from PIL import Image
from mcp import augmentation as maug
class AugmentationTest(unittest.TestCase):
def test_tensor(self):
float_img = np.random.rand(255, 255, 3)
uint_img = (float_img * 255).astype(np.uint8)
img = Image.fromarray(uint_img)
size = [224, 224]
for method_name in maug.pil_modules:
module = getattr(maug, method_name)(size=size, prob=1.0)
# np.float32
out = module(float_img)
self.assertTrue(out.shape[0] == size[0] and out.shape[1] == size[1],
"np.float32: illegal size")
self.assertTrue(out.max() <= 1.0, "np.float32: max value <= 1.0")
self.assertTrue(out.min() >= 0.0, "np.float32: min value >= 0.0")
# np.uint8 out = module(uint_img)
self.assertTrue(out.shape[0] == size[0] and out.shape[1] == size[1],
"np.uint8: illegal size")
self.assertTrue(out.max() <= 255, "np.uint8: max value <= 255")
self.assertTrue(out.min() >= 0, "np.uint8: min value >= 0")
# Image -> np.uint8
out = module(img)
self.assertTrue(out.shape[0] == size[0] and out.shape[1] == size[1],
"Image: illegal size")
self.assertTrue(out.max() <= 255, "Image -> np.uint8: max value <= 255")
self.assertTrue(out.min() >= 0, "Image -> np.uint8: min value >= 0")
def test_augmentation(self):
for method_name in maug.modules:
print("testing", method_name)
# float64 prob=0.0
img = np.random.rand(255, 255, 3).astype(np.float64)
module0 = getattr(maug, method_name)(prob=0.0)
out = module0(img)
self.assertTrue(img.shape == out.shape, "Prob=0.0: inconsistent shape")
self.assertTrue(out.max() <= 1.0, "Prob=0.0: max value <= 1.0")
self.assertTrue(out.min() >= 0.0, "Prob=0.0: min value >= 0.0")
# float64 prob=1.0
module1 = getattr(maug, method_name)(prob=1.0)
out = module1(img)
self.assertTrue(img.shape == out.shape, "Prob=1.0: inconsistent shape")
self.assertTrue(out.max() <= 1.0, "Prob=1.0: max value <= 1.0")
self.assertTrue(out.min() >= 0.0, "Prob=1.0: min value >= 0.0")
<file_sep>/setup.py
import sys
from setuptools import setup, find_packages
sys.path.append("./mcp")
sys.path.append("./test")
with open("README.md") as f:
long_description = f.read()
setup(
name="mcp",
version="0.1",
author="mocobt",
author_email="<EMAIL>",
description="image pipeline for kaggle",
long_description=long_description,
license="BSD 3-Clause",
packages=find_packages(),
test_suite="context.suite"
)
<file_sep>/mcp/utils/reader.py
import re
import yaml
def read_yaml(path):
loader = yaml.SafeLoader # to read float number like 1e-5
loader.add_implicit_resolver(
u'tag:yaml.org,2002:float',
re.compile(u'''^(?:
[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)?
|[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
|\\.[0-9_]+(?:[eE][-+][0-9]+)?
|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*
|[-+]?\\.(?:inf|Inf|INF)
|\\.(?:nan|NaN|NAN))$''', re.X),
list(u'-+0123456789.'))
with open(path) as f:
cfg = yaml.load(f, Loader=loader)
return cfg
<file_sep>/mcp/augmentation/mixup.py
# Reference:
# - https://github.com/snakers4/MNASNet-pytorch-1/blob/master/mixup.py
# - https://github.com/snakers4/MNASNet-pytorch-1/blob/master/utils/cross_entropy.py
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Beta
def onehot(indexes, N=None, ignore_index=None):
"""
Creates a one-representation of indexes with N possible entries
if N is not specified, it will suit the maximum index appearing.
indexes is a long-tensor of indexes
ignore_index will be zero in onehot representation
"""
if N is None:
N = indexes.max() + 1
sz = list(indexes.size())
output = indexes.new().byte().resize_(*sz, N).zero_()
output.scatter_(-1, indexes.unsqueeze(-1), 1)
if ignore_index is not None and ignore_index >= 0:
output.masked_fill_(indexes.eq(ignore_index).unsqueeze(-1), 0)
return output
def mixup(x, y, num_classes, gamma=0.2, smooth_eps=0.1):
if gamma == 0 and smooth_eps == 0:
return x, y
m = Beta(torch.tensor([gamma]), torch.tensor([gamma]))
lambdas = m.sample([x.size(0), 1, 1]).to(x)
my = onehot(y, num_classes).to(x)
true_class, false_class = 1. - smooth_eps * num_classes / (num_classes - 1), smooth_eps / (num_classes - 1)
my = my * true_class + torch.ones_like(my) * false_class
perm = torch.randperm(x.size(0))
x2 = x[perm]
y2 = my[perm]
return x * (1 - lambdas) + x2 * lambdas, my * (1 - lambdas) + y2 * lambdas
class Mixup(torch.nn.Module):
def __init__(self, num_classes=1000, gamma=0.2, smooth_eps=0.1):
super(Mixup, self).__init__()
self.num_classes = num_classes
self.gamma = gamma
self.smooth_eps = smooth_eps
def forward(self, input, target):
return mixup(input, target, self.num_classes, self.gamma, self.smooth_eps)
<file_sep>/README.md
# 🐅 Moco Image Pipeline


PyTorch-based image pipeline for kaggle competition
---
## 🎵 Installation
```
git clone --recursive <EMAIL>:j20232/moco_image_pipeline.git
pip install -r requirements.txt
```
---
## 🏃♂️ Quick Start
### Training
```py
python train.py [competition_name] [index]
```
|Competition|Train|Kernel|Config|
|:-|:-|:-|:-|
|[`bengaliai-cv19`](https://www.kaggle.com/c/bengaliai-cv19)|[Link](https://github.com/j20232/moco_image_pipeline/blob/master/competition/Bengali.py) | [Link](https://github.com/j20232/moco_image_pipeline/blob/master/competition/BengaliKernel.py) |[Link](https://github.com/j20232/moco_image_pipeline/tree/master/config/bengaliai-cv19)|
e.g.
```py
python train.py bengaliai-cv19 0000
```
### Submission at Kaggle Kernel
To load pipeline in Kaggle kernel, you can use this module as follows.
[kernel_sample.py](https://github.com/j20232/moco_image_pipeline/blob/master/kernel_sample.py)
```py
from mcp import Kernel
from pathlib import Path
if __name__ == "__main__":
# Please change here
competition_name = "bengaliai-cv19"
index = "0001"
input_path = Path(".").resolve() / "input"
model_weight_path = Path(".").resolve() / "models" / competition_name / index / f"{index}.pth"
config_path = Path(".").resolve() / "config" / competition_name / f"{index}.yaml"
competition_yaml_path = Path(".").resolve() / "competition.yaml"
output_path = input_path / competition_name / "output"
kernel = Kernel(competition_name, input_path, config_path, competition_yaml_path,
model_weight_path, output_path)
kernel.predict()
```
---
## 📭 Others
- Port forwarding to GCP instances
```
gcloud compute ssh [instance_name] -- -N -f -L [local_port]:localhost:[remote_port]
```
- mlflow (local: `ip: 0.0.0.0`, `port: 8888`)
```
mlflow server -h [ip] -p [port]
```
- test
```
python setup.py test
```
## ➕ To Add Competitions
1. Create the competition class file at https://github.com/j20232/moco_image_pipeline/tree/master/competition
2. Add correspondence between the competition name and class to https://github.com/j20232/moco_image_pipeline/blob/master/competition.yaml
---
## 🐣 Tested Models
### Official Implementation
Reference: https://pytorch.org/docs/stable/torchvision/models.html
- `resnet18`, `resnet34`, `resnet50`, resnet101`, `resnet152`
- `resnext50_32x4d`, `resnext101_32x4d`
- `densenet121`, `densenet169`, `densenet201`, `densenet161`
- `mobilenet_v2`
- `shufflenet_v2_x0_5`, `shufflenet_v2_x1_0`, `shufflenet_v2_x1_5`, `shufflenet_v2_x2_0`
### pretrained-models
Reference: https://github.com/Cadene/pretrained-models.pytorch
- `resnext101_64x4d`
- `nasnetalarge`,
- `nasnetamobile`
- `dpn68`, `dpn68b`, `dpn92`, `dpn98`, `dpn131`, `dpn107`
- `xception`
- `senet154`, `se_resnet50`, `se_resnet101`, `se_resnet152`, `se_resnext50_32x4d`, `se_resnext101_32x4d`
- `pnasnet5large`
### pytorch-image-models
Reference: https://github.com/rwightman/pytorch-image-models
- `mnasnet_050`, `mnasnet_075`, `mnasnet_100`, `mnasnet_140`
- `semnasnet_050`, `semnasnet_075`, `semnasnet_100`, `semnasnet_140`
- `mnasnet_small`
- `mobilenetv2_100`
- `fbnetc_100`
- `spnasnet_100`
- `efficientnet_b0`, `efficientnet_b1`, `efficientnet_b2`, `efficientnet_b2a`
- `efficientnet_b3`, `efficientnet_b3a`, `efficientnet_b4`, `efficientnet_b5`
- `efficientnet_b6`, `efficientnet_b7`, `efficientnet_b8`
- `efficientnet_es`, `efficientnet_em`, `efficientnet_el`
- `efficientnet_cc_b0_4e`, `efficientnet_cc_b0_8e`, `efficientnet_cc_b1_8e`
- `mixnet_s`, `mixnet_m`, `mixnet_l`, `mixnet_xl`, `mixnet_xxl`
<file_sep>/mcp/functions/metrics.py
import torch
def accuracy(y, true_label):
pred_label = torch.argmax(y, dim=1)
return torch.tensor((pred_label == true_label).sum().item() / len(y))
<file_sep>/mcp/datasets/__init__.py
from .simple_dataset import SimpleDataset, SimpleDatasetNoCache
<file_sep>/pyproject.toml
[tool.poetry]
name = "kaggle"
version = "0.1.0"
description = ""
authors = ["mocobt <<EMAIL>>"]
[tool.poetry.dependencies]
python = "^3.7"
jupyter = "^1.0.0"
notebook = "^6.0.3"
matplotlib = "^3.1.3"
mlflow = "^1.6.0"
numba = "^0.48.0"
numpy = "^1.18.1"
opencv-python = "^4.2.0"
pandas = "^1.0.1"
pathlib = "^1.0.1"
Pillow = "6.2.0"
torch = "^1.4.0"
torchvision = "^0.5.0"
tqdm = "^4.42.1"
albumentations = "^0.4.3"
scipy = "^1.4.1"
scikit-learn = "^0.22.1"
PyYAML = "^5.3"
pyarrow = "^0.16.0"
pretrainedmodels = "^0.7.4"
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
<file_sep>/mcp/functions/__init__.py
from .metrics import accuracy
<file_sep>/train.py
import os
import sys
import argparse
import importlib
import warnings
from pathlib import Path
from mcp import utils
sys.path.append(os.path.join("./competition"))
def main():
# argparser
parser = argparse.ArgumentParser(description="Please set the index of the input config file")
parser.add_argument("competition", help="directory of config files")
parser.add_argument("index", help="the index of the input config file")
parser.add_argument('-w', '--show_warnings', action='store_false',
help="whether to show debug messages")
competition = parser.parse_args().competition
index = parser.parse_args().index
config_path = Path(".").resolve() / "config"
cfg = utils.read_yaml(config_path / competition / f"{index}.yaml")
competitions = utils.read_yaml(Path(".").resolve() / "competition.yaml")
# initialization
if parser.parse_args().show_warnings:
warnings.simplefilter("ignore")
utils.seed_everything(cfg["seed"])
# training
yml_competition_name = competitions[competition]
modulelib = importlib.import_module(yml_competition_name)
classifier = getattr(modulelib, yml_competition_name)(competition, index, cfg)
classifier.fit()
if __name__ == "__main__":
main()
<file_sep>/mcp/models/pretrained_cnn.py
from torch import nn
import torch.nn.functional as F
import os
import sys
DIR_NAME = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(DIR_NAME + "/local_cnn_finetune/"))
sys.path.append(os.path.join(DIR_NAME + "/local_timm/"))
import cnn_finetune
import timm
def dropout_replace(model):
for child_name, child in model.named_children():
if isinstance(child, nn.Dropout):
setattr(model, child_name, nn.Dropout(p=0.))
else:
dropout_replace(child)
def get_official_names():
return [
# torchvision
"resnet18", "resnet34", "resnet50", "resnet101", "resnet152",
"resnext50_32x4d", "resnext101_32x8d",
"densenet121", "densenet169", "densenet201", "densenet161",
"mobilenet_v2",
"shufflenet_v2_x0_5", "shufflenet_v2_x1_0",
]
def get_pretrained_names():
return [
"resnext101_64x4d",
"nasnetalarge",
"nasnetamobile",
"dpn68", "dpn68b", "dpn92", "dpn98", "dpn131", "dpn107",
"xception",
"senet154", "se_resnet50", "se_resnet101", "se_resnet152", "se_resnext50_32x4d", "se_resnext101_32x4d", "pnasnet5large",
]
def get_timm_names():
return [
"mnasnet_050", "mnasnet_075", "mnasnet_100", "mnasnet_140",
"semnasnet_050", "semnasnet_075", "semnasnet_100", "semnasnet_140",
"mnasnet_small",
"mobilenetv2_100",
"fbnetc_100",
"spnasnet_100",
"efficientnet_b0",
"efficientnet_b1",
"efficientnet_b2", "efficientnet_b2a",
"efficientnet_b3", "efficientnet_b3a",
"efficientnet_b4", "efficientnet_b5", "efficientnet_b6", "efficientnet_b7", "efficientnet_b8",
"efficientnet_es", "efficientnet_em", "efficientnet_el",
"efficientnet_cc_b0_4e", "efficientnet_cc_b0_8e", "efficientnet_cc_b1_8e",
"mixnet_s", "mixnet_m", "mixnet_l", "mixnet_xl", "mixnet_xxl"
]
class PretrainedCNN(nn.Module):
def __init__(self, model_name,
in_channels=3, out_dim=10, hdim=512,
use_dropout=True, activation=F.leaky_relu,
use_bn=True, pretrained=False, kernel_size=3, stride=1, padding=1):
super(PretrainedCNN, self).__init__()
print("Architecture: ", model_name)
is_remote = os.getcwd() != "/kaggle/working"
if model_name in get_official_names() or model_name in get_pretrained_names():
self.base_model = cnn_finetune.make_model(model_name, num_classes=out_dim,
pretrained=is_remote and pretrained)
elif model_name in get_timm_names():
self.base_model = timm.create_model(model_name, num_classes=out_dim,
pretrained=is_remote and pretrained)
else:
print("Not supported architecture")
assert False
if not use_dropout:
dropout_replace(self.base_model)
self.conv0 = nn.Conv2d(in_channels, 3,
kernel_size=kernel_size, stride=stride, padding=padding,
bias=True)
def forward(self, x):
return self.base_model(self.conv0(x))
|
98f4e4ef15f69d24075294ba76af1714a1d15f27
|
[
"Markdown",
"TOML",
"Python",
"Text"
] | 34 |
Python
|
j20232/moco_image_pipeline
|
997ae76e795548e75f95e862284c1fc0a3c7541a
|
0d7ac0f154dcf26fbdfaf67556b722edb3b70eba
|
refs/heads/master
|
<file_sep># python3
# -*- coding: utf-8 -*-
# @Author : lina
# @Time : 2018/5/13 11:40
import fp_growth_py3 as fpg
from csv import reader
import pandas as pd
import csv
import pandas as pd
import num as nu
import numpy as np
dataset = list(reader(open('/Users/apple/PycharmProjects/Apriori/python3-fp-growth-master/student_id.csv')))
# 数据集
'''
dataset = [
['啤酒', '牛奶', '可乐'],
['尿不湿', '啤酒', '牛奶', '橙汁'],
['啤酒', '尿不湿'],
['啤酒', '可乐', '尿不湿'],
['啤酒', '牛奶', '可乐']
]
'''
if __name__ == '__main__':
'''
调用find_frequent_itemsets()生成频繁项
@:param minimum_support表示设置的最小支持度,即若支持度大于等于minimum_support,保存此频繁项,否则删除
@:param include_support表示返回结果是否包含支持度,若include_support=True,返回结果中包含itemset和support,否则只返回itemset
'''
#print(nu.get_num(1,'/Users/apple/PycharmProjects/Apriori/python3-fp-growth-master/dataset/3-25.csv'))
#print(nu.get_num(0,'/Users/apple/PycharmProjects/Apriori/python3-fp-growth-master/dataset/3-22.csv'))
frequent_itemsets = fpg.find_frequent_itemsets(dataset, minimum_support=2,include_support=True)
#print(type(frequent_itemsets)) # print type
result = []
for itemset, support in frequent_itemsets: # 将generator结果存入list
result.append((itemset, support))
result = sorted(result, key=lambda support: support[0]) # 排序后输出
print(result)
f = open('频繁项集.csv', 'w', encoding='utf-8')
csv_writer = csv.writer(f)
csv_writer.writerow(["频繁项集", "支持度"])
for itemset, support in result:
csv_writer.writerow([itemset, support])
#print(str(itemset) + ',' + str(support))
<file_sep>'''import pandas as pd
from pandas.tseries.offsets import Second
import time
df = pd.read_csv('/Users/apple/PycharmProjects/Apriori/python3-fp-growth-master/课程出勤详情.csv',encoding = 'UTF-8')
df = df.dropna(subset = ['face_area'])
df = df.dropna(subset = ['auto_signed_time'])
df.groupby(['auto_signed_time'])
df = df.sort_values(by = "auto_signed_time" , ascending = True)
df.reset_index(drop = True ,inplace = True)
df = df.set_index('auto_signed_time')
#print(df['2019-03-14 08:00:16':'2019-03-14 09:00:15'][['student_id','attention','face_area','real_name','gender']])
df['auto_signed_time'] = pd.to_datetime(df['auto_signed_time'],format = '%Y-%m-%d %H:%M:%S')
frequency = 1800
time_range = pd.date_range(df['auto_signed_time'][0],df['auto_signed_time'][df.shape[0]-1]+frequency*Second(),freq = '%sS'%frequency)
df = df.set_index('auto_signed_time')
for i in range(0,len(time_range) - 1):
print(df.loc[time_range[i]:time_range[i+1]-1*Second()]['student_id'])
'''
import pandas as pd
from pandas.tseries.offsets import Second
df = pd.read_csv('/Users/apple/PycharmProjects/Apriori/python3-fp-growth-master/课程出勤详情.csv',encoding = 'UTF-8')
df = df.dropna(subset = ['face_area'])
df = df.dropna(subset = ['auto_signed_time'])
df = df.dropna(subset=['student_id'])
df.groupby(['auto_signed_time'])
df = df.sort_values(by = "auto_signed_time" , ascending = True)
df.reset_index(drop = True ,inplace = True)
df['auto_signed_time'] = pd.to_datetime(df['auto_signed_time'] , format = '%Y-%m-%d %H:%M:%S')
frequency = 300
time_range = pd.date_range(df['auto_signed_time'][0],
df['auto_signed_time'][df.shape[0]-1]+frequency*Second(),freq = '%sS'%frequency)
df = df.set_index('auto_signed_time')
for i in range(0,len(time_range) - 1):
Series = df.loc[time_range[i]:time_range[i+1]-1*Second()]['student_id']
<file_sep>import csv
import pandas as pd
def get_num(n,path):
with open(path, 'r') as csvfile:
reader = csv.reader(csvfile)
column1 = [row[n] for row in reader]
# list()方法是把字符串str或元组转成数组
List1 = list(set(column1))
print(len(List1) - 1)
<file_sep>import pandas as pd
df = pd.read_csv('/Users/apple/PycharmProjects/Apriori/python3-fp-growth-master/顺序数据集.csv', header=None)
print(df.max)
<file_sep>import os
import codecs
def convert(file_name,file, in_code="GB2312", out_code="UTF-8"):
"""
该程序用于将目录下的文件从指定格式转换到指定格式,默认的是GBK转到UTF-8
:param file: 文件路径
:param in_code: 输入文件格式
:param out_code: 输出文件格式
:return:
"""
out_path='输出文件路径'
try:
with codecs.open(file_name, 'r', in_code) as f_in:
new_content = f_in.read()
f_out = codecs.open(os.path.join(out_path,file), 'w', out_code)
f_out.write(new_content)
f_out.close
except IOError as err:
print("I/O error: {0}".format(err))
if __name__ == '__main__':
convert('课程出勤详情.csv','/Users/apple/PycharmProjects/Apriori/python3-fp-growth-master/课程出勤详情.csv')<file_sep>import chardet
#解析文件编码格式
def code(self,path):
f = open(path, 'rb')
f_read = f.read()
f_charInfo = chardet.detect(f_read)
print(f_charInfo)
return f_charInfo
if __name__ == '__main__':
code(self='1',path='/Users/apple/PycharmProjects/Apriori/python3-fp-growth-master/课程出勤详情.csv')<file_sep># python3-fp-growth
fp-growth算法是一个生成频繁项集的算法,其主要利用了FP树的数据结构,整个生成过程只需要遍历数据集2次。
# 文件说明
fp_growth_py3.py是功能代码函数文件;
test.py是测试文件,可以直接运行,调用功能;
# 使用说明
直接将fp_growth_py3.py作为代码文件放入源文件下,调用其中的功能;
|
ad49ea628135e786c265ce8cd29ae98a28c85dd2
|
[
"Markdown",
"Python"
] | 7 |
Python
|
sayspeak/social-relationship
|
fdcfcf7f8e72441ca6a6f511b739c6c161545e1a
|
057dea0e4ce25e128671551999be07a007d52d58
|
refs/heads/master
|
<repo_name>LenMark512/Python-Study<file_sep>/if_nest.py
print "Start"
x = 0
y = 0
if x == 0:
print "x is 0"
if y == 0:
print "y is 0"
if y != 0:
print "y is not 0"
if x == 1:
print "should not come here"
if y == 0:
print "should not come here neither"
print "End"<file_sep>/list01.py
plist = ["Daisuke", "Tamaki", 5, 12, "Male"]
print "Name: " + plist[0] + plist[1]
print "Birth: " + str(plist[2]) + "/" + str(plist[3])
print "Sex: " + plist[4]<file_sep>/connect_strlit.py
print "Hi!", "I'm Daisuke"<file_sep>/varSubstitute.py
#coding: UTF-8
pref1 = u"東京"
pref2 = pref1
print pref1, pref2 # 東京 東京
pref1 = u"大阪"
# pref2 is referencing object "東京"
print pref1, pref2 # 大阪 東京
list1 = [1,2]
list2 = list1
list1.append(3)
# both list1 and list2 are referencing the same list object
print list1
print list2<file_sep>/rawStr.py
print "C:\My Document\node\track\test.txt"
print r"C:\My Document\node\track\test.txt"
# used back slash just for testing<file_sep>/tripleQuote.py
print """Triple quotation?
This is pretty convenient...
That's it. Bye."""<file_sep>/if_1.py
remainder = 10 % 3
if remainder != 0:
print "indivisible!"
print "The remainder is ", str(remainder)
# okay this is very simple syntax...<file_sep>/listSlice.py
list = ["A", "B", "C", "D", "E"]
print "target list is: ", list
print "[1:2] ", list[1:2] #["B", "C"]
print "[1:-1] ", list[1:-1] #["B", "C", "D"]
print "[1:] ", list[1:] #["B", "C", "D", "E"]
print "[:] ", list[:] #["A", "B", "C", "D", "E"]<file_sep>/README.md
# Python-Study
Need to study python for AI!
<file_sep>/printNum.py
print 10
print 3.14e8
print 1.27e-3
print 075 #octal
print 0x4F #hexadecimal
print 3+4j # imaginary<file_sep>/substitution.py
name = "Daisuke"
age = 31
print "name: " + name
print "age: " + str(age)<file_sep>/calc.py
print "10 + 4 = ", 10 + 4
print "10 + 4.0 = ", 10 + 4.0
print "10 / 3 = ", 10 / 3
print "10 / 3.0 = ", 10 / 3.0 # if one is float, answer also float
print "10.0 / 3 = ", 10.0 / 3
print "17 / 5 = ", 17 / 5
print "-17 / 5 = ", -17 / 5 # answer would not exceed quotient
print "10.0 // 3 = ", 10.0 // 3 # this would cut off the decimal point
print "10 % 3 = ", 10 % 3
print "5 ** 3 = ", 5 ** 3 # exponential<file_sep>/intConvert.py
# use single quotation to avoid using escape sequence.
print 'int("14") = ', int("14")
print 'int("14", 10) = ', int("14", 10)
print 'int("14", 8) = ', int("14", 8)
print 'int("14", 16) = ', int("14", 16)
print 'int("3F", 16) = ', int("3F", 16)
print 'int(14) = ', int(14)
print 'int(16.8) = ', int(16.8)
print 'int(-7.2) = ', int(-7.2)<file_sep>/substitution2.py
identifier = "Daisuke"
print "identifier: " + identifier
identifier = "Tamaki"
print "identifier: " + identifier
identifier = 1234
print "identifier: " + str(identifier)
|
cf7fbc4d6ed789865c9efa1f5bbc86b38bf44dd2
|
[
"Markdown",
"Python"
] | 14 |
Python
|
LenMark512/Python-Study
|
9917298f0f6a67673c3a7cce0f7369f0436acda0
|
0e3ee9ec460fa556ff82e7f96f9d8b16e0cbedf5
|
refs/heads/master
|
<file_sep>package Models;
/**
* Created by thanh on 5/9/2016.
*/
public class Photo {
private String path;
private String name;
private String mime;
private String date;
public Photo() {
}
public Photo(String path, String name, String mime, String date) {
this.path = path;
this.name = name;
this.mime = mime;
this.date = date;
}
public String getPath() {
return path;
}
public String getName() {
return name;
}
public String getMime() {
return mime;
}
public String getDate() {
return date;
}
public void setPath(String path) {
this.path = path;
}
public void setName(String name) {
this.name = name;
}
public void setMime(String mime) {
this.mime = mime;
}
public void setDate(String date) {
this.date = date;
}
}
<file_sep>package Models;
/**
* Created by thanh on 5/9/2016.
*/
public class SMS {
private String phoneNuber;
private String type;
private String date;
private String body;
public SMS() {
}
public SMS(String phoneNuber, String type, String date, String body) {
this.phoneNuber = phoneNuber;
this.type = type;
this.date = date;
this.body = body;
}
public String getPhoneNuber() {
return phoneNuber;
}
public String getType() {
return type;
}
public String getDate() {
return date;
}
public String getBody() {
return body;
}
public void setPhoneNuber(String phoneNuber) {
this.phoneNuber = phoneNuber;
}
public void setType(String type) {
this.type = type;
}
public void setDate(String date) {
this.date = date;
}
public void setBody(String body) {
this.body = body;
}
}
<file_sep>package Models;
/**
* Created by thanh on 5/9/2016.
*/
public class GPS {
private Double latitude;
private Double longtitude;
public GPS() {
}
public GPS(Double latitude, Double longtitude) {
this.latitude = latitude;
this.longtitude = longtitude;
}
public Double getLatitude() {
return latitude;
}
public Double getLongtitude() {
return longtitude;
}
public void setLongtitude(Double longtitude) {
this.longtitude = longtitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
}
|
540af720f7991af898fd3cdf1b05bbe1d9748c8f
|
[
"Java"
] | 3 |
Java
|
lehailinh/mobileMonitoring
|
76505df760f4b7b8072b49a12a0f3565dc689c75
|
54b78aa00b174822ac37561a011eeca474016c5b
|
refs/heads/main
|
<repo_name>joelapsansky/red-team<file_sep>/app/templates/static/js/charts.js
function init() {
// Grab a reference to the dropdown select element
var selector = d3.select("#selDataset");
// Use the list of sample names to populate the select options
d3.csv("https://raw.githubusercontent.com/joelapsansky/red-team/main/Excel%20%26%20CSV/reshaped_full_cleaned_dataset.csv", function(data) {
var stats = Object.keys(data[0]).splice(1,22)
stats.forEach((stat) => {
selector
.append("option")
.text(stat)
.property("value", stat);
});
// Use the first sample from the list to build the initial plots
var firststat = "SG_approach_green_AVERAGE";
buildCharts(firststat);
});
};
// Initialize the dashboard
init();
function optionChanged(newSample) {
// Fetch new data each time a new sample is selected
// buildMetadata(newSample);
buildCharts(newSample);
};
// Create the buildChart function
function buildCharts(golfstat) {
// Use d3.json to load the samples.json file
d3.csv("https://raw.githubusercontent.com/joelapsansky/red-team/main/Excel%20%26%20CSV/reshaped_full_cleaned_dataset.csv", function(data) {
console.log(data);
// Filter 5 years
var data2017 = data.filter(golfdata => golfdata["Year"]==2017)
var data2018 = data.filter(golfdata => golfdata["Year"]==2018)
var data2019 = data.filter(golfdata => golfdata["Year"]==2019)
var data2020 = data.filter(golfdata => golfdata["Year"]==2020)
var data2021 = data.filter(golfdata => golfdata["Year"]==2021)
// New x, y, and player name variables for trace
var yvalues2017 = data2017.map(golfdata => golfdata["money_MONEY"])
var xvalues2017 = data2017.map(golfdata => golfdata[golfstat])
var playername2017 = data2017.map(golfdata => golfdata["PLAYER NAME"])
var yvalues2018 = data2018.map(golfdata => golfdata["money_MONEY"])
var xvalues2018 = data2018.map(golfdata => golfdata[golfstat])
var playername2018 = data2018.map(golfdata => golfdata["PLAYER NAME"])
var yvalues2019 = data2019.map(golfdata => golfdata["money_MONEY"])
var xvalues2019 = data2019.map(golfdata => golfdata[golfstat])
var playername2019 = data2019.map(golfdata => golfdata["PLAYER NAME"])
var yvalues2020 = data2020.map(golfdata => golfdata["money_MONEY"])
var xvalues2020 = data2020.map(golfdata => golfdata[golfstat])
var playername2020 = data2020.map(golfdata => golfdata["PLAYER NAME"])
var yvalues2021 = data2021.map(golfdata => golfdata["money_MONEY"])
var xvalues2021 = data2021.map(golfdata => golfdata[golfstat])
var playername2021 = data2021.map(golfdata => golfdata["PLAYER NAME"])
// Make 5 traces (one for each year)
var trace2021 = {
x: xvalues2021,
y: yvalues2021,
mode: 'markers',
type: 'scatter',
text: playername2021,
name: "2021"
};
var trace2020 = {
x: xvalues2020,
y: yvalues2020,
mode: 'markers',
type: 'scatter',
text: playername2020,
name: "2020"
};
var trace2019 = {
x: xvalues2019,
y: yvalues2019,
mode: 'markers',
type: 'scatter',
text: playername2019,
name: "2019"
};
var trace2018 = {
x: xvalues2018,
y: yvalues2018,
mode: 'markers',
type: 'scatter',
text: playername2018,
name: "2018"
};
var trace2017 = {
x: xvalues2017,
y: yvalues2017,
mode: 'markers',
type: 'scatter',
text: playername2017,
name: "2017"
};
// Define legend (and filters) for scatter plot
var scatterData = [trace2021, trace2020, trace2019, trace2018, trace2017];
// Define layout
var layout = {
xaxis: {title: golfstat},
yaxis: {title: "Annual Winnings (millions $)"},
title:'Relationship between Performance Stat and Winnings',
legend: {
y: 0.5,
yref: 'paper',
font: {
family: 'Arial, sans-serif',
size: 20,
color: 'grey',
}
}
};
// Use Plotly to plot the data with the layout
Plotly.newPlot("scatter",scatterData, layout);
});
};<file_sep>/README.md
# Golf Performance Statistics
##  <ins>`Let's dive into the storyboard`</ins>
##### https://docs.google.com/presentation/d/1Y2zdGDBPXmdN_HR1W3VoXMS89-FKNL99FMIY0WZH-mQ/edit?usp=sharing
<img src=https://github.com/joelapsansky/red-team/blob/database_app/app/templates/static/images/StoryBoard_Image.png width="400" height="200">
###  <ins>`Selected topic`</ins>
Key reasons for topic selection:
* The analysts identified a key interest among worldwide sports fans in sports analytics
* Analysts used PGA data because of friendly use terms and a wide-array of available statistics to analyze
Data Source:
* www.PGATour.com/stats
Question to answer:
* Which specific performance statistics collected on professional golfers contribute most to overall winnings since the start of 2017?
Audience:
* PRIMARY: Fans/anyone trying to forecast
* SECONDARY: Media and news outlets
* OTHER: Player support groups (e.g. caddies, coaches, etc.) with specific interests in players' successes
###  <ins>`Communication protocols utilized for successful teamwork`</ins>
The analysts solely relied upon the below sources in order to provide a means of reliable and successful communication, video meetings, and screen sharing. Meetings convened at least two times a week along with check-ins, and resource sharing.
* Slack
* Zoom
## Approach and Technologies Used
###  <ins>`1. Data Cleaning and Analysis`</ins>
Data scrape revision: [scrape_golf_data_rewrite](/Scrape%20&%20Clean/scrape_golf_data_rewrite.ipynb)
* This project utilizes Pandas to scrape and clean the data
* Use of the "to_csv" function was adopted to send our cleaned dataset to a CSV for everyone to use
###  <ins>`2. Database Storage`</ins>
* The Red Team created a database in AWS and added the cleaned dataset to an S3 bucket. From there, the team wrote the data to Postgres using PySpark. The data is displayed on GitHub pages.
###  <ins>`3. Machine Learning`</ins>
* Considered 3 supervised learning regression models
1. PRIMARY: Elastic Net Regression
2. SECONDARY: Random Forest Regression
3. OTHER: Linear Regression
* Red Team analysts also used an unsupervised learning model to visualize data in clusters
###  <ins>`4. Website and Dashboard`</ins>
The Red Team used JS and html files in conjunction with GitHub pages for the presentation. Here is a sneak peek (screenshots taken at time of presentation, but have been revised on the actual site):
<img src=https://github.com/joelapsansky/red-team/blob/database_app/app/templates/static/images/Website_Clip1.png width="300" height="200">
<img src=https://github.com/joelapsansky/red-team/blob/database_app/app/templates/static/images/Website_Clip2.png width="300" height="200">
<img src=https://github.com/joelapsansky/red-team/blob/database_app/app/templates/static/images/Website_Clip3.png width="300" height="200">
## Summary and Results
###  <ins>`Summary`</ins>
* The Red Team leveraged 22 performance statistics from 2017-2021 and multiple machine learning models to conduct extensive quantitative analyses, the goal of which was to identify the key performance statistics that help predict a PGA Tour golfer's annual winnings
* Winnings are the ultimate measure of success for a professional golfer. Given that purses (the winnings offered by each tournament) increase with the profile of the tournament and the corresponding level of competition, it is a reasonable assumption that the best golfers will earn the highest winnings
* The Red Team analysts tried running all 3 aforementioned machine learning models without the highly correlated independent variables, but the R2 score did not improve (<70%)
* The elastic net model is the primary model because it did not require the team to trim unneeded features ahead of time
1. The team used the results from the elastic net in the linear and random forest regression models, but since the ensuing results did not improve, the Red Team published all 3 models using all identified features
2. The GitHub page incorporates charts from the elastic net machine learning Jupyter notebook so this is considered the primary model
###  <ins>`Key Findings and Results`</ins>
* The average PGA Tour golfer earned approximately $2 million between 2017 and 2021, although more than half of the golfers earned less than $1.55 million per year
* The Strokes Gained statistics were clearly the highest performers, and the Strokes Gained - Approach to the Green rose above the rest
###  <ins>`GitHub Page`</ins>
GitHub page at time of presentation 5/26/2021: https://ckyle121.github.io/golf_website/
FINAL revised GitHub page deployed 5/28/2021: https://joelapsansky.github.io/golf-stats-page/
##### Thank you for your time and consideration to Red Team's Project.
<img src=https://github.com/joelapsansky/red-team/blob/database_app/app/templates/static/images/Golf_Course.png width="550" height="200">
|
afe9afe95fe0b82ed2c54dca47c9e6ae9e43f463
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
joelapsansky/red-team
|
f16382531f05ce8c28e8caadf490cd40162a4734
|
a6e639a4e0a66b55f9419a3db3dd3d0ee8dab14a
|
refs/heads/master
|
<repo_name>NenaRachelle/Hangman<file_sep>/index.php
<html>
<head>
<body>
<h1>Galgje</h1>
</body>
</head>
<body>
<style>
h1,p {
text-align: center;
font-family: verdana;
}
body {
background-color: lightblue;
}
</style>
<button onclick="myFunction()".alfabet; </button>
<script>
//function myFunction() {
//alert("FOUT! Je hebt nog maar 9 levens over!");
}
</script>
</body>
</html>
<?php
session_start();
?>
<html>
<head>
<style type="text/css">
fieldset
{
width: 25%;
}
</style>
<title></title>
</head>
<body>
<?php
if ( !isset($_SESSION['word']) )
{
$aWords = array(
'cake',
'school',
'fruit'
);
$_SESSION['word'] = strtolower($aWords[array_rand($aWords)]);
$_SESSION['guesses'] = array();
$_SESSION['lives'] = 10;
}
if ( isset($_POST['guess']) )
{
$_POST['guess'] = strtolower($_POST['guess']);
if ( in_array($_POST['guess'], range('a', 'z')) )
{
if ( !in_array($_POST['guess'], $_SESSION['guesses']) )
{
if ( strpos($_SESSION['word'], $_POST['guess']) === FALSE )
{
--$_SESSION['lives'];
}
$_SESSION['guesses'][] = $_POST['guess'];
}
}
}
if ( $_SESSION['lives'] == 0 )
{
echo ' <p>The word was "' . $_SESSION['word'] . '"</p>' . "\n\n";
echo ' <p><a href="hangman.php">Unlucky, new game?</a></p>';
unset($_SESSION['word']);
}
else
{
$iLeft = 0;
$sShow = '';
for($i = 0; $i < strlen($_SESSION['word']); ++$i)
{
if ( in_array($_SESSION['word'][$i], $_SESSION['guesses']) )
{
$sShow .= $_SESSION['word'][$i];
}
else
{
$sShow .= '_';
++$iLeft;
}
$sShow .= ' ';
}
$sShow = trim($sShow);
echo ' <p>' . $sShow . '</p>' . "\n";
echo ' <p>' . $_SESSION['lives'] . ' live(s) left</p>';
if ( $iLeft == 0 )
{
echo "\n\n" . ' <p><a href="hangman.php">Congratulations, new game?</a></p>';
unset($_SESSION['word']);
}
}
?>
<form method="post" action="hangman.php">
<fieldset>
<legend>Make a Guess</legend>
<table>
<tr>
<td><label for="guess">Letter</label></td>
<td><select name="guess" id="guess">
<?php
foreach(range('A', 'Z') as $cLetter)
{
echo '<option value="' . strtolower($cLetter) . '">' . $cLetter . '</option>';
}
?>
</select></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" id="submit" value=
"Guess!" /></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
|
28bb0dd6e2aec50934fee1e88fe53935912d5132
|
[
"PHP"
] | 1 |
PHP
|
NenaRachelle/Hangman
|
d6fa3453f39320f4d3ac564ccbee26402a089312
|
65227b2ea8357678b5a9502df4118057ad524863
|
refs/heads/master
|
<repo_name>Raieen/BroadcastMessageDemo<file_sep>/app/src/main/java/xyz/raieen/broadcastmessagedemo/MessageView.java
package xyz.raieen.broadcastmessagedemo;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.Date;
public class MessageView extends LinearLayout {
private String message;
private long sent;
public MessageView(Context context) {
super(context);
init(context);
}
public MessageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MessageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
public MessageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
public void init(Context context) {
// Inflate
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.layout_message, this, true);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
TextView textMessage = findViewById(R.id.text_message);
textMessage.setText(message);
}
public long getSent() {
return sent;
}
public void setSent(long sent) {
this.sent = sent;
TextView textTimestamp = findViewById(R.id.text_timestamp);
textTimestamp.setText(new Date(sent).toString());
}
}
<file_sep>/README.md
# Broadcast Message Demo
Really simple one-way message demo for sending messages using Firestore.
### Images
Choosing Sender/Receiver View
<img src="https://github.com/Raieen/BroadcastMessageDemo/blob/master/images/mode.png" height="400">
Sending a message as the sender (Alice) to the user (Bob)
<img src="https://github.com/Raieen/BroadcastMessageDemo/blob/master/images/message_sender.png" height="400">
Receiving a message from the sender (Alice) as the user (Bob)
<img src="https://github.com/Raieen/BroadcastMessageDemo/blob/master/images/message_receiver.png" height="400">
<file_sep>/app/src/main/java/xyz/raieen/broadcastmessagedemo/MainActivity.java
package xyz.raieen.broadcastmessagedemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import com.google.firebase.firestore.FirebaseFirestore;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Buttons
Button sender = findViewById(R.id.button_sender);
Button receiver = findViewById(R.id.button_reciever);
// Listeners to start sender/receiver activities
sender.setOnClickListener(v -> {
Intent intent = new Intent(this, SenderActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
startActivity(intent);
finish(); // Close activity
});
receiver.setOnClickListener(v -> {
Intent intent = new Intent(this, ReceiverActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
startActivity(intent);
finish(); // Close activity
});
}
}
|
72511b2b6f5483e1b368ba451798931bc4aaeaa4
|
[
"Markdown",
"Java"
] | 3 |
Java
|
Raieen/BroadcastMessageDemo
|
55d41ca199a76c1e5f0b9589cd013f8b6a2fbae3
|
33b5ecdec9d74c72554e7c15e7adf417d03795fc
|
refs/heads/main
|
<repo_name>FinnyEby/Course-6-Project-Scribbler<file_sep>/scripts/post.js
/*function to add a comment*/
function addComment(commenttextarea) {
if(commenttextarea.value.length > 0) {
document.getElementById("comment-section").style.visibility = "visible";
var comment = commenttextarea.value;
document.getElementById('comment-section').innerHTML = '<p class="comment">'+comment+'</p>'+document.getElementById('comment-section').innerHTML;
document.getElementById('commenttextarea').value = "";
}
}
/*function to implement like feature*/
var likeCounter = 0;
function liked() {
document.getElementById('likebutton').innerHTML = '<i class="fa fa-thumbs-up" aria-hidden="true"></i> Liked';
likeCounter++;
if(likeCounter === 1) {
document.getElementById('likecounter').innerHTML = '<p>'+likeCounter+' person likes this!</p>';
} else {
document.getElementById('likecounter').innerHTML = '<p>'+likeCounter+' people liked this!</p>';
}
}
/*function to enable edit mode*/
/*0 - view mode / 1 - edit mode*/
var mode = 0;
/* variables to check if the title and content are editted */
/* when values are set to 1 the updated tag is not added*/
var titleUpdated = 0;
var contentUpdated = 0;
/*variables to check if content was updated*/
var title;
var content;
function enableEditableMode() {
if(mode == 0) {
title = document.getElementById("contentTitle").innerHTML;
content = document.getElementById("content").innerHTML;
mode = 1;
document.getElementById("contentTitle").style.border = '5px solid pink';
document.getElementById("content").style.border = '5px solid pink';
document.getElementById("contentTitle").contentEditable = true;
document.getElementById("content").contentEditable = true;
document.getElementById('editButton').innerHTML = 'Save <i class="fa fa-floppy-o" aria-hidden="true"></i>';
} else {
mode = 0;
document.getElementById("contentTitle").style.border = 'none';
document.getElementById("content").style.border = 'none';
document.getElementById("contentTitle").contentEditable = false;
document.getElementById("content").contentEditable = false;
document.getElementById('editButton').innerHTML = 'Edit <i class="fa fa-pencil-square-o" aria-hidden="true"></i>';
titleAfterEdit = document.getElementById("contentTitle").innerHTML;
contentAfterEdit = document.getElementById("content").innerHTML;
if(title != titleAfterEdit && titleUpdated == 0) {
document.getElementById("contentTitle").innerHTML = 'UPDATED: '+titleAfterEdit;
titleUpdated = 1;
}
if(content != contentAfterEdit && contentUpdated == 0) {
document.getElementById("content").innerHTML = '<p>UPDATED:</p>'+contentAfterEdit;
contentUpdated = 1;
}
}
}<file_sep>/scripts/index.js
/*function to redirect to next page*/
function goToPostListsPage() {
location.href='html/postslist.html';
}
|
0229c698b466ef0ae605ea0141964e82748a7ec2
|
[
"JavaScript"
] | 2 |
JavaScript
|
FinnyEby/Course-6-Project-Scribbler
|
a107a9c437568f6ea5840e12cf5773857df46aaa
|
9c9fde32472c971567e387e0361ce32e3afc38f8
|
refs/heads/master
|
<repo_name>401-advanced-javascript-bp/lab-27<file_sep>/src/__tests__/components/footer/footer.test.js
import React from 'react';
import Footer from '../../../components/footer/footer';
describe("<Footer/>", () => {
test('basis rendering', () => {
const mountedFooter = shallow(<Footer/>);
expect(mountedFooter.find('footer')).toBeTruthy();
});
});<file_sep>/src/__tests__/components/header/header.test.js
import React from 'react';
import Header from '../../../components/header/header';
describe("<Header/>", () => {
test('basis rendering', () => {
const mountedHeader = shallow(<Header/>);
expect(mountedHeader.find('h1')).toBeTruthy();
});
});<file_sep>/src/__tests__/components/counter/counter.test.js
import React from 'react';
import Counter from '../../../components/counter/counter';
import renderer from 'react-test-renderer';
describe("<Counter/>", () => {
test('basis rendering', () => {
const mountedCounter = shallow(<Counter/>);
expect(mountedCounter.find('a')).toBeTruthy();
});
test('testing state changes', () => {
const mountedCounter = mount(<Counter/>);
const link = mountedCounter.find('a').first();
const secondLink = mountedCounter.find('a').last();
link.simulate('click');
expect(mountedCounter.state('count')).toBe(-1);
secondLink.simulate('click');
expect(mountedCounter.state('count')).toBe(0);
expect(mountedCounter.find('a').first().text()).toContain('-');
});
test('testing that the state is being transferred to the DOM', () => {
const mountedCounter = mount(<Counter/>);
expect(mountedCounter.find('span').text()).toContain('0');
});
xtest('rendering follows the snapshot', () => {
const snapshot = renderer.create(<Counter/>).toJSON();
expect(snapshot).toMatchSnapshot();
});
});
|
63a87a5a3efb945c43ed66ccbbc059a5b486442f
|
[
"JavaScript"
] | 3 |
JavaScript
|
401-advanced-javascript-bp/lab-27
|
ac6e9374c5765b67b06d5bbab0fb93693284e87f
|
9f7d276b50e1fbc457adb69308c9734126e0ceac
|
refs/heads/master
|
<file_sep># iwg-library
IWayGroup test task
note: при проблемах с автозагрузкой выполнить
`
$ composer dumpautoload -o
`
<file_sep><?php
/**
* Created by PhpStorm.
* User: andrey
* Date: 09.10.16
* Time: 14:51
*/
namespace Test\Model;
use IWG\Model\Book;
use Test\Model\IWGModelTestCase;
use IWG\Model\Author;
use IWG\Model\Category;
use IWG\Model\CategoryInterface;
class BookTest extends IWGModelTestCase
{
private $authors = [
['name' => 'Ben', 'fname' => 'Franklin', 'year' => 1800],
['name' => 'Klifford', 'fname' => 'Simak', 'year' => 1920],
['name' => 'Anton', 'fname' => 'Chekhov', 'year' => 1870],
];
private $categories = [
['name' => 'fiction'],
['name' => 'drama'],
['name' => 'tech'],
];
private function makeAuthors()
{
array_walk($this->authors, function($author_data){
$author = new Author();
$author->setName($author_data['name']);
$author->setFName($author_data['fname']);
$author->setYearOfBirth($author_data['year']);
self::$entity_manager->persist($author);
});
}
private function makeCategories()
{
array_walk($this->categories, function($cat_data){
$category = new Category();
$category->setName($cat_data['name']);
self::$entity_manager->persist($category);
});
}
public function testSetupData()
{
$this->makeAuthors();
$this->makeCategories();
self::$entity_manager->flush();
$repo = self::$entity_manager->getRepository('IWG\\Model\\Category');
/** @var $categories CategoryInterface[] */
$categories = $repo->findAll();
$this->assertNotEmpty($categories);
$this->assertEquals(count($this->categories), count($categories), 'categories should be counted as ' . count($this->categories));
$repo = self::$entity_manager->getRepository('IWG\\Model\\Author');
/** @var $categories CategoryInterface[] */
$authors = $repo->findAll();
$this->assertNotEmpty($authors);
$this->assertEquals(count($this->authors), count($authors), 'authors should be counted as ' . count($this->authors));
}
public function testBookPersist()
{
$this->makeAuthors();
$this->makeCategories();
self::$entity_manager->flush();
$dql = 'SELECT c FROM IWG\\Model\\Category c WHERE c.name = :name';
$cat_fiction = self::$entity_manager->createQuery($dql)
->setParameter('name', 'fiction')
->getSingleResult();
$this->assertEquals('fiction', $cat_fiction->getName());
$dql = 'SELECT a FROM IWG\\Model\\Author a WHERE a.fName = :fname';
$author = self::$entity_manager->createQuery($dql)
->setParameter('fname', 'Simak')
->getSingleResult();
$this->assertEquals('Simak', $author->getFName());
$book = new Book();
$book->setName('Precious');
$book->setYearOfIssue(1950);
$book->assignAuthor($author);
$book->setCategory($cat_fiction);
self::$entity_manager->persist($book);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: andrey
* Date: 08.10.16
* Time: 0:53
*/
namespace Test\Model;
use IWG\Model\Category;
use IWG\Model\CategoryInterface;
use Test\Model\IWGModelTestCase;
class CategoryTest extends IWGModelTestCase
{
const CAT_NAME = 'fiction';
public function testCategoryPersist()
{
try {
$category = new Category();
$category->setName(self::CAT_NAME);
self::$entity_manager->persist($category);
self::$entity_manager->flush();
$this->entityReading();
} catch (\Exception $e) {
$this->fail($e->getMessage());
}
$this->assertTrue(true, "category created successfully");
}
/**
* @depends testCategoryPersist
*/
public function testCategoryReading()
{
$this->markTestSkipped("skipped");
$repo = self::$entity_manager->getRepository('IWG\\Model\\Category');
/** @var $categories CategoryInterface[] */
$categories = $repo->findAll();
$this->assertNotEmpty($categories);
$this->assertEquals(1, count($categories), 'categories should be counted as 1');
$this->assertEquals(self::CAT_NAME, $categories[0]->getName(), 'category name should be same as created');
}
private function entityReading()
{
$repo = self::$entity_manager->getRepository('IWG\\Model\\Category');
/** @var $categories CategoryInterface[] */
$categories = $repo->findAll();
$this->assertNotEmpty($categories);
$this->assertEquals(1, count($categories), 'categories should be counted as 1');
$this->assertEquals(self::CAT_NAME, $categories[0]->getName(), 'category name should be same as created');
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: andrey
* Date: 07.10.16
* Time: 22:31
*/
$loader = require __DIR__ . '/../vendor/autoload.php';
echo "autoload " . 'Test\\' . ' to ' . __DIR__ ;
$loader->add('Test\\', __DIR__ . '/');<file_sep><?php
/**
* Created by PhpStorm.
* User: andrey
* Date: 07.10.16
* Time: 22:40
*
* see http://www.jeremygiberson.com
* and http://stackoverflow.com/questions/39575292/phpunit-init-schema-with-doctrine-for-sqlite-in-memory
*/
namespace Test\Model;
use IWG\Model\Author;
use IWG\Model\AuthorInterface;
use Test\Model\IWGModelTestCase;
class AuthorTest extends IWGModelTestCase
{
public function testAuthorPersist()
{
try {
$author = new Author();
$author->setName('Ben');
$author->setFName('Franklin');
$author->setYearOfBirth(1800);
self::$entity_manager->persist($author);
self::$entity_manager->flush();
$this->authorReading();
} catch (\Exception $e) {
$this->fail($e->getMessage());
}
$this->assertTrue(true, "author created successfully");
}
/**
* @depends testAuthorPersist
*/
public function testAuthorReading()
{
$this->markTestSkipped("skipped");
$repo = self::$entity_manager->getRepository('IWG\\Model\\Author');
/** @var $authors AuthorInterface[] */
$authors = $repo->findAll();
$this->assertNotEmpty($authors);
$this->assertEquals(1, count($authors), 'authors should be counted as 1');
$this->assertEquals('Ben', $authors[0]->getName(), 'name should be same as created');
$this->assertEquals('Franklin', $authors[0]->getFName(), 'FName should be same as created');
$this->assertEquals(1800, $authors[0]->getYearOfBirth(), 'YOB should be same as created');
}
private function authorReading()
{
$repo = self::$entity_manager->getRepository('IWG\\Model\\Author');
/** @var $authors AuthorInterface[] */
$authors = $repo->findAll();
$this->assertNotEmpty($authors);
$this->assertEquals(1, count($authors), 'authors should be counted as 1');
$this->assertEquals('Ben', $authors[0]->getName(), 'name should be same as created');
$this->assertEquals('Franklin', $authors[0]->getFName(), 'FName should be same as created');
$this->assertEquals(1800, $authors[0]->getYearOfBirth(), 'YOB should be same as created');
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: andrey
* Date: 08.10.16
* Time: 0:55
*/
namespace Test\Model;
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\SchemaTool;
use PHPUnit_Extensions_Database_TestCase;
abstract class IWGModelTestCase extends PHPUnit_Extensions_Database_TestCase
{
/** @var EntityManager */
protected static $entity_manager;
/** @var \Doctrine\ORM\Tools\SchemaTool */
protected static $schema_tool;
private static function getEntityManager()
{
$isDevMode = true;
$config = Setup::createAnnotationMetadataConfiguration([__DIR__ . '/../../classes/Model'], $isDevMode);
return EntityManager::create(['driver' => 'pdo_sqlite', 'memory' => true], $config);
}
public static function setUpBeforeClass()
{
self::$entity_manager = self::getEntityManager();
self::$entity_manager->clear();
self::$schema_tool = new SchemaTool(self::$entity_manager);
self::$schema_tool->createSchema(self::$entity_manager->getMetadataFactory()->getAllMetadata());
}
public static function tearDownAfterClass()
{
self::$schema_tool->dropDatabase();
}
public function getConnection()
{
// get pdo
$pdo = self::$entity_manager->getConnection()->getWrappedConnection();
// create connection
return $this->createDefaultDBConnection($pdo, ':memory:');
}
protected function getDataSet()
{
return $this->createFlatXMLDataSet(__DIR__ . '/fixtures/default_data.xml');
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: andrey
* Date: 07.10.16
* Time: 22:17
*/
namespace Test\Misc;
use PHPUnit\Framework\TestCase;
class MiscTest extends TestCase
{
public function testPHPUnitWorks()
{
$this->assertTrue(true, 'PHPUnit works');
}
}
|
18651cb295cf6f91e8efd7d10f5ecf62d2d98254
|
[
"Markdown",
"PHP"
] | 7 |
Markdown
|
anddorua/iwg-library
|
5b9127645611b831fdb34100f6992b913ad12d03
|
37bf263ce480f9e3c126257533358fcea417a579
|
refs/heads/master
|
<repo_name>Tomcy-wcc/strategy_demo<file_sep>/src/main/java/com/ys/strategy/config/HandleApiContext.java
package com.ys.strategy.config;
import com.ys.strategy.api.ApiEnum;
import com.ys.strategy.service.ApiHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Description
* @auther wcc
* @create 2020-01-06 21:42
*/
@Component
public class HandleApiContext {
@Autowired
private ApplicationContext applicationContext;
public static Map<ApiEnum, Class<ApiHandle>> apiHandleStrategyBeanMap = new ConcurrentHashMap<>();
public ApiHandle getApiHandle(ApiEnum apiEnum) {
Class<ApiHandle> apiHandleClass = apiHandleStrategyBeanMap.get(apiEnum);
if (apiHandleClass == null)
throw new IllegalArgumentException("没有对应的Api处理器");
return applicationContext.getBean(apiHandleClass);
}
}
<file_sep>/src/main/java/com/ys/strategy/service/GS002ApiHandle.java
package com.ys.strategy.service;
import com.ys.strategy.annotation.HandleApiType;
import com.ys.strategy.api.ApiEnum;
import org.springframework.stereotype.Service;
/**
* @Description
* @auther wcc
* @create 2020-01-06 22:20
*/
@Service
@HandleApiType(ApiEnum.GS002)
class GS002ApiHandle implements ApiHandle {
@Override
public Object handle() {
return ApiEnum.GS002.getApiName();
}
}
<file_sep>/README.md
# strategy_demo
在spring boot使用自定义注解实现策略模式
<file_sep>/src/main/java/com/ys/strategy/api/ApiEnum.java
package com.ys.strategy.api;
/**
* @Description
* @auther wcc
* @create 2020-01-06 21:32
*/
public enum ApiEnum {
GS001("基础信息"),
GS002("风险分析"),
GS003("舆情分析"),
GS004("关联分析"),
;
String apiName;
ApiEnum(String apiName) {
this.apiName = apiName;
}
public String getApiName() {
return apiName;
}
}
<file_sep>/src/main/java/com/ys/strategy/config/HandleApiProcessor.java
package com.ys.strategy.config;
import com.ys.strategy.annotation.HandleApiType;
import com.ys.strategy.api.ApiEnum;
import com.ys.strategy.service.ApiHandle;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @Description
* @auther wcc
* @create 2020-01-06 21:49
*/
@Component
public class HandleApiProcessor implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(HandleApiType.class);
beansWithAnnotation.forEach((k, v) -> {
Class<ApiHandle> apiHandleClass = (Class<ApiHandle>) v.getClass();
ApiEnum value = apiHandleClass.getAnnotation(HandleApiType.class).value();
HandleApiContext.apiHandleStrategyBeanMap.put(value, apiHandleClass);
});
}
}
|
495c2291cdf47279cf6bbcf240baed336b9eae0d
|
[
"Markdown",
"Java"
] | 5 |
Java
|
Tomcy-wcc/strategy_demo
|
3ed85f80e9ee89b8ba68026fa29b10434b1de41e
|
b0929f07c1317d49ba9e17c5d8ec03b35c0f2719
|
refs/heads/master
|
<file_sep>using System;
namespace QA_test_Kryvosheina
{
class Program
{
static void Main(string[] args)
{
int i;
try
{
do
{
Console.Write("Меню:\n1) Решение задачи 1\n2) Решение задачи 2\n3) Решение задачи 3\n4) Выйти из программы\n\nВаш выбор: ");
i = int.Parse(Console.ReadLine());
switch (i)
{
case 1:
Algoritm1();
break;
case 2:
Algoritm2();
break;
case 3:
Algoritm3();
break;
case 4:
Console.WriteLine("Exit");
break;
default:
Console.WriteLine("Вы что-то другое нажали...");
break;
}
Console.Write("\n\n\t\t\tНажмите любую клавишу...");
Console.ReadLine();
Console.Clear();
}
while (i != 4);
}
catch (Exception)
{
Console.WriteLine("Упс, ошибка! Нажмите цифру! ");
}
}
static void Algoritm1()
{
Console.WriteLine("Введите число: ");
int correct_num;
string number = Console.ReadLine();
if (Int32.TryParse(number, out correct_num))
{
if (correct_num > 7)
{
Console.WriteLine("Привет!");
Console.ReadKey();
}
else if (correct_num <= 7)
{
Console.WriteLine("Введенная цифра равна 7 или меньше ");
Console.ReadKey();
}
}
else
{
Console.WriteLine("Вы ввели не цифру!");
Console.ReadKey();
}
}
static void Algoritm2()
{
string verif_name = "Вячеслав";
Console.WriteLine("Введите имя :");
string input_name = Console.ReadLine();
if (input_name == verif_name)
{
Console.WriteLine("Привет, Вячеслав!");
Console.ReadKey();
}
else
{
Console.WriteLine("Нет такого имени");
Console.ReadKey();
}
}
static void Algoritm3()
{
int n;
int[] arr;
int currint;
do
{
Console.Clear();
Console.Write("Введите длину массива: ");
} while (!int.TryParse(Console.ReadLine(), out currint));
n = currint;
arr = new int[n];
for (int i = 0; i < n; i++)
{
Console.Write("Введите элемент {0}: ", i + 1);
if (int.TryParse(Console.ReadLine(), out currint))
{
arr[i] = currint;
}
else --i;
}
Console.Write("Массив: " + string.Join(" ", arr));
int mult_numb;
do
{
Console.WriteLine();
Console.WriteLine(" Введите кратное число: ");
} while (!int.TryParse(Console.ReadLine(), out mult_numb));
for (int i = 0; i < n; i++)
{
if ((arr[i] % mult_numb) == 0)
{
Console.WriteLine($"Элемент массива, кратный {mult_numb} : "
+ string.Join(" ", arr[i]));
}
}
Console.ReadKey();
}
}
}
|
d87fc322ca434440a2bbf9f6fd10a5806bb87eaa
|
[
"C#"
] | 1 |
C#
|
Kryvosheina/-
|
e808db50b942cb451543c7ac2f6c1626330de560
|
29b2d1dda2df34e612929b315c7a0712f055fd57
|
refs/heads/master
|
<repo_name>DongDDD/JianMian<file_sep>/Podfile
target "JMian"
pod 'Masonry', '~> 1.0.1'
pod 'AFNetworking'
pod 'MJExtension'
pod 'SDWebImage'
pod 'MJRefresh'
pod 'SDCycleScrollView'
pod 'YYText'
pod 'SYWechatOpenSDK', '~> 1.7.9'
pod 'TXIMSDK_iOS'
pod ‘YYCache’
pod 'PrintBeautifulLog'
pod 'AMap2DMap'
pod 'AMapSearch'
pod 'AMapLocation'
<file_sep>/JMian/Define/VendorKeyMacros.h
//
// VendorKeyMacros.h
// JMian
//
// Created by chitat on 2019/4/11.
// Copyright © 2019 mac. All rights reserved.
//
#ifndef VendorKeyMacros_h
#define VendorKeyMacros_h
#define TIMSdkAppid @"1400193090"
#define TIMSdkAccountType @"36862"
#endif /* VendorKeyMacros_h */
<file_sep>/JMian/Utilities/Nw/Service/JMHTTPConstant.h
//
// JMHTTPConstant.h
// JMian
//
// Created by Chitat on 2019/3/30.
// Copyright © 2019 mac. All rights reserved.
//
#ifndef JMHTTPConstant_h
#define JMHTTPConstant_h
/// 服务器返回的三个固定字段
/// 状态码key
#define JMHTTPServiceResponseCodeKey @"code"
/// 消息key
#define JMHTTPServiceResponseMsgKey @"message"
/// 数据data
#define JMHTTPServiceResponseDataKey @"data"
#endif /* JMHTTPConstant_h */
<file_sep>/JMian/Define/APIStringMacros.h
//
// APIStringMacros.h
// JMian
//
// Created by mac on 2019/3/25.
// Copyright © 2019 mac. All rights reserved.
//
#ifndef APIStringMacros_h
#define APIStringMacros_h
#ifdef DEBUG
//Debug状态下的测试API
#define API_BASE_URL_STRING @"http://app.jmzhipin.com/"
#else
//Release状态下的线上API
#define API_BASE_URL_STRING @"http://www.companydomain.com/api/"
#endif
//身份切换
#define User_Change @"api/user/change"
//C端接口
#define Login_URL @"api/login"
//发送验证码
#define Login_Captcha_URL @"sms/captcha"
#define User_info_URL @"api/user/info"
#define Update_info_URL @"api/user/update"
#define Position_label_URL @"labels"
//上传图片
#define Uploads_Image_URL @"file/uploads"
//身份证识别
#define Ocr_idcard_URL @"api/tools/ocr/idcard"
//个人简历
#define Create_Vita_URL @"api/vita/create"
#define Update_Vita_URL @"api/vita/update"
//简历分页
#define Paginate_Vita_URL @"api/vita/paginate"
//简历详情
#define Info_Vita_URL @"api/vita/info"
//岗位
#define Update_job_URL @"api/user/job/update"
//工作经历
#define Create_Experience_URL @"api/user/experience/create"
#define Update_Experience_URL @"api/user/experience/update"
#define Delete_Experience_URL @"api/user/experience/delete"
//教育经历
#define Create_EducationExperience_URL @"api/education/create"
#define Update_EducationExperience_URL @"api/education/update"
#define Delete_EducationExperience_URL @"api/education/delete"
#define Paginate_Work_URL @"api/work/paginate"
#define Create_Work_URL @"api/work/create"
#define Info_Work_URL @"api/work/info"
//B端接口
#define Create_Company_URL @"api/company/create"
#define Fectch_CompanyInfo_URL @"api/company/info"
#define Paginate_Vita_URL @"api/vita/paginate"
#define List_Interview_URL @"api/work/interview/lists"
//接口
#define GET_CONTENT_DETAIL @"channel/getContentDetail" //获取内容详情(含上一个和下一个)
#define GET_COMMENT_LIST @"comment/getCommentList" //获取评论列表
#define COMMENT_LOGIN @"comment/login" //获取评论列表
#define COMMENT_PUBLISH @"comment/publish" //发布评论
#define COMMENT_DELETE @"comment/delComment" //删除评论
#define LOGINOUT @"common/logout" //登出
#endif /* APIStringMacros_h */
|
502078c7151470630096ce4c0c36fc79e9ef640d
|
[
"C",
"Ruby"
] | 4 |
Ruby
|
DongDDD/JianMian
|
087782c4121325471a53157f27f0a61a2ea22099
|
6b0fa72f48ec3568c1b3fd6b8fc2e78c21457b50
|
refs/heads/master
|
<file_sep>class Bringitemassociation < ActiveRecord::Base
belongs_to :rsvp
belongs_to :bringitem
end
<file_sep>class Allergy < ActiveRecord::Base
has_many :allergyassociations
has_many :rsvps, through: :allergyassociations
end
<file_sep>class CreateBringitemassociations < ActiveRecord::Migration
def change
create_table :bringitemassociations do |t|
t.belongs_to :bringitem, index: true
t.belongs_to :rsvp, index: true
end
end
end
<file_sep>class Allergyassociation < ActiveRecord::Base
belongs_to :rsvp
belongs_to :allergy
end
<file_sep>class Meal < ActiveRecord::Base
has_many :mealassociations
has_many :rsvps, through: :mealassociations
end
<file_sep>class Bringitem < ActiveRecord::Base
has_many :bringitemassociations
has_many :rsvps, through: :bringitemassociations
end
<file_sep>class CreateMealassociations < ActiveRecord::Migration
def change
create_table :mealassociations do |t|
t.belongs_to :meal, index: true
t.belongs_to :rsvp, index: true
end
end
end
<file_sep>class Mealassociation < ActiveRecord::Base
belongs_to :rsvp
belongs_to :meal
end
|
af03baf02cc75202dda37cfb7386dc054a6f2823
|
[
"Ruby"
] | 8 |
Ruby
|
gbanis/bbqplannr
|
5fb2cd4f7feef9f0551d507a6e818226752eca5d
|
47971b7e14025ee99d3800a6de5d9700b49078f2
|
refs/heads/master
|
<repo_name>jobrot/secblocks<file_sep>/ui/src/app/token/token.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Erc1594Component } from './erc1594/erc1594.component';
import {
MatButtonModule,
MatCardModule, MatChipsModule, MatExpansionModule,
MatFormFieldModule, MatIconModule,
MatInputModule,
MatListModule,
MatSelectModule
} from "@angular/material";
import {FormsModule} from "@angular/forms";
import { DividendComponent } from './dividend/dividend.component';
import { VotingComponent } from './voting/voting.component';
@NgModule({
declarations: [Erc1594Component, DividendComponent, VotingComponent],
imports: [
CommonModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
FormsModule,
MatSelectModule,
MatListModule,
MatIconModule,
MatExpansionModule,
MatChipsModule
]
})
export class TokenModule { }
<file_sep>/ui/src/app/token/voting/voting.component.ts
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {Web3Service} from "../../util/web3.service";
import {MatChipInputEvent, MatSnackBar} from "@angular/material";
import {NgForm} from "@angular/forms";
import {COMMA, ENTER} from '@angular/cdk/keycodes';
const abi = require('ethereumjs-abi');
const Web3 = require('web3');
declare let require: any; //declares that require in code is defined by external component, in this case web3.service
const dividendToken_artifacts = require('../../../../../build/contracts/VotingToken.json');
type Ballot = { name: string, endDate: Date, optionNames: string[], optionVoteCounts: number[] };
@Component({
selector: 'app-voting',
templateUrl: './voting.component.html',
styleUrls: ['./voting.component.css']
})
export class VotingComponent implements OnInit {
readonly separatorKeysCodes: number[] = [ENTER, COMMA];
address: string;
sub: any;
dividendToken: any;
deployed: any;
isIssuer: boolean;
/* isOrchestrator: boolean;*/
account: string;
/* name: string;*/
optionNames: string[] = [];
ballots: Ballot[] = [];
status = '';
constructor(private route: ActivatedRoute, private web3Service: Web3Service, private matSnackBar: MatSnackBar) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.address = '' + params['address'];
});
this.web3Service.artifactsToContract(dividendToken_artifacts)
.then((DividendTokenAbstraction) => {
this.dividendToken = DividendTokenAbstraction;
this.dividendToken.at(Web3.utils.toChecksumAddress(this.address)).then(deployed => {
console.log(deployed);
this.deployed = deployed;
/* this.deployed.name.call({from: this.account}).then((name) => {
this.name = Web3.utils.toUtf8(name);
});*/
/*this.deployed.isIssuable.call({from: this.account}).then((is) => {
this.issuable = is;
});*/
this.web3Service.getAccounts().then(accs => {
this.account = accs[0];
this.watchAccount();
this.checkRole();
});
this.updateBallots();
});
});
}
async createBallot(createForm: NgForm) {
if (!createForm.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to send');
return;
}
let ballotName = createForm.value.name;
let endTime = new Date(createForm.value.endTime);
console.log("form:");
try {
console.log("Trying to create " + ballotName + " Ballot with endtime " + endTime.getTime() / 1000); //endTime.getTime()/1000
let bytes32OptionNames = [];
this.optionNames.forEach(name => {
bytes32OptionNames.push(Web3.utils.fromAscii(name));
});
const transaction = await this.deployed.createBallot(Web3.utils.fromAscii(ballotName), bytes32OptionNames, (endTime.getTime() / 1000), {from: this.account});
console.log("transaction:");
console.log(transaction);
if (!transaction) {
this.setStatusFailure('Creating Failed.');
} else {
this.setStatusSuccess(ballotName + ' Ballot created.');
}
} catch (e) {
this.showError(e);
}
this.updateBallots();
}
async updateBallots() {
console.log("Updating Ballots..");
const deployed = this.deployed;
this.ballots = [];
for (var i = 0; ; i++) {
try {
let ballot = (await deployed.ballots.call(i, {from: this.account}));
let optionNames = (await deployed.getOptionNames.call(i, {from: this.account})).map(Web3.utils.toUtf8);
let optionVoteCounts = await deployed.getOptionVoteCounts.call(i, {from: this.account});
let ballotname = Web3.utils.toUtf8(ballot.name)
/*console.log(ballotname);
console.log(new Date(ballot.endDate.toNumber()));
console.log(optionNames);
console.log(optionVoteCounts);*/
this.ballots.push({name: ballotname, endDate: new Date(ballot.endDate.toNumber()), optionNames: optionNames, optionVoteCounts: optionVoteCounts});
} catch (e) {
break;
}
}
}
async vote(voteForm: NgForm) {
if (!voteForm.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to send');
return;
}
let ballotName = voteForm.value.ballotName;
let optionName = voteForm.value.optionName;
try {
console.log("Trying to send vote for " + optionName + " in " + ballotName);
const transaction = await this.deployed.vote(Web3.utils.fromAscii(ballotName), Web3.utils.fromAscii(optionName), {from: this.account});
if (!transaction) {
this.setStatusFailure('Voting Failed.');
} else {
this.setStatusSuccess('Voting for ' + optionName + ' successful.');
}
} catch (e) {
this.showError(e);
}
this.updateBallots();
}
async currentlyWinningOption(form: NgForm) {
if (!form.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, cannot calculate winning Option');
return;
}
let ballotName = form.value.ballotName;
try {
console.log("Trying to check winning option of " + ballotName);
const result = await this.deployed.currentlyWinningOption.call(Web3.utils.fromAscii(ballotName), {from: this.account});
if (!result) {
this.setStatusFailure('Checking Failed.');
} else if (result[1] <= 0) {
this.setStatusFailure(Web3.utils.toUtf8(result[0]));
} else {
this.setStatus('Option ' + Web3.utils.toUtf8(result[0]) + ' is currently winning with ' + result[1] + ' votes.');
}
} catch (e) {
this.showError(e);
}
}
addChip(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
if ((value || '').trim()) {
this.optionNames.push(value.trim());
}
if (input) {
input.value = '';
}
}
removeChip(optionName: string): void {
const index = this.optionNames.indexOf(optionName);
if (index >= 0) {
this.optionNames.splice(index, 1);
}
}
showError(e) {
let errorstring = new String(e);
let index: number = errorstring.indexOf("VM Exception while processing transaction: revert");
if (index != -1) {
this.setStatusFailure(errorstring.substring(index + 49));
} else this.setStatusFailure('Error sending tokens; see log.');
console.log(e);
}
setStatus(status) {
this.matSnackBar.open(status, null, {duration: 3000});
}
setStatusSuccess(status) {
this.matSnackBar.open(status, null, {duration: 3000, panelClass: ['style-success'],});
}
setStatusFailure(status) {
this.matSnackBar.open(status, null, {duration: 3000, panelClass: ['style-failure'],});
}
watchAccount() {
this.web3Service.accountsObservable.subscribe((accounts) => {
this.account = accounts[0];
this.checkRole();
});
}
checkRole() {
console.log("CheckingRole..");
if (this.account) {
this.deployed.isIssuer.call(this.account, {from: this.account}).then((is) => {
console.log("Is Issuer:");
console.log(is);
this.isIssuer = is;
});
}
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
<file_sep>/ui/src/app/token/dividend/dividend.component.ts
import {Component, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {Web3Service} from "../../util/web3.service";
import {MatSnackBar} from "@angular/material";
import {NgForm} from "@angular/forms";
const abi = require('ethereumjs-abi');
const Web3 = require('web3');
declare let require: any; //declares that require in code is defined by external component, in this case web3.service
const dividendToken_artifacts = require('../../../../../build/contracts/DividendToken.json');
@Component({
selector: 'app-dividend',
templateUrl: './dividend.component.html',
styleUrls: ['./dividend.component.css']
})
export class DividendComponent implements OnInit,OnDestroy { //
address: string;
sub: any;
dividendToken: any;
deployed: any;
/* isIssuer: boolean;
isOrchestrator: boolean;*/
account: string;
/* name: string;*/
status = '';
constructor(private route: ActivatedRoute, private web3Service: Web3Service, private matSnackBar: MatSnackBar) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.address = '' + params['address'];
});
this.web3Service.artifactsToContract(dividendToken_artifacts)
.then((DividendTokenAbstraction) => {
this.dividendToken = DividendTokenAbstraction;
this.dividendToken.at(Web3.utils.toChecksumAddress(this.address)).then(deployed => {
console.log(deployed);
this.deployed = deployed;
/* this.deployed.name.call({from: this.account}).then((name) => {
this.name = Web3.utils.toUtf8(name);
});*/
/*this.deployed.isIssuable.call({from: this.account}).then((is) => {
this.issuable = is;
});*/
this.web3Service.getAccounts().then(accs => {
this.account = accs[0];
this.watchAccount();
/* this.checkRole();
this.watchAccount();*/
}); //fallback if the observable does not publish
});
});
}
async distributeDividends(sendForm: NgForm) {
if (!sendForm.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to send');
return;
}
let amount = sendForm.value.amount;
try {
console.log("Trying to distribute " + amount + " Ether.");
const transaction = await this.deployed.distributeDividends({from: this.account , value: Web3.utils.toWei(amount, "ether")});
if (!transaction) {
this.setStatusFailure('Distributing Failed.');
} else {
this.setStatusSuccess(amount + ' Ether distributed.');
}
} catch (e) {
this.showError(e);
}
}
async withdrawDividends(form: NgForm) {
if (!form.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to send');
return;
}
try {
console.log("Trying to withdraw");
const transaction = await this.deployed.withdrawDividend({from: this.account});
if (!transaction) {
this.setStatusFailure('Withrawing Failed.');
} else {
this.setStatusSuccess('Ether withdrawn.');
}
} catch (e) {
this.showError(e);
}
}
async dividendOf(form: NgForm) {
if (!form.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, calculate dividends');
return;
}
let owner = form.value.owner;
try {
console.log("Trying to check dividends of " + owner);
const dividends = await this.deployed.dividendOf(Web3.utils.toChecksumAddress(owner), {from: this.account});
if (!dividends) {
this.setStatusFailure('Sending Token Failed.');
} else {
this.setStatus(owner + ' is entitled to ' + Web3.utils.fromWei(dividends, 'ether') + ' Ether in dividends');
}
} catch (e) {
this.showError(e);
}
}
showError(e) {
let errorstring = new String(e);
let index: number = errorstring.indexOf("VM Exception while processing transaction: revert");
if (index != -1) {
this.setStatusFailure(errorstring.substring(index + 49));
} else this.setStatusFailure('Error sending tokens; see log.');
console.log(e);
}
setStatus(status) {
this.matSnackBar.open(status, null, {duration: 3000});
}
setStatusSuccess(status) {
this.matSnackBar.open(status, null, {duration: 3000, panelClass: ['style-success'],});
}
setStatusFailure(status) {
this.matSnackBar.open(status, null, {duration: 3000, panelClass: ['style-failure'],});
}
watchAccount() {
this.web3Service.accountsObservable.subscribe((accounts) => {
this.account = accounts[0];
});
}
/*
updateRolesAndBalance() {
this.checkRole();
this.refreshBalance();
}
async refreshBalance() {
console.log('Refreshing balance');
try {
const balance = await this.deployed.balanceOf.call(this.account);
console.log('Found balance: ' + balance);
this.balance = balance;
} catch (e) {
console.log(e);
this.setStatusFailure('Error getting balance; see log.');
}
}
checkRole() {
console.log("CheckingRole..");
if (this.account) {
this.deployed.isOrchestrator.call(this.account, {from: this.account}).then((is) => {
console.log("Is Orchestrator:");
console.log(is);
this.isOrchestrator = is;
});
this.deployed.isIssuer.call(this.account, {from: this.account}).then((is) => {
console.log("Is Issuer:");
console.log(is);
this.isIssuer = is;
});
}
}
*/
ngOnDestroy() {
this.sub.unsubscribe();
}
}
<file_sep>/ui/src/app/registry/registry.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RegistryComponent } from './registry/registry.component';
import {
MatButtonModule,
MatCardModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatListModule,
MatSelectModule
} from "@angular/material";
import {FormsModule} from "@angular/forms";
@NgModule({
declarations: [RegistryComponent],
imports: [
CommonModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
FormsModule,
MatSelectModule,
MatListModule,
MatIconModule
]
})
export class RegistryModule { }
<file_sep>/ui/src/app/registry/registry/registry.component.ts
import {Component, OnInit} from '@angular/core';
import {Web3Service} from '../../util/web3.service';
import {MatSnackBar} from '@angular/material';
import {NgForm} from "@angular/forms";
import {Router} from "@angular/router";
const abi = require('ethereumjs-abi');
const Web3 = require('web3');
declare let require: any; //declares that require is defined by external component, in this case web3.service
const registry_artifacts = require('../../../../../build/contracts/Registry.json');
@Component({
selector: 'app-registry',
templateUrl: './registry.component.html',
styleUrls: ['./registry.component.css']
})
export class RegistryComponent implements OnInit {
proxyList: { id, address }[] = [];
registry: any;
deployed: any;
isOrchestrator: boolean;
account='';
status = '';
constructor(private web3Service: Web3Service, private matSnackBar: MatSnackBar, private router: Router) {
}
ngOnInit() {
this.web3Service.artifactsToContract(registry_artifacts)
.then((RegistryAbstraction) => {
this.registry = RegistryAbstraction;
this.registry.deployed().then(deployed => {
console.log(deployed);
this.deployed = deployed;
this.web3Service.getAccounts().then(accs => {
this.account = accs[0];
this.checkRole();
this.watchAccount();
}); //fallback if the observable does not publish
this.updateProxies();
});
});
}
async updateProxies() {
console.log("Updating Proxies..");
const deployed = this.deployed;
for (let id of await deployed.getProxyIdList.call({from: this.account})) {
let asciiid = Web3.utils.toUtf8(id);
let address = await deployed.proxies.call(id);
this.proxyList.push({id: asciiid, address: address});
}
console.log(this.proxyList);
}
route(id: string, address: string){
console.log(id);
console.log(address);
if(id.startsWith("KYC")){
this.router.navigate(['kyc/'+address]);
}
else if(id.startsWith("InsiderList")){
this.router.navigate(['ins/'+address]);
}
else if(id.startsWith("PEPList")){
this.router.navigate(['pep/'+address]);
}
else if(id.startsWith("ERC1495")){
this.router.navigate(['erc1594/'+address]);
}
else if(id.startsWith("DividendToken")){
this.router.navigate(['dividendToken/'+address]);
}
else if(id.startsWith("VotingToken")){
this.router.navigate(['votingToken/'+address]);
}
else if(id.startsWith("Controller")){
this.router.navigate(['controller/'+address]);
}
else {
this.setStatusFailure("Could not Recognize this kind of Proxy. Please rename it according to the conventions in Registry.sol.")
}
}
async createProxy(createForm: NgForm) {
if(!createForm.valid){
this.setStatusFailure('Form invalid');
}
if (!this.registry) {
this.setStatusFailure('registry is not loaded, unable to create Proxy');
return;
}
let proxyId = createForm.value.proxyId;
console.log('Creating proxy with id' + proxyId);
try {
const transaction = await this.deployed.createProxy.sendTransaction(Web3.utils.fromAscii(proxyId), {from: this.account});
if (!transaction) {
this.setStatusFailure('Proxy Creation Failed.');
} else {
this.setStatusSuccess('Proxy' + proxyId + ' created at '+ transaction.logs[0].args.proxyAddress);
this.updateProxies()
}
} catch (e) {
console.log(e);
this.setStatusFailure('Error creating proxy; see log.');
}
}
async addProxy(addForm: NgForm) {
if(!addForm.valid){
this.setStatusFailure('Form invalid');
}
if (!this.registry) {
this.setStatusFailure('registry is not loaded, unable to add Proxy');
return;
}
let proxyId = addForm.value.proxyId;
let address = addForm.value.address;
console.log('Adding proxy with id' + proxyId);
try {
const transaction = await this.deployed.addProxy.sendTransaction(Web3.utils.fromAscii(proxyId),Web3.utils.toChecksumAddress(address), {from: this.account});
if (!transaction) {
this.setStatusFailure('Proxy Adding Failed.');
} else {
this.setStatusSuccess('Proxy' + proxyId + ' added at '+ transaction.logs[0].args.proxyAddress);
this.updateProxies()
}
} catch (e) {
console.log(e);
this.setStatusFailure('Error adding proxy; see log.');
}
}
async updateProxy(updateForm: NgForm) {
if(!updateForm.valid){
this.setStatusFailure('Form invalid');
}
if (!this.registry) {
this.setStatusFailure('registry is not loaded, unable to update Proxy');
return;
}
let proxyId = updateForm.value.proxyId;
let address = updateForm.value.address;
console.log('Updating proxy with id' + proxyId);
try {
const transaction = await this.deployed.updateProxy.sendTransaction(Web3.utils.fromAscii(proxyId),Web3.utils.toChecksumAddress(address), {from: this.account});
// console.log("t");
// console.log(transaction);
if (!transaction) {
this.setStatusFailure('Proxy Updating Failed.');
} else {
this.setStatusSuccess('Proxy' + proxyId + ' updated at '+ transaction.logs[0].args.proxyAddress);
this.updateProxies()
}
} catch (e) {
console.log(e);
this.setStatusFailure('Error updating proxy; see log.');
}
}
setStatus(status) {
this.matSnackBar.open(status, null, {duration: 3000});
}
setStatusFailure(status) {
this.matSnackBar.open(status, null, {duration: 3000, panelClass: ['style-failure'],});
}
setStatusSuccess(status) {
this.matSnackBar.open(status, null, {duration: 3000, panelClass: ['style-success'],});
}
watchAccount() {
this.web3Service.accountsObservable.subscribe((accounts) => {
this.account = accounts[0];
this.checkRole();
});
}
checkRole(){
if(this.account) {
this.deployed.isOrchestrator.call(this.account, {from: this.account}).then((is) => {
console.log("Is Orchestrator:");
console.log(is);
this.isOrchestrator = is;
});
}
}
}
<file_sep>/test/ERC1594Tests.js
const {BN, constants, expectEvent, expectRevert} = require('openzeppelin-test-helpers');
const {ZERO_ADDRESS} = constants;
const should = require('chai').should();
const abi = require('ethereumjs-abi');
const MockContract = artifacts.require("../contracts/Mocks/MockContract.sol"); //Gnosis Mock contract framework
const GeneralVerifierMock = artifacts.require("../contracts/Mocks/GeneralVerifierMock.sol");
const ERC1594 = artifacts.require("../contracts/Tokens/ERC1594.sol");
const VotingToken = artifacts.require("../contracts/Tokens/VotingToken.sol");
const KYCVerifier = artifacts.require("../contracts/Controlling/KYCVerifier.sol");
const InsiderListVerifier = artifacts.require("../contracts/Controlling/InsiderListVerifier.sol");
const PEPListVerifier = artifacts.require("../contracts/Controlling/PEPListVerifier.sol");
const TransferQueues = artifacts.require("../contracts/AML/TransferQueues.sol");
const Controller = artifacts.require("../contracts/Controlling/Controller.sol");
const UnstructuredProxy = artifacts.require("../contracts/Proxy/UnstructuredProxy.sol");
const {
shouldBehaveLikeERC20,
shouldBehaveLikeERC20Transfer,
shouldBehaveLikeERC20Approve,
} = require('./ERC20BehaviourTests.js');
const ERC1594Mock = artifacts.require('ERC1594Mock');
const TRANSFER_RETENTION_TIME = 604800; //604800 == 1 Week in Seconds
const AMLLimit = new BN(15000);
const initialSupply = AMLLimit;
const UnderAMLLimit = AMLLimit.sub(new BN(1));
const HalfAMLLimit = AMLLimit.div(new BN(2));
contract('ERC1594, TransferQueues, Controller', function ([deployer, initialHolder, recipient, anotherAccount]) {
beforeEach(async function () {
this.kycVerifier = await KYCVerifier.new();
this.insiderListVerifier = await InsiderListVerifier.new();
this.pepListVerifier = await PEPListVerifier.new();
this.kycMock = await MockContract.new();
this.insiderListMock = await MockContract.new();
this.pepListMock = await MockContract.new();
//Let the mocks of all Controllers return Success by default, except if defined differently for tests
await this.kycMock.givenAnyReturnBool(true);
await this.insiderListMock.givenAnyReturnBool(true);
await this.pepListMock.givenAnyReturnBool(true);
//const verifyTransfer = this.kycVerifier.contract.methods.verifyTransfer(0, 0, 0,0).encodeABI();
//await this.kycMock.givenMethodReturn(verifyTransfer,abi.rawEncode(['bool','bytes'], ['true','0x51']))
//await this.insiderMock.givenAnyReturn(abi.rawEncode(['bool','bytes'], ['true','0x51']));
//await this.pepListMock.givenAnyReturn(abi.rawEncode(['bool','bytes'], ['true','0x51']));
//console.log(await this.kycMock.test("x"));
/*console.log("kycVerifier:");
console.log(this.kycVerifier);
console.log("DG:");
console.log(this.kycControllerDG);
await this.kycControllerDG.deploy(deployer);*/
//this.insiderListVerifier = await InsiderListVerifier.new();
//this.pepListVerifier = await PEPListVerifier.new();
//create SUT
this.transferQueues = await TransferQueues.new();
this.controller = await Controller.new(); //this.kycMock.address, this.insiderListMock.address, this.pepListMock.address
this.token = await ERC1594Mock.new(); //this.controller.address, this.transferQueues.address, initialHolder, initialSupply
//Comment this in for full proxy test
this.controllerProxy = await UnstructuredProxy.new(deployer);
await this.controllerProxy.upgradeToInit(this.controller.address);
this.controller = await Controller.at(this.controllerProxy.address);
this.controller.setKYCVerifier(this.kycMock.address);
this.controller.setPEPListVerifier(this.pepListMock.address);
this.controller.setInsiderListVerifier(this.insiderListMock.address);
this.proxy = await UnstructuredProxy.new(deployer);
await this.proxy.upgradeToInit(this.token.address);
this.token = await ERC1594Mock.at(this.proxy.address);
await this.token.setController(this.controller.address);
await this.token.setTransferQueues(this.transferQueues.address);
await this.transferQueues.transferOwnership(this.token.address);
await this.token.addIssuerOrchestrator(deployer);
await this.token.mint(initialHolder, initialSupply);
});
describe('transferWithData', function () {
//kyc
describe('when the sender or recipient is not kycd', function () {
it('reverts', async function () {
const transferFromInitialHolder = this.kycVerifier.contract.methods.verifyTransfer(initialHolder, recipient, 1, abi.rawEncode(['bytes'], [''])).encodeABI();
await this.kycMock.givenMethodReturnBool(transferFromInitialHolder, false);
await expectRevert(this.token.transferWithData(recipient, 1, abi.rawEncode(['bytes'], ['']), {from: initialHolder}),
'The transfer is not allowed by the KYCVerifier!'
);
});
});
describe('when the sender and recipient are kycd', function () {
it('transfers correctly', async function () {
await this.token.transferWithData(recipient, 1, abi.rawEncode(['bytes'], ['']), {from: initialHolder});
(await this.token.balanceOf(initialHolder)).should.be.bignumber.equal(initialSupply.sub(new BN(1)));
(await this.token.balanceOf(recipient)).should.be.bignumber.equal('1');
});
});
// insiderlist
describe('when the sender or recipient are insiders', function () {
it('reverts', async function () {
const transferFromInitialHolder = this.insiderListVerifier.contract.methods.verifyTransfer(initialHolder, recipient, 1, abi.rawEncode(['bytes'], [''])).encodeABI();
await this.insiderListMock.givenMethodReturnBool(transferFromInitialHolder, false);
await expectRevert(this.token.transferWithData(recipient, 1, abi.rawEncode(['bytes'], ['']), {from: initialHolder}),
'The transfer is not allowed by the InsiderListVerifier!'
);
});
});
describe('when the sender and recipient are not insiders', function () {
it('transfers correctly', async function () {
await this.token.transferWithData(recipient, 1, abi.rawEncode(['bytes'], ['']), {from: initialHolder});
(await this.token.balanceOf(initialHolder)).should.be.bignumber.equal(initialSupply.sub(new BN(1)));
(await this.token.balanceOf(recipient)).should.be.bignumber.equal('1');
});
});
// peplist
describe('when the sender or recipient are politically exposed persons', function () {
it('reverts', async function () {
const transferFromInitialHolder = this.pepListVerifier.contract.methods.verifyTransfer(initialHolder, recipient, 1, abi.rawEncode(['bytes'], [''])).encodeABI();
await this.pepListMock.givenMethodReturnBool(transferFromInitialHolder, false);
await expectRevert(this.token.transferWithData(recipient, 1, abi.rawEncode(['bytes'], ['']), {from: initialHolder}),
'The transfer is not allowed by the PoliticallyExposedPersonVerifier!'
);
});
});
describe('when the sender and recipient are not politically exposed persons', function () {
it('transfers correctly', async function () {
await this.token.transferWithData(recipient, 1, abi.rawEncode(['bytes'], ['']), {from: initialHolder});
(await this.token.balanceOf(initialHolder)).should.be.bignumber.equal(initialSupply.sub(new BN(1)));
(await this.token.balanceOf(recipient)).should.be.bignumber.equal('1');
});
});
// AML
describe('when the amount of a single transfer is just beyond the AML Limit', function () {
it('transfers correctly', async function () {
//await this.token.issue(initialHolder, AMLLimit, abi.rawEncode(['bytes'],['']));
await this.token.transferWithData(recipient, UnderAMLLimit, abi.rawEncode(['bytes'], ['']), {from: initialHolder});
(await this.token.balanceOf(initialHolder)).should.be.bignumber.equal('1');
(await this.token.balanceOf(recipient)).should.be.bignumber.equal(UnderAMLLimit);
});
});
describe('when the amount of a single transfer is at the AML Limit', function () {
it('reverts', async function () {
//await this.token.issue(initialHolder, AMLLimit, abi.rawEncode(['bytes'],['']));
await expectRevert(this.token.transferWithData(recipient, AMLLimit, abi.rawEncode(['bytes'], ['']), {from: initialHolder}),
'ERC1594: The transfer exceeds the allowed quota within the retention period.'
);
});
});
describe('when the amount of two concurrent transfers to a single recipient is at the AML Limit', function () {
it('reverts', async function () {
//await this.token.issue(initialHolder, AMLLimit, abi.rawEncode(['bytes'],['']));
await this.token.transferWithData(recipient, HalfAMLLimit, abi.rawEncode(['bytes'], ['']), {from: initialHolder})
await expectRevert(this.token.transferWithData(recipient, HalfAMLLimit, abi.rawEncode(['bytes'], ['']), {from: initialHolder}),
'ERC1594: The transfer exceeds the allowed quota within the retention period.'
);
});
});
describe('when the amount of two concurrent transfers to multiple recipient is at the AML Limit', function () {
it('reverts', async function () {
//await this.token.issue(initialHolder, AMLLimit, abi.rawEncode(['bytes'],['']));
await this.token.transferWithData(recipient, HalfAMLLimit, abi.rawEncode(['bytes'], ['']), {from: initialHolder})
await expectRevert(this.token.transferWithData(anotherAccount, HalfAMLLimit, abi.rawEncode(['bytes'], ['']), {from: initialHolder}),
'ERC1594: The transfer exceeds the allowed quota within the retention period.'
);
});
});
//this test should run last, as it changes time
describe('when the amount of two transfers more than RETENTION_TIME apart to a single recipient are under the AML Limit', function () {
it('transfers correctly', async function () {
await this.token.issue(initialHolder, AMLLimit, abi.rawEncode(['bytes'], ['']));
await this.token.transferWithData(recipient, UnderAMLLimit, abi.rawEncode(['bytes'], ['']), {from: initialHolder});
await advanceTime(TRANSFER_RETENTION_TIME + 1000);
await advanceBlock();
await this.token.transferWithData(recipient, UnderAMLLimit, abi.rawEncode(['bytes'], ['']), {from: initialHolder});
(await this.token.balanceOf(initialHolder)).should.be.bignumber.equal('2');
(await this.token.balanceOf(recipient)).should.be.bignumber.equal(UnderAMLLimit.add(UnderAMLLimit));
});
});
describe('when the amount of two transfers more than RETENTION_TIME apart to multiple recipients are exactly the AML Limit', function () {
it('transfers correctly', async function () {
await this.token.transferWithData(recipient, HalfAMLLimit, abi.rawEncode(['bytes'], ['']), {from: initialHolder});
await advanceTime(TRANSFER_RETENTION_TIME + 1000);
await advanceBlock();
await this.token.transferWithData(anotherAccount, HalfAMLLimit, abi.rawEncode(['bytes'], ['']), {from: initialHolder});
(await this.token.balanceOf(initialHolder)).should.be.bignumber.equal('0');
(await this.token.balanceOf(recipient)).should.be.bignumber.equal(HalfAMLLimit);
(await this.token.balanceOf(anotherAccount)).should.be.bignumber.equal(HalfAMLLimit);
});
});
describe('when the amount of multiple transfers less than RETENTION_TIME apart to a single recipient are under the AML Limit', function () {
it('transfers correctly', async function () {
await this.token.transferWithData(recipient, AMLLimit.div(new BN(4)), abi.rawEncode(['bytes'], ['']), {from: initialHolder});
await advanceTime(1000);
await advanceBlock();
await this.token.transferWithData(recipient, AMLLimit.div(new BN(4)), abi.rawEncode(['bytes'], ['']), {from: initialHolder});
await advanceTime(1000);
await advanceBlock();
await this.token.transferWithData(recipient, AMLLimit.div(new BN(4)), abi.rawEncode(['bytes'], ['']), {from: initialHolder});
await advanceTime(1000);
await advanceBlock();
await this.token.transferWithData(recipient, AMLLimit.div(new BN(4)).sub(new BN(1)), abi.rawEncode(['bytes'], ['']), {from: initialHolder});
(await this.token.balanceOf(initialHolder)).should.be.bignumber.equal('1');
(await this.token.balanceOf(recipient)).should.be.bignumber.equal(UnderAMLLimit);
});
});
//this test should run last, as it changes time
describe('when the amount of two transfers more than RETENTION_TIME apart to a single recipient are under the AML Limit', function () {
it('transfers correctly', async function () {
await this.token.transferWithData(recipient, AMLLimit.div(new BN(4)), abi.rawEncode(['bytes'], ['']), {from: initialHolder});
await advanceTime(1000);
await advanceBlock();
await this.token.transferWithData(recipient, AMLLimit.div(new BN(4)), abi.rawEncode(['bytes'], ['']), {from: initialHolder});
await advanceTime(1000);
await advanceBlock();
await this.token.transferWithData(recipient, AMLLimit.div(new BN(4)), abi.rawEncode(['bytes'], ['']), {from: initialHolder});
(await this.token.balanceOf(initialHolder)).should.be.bignumber.equal(AMLLimit.div(new BN(4)));
(await this.token.balanceOf(recipient)).should.be.bignumber.equal(AMLLimit.div(new BN(4)).mul(new BN(3)));
await advanceTime(1000);
await advanceBlock();
await expectRevert(this.token.transferWithData(recipient, AMLLimit.div(new BN(4)), abi.rawEncode(['bytes'], ['']), {from: initialHolder}),
'ERC1594: The transfer exceeds the allowed quota within the retention period.'
);
});
});
describe('when the amount of multiple transfers less than RETENTION_TIME apart to a single recipient are at the AML Limit only when taking order into account', function () {
it('reverts before time is over, and transfers correctly afterwards', async function () {
await this.token.issue(initialHolder, AMLLimit, abi.rawEncode(['bytes'], ['']));
await this.token.transferWithData(recipient, HalfAMLLimit, abi.rawEncode(['bytes'], ['']), {from: initialHolder});
await advanceTime(TRANSFER_RETENTION_TIME / 4);
await advanceBlock();
//Reverts, as retention time is not yet over
await expectRevert(this.token.transferWithData(recipient, HalfAMLLimit, abi.rawEncode(['bytes'], ['']), {from: initialHolder}),
'ERC1594: The transfer exceeds the allowed quota within the retention period.'
);
await advanceTime(TRANSFER_RETENTION_TIME / 4);
await advanceBlock();
//smaller amounts to fill up queue
await this.token.transferWithData(recipient, new BN(1), abi.rawEncode(['bytes'], ['']), {from: initialHolder});
await this.token.transferWithData(recipient, new BN(1), abi.rawEncode(['bytes'], ['']), {from: initialHolder});
await advanceTime(TRANSFER_RETENTION_TIME / 2);
await advanceBlock();
//this should now work, as the first transfer is cleared
await this.token.transferWithData(recipient, AMLLimit.sub(new BN(3)), abi.rawEncode(['bytes'], ['']), {from: initialHolder});
(await this.token.balanceOf(recipient)).should.be.bignumber.equal(UnderAMLLimit.add(HalfAMLLimit));
await advanceTime(TRANSFER_RETENTION_TIME / 2);
await advanceBlock();
//small transfers should be cleared out by now, so a transfer of 2 should work, but not a transfer of 3
await expectRevert(this.token.transferWithData(recipient, new BN(3), abi.rawEncode(['bytes'], ['']), {from: initialHolder}),
'ERC1594: The transfer exceeds the allowed quota within the retention period.'
);
await this.token.transferWithData(recipient, new BN(2), abi.rawEncode(['bytes'], ['']), {from: initialHolder});
(await this.token.balanceOf(initialHolder)).should.be.bignumber.equal(UnderAMLLimit.sub(HalfAMLLimit));
(await this.token.balanceOf(recipient)).should.be.bignumber.equal(UnderAMLLimit.add(HalfAMLLimit).add(new BN(2)));
});
});
});
describe('Verifiers General Adding and Removing', function () {
describe('when a general verifier is added', function () {
it('an event is emitted', async function () {
this.generalVerifierMock = await GeneralVerifierMock.new();
var { logs } = await this.controller.addVerifier(this.generalVerifierMock.address);
expectEvent.inLogs(logs, 'VerifierAdded', { verifier: this.generalVerifierMock.address });
});
});
describe('when a non existing general verifiers is removed', function () {
it('reverts', async function () {
this.generalVerifierMock = await GeneralVerifierMock.new();
await expectRevert(this.controller.removeVerifier(this.generalVerifierMock.address),
'Verifiers list is empty.'
);
});
});
describe('when multiple general verifiers are added and removed', function () {
it('all adds and removes work as expected', async function () {
this.generalVerifierMock1 = await GeneralVerifierMock.new();
this.generalVerifierMock2 = await GeneralVerifierMock.new();
this.generalVerifierMock3 = await GeneralVerifierMock.new();
this.generalVerifierMock4 = await GeneralVerifierMock.new();
var { logs } = await this.controller.addVerifier(this.generalVerifierMock1.address);
expectEvent.inLogs(logs, 'VerifierAdded', { verifier: this.generalVerifierMock1.address });
var { logs } = await this.controller.addVerifier(this.generalVerifierMock2.address);
expectEvent.inLogs(logs, 'VerifierAdded', { verifier: this.generalVerifierMock2.address });
var { logs } = await this.controller.addVerifier(this.generalVerifierMock3.address);
expectEvent.inLogs(logs, 'VerifierAdded', { verifier: this.generalVerifierMock3.address });
assert((await this.controller.getVerifierCount())==3);
var { logs } = await this.controller.removeVerifier(this.generalVerifierMock1.address);
expectEvent.inLogs(logs, 'VerifierRemoved', { verifier: this.generalVerifierMock1.address });
assert((await this.controller.getVerifierCount())==2);
var { logs } = await this.controller.removeVerifier(this.generalVerifierMock2.address);
expectEvent.inLogs(logs, 'VerifierRemoved', { verifier: this.generalVerifierMock2.address });
assert((await this.controller.getVerifierCount())==1);
await expectRevert(this.controller.removeVerifier(this.generalVerifierMock1.address),
'Verifier to remove is not in the verifiers list.'
);
assert((await this.controller.getVerifierCount())==1);
var { logs } = await this.controller.addVerifier(this.generalVerifierMock4.address);
expectEvent.inLogs(logs, 'VerifierAdded', { verifier: this.generalVerifierMock4.address });
});
});
describe('when verifyall is called', function () {
it('general Verifiers are also called', async function () {
this.generalVerifierMock = await GeneralVerifierMock.new();
var { logs } = await this.controller.addVerifier(this.generalVerifierMock.address);
expectEvent.inLogs(logs, 'VerifierAdded', { verifier: this.generalVerifierMock.address });
await expectRevert(this.token.transferWithData(recipient,1 ,abi.rawEncode(['bytes'], ['']),{from: initialHolder}),
'The transfer is not allowed by a general Verifier!'
);
});
});
});
});
// Source for helper functions: https://medium.com/fluidity/standing-the-time-of-test-b906fcc374a9
advanceTime = (time) => {
return new Promise((resolve, reject) => {
web3.currentProvider.send({
jsonrpc: '2.0',
method: 'evm_increaseTime',
params: [time],
id: new Date().getTime()
}, (err, result) => {
if (err) {
return reject(err)
}
return resolve(result)
})
})
}
advanceBlock = () => {
return new Promise((resolve, reject) => {
web3.currentProvider.send({
jsonrpc: '2.0',
method: 'evm_mine',
id: new Date().getTime()
}, (err, result) => {
if (err) {
return reject(err)
}
const newBlockHash = web3.eth.getBlock('latest').hash
return resolve(newBlockHash)
})
})
}
<file_sep>/test/KYCTests.js
const tryExpectCatch = require('./misc/trycatch');
const KYCVerifier = artifacts.require('KYCVerifier.sol');
const truffleAssert = require('truffle-assertions');
const UnstructuredProxy = artifacts.require("../contracts/Proxy/UnstructuredProxy.sol");
const abi = require('ethereumjs-abi');
const should = require('chai').should();
const NULLBYTE=abi.rawEncode(['bytes'],['']);
contract(['KYCVerifier', 'KYCListManagerRole'], (accounts) => {
let origSut;
let sut;
let proxy;
let deployer = accounts[0];
let verifier = accounts[1];
let otherAccount = accounts[2];
let whitelisted = accounts[3];
let unwhitelisted = accounts[4];
let unrelatedAccount = accounts[9];
before(async () => {
sut = await KYCVerifier.new();
//comment this in for proxy test
proxy = await UnstructuredProxy.new(deployer);
await proxy.upgradeToInit(sut.address);
sut = await KYCVerifier.at(proxy.address);
});
it('deployer should be a verifier', async () => {
const result = await sut.isKYCListManager(deployer);
assert.equal(result, true);
});
it('unrelated accounts should not be able to add new verifiers', async () => {
//await expectThrow(this.moderator.addModerator(moderatorRole, { from: unrelatedAccount }));
await tryExpectCatch(sut.addKYCListManager(verifier, {from: unrelatedAccount}), 'KYCListManagerRole: caller does not have the KYCListManager role');
await truffleAssert.reverts(
sut.addKYCListManager(verifier, {from: unrelatedAccount}), 'KYCListManagerRole: caller does not have the KYCListManager role');
const result = await sut.isKYCListManager(verifier);
assert.equal(result, false);
});
it('verifiers should be able to add new verifiers', async () => {
const result1 = await sut.addKYCListManager(verifier, {from: deployer});
truffleAssert.eventEmitted(result1, 'KYCListManagerAdded', (ev) => {
return ev.account === verifier;
});
const status1 = await sut.isKYCListManager(verifier);
assert.equal(status1, true);
const result2 = await sut.addKYCListManager(otherAccount, {from: verifier});
truffleAssert.eventEmitted(result2, 'KYCListManagerAdded', (ev) => {
return ev.account === otherAccount;
});
const status2 = await sut.isKYCListManager(otherAccount);
assert.equal(status2, true);
});
//as all functions test only on the whitelist, they can all be tested in parallel
it('all verify actions should fail if one participating address is not whitelisted', async () => {
await sut.addAddressToWhitelist(whitelisted);
const resultIssue = (await sut.verifyIssue( unwhitelisted, 100,NULLBYTE, {from: deployer}));
const resultTransferUU= (await sut.verifyTransfer(unwhitelisted, unwhitelisted, 100, NULLBYTE, {from: deployer}));
const resultTransferWU = (await sut.verifyTransfer(whitelisted, unwhitelisted, 100, NULLBYTE, {from: deployer}));
const resultTransferUW = (await sut.verifyTransfer(unwhitelisted, whitelisted, 100, NULLBYTE, {from: deployer}));
const resultTransferFromUUU= (await sut.verifyTransferFrom(unwhitelisted, unwhitelisted, unwhitelisted, 100, NULLBYTE, {from: deployer}));
const resultTransferFromWUU = (await sut.verifyTransferFrom(whitelisted, unwhitelisted, unwhitelisted, 100, NULLBYTE, {from: deployer}));
const resultTransferFromWWU = (await sut.verifyTransferFrom(whitelisted, whitelisted, unwhitelisted, 100, NULLBYTE, {from: deployer}));
const resultTransferFromUWU = (await sut.verifyTransferFrom(unwhitelisted, whitelisted, unwhitelisted, 100, NULLBYTE, {from: deployer}));
const resultTransferFromUUW = (await sut.verifyTransferFrom(unwhitelisted, unwhitelisted, whitelisted, 100, NULLBYTE, {from: deployer}));
const resultTransferFromUWW = (await sut.verifyTransferFrom(unwhitelisted, whitelisted, whitelisted, 100, NULLBYTE, {from: deployer}));
const resultRedeem = (await sut.verifyRedeem(unwhitelisted, 100, NULLBYTE, {from: deployer}));
const resultRedeemFromUU= (await sut.verifyRedeemFrom(unwhitelisted, unwhitelisted, 100, NULLBYTE, {from: deployer}));
const resultRedeemFromWU = (await sut.verifyRedeemFrom(whitelisted, unwhitelisted, 100, NULLBYTE, {from: deployer}));
const resultRedeemFromUW = (await sut.verifyRedeemFrom(unwhitelisted, whitelisted, 100, NULLBYTE, {from: deployer}));
assert.equal(resultIssue, false);
assert.equal(resultTransferUU, false);
assert.equal(resultTransferWU, false);
assert.equal(resultTransferUW, false);
assert.equal(resultTransferFromUUU, false);
assert.equal(resultTransferFromWUU, false);
assert.equal(resultTransferFromWWU, false);
assert.equal(resultTransferFromUWU, false);
assert.equal(resultTransferFromUUW, false);
assert.equal(resultTransferFromUWW, false);
assert.equal(resultRedeem, false);
assert.equal(resultRedeemFromUU, false);
assert.equal(resultRedeemFromWU, false);
assert.equal(resultRedeemFromUW, false);
});
it('all verify actions should succeed if all participating address are not whitelisted', async () => {
await sut.addAddressToWhitelist(whitelisted);
const resultIssue = await sut.verifyIssue( whitelisted, 100, NULLBYTE,{from: deployer});
const resultTransfer= await sut.verifyTransfer(whitelisted, whitelisted, 100, NULLBYTE, {from: deployer});
const resultTransferFrom= await sut.verifyTransferFrom(whitelisted, whitelisted, whitelisted, 100, NULLBYTE, {from: deployer});
const resultRedeem = await sut.verifyRedeem(whitelisted, 100, NULLBYTE, {from: deployer});
const resultRedeemFrom= await sut.verifyRedeemFrom(whitelisted, whitelisted, 100, NULLBYTE, {from: deployer});
assert.equal(resultIssue, true);
assert.equal(resultTransfer, true);
assert.equal(resultTransferFrom, true);
assert.equal(resultRedeem, true);
assert.equal(resultRedeemFrom, true);
});
});<file_sep>/ui/src/app/kyc/kyc/kyc.component.ts
import {Component, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Web3Service} from "../../util/web3.service";
import {MatSnackBar} from "@angular/material";
import {NgForm} from "@angular/forms";
const abi = require('ethereumjs-abi');
const Web3 = require('web3');
declare let require: any; //declares that require is defined by external component, in this case web3.service
const kyc_artifacts = require('../../../../../build/contracts/KYCVerifier.json');
@Component({
selector: 'app-kyc',
templateUrl: './kyc.component.html',
styleUrls: ['./kyc.component.css']
})
export class KycComponent implements OnInit, OnDestroy {
address: string;
sub: any;
kyc: any;
deployed: any;
isListManager: boolean;
account: string;
status = '';
constructor(private route: ActivatedRoute, private web3Service: Web3Service, private matSnackBar: MatSnackBar) {
this.sub = this.route.params.subscribe(params => {
this.address = '' + params['address'];
});
}
ngOnInit() {
this.web3Service.artifactsToContract(kyc_artifacts)
.then((KYCAbstraction) => {
this.kyc = KYCAbstraction;
this.kyc.at(Web3.utils.toChecksumAddress(this.address)).then(deployed => {
console.log(deployed);
this.deployed = deployed;
this.web3Service.getAccounts().then(accs => {
this.account = accs[0];
this.checkRole();
this.watchAccount();
}); //fallback if the observable does not publish
});
});
}
async addAddress(addForm: NgForm) {
if (!addForm.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.kyc) {
this.setStatusFailure('kyc is not loaded, unable to add Address');
return;
}
let address = addForm.value.address;
console.log('Adding ' + address + ' to whitelist.');
try {
const transaction = await this.deployed.addAddressToWhitelist.sendTransaction(Web3.utils.toChecksumAddress(address), {from: this.account});
if (!transaction) {
this.setStatusFailure('Whitelist Adding Failed.');
} else {
this.setStatusSuccess('Address ' + address + ' added to whitelist');
}
} catch (e) {
this.showError(e);
}
}
async removeAddress(removeForm: NgForm) {
if (!removeForm.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.kyc) {
this.setStatusFailure('kyc is not loaded, unable to remove Address');
return;
}
let address = removeForm.value.address;
console.log('Removing ' + address + ' from whitelist.');
try {
const transaction = await this.deployed.removeAddressFromWhitelist.sendTransaction(Web3.utils.toChecksumAddress(address), {from: this.account});
if (!transaction) {
this.setStatusFailure('Whitelist Removing Failed.');
} else {
this.setStatusSuccess('Address ' + address + ' removed from whitelist');
}
} catch (e) {
this.showError(e);
}
}
async checkAddress(checkForm: NgForm) {
if (!checkForm.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.kyc) {
this.setStatusFailure('kyc is not loaded, unable to check Address');
return;
}
let address = checkForm.value.address;
console.log('Checking ' + address + ' on whitelist.');
const onWhitelist = await this.deployed._onWhitelist.call(Web3.utils.toChecksumAddress(address), {from: this.account});
if (!onWhitelist) {
this.setStatusFailure(address + ' is not on Whitelist');
} else {
this.setStatusSuccess(address + ' is on Whitelist');
}
}
setStatus(status) {
this.matSnackBar.open(status, null, {duration: 3000});
}
setStatusSuccess(status) {
this.matSnackBar.open(status, null, {duration: 3000, panelClass: ['style-success'],});
}
setStatusFailure(status) {
this.matSnackBar.open(status, null, {duration: 3000, panelClass: ['style-failure'],});
}
watchAccount() {
this.web3Service.accountsObservable.subscribe((accounts) => {
this.account = accounts[0];
this.checkRole();
});
}
checkRole() {
console.log("CheckingRole..");
if(this.account) {
this.deployed.isKYCListManager.call(this.account, {from: this.account}).then((is) => {
console.log("Is ListManager:");
console.log(is);
this.isListManager = is;
});
}
}
ngOnDestroy() {
this.sub.unsubscribe();
}
showError(e) {
let errorstring = new String(e);
let index: number = errorstring.indexOf("VM Exception while processing transaction: revert");
if (index != -1) {
this.setStatusFailure(errorstring.substring(index + 49));
} else this.setStatusFailure('Error executing Transaction; see log.');
console.log(e);
}
}
<file_sep>/ui/src/app/controller/controller/controller.component.ts
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {Web3Service} from "../../util/web3.service";
import {MatSnackBar} from "@angular/material";
import {NgForm} from "@angular/forms";
const abi = require('ethereumjs-abi');
const Web3 = require('web3');
declare let require: any; //declares that require in code is defined by external component, in this case web3.service
const controller_artifacts = require('../../../../../build/contracts/Controller.json');
@Component({
selector: 'app-controller',
templateUrl: './controller.component.html',
styleUrls: ['./controller.component.css']
})
export class ControllerComponent implements OnInit {
address: string;
sub: any;
controller: any;
deployed: any;
isOrchestrator: boolean;
account: string;
kycVerifier: string;
insiderListVerifier: string;
pepListVerifier: string;
generalVerifiers: string[] = [];
constructor(private route: ActivatedRoute, private web3Service: Web3Service, private matSnackBar: MatSnackBar, private router: Router) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.address = '' + params['address'];
});
this.web3Service.artifactsToContract(controller_artifacts)
.then((ControllerAbstraction) => {
this.controller = ControllerAbstraction;
this.controller.at(Web3.utils.toChecksumAddress(this.address)).then(deployed => {
console.log(deployed);
this.deployed = deployed;
this.web3Service.getAccounts().then(accs => {
this.account = accs[0];
this.checkRole();
this.watchAccount();
this.getVerifiers();
}); //fallback if the observable does not publish
});
});
}
async setKYC(form: NgForm) {
if(!form.valid){
this.setStatusSuccess('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('registry is not loaded, unable set KYC');
return;
}
let address = form.value.address;
console.log('Setting KYC with address' + address);
try {
const transaction = await this.deployed.setKYCVerifier.sendTransaction(Web3.utils.toChecksumAddress(address), {from: this.account});
if (!transaction) {
this.setStatusFailure('Setting KYC Failed.');
} else {
this.setStatusSuccess('KYC set to '+ address);
this.getVerifiers();
}
} catch (e) {
this.showError(e);
}
}
async setPEP(form: NgForm) {
if(!form.valid){
this.setStatusSuccess('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('registry is not loaded, unable set PEP');
return;
}
let address = form.value.address;
console.log('Setting PEP with address' + address);
try {
const transaction = await this.deployed.setPEPListVerifier.sendTransaction(Web3.utils.toChecksumAddress(address), {from: this.account});
if (!transaction) {
this.setStatusFailure('Setting PEP Failed.');
} else {
this.setStatusSuccess('PEP set to '+ address);
this.getVerifiers();
}
} catch (e) {
this.showError(e);
}
}
async setInsiderList(form: NgForm) {
if(!form.valid){
this.setStatusSuccess('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('registry is not loaded, unable set InsiderList');
return;
}
let address = form.value.address;
console.log('Setting InsiderList with address' + address);
try {
const transaction = await this.deployed.setInsiderListVerifier.sendTransaction(Web3.utils.toChecksumAddress(address), {from: this.account});
if (!transaction) {
this.setStatusFailure('Setting InsiderList Failed.');
} else {
this.setStatusSuccess('InsiderList set to '+ address);
this.getVerifiers();
}
} catch (e) {
this.showError(e);
}
}
async addGeneralVerifier(form: NgForm) {
if(!form.valid){
this.setStatusSuccess('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('registry is not loaded, unable add Verifier');
return;
}
let address = form.value.address;
console.log('Adding Verifier with address' + address);
try {
const transaction = await this.deployed.addVerifier.sendTransaction(Web3.utils.toChecksumAddress(address), {from: this.account});
if (!transaction) {
this.setStatusFailure('Adding Verifier Failed.');
} else {
this.setStatusSuccess('Verifier with address '+ address+ ' added.');
this.getVerifiers();
}
} catch (e) {
this.showError(e);
}
}
async removeGeneralVerifier(address: string) {
if (!this.deployed) {
this.setStatusFailure('registry is not loaded, unable remove Verifier');
return;
}
console.log('Removing Verifier with address' + address);
try {
const transaction = await this.deployed.removeVerifier.sendTransaction(Web3.utils.toChecksumAddress(address), {from: this.account});
if (!transaction) {
this.setStatusFailure('Removing Verifier Failed.');
} else {
this.setStatusSuccess('Verifier with address '+ address+ ' removed.');
this.getVerifiers();
}
} catch (e) {
this.showError(e);
}
}
async getVerifiers(){
this.kycVerifier = await this.deployed.kycVerifier.call({from: this.account});
this.insiderListVerifier = await this.deployed.insiderListVerifier.call({from: this.account});
this.pepListVerifier = await this.deployed.pepListVerifier.call({from: this.account});
this.generalVerifiers = [];
var verifierCount = (await this.deployed.getVerifierCount.call({from: this.account}));
for (var i = 0; i<verifierCount ; i++) {
this.generalVerifiers.push(await this.deployed.verifiers.call(i, {from: this.account}));
}
}
showError(e) {
let errorstring = new String(e);
let index: number = errorstring.indexOf("VM Exception while processing transaction: revert");
if (index != -1) {
this.setStatusFailure(errorstring.substring(index + 49));
} else this.setStatusFailure('Error executing transaction; see log.');
console.log(e);
}
setStatusSuccess(status) {
this.matSnackBar.open(status, null, {duration: 3000, panelClass: ['style-success'],});
}
setStatusFailure(status) {
this.matSnackBar.open(status, null, {duration: 3000, panelClass: ['style-failure'],});
}
watchAccount() {
this.web3Service.accountsObservable.subscribe((accounts) => {
this.account = accounts[0];
this.checkRole();
});
}
checkRole() {
console.log("CheckingRole..");
if (this.account) {
this.deployed.isOrchestrator.call(this.account, {from: this.account}).then((is) => {
console.log("Is Orchestrator:");
console.log(is);
this.isOrchestrator = is;
});
}
}
}
<file_sep>/ui/src/app/token/erc1594/erc1594.component.ts
import {Component, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {Web3Service} from "../../util/web3.service";
import {MatSnackBar} from "@angular/material";
import {NgForm} from "@angular/forms";
const abi = require('ethereumjs-abi');
const Web3 = require('web3');
declare let require: any; //declares that require in code is defined by external component, in this case web3.service
const erc1594_artifacts = require('../../../../../build/contracts/ERC1594.json');
const emptyBytes = Web3.utils.fromAscii("");
@Component({
selector: 'app-erc1594',
templateUrl: './erc1594.component.html',
styleUrls: ['./erc1594.component.css']
})
export class Erc1594Component implements OnInit, OnDestroy {
address: string;
sub: any;
erc1594: any;
deployed: any;
isIssuer: boolean;
isOrchestrator: boolean;
account: string;
name: string;
balance: number = 0;
issuable: boolean;
status = '';
constructor(private route: ActivatedRoute, private web3Service: Web3Service, private matSnackBar: MatSnackBar) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.address = '' + params['address'];
});
this.web3Service.artifactsToContract(erc1594_artifacts)
.then((ERC1594Abstraction) => {
this.erc1594 = ERC1594Abstraction;
this.erc1594.at(Web3.utils.toChecksumAddress(this.address)).then(deployed => {
console.log(deployed);
this.deployed = deployed;
this.deployed.name.call({from: this.account}).then((name) => {
this.name = Web3.utils.toUtf8(name);
});
this.deployed.isIssuable.call({from: this.account}).then((is) => {
this.issuable = is;
});
this.web3Service.getAccounts().then(accs => {
this.account = accs[0];
this.checkRole();
this.watchAccount();
}); //fallback if the observable does not publish
});
});
}
async sendTokens(sendForm: NgForm) {
if (!sendForm.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to send');
return;
}
let amount = sendForm.value.amount;
let receiver = sendForm.value.receiver;
try {
console.log("Trying to send " + amount + " to " + receiver);
const transaction = await this.deployed.transfer(Web3.utils.toChecksumAddress(receiver), amount, {from: this.account});
if (!transaction) {
this.setStatusFailure('Sending Token Failed.');
} else {
this.setStatusSuccess(amount + ' Tokens sent to ' + receiver);
}
} catch (e) {
this.showError(e);
}
this.updateRolesAndBalance();
}
async sendTokensFrom(sendForm: NgForm) {
if (!sendForm.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to send');
return;
}
let amount = sendForm.value.amount;
let receiver = sendForm.value.receiver;
let from = sendForm.value.from;
try {
console.log("Trying to send " + amount + " from " + from + " to " + receiver);
const transaction = await this.deployed.transferFrom(Web3.utils.toChecksumAddress(from), Web3.utils.toChecksumAddress(receiver), amount, {from: this.account});
if (!transaction) {
this.setStatusFailure('Sending Token Failed.');
} else {
this.setStatusSuccess(amount + ' Tokens sent to ' + receiver);
}
} catch (e) {
this.showError(e);
}
this.updateRolesAndBalance();
}
async checkSendTokens(sendForm: NgForm) {
if (!sendForm.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to send');
return;
}
let amount = sendForm.value.amount;
let receiver = sendForm.value.receiver;
console.log("Checking to send " + amount + " to " + receiver);
const result = await this.deployed.canTransfer(Web3.utils.toChecksumAddress(receiver), amount, emptyBytes, {from: this.account});
if (!result[0]) {
let reason:string;
if(Web3.utils.toUtf8(result[2])=="")reason = ' Transfer not possible';
else reason = ' Transfer is not possible due to: ' + Web3.utils.toUtf8(result[2]);
this.setStatusFailure('Statuscode: '+ result[1] + reason);
} else {
this.setStatusSuccess('Transfer is possible');
}
this.updateRolesAndBalance();
}
async checkSendTokensFrom(sendForm: NgForm) {
if (!sendForm.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to send');
return;
}
let amount = sendForm.value.amount;
let receiver = sendForm.value.receiver;
let from = sendForm.value.from;
console.log("Checking to send " + amount + " from "+from+" to " + receiver);
const result = await this.deployed.canTransferFrom(Web3.utils.toChecksumAddress(from), Web3.utils.toChecksumAddress(receiver), amount, emptyBytes, {from: this.account});
if (!result[0]) {
let reason:string;
if(Web3.utils.toUtf8(result[2])=="")reason = ' Transfer not possible';
else reason = ' Transfer is not possible due to: ' + Web3.utils.toUtf8(result[2]);
this.setStatusFailure('Statuscode: '+ result[1] + reason);
} else {
this.setStatusSuccess('Transfer is possible');
}
this.updateRolesAndBalance();
}
async redeemTokens(redeemForm: NgForm) {
if (!redeemForm.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to redeem');
return;
}
let amount = redeemForm.value.amount;
try {
console.log("Trying to redeem " + amount);
const transaction = await this.deployed.redeem(amount, emptyBytes, {from: this.account});
if (!transaction) {
this.setStatusFailure('redeeming Token Failed.');
} else {
this.setStatusSuccess(amount + ' Tokens redeemed ');
}
} catch (e) {
this.showError(e);
}
this.updateRolesAndBalance();
}
async redeemTokensFrom(redeemForm: NgForm) {
if (!redeemForm.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to redeem');
return;
}
let amount = redeemForm.value.amount;
let from = redeemForm.value.from;
try {
console.log("Trying to redeem " + amount + " from " + from);
const transaction = await this.deployed.redeemFrom(Web3.utils.toChecksumAddress(from), amount, emptyBytes, {from: this.account});
if (!transaction) {
this.setStatusFailure('Redeeming Token Failed.');
} else {
this.setStatusSuccess(amount + ' Tokens redeemed for ' + from);
}
} catch (e) {
this.showError(e);
}
this.updateRolesAndBalance();
}
async addIssuer(form: NgForm) {
if (!form.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to send');
return;
}
let issuer = form.value.issuer;
try {
console.log("Trying to add " + issuer + " as issuer.");
let transaction;
if (this.isIssuer) {
transaction = await this.deployed.addIssuer(Web3.utils.toChecksumAddress(issuer), {from: this.account});
} else if (this.isOrchestrator) {
transaction = await this.deployed.addIssuerOrchestrator(Web3.utils.toChecksumAddress(issuer), {from: this.account});
}
if (!transaction) {
this.setStatusFailure('Adding Issuer Failed.');
} else {
this.setStatusSuccess(issuer + ' set as Issuer.');
}
} catch (e) {
this.showError(e);
}
this.updateRolesAndBalance();
}
async closeIssuance() {
try {
console.log("Trying to close issuance");
let transaction;
transaction = await this.deployed.closeIssuance({from: this.account});
if (!transaction) {
this.setStatusFailure('Closing Issuance.');
} else {
this.setStatusSuccess('Issuance closed successfully');
this.issuable = false;
}
} catch (e) {
this.showError(e);
}
this.updateRolesAndBalance();
}
async issue(form: NgForm) {
if (!form.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to issue');
return;
}
let amount = form.value.amount;
let receiver = form.value.receiver;
try {
console.log("Trying to issue " + amount + " to " + receiver);
const transaction = await this.deployed.issue(Web3.utils.toChecksumAddress(receiver), amount, emptyBytes, {from: this.account});
if (!transaction) {
this.setStatusFailure('Issuing Token Failed.');
} else {
this.setStatusSuccess(amount + ' Tokens issued to ' + receiver);
}
} catch (e) {
this.showError(e);
}
this.updateRolesAndBalance();
}
async approve(form: NgForm) {
if (!form.valid) {
this.setStatusFailure('Form invalid');
}
if (!this.deployed) {
this.setStatusFailure('contract is not loaded, unable to issue');
return;
}
let amount = form.value.amount;
let spender = form.value.spender;
try {
console.log("Trying to approve " + amount + " to " + spender);
const transaction = await this.deployed.approve(Web3.utils.toChecksumAddress(spender), amount, {from: this.account});
if (!transaction) {
this.setStatusFailure('Approving Failed.');
} else {
this.setStatusSuccess(amount + ' Tokens approved to ' + spender);
}
} catch (e) {
this.showError(e);
}
this.updateRolesAndBalance();
}
showError(e) {
let errorstring = new String(e);
let index: number = errorstring.indexOf("VM Exception while processing transaction: revert");
if (index != -1) {
this.setStatusFailure(errorstring.substring(index + 49));
} else this.setStatusFailure('Error sending tokens; see log.');
console.log(e);
}
setStatus(status) {
this.matSnackBar.open(status, null, {duration: 3000});
}
setStatusSuccess(status) {
this.matSnackBar.open(status, null, {duration: 3000, panelClass: ['style-success'],});
}
setStatusFailure(status) {
this.matSnackBar.open(status, null, {duration: 3000, panelClass: ['style-failure'],});
}
watchAccount() {
this.web3Service.accountsObservable.subscribe((accounts) => {
this.account = accounts[0];
this.updateRolesAndBalance();
});
}
updateRolesAndBalance() {
this.checkRole();
this.refreshBalance();
}
async refreshBalance() {
console.log('Refreshing balance');
try {
const balance = await this.deployed.balanceOf.call(this.account);
console.log('Found balance: ' + balance);
this.balance = balance;
} catch (e) {
console.log(e);
this.setStatusFailure('Error getting balance; see log.');
}
}
checkRole() {
console.log("CheckingRole..");
if (this.account) {
this.deployed.isOrchestrator.call(this.account, {from: this.account}).then((is) => {
console.log("Is Orchestrator:");
console.log(is);
this.isOrchestrator = is;
});
this.deployed.isIssuer.call(this.account, {from: this.account}).then((is) => {
console.log("Is Issuer:");
console.log(is);
this.isIssuer = is;
});
}
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
<file_sep>/ui/src/app/app-routing/app-routing.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import {RegistryComponent} from "../registry/registry/registry.component";
import {KycComponent} from "../kyc/kyc/kyc.component";
import {Erc1594Component} from "../token/erc1594/erc1594.component";
import {DividendComponent} from "../token/dividend/dividend.component";
import {VotingComponent} from "../token/voting/voting.component";
import {ControllerComponent} from "../controller/controller/controller.component";
import {InsiderListComponent} from "../insiderlist/insiderList/insiderList.component";
import {PepListComponent} from "../peplist/pepList/pepList.component";
const routes: Routes = [
{
path: 'registry',
component: RegistryComponent
},
{
path: 'kyc/:address',
component: KycComponent
},
{
path: 'ins/:address',
component: InsiderListComponent
},
{
path: 'pep/:address',
component: PepListComponent
},
{
path: 'erc1594/:address',
component: Erc1594Component
},
{
path: 'dividendToken/:address',
component: DividendComponent
},
{
path: 'votingToken/:address',
component: VotingComponent
},
{
path: 'controller/:address',
component: ControllerComponent
},
];
@NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/test/VotingTokenTests.js
const { BN, constants, expectEvent, expectRevert } = require('openzeppelin-test-helpers');
const { ZERO_ADDRESS } = constants;
const { expect, assert } = require('chai')
.use(require('chai-bytes'));
const should = require('chai').should();
const abi = require('ethereumjs-abi');
const MockContract = artifacts.require("../contracts/Mocks/MockContract.sol"); //Gnosis Mock contract framework
const VotingToken = artifacts.require("../contracts/Tokens/VotingToken.sol");
const TransferQueues = artifacts.require("../contracts/AML/TransferQueues.sol");
const Controller = artifacts.require("../contracts/Controlling/Controller.sol");
const UnstructuredProxy = artifacts.require("../contracts/Proxy/UnstructuredProxy.sol");
contract('VotingToken', function ([deployer, initialHolder, recipient, issuer, anotherAccount]) {
beforeEach(async function () {
this.kycMock = await MockContract.new();
this.insiderListMock = await MockContract.new();
this.pepListMock = await MockContract.new();
//Let the mocks of all Controllers return Success by default, except if defined differently for tests
await this.kycMock.givenAnyReturnBool(true);
await this.insiderListMock.givenAnyReturnBool(true);
await this.pepListMock.givenAnyReturnBool(true);
//create SUT
this.transferQueues = await TransferQueues.new();
this.controller = await Controller.new(); //this.kycMock.address, this.insiderListMock.address, this.pepListMock.address
//not via mocked Token and initial supply, because erc20 functionality tests are not required anymore here, and
//initial minting would distort test results
this.token = await VotingToken.new(); //this.controller.address, this.transferQueues.address
//Comment this in for full proxy test
this.controllerProxy = await UnstructuredProxy.new(deployer);
await this.controllerProxy.upgradeToInit(this.controller.address);
this.controller = await Controller.at(this.controllerProxy.address);
this.controller.setKYCVerifier(this.kycMock.address);
this.controller.setPEPListVerifier(this.pepListMock.address);
this.controller.setInsiderListVerifier(this.insiderListMock.address);
this.proxy = await UnstructuredProxy.new(deployer);
await this.proxy.upgradeToInit(this.token.address);
this.token = await VotingToken.at(this.proxy.address);
await this.token.setController(this.controller.address);
await this.token.setTransferQueues(this.transferQueues.address);
await this.token.addIssuerOrchestrator(deployer);
await this.token.addIssuer(issuer);
await this.transferQueues.transferOwnership(this.token.address);
this.futureDate = (await web3.eth.getBlock('latest')).timestamp + 1000000;
});
describe('createBallot', function () {
describe('when the ballotname is empty', function () {
it('reverts', async function () {
await expectRevert(this.token.createBallot( abi.rawEncode(['bytes32'],['']), [abi.rawEncode(['bytes32'],[''])],this.futureDate,{from: issuer}),
'BallotName must not be empty!'
);
});
});
describe('when the optionNames parameter is empty', function () {
it('reverts', async function () {
await expectRevert(this.token.createBallot( abi.rawEncode(['bytes32'],['Vote']), [],this.futureDate,{from: issuer}),
'OptionNames must not be empty!'
);
});
});
describe('when all parameters are correct', function () {
it('creates a ballot and stores it', async function () {
const { logs } = await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote']), [abi.rawEncode(['bytes32'],['A']),abi.rawEncode(['bytes32'],['B'])],this.futureDate,{from: issuer});
assert((await this.token.ballots(0)).name!=0);
expectEvent.inLogs(logs, 'BallotCreated', { ballotName: '0x566f746500000000000000000000000000000000000000000000000000000000' });
});
});
});
describe('Basic voting and reverts', function () {
describe('when the ballot does not exist', function () {
it('reverts', async function () {
await this.token.issue(initialHolder, 100, abi.rawEncode(['bytes'],[''])); //issue must be before create, for cutoff time
await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote']), [abi.rawEncode(['bytes32'],['Option A']),abi.rawEncode(['bytes32'],['Option B'])],this.futureDate,{from: issuer});
await expectRevert(this.token.vote( abi.rawEncode(['bytes32'],['VoteWRONG']), abi.rawEncode(['bytes32'],['Option A']),{from: initialHolder}),
'Ballot not found!'
);
});
});
describe('when the option does not exist', function () {
it('reverts', async function () {
await this.token.issue(initialHolder, 100, abi.rawEncode(['bytes'],['']));
await advanceBlock();
await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote']), [abi.rawEncode(['bytes32'],['Option A']),abi.rawEncode(['bytes32'],['Option B'])],this.futureDate,{from: issuer});
await expectRevert(this.token.vote( abi.rawEncode(['bytes32'],['Vote']), abi.rawEncode(['bytes32'],['Option C']),{from: initialHolder}),
'Option does not exist in Ballot.'
);
});
});
describe('when the sender did not possess tokens at time of creation of the Ballot', function () {
it('reverts', async function () {
await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote']), [abi.rawEncode(['bytes32'],['Option A']),abi.rawEncode(['bytes32'],['Option B'])],this.futureDate,{from: issuer});
//we issue the tokens after the creation of the ballot, after the cutoff time
await this.token.issue(initialHolder, 100, abi.rawEncode(['bytes'],['']));
await expectRevert(this.token.vote( abi.rawEncode(['bytes32'],['Vote']), abi.rawEncode(['bytes32'],['Option A']),{from: initialHolder}),
'Sender held no tokens at cutoff'
);
});
});
describe('when the sender already voted', function () {
it('reverts', async function () {
await this.token.issue(initialHolder, 100, abi.rawEncode(['bytes'],['']));
await advanceBlock();
await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote']), [abi.rawEncode(['bytes32'],['Option A']),abi.rawEncode(['bytes32'],['Option B'])],this.futureDate,{from: issuer});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote']), abi.rawEncode(['bytes32'],['Option B']),{from: initialHolder});
await expectRevert(this.token.vote( abi.rawEncode(['bytes32'],['Vote']), abi.rawEncode(['bytes32'],['Option B']),{from: initialHolder}),
'Sender already voted'
);
});
});
describe('when the Voting Time is over', function () {
it('reverts', async function () {
await this.token.issue(initialHolder, 100, abi.rawEncode(['bytes'],['']));
await advanceBlock();
await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote']), [abi.rawEncode(['bytes32'],['Option A']),abi.rawEncode(['bytes32'],['Option B'])],(await web3.eth.getBlock('latest')).timestamp,{from: issuer});
//await this.token.vote( abi.rawEncode(['bytes32'],['Vote']), abi.rawEncode(['bytes32'],['Option B']),{from: initialHolder});
await expectRevert(this.token.vote( abi.rawEncode(['bytes32'],['Vote']), abi.rawEncode(['bytes32'],['Option B']),{from: initialHolder}),
'Vote has ended.'
);
});
});
describe('when the enddate is in the future', function () {
it('votes, reverts on voting again', async function () {
await this.token.issue(initialHolder, 100, abi.rawEncode(['bytes'],['']));
await advanceBlock();
await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote']), [abi.rawEncode(['bytes32'],['Option A']),abi.rawEncode(['bytes32'],['Option B'])],this.futureDate,{from: issuer});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote']), abi.rawEncode(['bytes32'],['Option B']),{from: initialHolder});
await expectRevert(this.token.vote( abi.rawEncode(['bytes32'],['Vote']), abi.rawEncode(['bytes32'],['Option B']),{from: initialHolder}),
'Sender already voted'
);
});
});
});
describe('Voting and winner Calculations', function () {
describe('when one holder has more tokens than another', function () {
it('correct option wins', async function () {
await this.token.issue(initialHolder, new BN(100), abi.rawEncode(['bytes'],['']));
await this.token.issue(anotherAccount, new BN(101), abi.rawEncode(['bytes'],['']));
await advanceBlock();
await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote']), [abi.rawEncode(['bytes32'],['Option A']),abi.rawEncode(['bytes32'],['Option B'])],this.futureDate,{from: issuer});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote']), abi.rawEncode(['bytes32'],['Option A']),{from: initialHolder});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote']), abi.rawEncode(['bytes32'],['Option B']),{from: anotherAccount});
var result = (await this.token.currentlyWinningOption(abi.rawEncode(['bytes32'],['Vote']),{from: initialHolder})); //abi.rawEncode(['bytes32'],['Vote'])
web3.utils.toAscii(result.winningOptionName).should.be.equal(abi.rawEncode(['bytes32'],['Option B']).toString("ascii"));
result.winningOptionVoteCount.should.be.bignumber.equal(new BN(101));
});
});
describe('when one holder has more tokens than another, than changing in another vote', function () {
it('correct option wins', async function () {
await this.token.issue(initialHolder, new BN(100), abi.rawEncode(['bytes'],['']));
await this.token.issue(anotherAccount, new BN(101), abi.rawEncode(['bytes'],['']));
await advanceBlock();
await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote1']), [abi.rawEncode(['bytes32'],['Option A']),abi.rawEncode(['bytes32'],['Option B'])],this.futureDate,{from: issuer});
await this.token.issue(initialHolder, new BN(2), abi.rawEncode(['bytes'],['']));
await advanceBlock();
await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote2']), [abi.rawEncode(['bytes32'],['Option C']),abi.rawEncode(['bytes32'],['Option D'])],this.futureDate,{from: issuer});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote1']), abi.rawEncode(['bytes32'],['Option A']),{from: initialHolder});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote1']), abi.rawEncode(['bytes32'],['Option B']),{from: anotherAccount});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote2']), abi.rawEncode(['bytes32'],['Option C']),{from: initialHolder});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote2']), abi.rawEncode(['bytes32'],['Option D']),{from: anotherAccount});
var result = (await this.token.currentlyWinningOption(abi.rawEncode(['bytes32'],['Vote1']),{from: initialHolder})); //abi.rawEncode(['bytes32'],['Vote'])
web3.utils.toAscii(result.winningOptionName).should.be.equal(abi.rawEncode(['bytes32'],['Option B']).toString("ascii"));
result.winningOptionVoteCount.should.be.bignumber.equal(new BN(101));
var result = (await this.token.currentlyWinningOption(abi.rawEncode(['bytes32'],['Vote2']),{from: initialHolder})); //abi.rawEncode(['bytes32'],['Vote'])
web3.utils.toAscii(result.winningOptionName).should.be.equal(abi.rawEncode(['bytes32'],['Option C']).toString("ascii"));
result.winningOptionVoteCount.should.be.bignumber.equal(new BN(102));
});
});
describe('when multiple token holders vote', function () {
it('correct option wins', async function () {
await this.token.issue(initialHolder, new BN(100), abi.rawEncode(['bytes'],['']));
await this.token.issue(anotherAccount, new BN(51), abi.rawEncode(['bytes'],['']));
await this.token.issue(recipient, new BN(50), abi.rawEncode(['bytes'],['']));
await advanceBlock();
await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote1']), [abi.rawEncode(['bytes32'],['Option A']),abi.rawEncode(['bytes32'],['Option B'])],this.futureDate,{from: issuer});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote1']), abi.rawEncode(['bytes32'],['Option A']),{from: initialHolder});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote1']), abi.rawEncode(['bytes32'],['Option B']),{from: anotherAccount});
var result = (await this.token.currentlyWinningOption(abi.rawEncode(['bytes32'],['Vote1']),{from: initialHolder})); //abi.rawEncode(['bytes32'],['Vote'])
web3.utils.toAscii(result.winningOptionName).should.be.equal(abi.rawEncode(['bytes32'],['Option A']).toString("ascii"));
result.winningOptionVoteCount.should.be.bignumber.equal(new BN(100));
await this.token.vote( abi.rawEncode(['bytes32'],['Vote1']), abi.rawEncode(['bytes32'],['Option B']),{from: recipient});
var result = (await this.token.currentlyWinningOption(abi.rawEncode(['bytes32'],['Vote1']),{from: initialHolder})); //abi.rawEncode(['bytes32'],['Vote'])
web3.utils.toAscii(result.winningOptionName).should.be.equal(abi.rawEncode(['bytes32'],['Option B']).toString("ascii"));
result.winningOptionVoteCount.should.be.bignumber.equal(new BN(101));
});
});
describe('when multiple token holders vote and tokens are transferred', function () {
it('correct option wins', async function () {
await this.token.issue(initialHolder, new BN(101), abi.rawEncode(['bytes'],['']));
await this.token.issue(anotherAccount, new BN(100), abi.rawEncode(['bytes'],['']));
await this.token.issue(recipient, new BN(2), abi.rawEncode(['bytes'],['']));
await this.token.transferWithData(anotherAccount,2, abi.rawEncode(['bytes'],['']),{from:recipient});
await advanceBlock();
await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote1']), [abi.rawEncode(['bytes32'],['Option A']),abi.rawEncode(['bytes32'],['Option B'])],this.futureDate,{from: issuer});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote1']), abi.rawEncode(['bytes32'],['Option A']),{from: initialHolder});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote1']), abi.rawEncode(['bytes32'],['Option B']),{from: anotherAccount});
var result = (await this.token.currentlyWinningOption(abi.rawEncode(['bytes32'],['Vote1']),{from: initialHolder})); //abi.rawEncode(['bytes32'],['Vote'])
web3.utils.toAscii(result.winningOptionName).should.be.equal(abi.rawEncode(['bytes32'],['Option B']).toString("ascii"));
result.winningOptionVoteCount.should.be.bignumber.equal(new BN(102));
});
});
describe('when multiple token holders vote and tokens are burned', function () {
it('correct option wins', async function () {
await this.token.issue(initialHolder, new BN(101), abi.rawEncode(['bytes'],['']));
await this.token.issue(anotherAccount, new BN(100), abi.rawEncode(['bytes'],['']));
await this.token.redeem(2, abi.rawEncode(['bytes'],['']),{from:initialHolder});
await advanceBlock();
await this.token.createBallot( abi.rawEncode(['bytes32'],['Vote1']), [abi.rawEncode(['bytes32'],['Option A']),abi.rawEncode(['bytes32'],['Option B'])],this.futureDate,{from: issuer});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote1']), abi.rawEncode(['bytes32'],['Option A']),{from: initialHolder});
await this.token.vote( abi.rawEncode(['bytes32'],['Vote1']), abi.rawEncode(['bytes32'],['Option B']),{from: anotherAccount});
var result = (await this.token.currentlyWinningOption(abi.rawEncode(['bytes32'],['Vote1']),{from: initialHolder})); //abi.rawEncode(['bytes32'],['Vote'])
web3.utils.toAscii(result.winningOptionName).should.be.equal(abi.rawEncode(['bytes32'],['Option B']).toString("ascii"));
result.winningOptionVoteCount.should.be.bignumber.equal(new BN(100));
});
});
});
});
// Source for helper functions: https://medium.com/fluidity/standing-the-time-of-test-b906fcc374a9
advanceTime = (time) => {
return new Promise((resolve, reject) => {
web3.currentProvider.send({
jsonrpc: '2.0',
method: 'evm_increaseTime',
params: [time],
id: new Date().getTime()
}, (err, result) => {
if (err) { return reject(err) }
return resolve(result)
})
})
}
advanceBlock = () => {
return new Promise((resolve, reject) => {
web3.currentProvider.send({
jsonrpc: '2.0',
method: 'evm_mine',
id: new Date().getTime()
}, (err, result) => {
if (err) { return reject(err) }
const newBlockHash = web3.eth.getBlock('latest').hash
return resolve(newBlockHash)
})
})
}
<file_sep>/README.MD
# SecBlocks
Secblocks, shorthand for "Securities on the Blockchain" is a prototypical Implementation of a decentralized Securities Trading system on the [Ethereum](https://ethereum.org/) platform. It aims to enable retail banks to tokenize securities that already exist in the traditional system. The technical possibilities for legal compliance with the respective jurisdiction are given by expandable and configurable KYC and AML modules.
The system is written in Solidity with an Angular Frontend and builds upon the [ERC-1400 Security Token Standard](https://thesecuritytokenstandard.org/) and also implements the ERC-20 Token Standard. It also utilizes some libraries by [OpenZeppelin](https://openzeppelin.com/) and [truffle](https://www.trufflesuite.com/).
# Features
Some exemplary features include:
* Creation and Trading of Security Tokens
* [KYC](https://en.wikipedia.org/wiki/Know_your_customer)-, [Insider](https://en.wikipedia.org/wiki/Insider_trading)- and [PEP](https://en.wikipedia.org/wiki/Politically_exposed_person)- white and blacklisting, as well as custom lists
* [AML](https://en.wikipedia.org/wiki/Money_laundering#Combating) checks with regards to recipient of funds over a configurable rolling timeframe
* Voting with regards to held shares, corresponding to [shareholder voting](https://www.investor.gov/research-before-you-invest/research/shareholder-voting)
* Dividend payments for shareholders
* Extensibility of smart contracts
* Upgradeability without data loss via the [Unstructured Proxy Pattern](https://blog.openzeppelin.com/proxy-patterns/)
* Role Based Access Model
## Requirements
Use npm to install [ganache-cli](https://github.com/trufflesuite/ganache-cli), or install the [gui version](https://www.trufflesuite.com/ganache). Ganache is used to start a local Ethereum blockchain for local testing.
```bash
npm install -g ganache-cli
```
Install [truffle](https://www.trufflesuite.com/docs/truffle/overview) which is used to deploy smart contracts to a blockchain.
```bash
npm install -g truffle
```
## Usage
### Starting the System
Start a ganache chain with a mnemonic phrase. You need to use this phrase later to import the private keys of the wallet that has the initial supply of tokens into [Metamask](https://metamask.io/) or another client that you use to interact with the blockchain.
```bash
ganache-cli -m "mystery various crawl foam old often soon desk story help oil flight"
truffle migrate --reset
npm start
```
### Interacting with the System
The system can be interacted with via any Ethereum client (Geth, Parity..) by connecting to the local blockchain on port 8545, or by using the provided frontend client.
```npm start``` starts a webserver that provides an Angular frontend client. This frontend shows all methods of interaction with the smart contract system.
Initially, the first address generated by the mnemonic phrase has the "Orchestrator" role, and can set up all other roles.
In the provided deployment script, only a single exemplary token is deployed, but this can be adapted trivially.
For further descriptions of the interactions, roles and usage of the system, refer to the thesis linked below.
## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
## License
[MIT](https://choosealicense.com/licenses/mit/)
This work is released as a supplement for my Master's Thesis, which can be viewed [here](https://repositum.tuwien.at/retrieve/13070)
<file_sep>/ui/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {
MatButtonModule,
MatCardModule, MatChipsModule, MatExpansionModule,
MatFormFieldModule, MatIconModule,
MatInputModule, MatMenuModule, MatSnackBar, MatSnackBarModule,
MatToolbarModule
} from '@angular/material';
import { HeaderComponent } from './header/header.component';
import {AppRoutingModule} from "./app-routing/app-routing.module";
import {RegistryModule} from "./registry/registry.module";
import {RouterModule} from "@angular/router";
import {KycModule} from "./kyc/kyc.module";
import {TokenModule} from "./token/token.module";
import {ControllerModule} from "./controller/controller.module";
import {InsiderListModule} from "./insiderlist/insiderList.module";
import {PepListModule} from "./peplist/pepList.module";
import {Web3Service} from "./util/web3.service";
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
],
imports: [
BrowserAnimationsModule,
CommonModule,
MatButtonModule,
MatCardModule,
MatIconModule,
MatFormFieldModule,
MatInputModule,
MatToolbarModule,
BrowserModule,
FormsModule,
HttpClientModule,
RouterModule,
AppRoutingModule,
RegistryModule,
KycModule,
InsiderListModule,
PepListModule,
TokenModule,
ControllerModule,
MatMenuModule,
MatIconModule,
MatExpansionModule,
MatChipsModule,
MatSnackBarModule
],
providers: [Web3Service],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/truffle-config.js
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
networks: {
development: {
host: "127.0.0.1",
port: 8545, //7545 truffle dev, 8545 ganache-cli, 9545 ganache-gui
network_id: "*",
//gas: 7900000//default is 4712388, raised for testing
}
},
compilers: {
solc: {
version: "^0.5.2", // A version or constraint - Ex. "^0.5.0"
// Can also be set to "native" to use a native solc
optimizer: { // enable optimization as test, 200 runs is obviously not the right choice
enabled: true,
runs: 2000
}
}
}
};
<file_sep>/migrations/2_deploy_contracts.js
const KYCVerifier = artifacts.require("../contracts/Controlling/KYCVerifier.sol");
const InsiderListVerifier = artifacts.require("../contracts/Controlling/InsiderListVerifier.sol");
const PEPListVerifier = artifacts.require("../contracts/Controlling/PEPListVerifier.sol");
const TransferQueues = artifacts.require("../contracts/AML/TransferQueues.sol");
const Controller = artifacts.require("../contracts/Controlling/Controller.sol");
const Registry = artifacts.require("../contracts/registry.sol");
const UnstructuredProxy = artifacts.require("../contracts/Proxy/UnstructuredProxy.sol");
const ERC1594 = artifacts.require("../contracts/Tokens/ERC1594.sol");
const DividendToken = artifacts.require("../contracts/Tokens/DividendToken.sol");
const VotingToken = artifacts.require("../contracts/Tokens/VotingToken.sol");
const abi = require('ethereumjs-abi');
module.exports = async function (deployer) {
await deployer.deploy(KYCVerifier);
await deployer.deploy(InsiderListVerifier);
await deployer.deploy(PEPListVerifier);
await deployer.deploy(TransferQueues);
await deployer.deploy(Controller, KYCVerifier.address, InsiderListVerifier.address, PEPListVerifier.address);
await deployer.deploy(VotingToken, Controller.address, TransferQueues.address);
var registrydeployed = await deployer.deploy(Registry);
//--- Create all Subcontroller proxies ---
var kycControllerProxy = await UnstructuredProxy.at(await registrydeployed.createProxy(abi.rawEncode(['bytes32'], ['KYC'])).then((result)=>{
return result.logs[0].args.proxyAddress;
}));
kycControllerProxy.upgradeToInit(KYCVerifier.address);
var kycVerifier = await KYCVerifier.at(kycControllerProxy.address); // this line is unneccessary, proxy address could also be used if we dont need functions of the controller itself
var insiderListControllerProxy = await UnstructuredProxy.at(await registrydeployed.createProxy(abi.rawEncode(['bytes32'], ['InsiderListExampleCompany'])).then((result)=>{
return result.logs[0].args.proxyAddress;
}));
insiderListControllerProxy.upgradeToInit(InsiderListVerifier.address);
var insiderListVerifier = await InsiderListVerifier.at(insiderListControllerProxy.address);
var pepListControllerProxy = await UnstructuredProxy.at(await registrydeployed.createProxy(abi.rawEncode(['bytes32'], ['PEPList'])).then((result)=>{
return result.logs[0].args.proxyAddress;
}));
pepListControllerProxy.upgradeToInit(PEPListVerifier.address);
var pepListVerifier = await PEPListVerifier.at(pepListControllerProxy.address);
//--- create controller proxy ---
var controllerProxy = await UnstructuredProxy.at(await registrydeployed.createProxy(abi.rawEncode(['bytes32'], ['ControllerExampleCompany'])).then((result)=>{
return result.logs[0].args.proxyAddress;
}));
controllerProxy.upgradeToInit(Controller.address);
var controller = await Controller.at(controllerProxy.address);
//--- create TransferQueues proxy ---
var transferQueuesProxy = await UnstructuredProxy.at(await registrydeployed.createProxy(abi.rawEncode(['bytes32'], ['TransferQueuesExampleCompany'])).then((result)=>{
return result.logs[0].args.proxyAddress;
}));
transferQueuesProxy.upgradeToInit(TransferQueues.address);
var transferQueues = await TransferQueues.at(transferQueuesProxy.address);
// add subcontroller proxies to controller proxy
controller.setKYCVerifier(kycVerifier.address);
controller.setPEPListVerifier(pepListVerifier.address);
controller.setInsiderListVerifier(insiderListVerifier.address);
//--- Deploying the main Token contract (in real world use, this would happen for each token that is listed
var votingTokenProxy = await UnstructuredProxy.at(await registrydeployed.createProxy(abi.rawEncode(['bytes32'], ['VotingTokenExampleCompany'])).then((result)=>{
return result.logs[0].args.proxyAddress;
}));
votingTokenProxy.upgradeToInit(VotingToken.address);
var votingToken = await VotingToken.at(votingTokenProxy.address);
await transferQueues.transferOwnership(votingToken.address);
votingToken.setController(controller.address);
votingToken.setTransferQueues(transferQueues.address);
votingToken.setName(abi.rawEncode(['bytes32'], ['ExampleCompany']));
};
|
ba541efa2c0f69346962f6a662d2e7acf9f5ecc5
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 16 |
TypeScript
|
jobrot/secblocks
|
4491ffb2d468f737f91f42f08e92ca0a2136fefc
|
aa685f8d93843218124dce4579ba0e3449d35bf7
|
refs/heads/master
|
<repo_name>almokhtarbr/tdd_test<file_sep>/tests/Feature/SerieTest.php
<?php
namespace Tests\Feature;
use App\Serie;
use App\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class SerieTest extends TestCase
{
use RefreshDatabase;
public function test_see_all_series(){
$this->Admin();
$serie = factory(Serie::class)->create();
$this->get('/admin/serie')->assertStatus(200)->assertSee($serie->title);
}
public function test_show_one_serie(){
$this->Admin();
$serie = factory(Serie::class)->create();
$this->get('admin/serie/'.$serie->slug)
->assertStatus(200)
->assertSee($serie->title);
}
public function test_a_user_can_create_serie(){
$this->Admin();
Storage::fake();
$this->post(route('serie.store'),[
'title'=>'loerm ipsum',
'description'=>'loerm ipsum emit',
'image'=>UploadedFile::fake()->image('test.png')
])->assertRedirect();
Storage::disk()->assertExists('/series/'.str_slug('loerm ipsum').'.png');
$this->assertDatabaseHas('series',['slug'=>str_slug('loerm ipsum')]);
}
public function test_a_serie_must_be_with_title(){
$this->Admin();
Storage::fake();
$this->post(route('serie.store'),[
'description'=>'loerm ipsum emit',
'image'=>UploadedFile::fake()->image('test.png')
])->assertSessionHasErrors('title');
}
public function test_a_serie_must_be_with_description(){
$this->Admin();
Storage::fake();
$this->post(route('serie.store'),[
'title'=>'loerm ipsum',
'image'=>UploadedFile::fake()->image('test.png')
])->assertSessionHasErrors('description');
}
public function test_a_serie_must_be_with_image(){
$this->Admin();
Storage::fake();
$this->post(route('serie.store'),[
'title'=>'loerm ipsum',
'description'=>'loerm ipsum emit',
])->assertSessionHasErrors('image');
}
public function test_only_admin_can_create_serie(){
$this->withoutExceptionHandling();
Storage::fake();
$user = factory(User::class)->create();
$this->actingAs($user);
$this->post(route('serie.store'),[
'title'=>'loerm ipsum',
'description'=>'loerm ipsum emit',
'image'=>UploadedFile::fake()->image('test.png')
])->assertRedirect();
}
}
<file_sep>/app/Http/Requests/SerieRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Serie;
class SerieRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(){
return [
'title'=>'required',
'description'=>'required',
'image'=>'required'
];
}
public function UploadImage(){
$image = $this->image;
$this->image_name = str_slug($this->title).'.'.$image->getClientOriginalExtension();
$image->storePubliclyAs('series',$this->image_name);
return $this;
}
public function CreateSerie(){
$serie = Serie::create([
'title'=>$this->title,
'description'=>$this->description,
'image'=>$this->image_name,
'slug'=>str_slug($this->title)
]);
return redirect()->route('serie.show',$serie->slug);
}
}
<file_sep>/database/factories/SerieFactory.php
<?php
use Faker\Generator as Faker;
$factory->define(App\Serie::class, function (Faker $faker) {
$title = $faker->sentence(2);
return [
'title'=>$title,
'description'=>$faker->paragraph(3),
'slug'=>str_slug($title),
'image'=>$faker->imageUrl()
];
});
<file_sep>/tests/Feature/LessonTest.php
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Serie;
class LessonTest extends TestCase
{
use DatabaseMigrations;
public function test_a_user_can_create_lesson(){
$this->Admin();
$serie = factory(Serie::class)->create();
$lessons = [
'title'=>'hello world',
'description'=>'loerm ipsum emit world hello',
'video_number'=>112872,
'epsiode_number'=>4,
];
$this->post('/admin/'.$serie->id.'/lessons',$lessons)
->assertStatus(201)
->assertJson($lessons);
$this->assertDatabaseHas('lessons',['title'=>$lessons['title']]);
}
public function test_a_user_must_enter_a_valid_title(){
$this->Admin();
$serie = factory(Serie::class)->create();
$lessons = [
'description'=>'loerm ipsum emit world hello',
'video_number'=>112872,
'epsiode_number'=>4,
];
$this->post('/admin/'.$serie->id.'/lessons',$lessons)
->assertSessionHasErrors('title');
}
public function test_a_user_must_enter_a_valid_description(){
$this->Admin();
$serie = factory(Serie::class)->create();
$lessons = [
'title'=>'loerm ipsum ',
'video_number'=>112872,
'epsiode_number'=>4,
];
$this->post('/admin/'.$serie->id.'/lessons',$lessons)
->assertSessionHasErrors('description');
}
public function test_a_user_must_enter_a_valid_video_number(){
$this->Admin();
$serie = factory(Serie::class)->create();
$lessons = [
'title'=>'loerm ipsum ',
'description'=>'loerm ipsum emit',
'epsiode_number'=>4,
];
$this->post('/admin/'.$serie->id.'/lessons',$lessons)
->assertSessionHasErrors('video_number');
}
public function test_a_user_must_enter_a_valid_epsiode_number(){
$this->Admin();
$serie = factory(Serie::class)->create();
$lessons = [
'title'=>'loerm ipsum ',
'description'=>'loerm ipsum emit',
'video_number'=>112872,
];
$this->post('/admin/'.$serie->id.'/lessons',$lessons)
->assertSessionHasErrors('epsiode_number');
}
}
<file_sep>/app/Http/Controllers/LessonController.php
<?php
namespace App\Http\Controllers;
use App\Lesson;
use App\Serie;
use App\Http\Requests\CreateLesson;
use App\Http\Requests\UpdateLesson;
class LessonController extends Controller
{
public function index()
{
//
}
public function create()
{
//
}
public function store(Serie $serie, CreateLesson $request)
{
return $serie->lessons()->create($request->all());
}
public function show(Lesson $lesson)
{
// return view('serie.show')->with('serie',$serie);
}
public function edit(Lesson $lesson)
{
//
}
public function update(Serie $serie, Lesson $lesson, UpdateLesson $request)
{
$lesson->update($request->all());
return $lesson->fresh();
}
public function destroy(Serie $serie,Lesson $lesson)
{
$lesson->delete();
return response()->json(['message'=>'has been delted']);
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('home', 'HomeController@index')->name('home');
Route::get('register/confirm','Auth\RegisterController@fun_confirm_email')->name('confirm_email');
// that route was for testing model binding beauty (fuck)
//Route::get('admin/serie/{serie_by_id}',function (\App\Serie $serie){
// dd($serie);
//});
Route::group(['prefix'=>'admin','middleware'=>['admin']],function (){
Route::resource('/{serie_by_id}/lessons','LessonController');
Route::get('{serie_by_id}/lessons','SerieController@show');
Route::resource('serie','SerieController');
});
<file_sep>/app/Exceptions/FailedLogin.php
<?php
namespace App\Exceptions;
use Exception;
class FailedLogin extends Exception
{
public function render(){
return response()->json(['error'=>'please enter your corditionals and try again'],422);
}
}
<file_sep>/tests/Feature/LoginTest.php
<?php
namespace Tests\Feature;
use App\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class LoginTest extends TestCase
{
use DatabaseMigrations;
public function test_a_success_login(){
$user = factory(User::class)->create();
$this->postJson('/login',['name'=>$user->name,'password'=>'<PASSWORD>'])
->assertStatus(200)
->assertJson(['status'=>'ok']);
}
}
<file_sep>/resources/assets/js/app.js
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
window.Vue = require('vue');
window.events = new Vue();
window.noty = function(notification){
window.events.$emit('notification',notification);
}
window.HandleErrors = function(error){
if (error.response.status == 422) {
window.noty({
message : 'Please enter all fields and try again',
type : 'danger'
})
}else {
window.noty({
message : 'Something refresh page and try again',
type : 'warning'
})
}
}
Vue.component('example-component', require('./components/ExampleComponent.vue'));
Vue.component('vue-login', require('./components/Login.vue'));
Vue.component('all-lessons', require('./components/Lessons.vue'));
Vue.component('vue-noty',require('./components/Noty.vue'));
const app = new Vue({
el: '#app'
});
<file_sep>/app/Lesson.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Lesson extends Model
{
protected $fillable = ['title','serie_id','title','description','video_number','epsiode_number'];
public function serie(){
return $this->belongsTo(Serie::class);
}
}
<file_sep>/tests/Feature/RestrationTest.php
<?php
namespace Tests\Feature;
use App\Mail\RegisterConfirmation;
use App\User;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class RestrationTest extends TestCase
{
use RefreshDatabase ;
public function test_a_user_can_register(){
// arrangement
// action
// assert
/*
if there an error will be from db field not found
or from fillable fileds
or confirmed password remove it
or you didn't add the field to controller
*/
$this->post('/register',['name'=>'<NAME>','email'=>'<EMAIL>','password'=>'<PASSWORD>'])->assertRedirect();
$this->assertDatabaseHas('users',['username'=>'juan-doe']);
}
public function test_email_has_sent_to_newly_user(){
Mail::fake();
$this->post('/register',['name'=>'<NAME>','email'=>'<EMAIL>','password'=>'<PASSWORD>'])
->assertRedirect()
->assertSessionHas('message','please check your email to active your account');
Mail::assertSent(RegisterConfirmation::class);
}
public function test_after_registration_user_have_atoken(){
$this->post('/register',['name'=>'<NAME>','email'=>'<EMAIL>','password'=>'<PASSWORD>'])->assertRedirect();
$user = User::find(1);
$this->assertNotNull($user->confirm_email);
$this->assertFalse($user->isConfirmed());
}
public function test_user_confirm_his_email(){
$user = factory(User::class)->create();
$this->get("register/confirm?token={$user->confirm_email}")->assertStatus(302)
->assertSessionHas('success','your email has been activated');
$this->assertTrue($user->fresh()->isConfirmed());
}
public function test_if_hack_enter_nonvalid_token(){
$this->get("register/confirm?token=WRONG_TOKEN")
->assertRedirect()
->assertSessionHas('error','this token is not valid');
}
}
|
bcecac4af842b8647ff154fe244f9e0f8da1bd94
|
[
"JavaScript",
"PHP"
] | 11 |
PHP
|
almokhtarbr/tdd_test
|
3c63966e67227c9c7665db737000991ddd7d41d3
|
0ad3be5b8c8b243f6873c196de81d6a916ffd0c8
|
refs/heads/master
|
<repo_name>theriosmari/js-deli-counter-bootcamp-prep-000<file_sep>/index.js
var katzDeli = [];
function takeANumber(katzDeli, name) {
katzDeli.push(name)
return "Welcome, " + name + ". You are number " + katzDeli.length + " in line."
}
function nowServing(katzDeli) {
if (katzDeli.length === 0) {
return 'There is nobody waiting to be served!'
}
else {
return "Currently serving " + katzDeli[0] + "."
katzDeli.splice(0,1)
}
}
|
149066516ae2c15c8a11e2e8f729046166f0d3ae
|
[
"JavaScript"
] | 1 |
JavaScript
|
theriosmari/js-deli-counter-bootcamp-prep-000
|
2df49ee327d9f0663aca01adb827dcb3c0971036
|
d72620b8d7ccec3f5c35caeb11277318d7545464
|
refs/heads/master
|
<file_sep>from django.db import models
class Pokemon(models.Model):
id = models.CharField(max_length=255, default='')
spawn = models.CharField(max_length=255, default='')
lat = models.CharField(max_length=255, default='')
long = models.CharField(max_length=255, default='')
expires = models.DateTimeField(null=True)<file_sep>from django.contrib import admin
from api.models import Pokemon
admin.site.register(Pokemon)
|
fb9fe440fe9d31473c28e02976a2066ed45653db
|
[
"Python"
] | 2 |
Python
|
benjy3gg/pokelocater
|
716191fb2c8a2134ca90c8e720eabf5ec0e02b0a
|
285a74a4fbd7fad0f653f682cd6d16b5dfe1cfb6
|
refs/heads/master
|
<file_sep>package com.aggregationplatform.aggregationdatawritter.exception
import java.lang.RuntimeException
object NotFoundException: RuntimeException("Not Found")<file_sep>package com.aggregationplatform.aggregationdatawritter.service
import com.aggregationplatform.aggregationdatawritter.model.Aggregation
import com.aggregationplatform.aggregationdatawritter.model.Event
import com.aggregationplatform.aggregationdatawritter.repository.AggregationRepository
import org.springframework.stereotype.Service
@Service
class AggregationService(
private val aggregationRepository: AggregationRepository
) {
fun all(event: Event) = aggregationRepository.findByEvent(event)
}
<file_sep>package com.aggregationplatform.aggregationdatawritter.repository
import com.aggregationplatform.aggregationdatawritter.model.Event
import org.springframework.stereotype.Repository
@Repository
class EventRepository {
fun findByName(name: String) = try{
Event.valueOf(name)
}catch (e: IllegalArgumentException){
null
}
}<file_sep>package com.aggregationplatform.aggregationdatawritter.repository
import com.aggregationplatform.aggregationdatawritter.model.Aggregation
import com.aggregationplatform.aggregationdatawritter.model.Event
import org.springframework.stereotype.Repository
@Repository
class AggregationRepository {
fun findByEvent(event: Event) = Aggregation.values().filter { it.event == event }
}<file_sep>db.createUser(
{
user: "$MONGO_INITDB_ROOT_USERNAME",
pwd: "$<PASSWORD>",
roles: [
{
role: "admin",
db: "$MONGO_INITDB_DATABASE"
}
]
}
);<file_sep>package com.aggregationplatform.aggregationdatawritter.model
import com.aggregationplatform.aggregationdatawritter.model.Event.ORDER_CREATED
enum class Aggregation(
val event: Event,
val field: Field
){
ORDERS_BY_CUSTOMER(ORDER_CREATED, ORDER_CREATED.fieldByName("customerId"))
}<file_sep>package com.aggregationplatform.aggregationdatawritter.service
import com.aggregationplatform.aggregationdatawritter.exception.NotFoundException
import com.aggregationplatform.aggregationdatawritter.repository.EventRepository
import org.springframework.stereotype.Service
@Service
class EventService(
private val eventRepository: EventRepository
) {
fun get(name: String) = eventRepository.findByName(name) ?: throw NotFoundException
}<file_sep>package com.aggregationplatform.aggregationdatawritter.model
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.time.OffsetDateTime
@Document("aggregation-data")
data class AggregationData(
@Id val key: String,
val createdAt: OffsetDateTime = OffsetDateTime.now(),
val count: Int = 0
)<file_sep>package com.aggregationplatform.aggregationdatawritter.controller
import com.aggregationplatform.aggregationdatawritter.repository.AggregationDataRepository
import com.aggregationplatform.aggregationdatawritter.service.AggregationDataService
import com.aggregationplatform.aggregationdatawritter.service.AggregationService
import com.aggregationplatform.aggregationdatawritter.service.EventDataService
import com.aggregationplatform.aggregationdatawritter.service.EventService
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.*
@Controller
@RequestMapping("/v1/events/{eventName}/data")
class EventDataController(
private val eventService: EventService,
private val eventDataService: EventDataService,
private val aggregationService: AggregationService,
private val aggregationDataService: AggregationDataService,
private val aggregationDataRepository: AggregationDataRepository
) {
@GetMapping
fun all() = ResponseEntity.ok(
aggregationDataRepository.findAll()
)
@PostMapping
fun create(@PathVariable eventName: String, @RequestBody eventData: Map<String, Any>) : ResponseEntity<*>{
val event = eventService.get(eventName)
val aggregations = aggregationService.all(event)
val mappedEventData = eventDataService.parse(event, eventData)
aggregationDataService.upsert(aggregations, mappedEventData)
return ResponseEntity.ok(
mapOf("status" to "OK")
)
}
}<file_sep>package com.aggregationplatform.aggregationdatawritter.service
import com.aggregationplatform.aggregationdatawritter.exception.NotFoundException
import com.aggregationplatform.aggregationdatawritter.model.Event
import org.springframework.stereotype.Service
@Service
class EventDataService {
fun parse(event: Event, eventData: Map<String, Any>) = event.fields.map {
Pair(it.name, eventData[it.path] ?: throw NotFoundException)
}.toMap()
}<file_sep>rootProject.name = "aggregation-data-writter"
<file_sep>package com.aggregationplatform.aggregationdatawritter.service
import com.aggregationplatform.aggregationdatawritter.model.Aggregation
import com.aggregationplatform.aggregationdatawritter.model.AggregationData
import com.aggregationplatform.aggregationdatawritter.repository.AggregationDataRepository
import org.springframework.stereotype.Service
import java.lang.Exception
import java.lang.RuntimeException
@Service
class AggregationDataService(
private val aggregationDataRepository: AggregationDataRepository
) {
fun upsert(aggregations: List<Aggregation>, eventData: Map<String, Any>) = aggregations.forEach{
try{
this.upsert(it, eventData)
}catch (e: Exception){
}
}
fun upsert(aggregation: Aggregation, eventData: Map<String, Any>){
val key = "${aggregation.name.toLowerCase()}-${eventData[aggregation.field.name]}"
getByKey(key).ifPresentOrElse ({ update(it, eventData) }, { insert(key, eventData)})
}
fun insert(key: String, eventData: Map<String, Any>) {
aggregationDataRepository.insert(AggregationData(key=key))
}
fun getByKey(key: String) = aggregationDataRepository.findById(key)
fun update(aggregationData: AggregationData, eventData: Map<String, Any>){
aggregationDataRepository.save(
aggregationData.copy(count = aggregationData.count + 1)
)
}
}<file_sep>package com.aggregationplatform.aggregationdatawritter.repository
import com.aggregationplatform.aggregationdatawritter.model.AggregationData
import org.springframework.data.mongodb.repository.MongoRepository
import org.springframework.stereotype.Repository
@Repository
interface AggregationDataRepository : MongoRepository<AggregationData, String><file_sep>package com.aggregationplatform.aggregationdatawritter.model
import com.aggregationplatform.aggregationdatawritter.model.FieldType.STRING
enum class Event(
val fields: List<Field>
) {
ORDER_CREATED(
fields = listOf(
Field(name = "customerId", path = "customerId", type = STRING)
)
)
;
fun fieldByName(name: String) = fields.first { it.name == name }
}
data class Field(
val name: String,
val path: String,
val type: FieldType
)
enum class FieldType{
STRING
}
|
870a58ef00750188b56e40f96f2868d1a5082a94
|
[
"JavaScript",
"Kotlin"
] | 14 |
Kotlin
|
eduardogranetto/aggregation-platform
|
e6af2d4b4d03c36530b7bc29ffe464847738bbba
|
7884bd9f5afb67e5b45fe77485e709d37db3e726
|
refs/heads/main
|
<file_sep>package com.gmail.service;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.PriorityQueue;
import java.util.TreeSet;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class ServiceApplication {
public static void main(String[] args) throws MalformedURLException {
/*TreeSet<Domain> treeSet=new TreeSet<>();
treeSet.add(new Domain("asd","asd"));
treeSet.add(new Domain("aaa","asdjh"));
for(Domain a:treeSet) {
System.out.println(a.urlString+' '+a.titleString);
}
try {
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),
options);
PriorityQueue<String> urlQueue=new PriorityQueue<>();
driver.get("https://news.google.com/topstories?hl=en-IN&gl=IN&ceid=IN:en");
//System.out.println(driver.findElement(By.tagName("html")).getText());
List<WebElement> webElement=driver.findElements(By.tagName("a"));
displayList(webElement);
}
catch (Exception e) {
// TODO: handle exception
} */
SpringApplication.run(ServiceApplication.class, args);
}
static void displayList(List<WebElement> elementsList) {
for(WebElement element:elementsList) {
System.out.println(element.getAttribute("href"));
}
}
static class Domain implements Comparable<Domain>{
String urlString;String titleString;
public Domain(String urlString,String titleString) {
this.urlString=urlString;this.titleString=titleString;
}
@Override
public int compareTo(Domain o) {
if(this.urlString.equals(o.urlString))
return 0;
else if(this.urlString.compareTo(o.urlString)>0)
return 1;
else
return -1;
}
}
}
/**
//
*
*/
<file_sep>package com.gmail.service;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
@RestController
public class emitter {
@GetMapping("/test")
public String test() {
return "how/";
}
@GetMapping("/emitter")
@CrossOrigin(origins ="http://localhost:10")
public SseEmitter eventEmitter() {
SseEmitter emitter = new SseEmitter(); //12000 here is the timeout and it is optional
//create a single thread for sending messages asynchronously
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
try {
for (int i = 0; i < 4; i++) {
emitter.send("message" + i);
}
} catch(Exception e) {
emitter.completeWithError(e);
} finally {
emitter.complete();
}
});
executor.shutdown();
return emitter;
}
}
<file_sep># web-drivers
##### fetching news sources site trees using chrome headless browser [->](https://github.com/Spectre-ak/web-drivers/blob/main/src/main/java/com/gmail/service/ProcessorAndRController.java)
<file_sep>
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.security.auth.callback.Callback;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
public class ParallelProcessing {
public static void main(String[] args) {
// TODO Auto-generated method stub
String arr[] = {""};
seriesExecution(arr);
try {
//parallelExecution(arr);
}
catch (Exception e) {
System.out.println("execution completed ");
}
}
static ConcurrentHashMap<Integer,Integer> hm=new ConcurrentHashMap<>();
static void prallelExecutionDifference(long mills) {
System.out.println(System.currentTimeMillis()-mills);
throw new ArrayIndexOutOfBoundsException();
}
static void parallelExecution(String arr[]) {
ConcurrentHashMap<Integer,Integer> hm=new ConcurrentHashMap<>();
long beforExecution=System.currentTimeMillis();
hm.put(1,0);
int cont=0;
for(String url:arr) {
//if(ind==5)break;ind++;
cont++;
Thread t1=new Thread(new Runnable() {
@Override
public void run(){
// TODO Auto-generated method stub
try {
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),
options);
driver.get(url);
LocalDateTime now2 = LocalDateTime.now();
System.out.println(driver.getTitle());
hm.put(1,hm.get(1)+1);
if(hm.get(1)==30) {
prallelExecutionDifference(beforExecution);
}
driver.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});t1.start();
}
}
static long seriesExecution(String arr[]) {
long beforExecution=System.currentTimeMillis();
for(String url:arr) {
try {
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),
options);
driver.get(url);
LocalDateTime now2 = LocalDateTime.now();
System.out.println(driver.getTitle());
driver.close();
} catch (Exception e) {
// TODO: handle exception
}
}
return System.currentTimeMillis()-beforExecution;
}
}
/*
*
System.out.println(arr.length);
List<Callable<Void>> callablesList=new ArrayList<>();
List<String> timeStamps=Collections.synchronizedList(new ArrayList<String>());
int ind=0;
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalDateTime now2 = LocalDateTime.now();
System.out.println("Before Execution "+dtf.format(now2));
String afterReString[]=new String[1];
hm.put(1,0);
for(String url:arr) {
//if(ind==5)break;ind++;
Thread t1=new Thread(new Runnable() {
@Override
public void run(){
// TODO Auto-generated method stub
try {
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),
options);
driver.get(url);
//timeStamps.add(driver.getTitle());
LocalDateTime now2 = LocalDateTime.now();
afterReString[0]=dtf.format(now2);
System.out.println(driver.getTitle());
hm.put(1,hm.get(1)+1);
if(hm.get(1)==30) {
System.out.println("After execution "+afterReString[0]);
}
driver.close();
} catch (Exception e) {
// TODO: handle exception
}
}
});t1.start();
}
Callable<Void> callable=new Callable<Void>() {
@Override
public Void call() throws Exception {
// TODO Auto-generated method stub
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),
options);
driver.get(url);
timeStamps.add(driver.getTitle());
System.out.println(driver.getTitle());
driver.close();
return null;
}
};
callablesList.add(callable);
ExecutorService executor = Executors.newFixedThreadPool(arr.length);
try {
executor.invokeAll(callablesList);
System.out.println("completed");
System.out.println(timeStamps.size());
}
catch (Exception e) {
// TODO: handle exception
}
*/
|
7c77ca284176603fdb129b48613ad8e9e66c6534
|
[
"Markdown",
"Java"
] | 4 |
Java
|
Spectre-ak/web-drivers
|
df5d30a5a3b20d716a549addec05da21639f50f7
|
e746d322ac9cacac894750777409472f5cfbd43e
|
refs/heads/master
|
<file_sep>$('.carousel').carousel()
// filtro input
$('#search').keyup(function () {
var text = $(this).val().toLowerCase();
if(text.trim().length > 0 ){
console.log(text==educacion.name)
}
});
// filtro2
// CARRITO
|
e561ebf61becbfc84b9ae2a59c8cf36bf9ad5ce1
|
[
"JavaScript"
] | 1 |
JavaScript
|
rosColunga/e-commerce-accesible
|
da42510d93b3e324721a04e5d16b5d120dfbce65
|
1b54e1560b9cfa5f7523785b7d5e58b8287551d8
|
refs/heads/master
|
<repo_name>medusa-project/kumquat-f4<file_sep>/app/models/solr/solr.rb
module Solr
class Solr
def initialize
@http = HTTPClient.new
@url = Kumquat::Application.kumquat_config[:solr_url].chomp('/')
end
def commit
@http.get(@url + '/update?commit=true')
end
end
end<file_sep>/test/models/fedora/bytestream_test.rb
require 'test_helper'
class BytestreamTest < ActiveSupport::TestCase
# create
test 'create should respect the container_url argument' do
resource = Bytestream.create(@root_container_url)
assert resource.fedora_url.start_with?(@root_container_url)
resource.delete
end
test 'create should respect the slug argument' do
slug = 'sadfasfdasfd'
resource = Bytestream.create(@root_container_url, slug)
assert resource.fedora_url.end_with?(slug)
resource.delete
end
test 'create should respect the pathname argument' do
pathname = File.realpath(__FILE__)
resource = Bytestream.create(@root_container_url, nil, pathname)
expected = File.read(pathname)
actual = @http.get(resource.fedora_url).body
assert_equal expected, actual
resource.delete
end
test 'create_binary should respect the external_resource_url argument' do
skip # TODO: write this
end
end
<file_sep>/app/models/role.rb
##
# Encapsulates a role in a role-based access control (RBAC) system.
# A role can have zero or more permissions as well as zero or more users.
#
class Role < ActiveRecord::Base
has_and_belongs_to_many :permissions
has_and_belongs_to_many :users
validates :key, presence: true, length: { maximum: 30 },
uniqueness: { case_sensitive: false }
validates :name, presence: true, length: { maximum: 255 },
uniqueness: { case_sensitive: false }
# TODO: assign all permissions whenever the admin role is loaded
def readonly?
self.key == 'admin'
end
def to_param
key
end
def has_permission?(key)
(self.permissions.where(key: key).count > 0)
end
end
<file_sep>/app/models/contentdm/describable.rb
module Contentdm
module Describable
WEB_ID_LENGTH = 5
attr_accessor :elements # array of Elements
def initialize
self.elements = []
end
##
# @param f4_url
# @param f4_json_structure JSON-LD structure in which to embed the
# object's metadata
# @return JSON string
#
def to_json_ld(f4_url, f4_json_structure = nil)
f4_json_structure = [] unless f4_json_structure
f4_metadata = f4_json_structure.
select{ |h| h['@id'] == "#{f4_url}/fcr:metadata" }.first
unless f4_metadata
f4_metadata = { '@id' => "#{f4_url}/fcr:metadata" }
f4_json_structure << f4_metadata
end
f4_metadata['@context'] = {} unless f4_metadata.keys.include?('@context')
self.elements.each do |element|
element_name = element.name ? element.name : 'unmapped'
f4_metadata['@context'][element.namespace_prefix] = element.namespace_uri
f4_metadata["#{element.namespace_prefix}:#{element_name}"] = element.value
end
f4_metadata['@context']['kumquat'] = 'http://example.org/' # TODO: fix
f4_metadata['kumquat:web_id'] = generate_web_id
JSON.pretty_generate(f4_json_structure)
end
private
##
# Generates a guaranteed-unique web ID, of which there are
# 36^WEB_ID_LENGTH available.
#
def generate_web_id
proposed_id = nil
while true
proposed_id = (36 ** (WEB_ID_LENGTH - 1) +
rand(36 ** WEB_ID_LENGTH - 36 ** (WEB_ID_LENGTH - 1))).to_s(36)
break unless ::Item.find_by_web_id(proposed_id)
end
proposed_id
end
end
end
<file_sep>/app/models/permission.rb
##
# Encapsulates a permission in a role-based access control (RBAC) system.
# Permissions can be owned by zero or more roles and a role can have zero or
# more permissions.
#
# Permissions are basically just keys; it's up to the application to decide
# what permissions to define.
#
# To check whether a user or role has a given permission, use
# User.has_permission? or Role.has_permission?.
#
# To add a permission:
#
# 1) Assign it a constant and string value corresponding to its key
# 2) Create a Permission object with that key and save it
# 3) Add it to seed data
# 4) Add its key to the strings file(s) in config/locales
#
class Permission < ActiveRecord::Base
has_and_belongs_to_many :roles
validates :key, presence: true, length: { maximum: 255 },
uniqueness: { case_sensitive: false }
CONTROL_PANEL_ACCESS = 'control_panel.access'
ROLES_CREATE = 'roles.create'
ROLES_DELETE = 'roles.delete'
ROLES_UPDATE = 'roles.update'
SETTINGS_UPDATE = 'settings.update'
USERS_CREATE = 'users.create'
USERS_DELETE = 'users.delete'
USERS_UPDATE = 'users.update'
USERS_UPDATE_SELF = 'users.update_self'
USERS_DISABLE = 'users.disable'
USERS_ENABLE = 'users.enable'
USERS_VIEW = 'users.view'
def name
I18n.t "permission_#{key.gsub('.', '_')}"
end
def readonly?
!new_record?
end
end
<file_sep>/app/models/contentdm/local_element.rb
module Contentdm
##
# Encapsulates an "unmapped" element.
#
class LocalElement < Element
def namespace_prefix
'uiuc' # TODO: externalize
end
def namespace_uri
'http://imagesearch.library.illinois.edu/' # TODO: externalize
end
end
end
<file_sep>/app/models/fedora/resource.rb
module Fedora
class Resource
@@http = HTTPClient.new
attr_accessor :fedora_json_ld
attr_accessor :fedora_url
attr_accessor :triples
attr_accessor :uuid
def initialize(params = {})
@triples = []
params.each do |k, v|
if respond_to?("#{k}=")
send "#{k}=", v
else
instance_variable_set "@#{k}", v
end
end
end
def delete(also_tombstone = false)
url = self.fedora_url.chomp('/')
@@http.delete(url)
@@http.delete("#{url}/fcr:tombstone") if also_tombstone
end
def fedora_json_ld=(json)
@fedora_json_ld = json
struct = JSON.parse(json).select do |node|
node['@type'] and node['@type'].include?('http://www.w3.org/ns/ldp#RDFSource')
end
if struct[0]['http://example.org/web_id']
self.web_id = struct[0]['http://example.org/web_id'].first['@value'] # TODO: fix namespace
end
self.uuid = struct[0]['http://fedora.info/definitions/v4/repository#uuid'].first['@value']
# populate triples
self.triples = []
struct[0].select{ |k, v| k[0] != '@' }.each do |k, v|
v.each do |value|
self.triples << Triple.new(predicate: k, object: value['@value'],
type: value['@type'])
end
end
end
def fedora_metadata_url
"#{self.fedora_url.chomp('/')}/fcr:metadata"
end
end
end
<file_sep>/app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
before_action :signed_out_user, only: [:new, :create]
def new
end
def create
username = params[:session] ? params[:session][:username] : ''
password = params[:session] ? params[:session][:password] : ''
command = SignInCommand.new(username, password, request.remote_ip)
begin
command.execute
rescue => e
flash[:error] = "#{e}"
redirect_to signin_url
else
sign_in command.object
redirect_back_or root_url
end
end
def destroy
command = SignOutCommand.new(current_user, request.remote_ip)
command.execute
sign_out
redirect_to root_url
end
private
def signed_out_user
if signed_in?
redirect_to root_url
end
end
end
<file_sep>/app/models/fedora/repository.rb
module Fedora
class Repository
TRANSFORM_NAME = 'kumquat'
##
# Creates or updates the Fedora indexing transform used by the application.
#
# https://wiki.duraspace.org/display/FEDORA41/Indexing+Transformations
#
def apply_indexing_transform
# TODO: fix kumquat namespace
body = '@prefix fcrepo : <http://fedora.info/definitions/v4/repository#>
@prefix dc : <http://purl.org/dc/elements/1.1/>
@prefix dcterms : <http://purl.org/dc/terms/>
@prefix kumquat : <http://example.org/>
id = . :: xsd:string;
uuid = fcrepo:uuid :: xsd:string;
web_id = kumquat:web_id :: xsd:string;
dc_contributor = dc:contributor :: xsd:string;
dc_coverage = dc:coverage :: xsd:string;
dc_creator = dc:creator :: xsd:string;
dc_date = dc:date :: xsd:string;
dc_description = dc:description :: xsd:string;
dc_format = dc:format :: xsd:string;
dc_identifier = dc:identifier :: xsd:string;
dc_language = dc:language :: xsd:string;
dc_publisher = dc:publisher :: xsd:string;
dc_relation = dc:relation :: xsd:string;
dc_rights = dc:rights :: xsd:string;
dc_source = dc:source :: xsd:string;
dc_subject = dc:subject :: xsd:string;
dc_title = dc:title :: xsd:string;
dc_type = dc:type :: xsd:string;
dcterm_abstract = dcterms:abstract :: xsd:string;
dcterm_accessRights = dcterms:accessRights :: xsd:string;
dcterm_accrualMethod = dcterms:accrualMethod :: xsd:string;
dcterm_accrualPeriodicity = dcterms:accrualPeriodicity :: xsd:string;
dcterm_accrualPolicy = dcterms:accrualPolicy :: xsd:string;
dcterm_alternative = dcterms:alternative :: xsd:string;
dcterm_audience = dcterms:audience :: xsd:string;
dcterm_available = dcterms:available :: xsd:string;
dcterm_bibliographicCitation = dcterms:bibliographicCitation :: xsd:string;
dcterm_conformsTo = dcterms:conformsTo :: xsd:string;
dcterm_contributor = dcterms:contributor :: xsd:string;
dcterm_coverage = dcterms:coverage :: xsd:string;
dcterm_created = dcterms:created :: xsd:string;
dcterm_creator = dcterms:creator :: xsd:string;
dcterm_date = dcterms:date :: xsd:string;
dcterm_dateAccepted = dcterms:dateAccepted :: xsd:string;
dcterm_dateCopyrighted = dcterms:dateCopyrighted :: xsd:string;
dcterm_dateSubmitted = dcterms:dateSubmitted :: xsd:string;
dcterm_description = dcterms:description :: xsd:string;
dcterm_educationLevel = dcterms:educationLevel :: xsd:string;
dcterm_extent = dcterms:extent :: xsd:string;
dcterm_format = dcterms:format :: xsd:string;
dcterm_hasFormat = dcterms:hasFormat :: xsd:string;
dcterm_hasPart = dcterms:hasPart :: xsd:string;
dcterm_hasVersion = dcterms:hasVersion :: xsd:string;
dcterm_identifier = dcterms:identifier :: xsd:string;
dcterm_instructionalMethod = dcterms:instructionalMethod :: xsd:string;
dcterm_isFormatOf = dcterms:isFormatOf :: xsd:string;
dcterm_isPartOf = dcterms:isPartOf :: xsd:string;
dcterm_isReferencedBy = dcterms:isReferencedBy :: xsd:string;
dcterm_isReplacedBy = dcterms:isReplacedBy :: xsd:string;
dcterm_isRequiredBy = dcterms:isRequiredBy :: xsd:string;
dcterm_issued = dcterms:issued :: xsd:string;
dcterm_isVersionOf = dcterms:isVersionOf :: xsd:string;
dcterm_language = dcterms:language :: xsd:string;
dcterm_license = dcterms:license :: xsd:string;
dcterm_mediator = dcterms:mediator :: xsd:string;
dcterm_medium = dcterms:medium :: xsd:string;
dcterm_modified = dcterms:modified :: xsd:string;
dcterm_provenance = dcterms:provenance :: xsd:string;
dcterm_publisher = dcterms:publisher :: xsd:string;
dcterm_references = dcterms:references :: xsd:string;
dcterm_relation = dcterms:relation :: xsd:string;
dcterm_replaces = dcterms:replaces :: xsd:string;
dcterm_requires = dcterms:requires :: xsd:string;
dcterm_rights = dcterms:rights :: xsd:string;
dcterm_rightsHolder = dcterms:rightsHolder :: xsd:string;
dcterm_source = dcterms:source :: xsd:string;
dcterm_spatial = dcterms:spatial :: xsd:string;
dcterm_subject = dcterms:subject :: xsd:string;
dcterm_tableOfContents = dcterms:tableOfContents :: xsd:string;
dcterm_temporal = dcterms:temporal :: xsd:string;
dcterm_title = dcterms:title :: xsd:string;
dcterm_type = dcterms:type :: xsd:string;
dcterm_valid = dcterms:valid :: xsd:string;'
http = HTTPClient.new
url = "#{Kumquat::Application.kumquat_config[:fedora_url].chomp('/')}"\
"/fedora:system/fedora:transform/fedora:ldpath/#{TRANSFORM_NAME}/fedora:Container"
http.put(url, body, { 'Content-Type' => 'application/rdf+ldpath' })
end
end
end<file_sep>/app/controllers/admin/roles_controller.rb
module Admin
class RolesController < ControlPanelController
before_action :create_roles_rbac, only: [:new, :create]
before_action :delete_roles_rbac, only: :destroy
before_action :update_roles_rbac, only: [:edit, :update]
def create
command = CreateRoleCommand.new(sanitized_params, current_user,
request.remote_ip)
@role = command.object
begin
command.execute
rescue ValidationError
render 'new'
rescue => e
flash[:error] = "#{e}"
render 'new'
else
flash[:success] = "Role \"#{@role.name}\" created."
redirect_to admin_role_url(@role)
end
end
def destroy
@role = Role.find_by_key(params[:key])
raise ActiveRecord::RecordNotFound unless @role
command = DeleteRoleCommand.new(@role, current_user,
request.remote_ip)
begin
command.execute
rescue => e
flash[:error] = "#{e}"
redirect_to admin_role_url(@role)
else
flash[:success] = "Role \"#{@role.name}\" deleted."
redirect_to admin_roles_url
end
end
def edit
@role = Role.find_by_key(params[:key])
raise ActiveRecord::RecordNotFound unless @role
@users = User.order(:username)
end
def index
@roles = Role.order(:name)
end
def new
@role = Role.new
@users = User.order(:username)
end
def show
@role = Role.find_by_key(params[:key])
raise ActiveRecord::RecordNotFound unless @role
@permissions = Permission.order(:key)
end
def update
@role = Role.find_by_key(params[:key])
raise ActiveRecord::RecordNotFound unless @role
command = UpdateRoleCommand.new(@role, sanitized_params,
current_user, request.remote_ip)
begin
command.execute
rescue ValidationError
render 'edit'
rescue => e
flash[:error] = "#{e}"
render 'edit'
else
flash[:success] = "Role \"#{@role.name}\" updated."
redirect_to admin_role_url(@role)
end
end
private
def create_roles_rbac
redirect_to(admin_root_url) unless
current_user.can?(Permission::ROLES_CREATE)
end
def delete_roles_rbac
redirect_to(admin_root_url) unless
current_user.can?(Permission::ROLES_DELETE)
end
def sanitized_params
params.require(:role).permit(:key, :name, permission_ids: [],
user_ids: [])
end
def update_roles_rbac
redirect_to(admin_root_url) unless
current_user.can?(Permission::ROLES_UPDATE)
end
end
end
<file_sep>/db/migrate/20150226173239_create_rbac_relationships.rb
class CreateRbacRelationships < ActiveRecord::Migration
def change
create_table "permissions_roles", id: false, force: true do |t|
t.integer "permission_id"
t.integer "role_id"
end
create_table "roles_users", id: false, force: true do |t|
t.integer "user_id"
t.integer "role_id"
end
end
end
<file_sep>/app/controllers/items_controller.rb
class ItemsController < ApplicationController
##
# Responds to GET /items/:uuid/bytestream
#
def bytestream
item = Container.find_by_uuid(params[:item_uuid])
redirect_to item.children.first.fedora_url # TODO: improve logic
end
def index
solr = RSolr.connect(url: Kumquat::Application.kumquat_config[:solr_url])
limit = Kumquat::Application.kumquat_config[:results_per_page]
response = solr.get('select', params: {
q: params[:q] ? params[:q] : '*:*',
df: 'dc_title',
start: params[:start] ? params[:start] : 0,
rows: limit })
@num_results_shown = response['response']['docs'].length
@num_results_total = response['response']['numFound'].to_i
@items = response['response']['docs'].map do |doc|
item = Item.find(doc['id'])
item.solr_representation = doc.to_s
item
end
end
def show
@item = Item.find_by_web_id(params[:web_id])
render text: '404 Not Found', status: 404 unless @item
end
end
<file_sep>/app/commands/sign_out_command.rb
class SignOutCommand < Command
def initialize(user, remote_ip)
@user = user
@remote_ip = remote_ip
end
def execute
#@user.events << Event.create(
# description: "User #{@user.username} signed out",
# user: @user, remote_ip: @remote_ip) if @user
end
def object
@user
end
end
<file_sep>/app/commands/delete_role_command.rb
class DeleteRoleCommand < Command
def initialize(role, doing_user, remote_ip)
@role = role
@doing_user = doing_user
@remote_ip = remote_ip
end
def execute
begin
raise "#{@doing_user.username} has insufficient privileges to "\
"delete roles." unless @doing_user.has_permission?('roles.delete')
@role.destroy!
rescue => e
#Event.create(description: "Attempted to delete role "\
#"\"#{@role.name},\" but failed: #{e.message}",
# user: @doing_user, remote_ip: @remote_ip,
# event_level: EventLevel::ERROR)
raise "Failed to delete role: #{e.message}"
else
#Event.create(description: "Deleted role \"#{@role.name}\"",
# user: @doing_user, remote_ip: @remote_ip)
end
end
def object
@role
end
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
validates :username, presence: true, length: { maximum: 255 },
uniqueness: { case_sensitive: false },
format: { with: /\A(?=.*[a-z])[a-z\d]+\Z/i,
message: 'Only letters and numbers are allowed.' }
def to_param
username
end
def has_permission?(key)
self.roles_having_permission(key).any?
end
alias_method :can?, :has_permission?
def is_admin?
(self.roles.where(key: 'admin').count > 0)
end
def roles_having_permission(key)
self.roles.select{ |r| r.has_permission?(key) }
end
end
<file_sep>/lib/tasks/kumquat.rake
namespace :kumquat do
desc 'Import content from CONTENTdm'
task :cdm_import, [:source_path] => :environment do |task, args|
importer = ContentdmImporter.new(args[:source_path])
importer.import
end
end
<file_sep>/app/services/contentdm_importer.rb
class ContentdmImporter
##
# @param source_path Path to the source CONTENTdm content folder
#
def initialize(source_path)
@source_path = source_path
@root_container_url = Kumquat::Application.kumquat_config[:fedora_url]
@http = HTTPClient.new
@solr = Solr::Solr.new
end
def import
catalog_pathname = File.join(File.expand_path(@source_path), 'catalog.txt')
File.open(catalog_pathname) do |file|
file.each_line do |line|
parts = line.gsub(/\t+/, "\t").split("\t")
col_alias = parts.first.strip
if col_alias[0] != '#'
collection_folder_pathname = File.join(
File.expand_path(@source_path), col_alias)
next unless File.directory?(collection_folder_pathname)
metadata_pathname = "#{collection_folder_pathname}.xml"
raise "#{File.basename(metadata_pathname)} is missing." unless
File.exists?(metadata_pathname)
self.import_collection(
Contentdm::Collection.with_alias(col_alias, @source_path))
end
end
end
end
##
# Ingests a collection and all of its items.
#
# @param collection Contentdm::Collection
#
def import_collection(collection)
puts "Ingesting #{collection.name} (#{collection.alias})"
# delete any old collection containers
url = "#{@root_container_url}/#{collection.slug}"
@http.delete(url) rescue nil
@http.delete("#{url}/fcr:tombstone") rescue nil
# create a new collection container
container = Fedora::Container.create(@root_container_url, collection.slug)
# GET the newly created container's JSON-LD representation
struct = JSON.parse(container.fedora_json_ld)
# append metadata to the JSON-LD representation via PUT
@http.put(container.fedora_metadata_url,
collection.to_json_ld(container.fedora_url, struct),
{ 'Content-Type' => 'application/ld+json' })
File.open(File.join(File.expand_path(@source_path),
collection.alias + '.xml')) do |file|
doc = Nokogiri::XML(file)
doc.xpath('//record').each do |record|
item = Contentdm::Item.from_cdm_xml(@source_path, collection, record)
self.import_item(item, container.fedora_url)
end
end
end
##
# Ingests an item and all of its pages (if a compound object).
#
# @param item Contentdm::Item
# @param container_url string
# @param make_indexable boolean
# @return string Resource URL from response Location header
#
def import_item(item, container_url, make_indexable = true)
puts "#{item.collection.alias} #{item.pointer}"
# create a new item container
container = Fedora::Container.create(container_url, item.slug)
# GET the newly created container's JSON-LD representation
struct = JSON.parse(container.fedora_json_ld)
# append metadata to the JSON-LD representation via PUT
@http.put(container.fedora_metadata_url,
item.to_json_ld(container.fedora_url, struct),
{ 'Content-Type' => 'application/ld+json' })
container.make_indexable if make_indexable
# create a binary resource for the item's bytestream within the item
# container
pathname = item.pages.any? ? nil : item.master_file_pathname
if item.url
Fedora::Bytestream.create(container.fedora_url, nil, nil, item.url)
elsif pathname and File.exists?(pathname)
Fedora::Bytestream.create(container.fedora_url, nil, pathname)
end
@solr.commit
item.pages.each { |p| self.import_item(p, container.fedora_url, false) }
container.fedora_url
end
end<file_sep>/app/commands/sign_in_command.rb
class SignInFailure < RuntimeError
def public_message
@public_message
end
def public_message=(msg)
@public_message = msg
end
end
class SignInCommand < Command
DEVELOPMENT_PASSWORD = '<PASSWORD>'
def initialize(username, password, remote_ip)
@username = username.chomp
@password = <PASSWORD>
@remote_ip = remote_ip
@user = nil
end
def execute
begin
@user = authenticate(@username, @password)
if @user
else
public_message = 'Sign-in failed.'
log_message = "Sign-in failed for #{@username}: invalid username "\
"or password."
ex = SignInFailure.new(log_message)
ex.public_message = public_message
raise ex
end
rescue SignInFailure => e
#@user.events << Event.create(
# description: "#{e}", user: @user, remote_ip: @remote_ip,
# event_level: EventLevel::NOTICE)
raise "#{e.public_message}"
rescue => e
#@user.events << Event.create(
# description: "#{e}", user: @user, remote_ip: @remote_ip,
# event_level: EventLevel::NOTICE)
raise e
else
#@user.events << Event.create(
# description: "User #{@user.username} signed in",
# user: @user, remote_ip: @remote_ip)
end
end
def object
@user
end
private
##
# @param username string
# @param password string
# @return User or nil depending on whether authentication was successful
#
def authenticate(username, password)
user = User.find_by_username(username.downcase)
if user
if 1 == 2 # TODO: replace with e.g. Shibboleth auth result
# noop
elsif Rails.env.development? and @password == DEVELOPMENT_PASSWORD
# noop
else
user = nil
end
end
user
end
end
<file_sep>/test/models/fedora/container_test.rb
require 'test_helper'
class ContainerTest < ActiveSupport::TestCase
test 'initializer should work' do
url = 'http://example.org/'
container = Container.new(fedora_url: url)
assert_equal(url, container.fedora_url)
end
# create
test 'create should respect the container_url argument' do
resource = Container.create(@root_container_url)
assert resource.fedora_url.start_with?(@root_container_url)
resource.delete
end
test 'create_container should respect the slug argument' do
slug = 'dfgdgfsdfgsdfg'
resource = Container.create(@root_container_url, slug)
assert resource.fedora_url.end_with?(slug)
resource.delete
end
# make_indexable
test 'make_indexable should make a container indexable' do
resource = Container.create(@root_container_url)
resource.make_indexable
response = @http.get(resource.fedora_url)
assert response.body.include?('indexable:Indexable')
resource.delete
end
end
<file_sep>/README-CONTENTdm.md
# Importing from CONTENTdm
## Features
* CONTENTdm collections are imported as Fedora 4 container nodes.
* CONTENTdm items are imported as F4 container nodes within their collection
node.
* CONTENTdm master bytestreams (files) are imported into a sub-node of their
item node.
* CONTENTdm compound object pages are imported as item nodes within their
parent item container node.
* CONTENTdm "URL items" are imported as F4 "binary resources redirecting to
external content," which work pretty much the same.
* Most descriptive metadata is preserved for items, collections, compound
objects, and compound object pages.
* Dublin Core metadata is imported into the appropriate namespace:
`http://purl.org/dc/elements/1.1/` or `http://purl.org/dc/terms/`.
* Local "unmapped" metadata is imported into a local namespace.
The resulting F4 node structure looks like this:
(parent node)
(collection 1 node)
(item 1 node)
(binary node)
(item 2 node)
(binary node)
(item 3 node)
(external binary node [for "URL items"])
(compound object node)
(page 1 node)
(binary node)
(page 2 node)
(binary node)
(collection 2 node)
...
## Notes & caveats
* "Full text" is skipped.
* Custom Dublin Core "field names" will be lost. For example, a field called
"Costume Name" mapped to the DC "title" element will become simply "Title."
* Unmapped elements will be assigned a name of "unmapped".
* Only one level of compound object structure will be imported.
* CONTENTdm field settings like searchable, hidden, etc. are ignored. (These
would either work differently or are not applicable to F4.)
## Instructions
1. The CONTENTdm source data should be a folder containing one or more
CONTENTdm collection folders, alongside XML metadata files exported from the
CONTENTdm administration module in "CONTENTdm Standard XML format including
all page-level metadata." Collection folders and XML files should be named
according to the collection's alias, like this:
source_folder/
collection1/ <-- Collection folder
collection1.xml <-- Collection's exported metadata
collection2/
collection2.xml
catalog.txt <-- CONTENTdm catalog.txt file
(The `catalog.txt` file can be found in the CONTENTdm web server's document
root. To skip certain collections, comment them out with a pound (`#`)
sign.)
2. Run `bundle exec rake kumquat:cdm_import[/path/to/source/data]`. This task
will output status information for each item.
This command will delete old collection node (and all child nodes) before
adding new ones, thus cleaning up after itself, but the generated "web IDs"
will be different, thus breaking public URLs. This is, for the time being
anyway, a one-shot importer.
<file_sep>/app/models/fedora/bytestream.rb
module Fedora
class Bytestream < Resource
attr_accessor :fedora_uri
attr_accessor :media_type
##
# @param container_url URL of the parent container
# @param pathname Optional file to upload into a child binary resource
# @param slug Optional URL slug
# @param external_resource_url string
# @return Bytestream
#
def self.create(container_url, slug = nil, pathname = nil,
external_resource_url = nil)
slug_url = slug ? "#{container_url}/#{slug}" : container_url
response = nil
if pathname
File.open(pathname) do |file|
response = slug ? @@http.put(slug_url, file) :
@@http.post(container_url, file)
end
elsif external_resource_url
response = @@http.post(container_url, nil,
{ 'Content-Type' => 'text/plain' })
headers = { 'Content-Type' => "message/external-body; "\
"access-type=URL; URL=\"#{external_resource_url}\"" }
response = @@http.put(response.header['Location'].first, nil, headers)
else
response = slug ? @@http.put(slug_url) : @@http.post(container_url)
end
Bytestream.new(fedora_url: response.header['Location'].first)
end
end
end
<file_sep>/app/commands/create_role_command.rb
class CreateRoleCommand < Command
def initialize(role_params, doing_user, remote_ip)
@role_params = role_params
@doing_user = doing_user
@remote_ip = remote_ip
@role = Role.new(role_params)
end
def execute
begin
raise "#{@doing_user.username} has insufficient privileges to "\
"create roles." unless @doing_user.has_permission?('roles.create')
@role.save!
rescue ActiveRecord::RecordInvalid => e
#Event.create(description: "Attempted to create role, but failed: "\
#"#{@role.errors.full_messages[0]}",
# user: @doing_user, remote_ip: @remote_ip,
# event_level: EventLevel::DEBUG)
#raise "Failed to create role: #{@role.errors.full_messages[0]}"
rescue => e
#Event.create(description: "Attempted to create role, but failed: "\
#"#{e.message}",
# user: @doing_user, remote_ip: @remote_ip,
# event_level: EventLevel::ERROR)
raise ValidationError, "Failed to create role: #{e.message}"
else
#Event.create(description: "Created role \"#{@role.name}\"",
# user: @doing_user, remote_ip: @remote_ip)
end
end
def object
@role
end
end
<file_sep>/app/controllers/admin/control_panel_controller.rb
module Admin
class ControlPanelController < ApplicationController
layout 'admin/application'
before_filter :signed_in_user, :can_access_control_panel
private
def can_access_control_panel
unless current_user.has_permission?('control_panel.access')
flash['error'] = 'Access denied.'
redirect_to root_url
end
end
end
end
<file_sep>/app/models/contentdm/item.rb
module Contentdm
class Item
include Describable
DC_ELEMENTS_TO_IMPORT = %w(abstract accessRights accrualMethod
accrualPeriodicity accrualPolicy alternative audience available
bibliographicCitation conformsTo contributor coverage created creator date
dateAccepted dateCopyrighted dateSubmitted description educationLevel
extent format hasFormat hasPart hasVersion identifier instructionalMethod
isFormatOf isPartOf isReferencedBy isReplacedBy isRequiredBy issued
isVersionOf language license mediator medium modified provenance publisher
relation references relation replaces requires rights rightsHolder source
spatial subject tableOfContents temporal title type valid)
attr_accessor :collection # Collection
attr_accessor :created # string date, yyyy-mm-dd
attr_accessor :filename # string
attr_accessor :full_text # string
attr_accessor :pages # array of Items
attr_accessor :pointer # integer
attr_accessor :source_path # string
attr_accessor :updated # string date, yyyy-mm-dd
attr_accessor :url # CONTENTdm redirect-to-URL
##
# Builds an item from its CONTENTdm XML representation.
#
# @param source_path string
# @param collection Collection
# @param fragment Nokogiri XML node
# @return Item
#
def self.from_cdm_xml(source_path, collection, node)
source_path = File.expand_path(source_path)
item = Item.new
item.collection = collection
item.pointer = node.xpath('cdmid').first.content
item.filename = node.xpath('cdmfile').first.content
item.created = node.xpath('cdmcreated').first.content
item.updated = node.xpath('cdmmodified').first.content
item.source_path = source_path
# populate metadata
item.elements = elements_from_xml(node)
# populate pages
page_nodes = node.xpath('structure/page')
if page_nodes.any?
cpd_pathname = File.join(source_path, collection.alias, 'image',
item.filename)
File.open(cpd_pathname) do |file|
cpd_doc = Nokogiri::XML(file)
page_nodes.each do |page_elem|
page = Item.new
page.collection = collection
page.pointer = page_elem.xpath('pageptr').first.content
page.elements = elements_from_xml(node)
page.full_text = page_elem.xpath('pagetext').first.content.strip
page.filename = cpd_doc.
xpath("//page[pageptr = #{page.pointer}]/pagefile").first.content
page.source_path = File.join(source_path, collection.alias,
'image', page.filename)
item.pages << page
end
end
end
# populate URL
if File.extname(item.filename) == '.url'
File.open(item.master_file_pathname) do |file|
file.each_line do |line|
if line.include?('http://')
item.url = line.gsub('URL=', '').strip
break
end
end
end
end
item
end
def initialize
super
self.pages = []
end
def master_file_pathname
File.join(File.expand_path(self.source_path), collection.alias, 'image',
self.filename)
end
def slug
self.pointer.to_s
end
private
def self.elements_from_xml(node)
elements = []
node.children.each do |child_node|
if DC_ELEMENTS_TO_IMPORT.include?(child_node.name)
unless child_node.content.empty?
elements << DCElement.new(name: child_node.name,
value: child_node.content)
end
elsif child_node.name == 'unmapped'
elements << LocalElement.new(value: child_node.content)
end
end
elements
end
end
end
<file_sep>/app/controllers/admin/users_controller.rb
module Admin
class UsersController < ControlPanelController
before_action :view_users_rbac, only: [:index, :show]
def index
q = "%#{params[:q]}%"
@users = User.where('users.username LIKE ?', q).order('username') # TODO: paginate
end
def show
@user = User.find_by_username params[:username]
raise ActiveRecord::RecordNotFound unless @user
@permissions = Permission.order(:key)
end
private
def view_users_rbac
redirect_to(admin_root_url) unless
current_user.can?(Permission::USERS_VIEW)
end
end
end<file_sep>/app/assets/javascripts/kumquat.js
var Kumquat = {
Flash: {
FADE_OUT_DELAY: 10000,
/**
* @param text
* @param type Value of the X-Kumquat-Message-Type header
* @return void
*/
set: function(text, type) {
var bootstrap_class;
switch (type) {
case 'success':
bootstrap_class = 'alert-success';
break;
case 'error':
bootstrap_class = 'alert-danger';
break;
case 'alert':
bootstrap_class = 'alert-block';
break;
default:
bootstrap_class = 'alert-info';
break;
}
// remove any existing messages
$('div.kq-flash').remove();
// construct the message
var flash = $('<div class="kq-flash alert ' + bootstrap_class + '"></div>');
var button = $('<button type="button" class="close"' +
' data-dismiss="alert" aria-hidden="true">×</button>');
flash.append(button);
button.after(text);
// append the flash to the DOM
$('div.container header, div.container-fluid header').after(flash);
// make it disappear after a delay
setTimeout(function() {
flash.fadeOut();
}, Kumquat.Flash.FADE_OUT_DELAY);
}
},
/**
* Application-level initialization.
*/
init: function() {
// make flash messages disappear after a delay
var flash = $('div.kq-flash');
if (flash.length) {
setTimeout(function () {
flash.fadeOut();
}, Kumquat.Flash.FADE_OUT_DELAY);
}
}
};
var ready = function() {
Kumquat.init();
};
$(document).ready(ready);
$(document).on('page:load', ready);
<file_sep>/app/models/contentdm/collection.rb
module Contentdm
class Collection
include Describable
# map of colldesc.txt tag names (first 3 characters) to DC element names
TAG_DC_MAP = {
'aud' => 'audience',
'con' => 'contributor',
'cov' => 'coverage',
'cre' => 'creator',
'dat' => 'date',
'des' => 'description',
'for' => 'format',
'ide' => 'identifier',
'lan' => 'language',
'pub' => 'publisher',
'rel' => 'relation',
'rig' => 'rights',
'sou' => 'source',
'sub' => 'subject',
'tit' => 'title',
'typ' => 'type'
}
attr_accessor :alias
##
# @param alias_ CONTENTdm collection alias
# @param source_path
# @return Collection
#
def self.with_alias(alias_, source_path)
collection = Collection.new
collection.alias = alias_.gsub('/', '')
# Extract the collection's Dublin Core properties from the colldesc.txt
# file, which despite its name is actually a pseudo-XML file with no root
# element.
desc_pathname = File.join(File.expand_path(source_path),
collection.alias, 'index', 'etc', 'colldesc.txt')
catalog_pathname = File.join(File.expand_path(source_path), 'catalog.txt')
if File.exists?(desc_pathname)
File.open(desc_pathname) do |file|
string = "<?xml version=\"1.0\"?><xml>#{file.readlines}</xml>"
doc = Nokogiri::XML(string)
doc.xpath('/xml/*').each do |node|
element = DCElement.new(
name: TAG_DC_MAP[node.name[0..2]], value: node.text)
collection.elements << element unless element.value.empty?
end
end
elsif File.exists?(catalog_pathname)
# Not all collections have a colldesc.txt file, so use the catalog.txt
# file (which contains only the collection's name) as a fallback.
File.open(catalog_pathname) do |file|
file.each_line do |line|
parts = line.gsub(/\t+/, "\t").split("\t")
if parts.first == "/#{collection.alias}"
element = DCElement.new(name: 'title', value: parts[1].strip)
collection.elements << element unless element.value.empty?
break
end
end
end
else
collection.elements << DCElement.new(
name: 'title', value: "CONTENTdm collection (#{collection.alias})")
end
collection
end
##
# @return The value of the collection's DC title element
#
def name
element = self.elements.select{ |e| e.name == 'title' }.first
element ? element.value : nil
end
def slug
self.alias
end
end
end
<file_sep>/app/models/triple.rb
class Triple
# the subject is implicitly the owning object, e.g. an Item
attr_accessor :object
attr_accessor :predicate
attr_accessor :type
alias_method :value, :object
alias_method :name, :predicate
LABELS = {
'http://purl.org/dc/elements/1.1/contributor' => 'Contributor',
'http://purl.org/dc/elements/1.1/coverage' => 'Coverage',
'http://purl.org/dc/elements/1.1/creator' => 'Creator',
'http://purl.org/dc/elements/1.1/date' => 'Date',
'http://purl.org/dc/elements/1.1/description' => 'Description',
'http://purl.org/dc/elements/1.1/format' => 'Format',
'http://purl.org/dc/elements/1.1/identifier' => 'Identifier',
'http://purl.org/dc/elements/1.1/language' => 'Language',
'http://purl.org/dc/elements/1.1/publisher' => 'Publisher',
'http://purl.org/dc/elements/1.1/relation' => 'Relation',
'http://purl.org/dc/elements/1.1/rights' => 'Rights',
'http://purl.org/dc/elements/1.1/source' => 'Source',
'http://purl.org/dc/elements/1.1/subject' => 'Subject',
'http://purl.org/dc/elements/1.1/title' => 'Title',
'http://purl.org/dc/elements/1.1/type' => 'Type',
'http://purl.org/dc/terms/abstract' => 'Abstract',
'http://purl.org/dc/terms/accessRights' => 'Access Rights',
'http://purl.org/dc/terms/accrualMethod' => 'Accrual Method',
'http://purl.org/dc/terms/accrualPeriodicity' => 'Accrual Periodicity',
'http://purl.org/dc/terms/accrualPolicy' => 'Accrual Policy',
'http://purl.org/dc/terms/alternative' => 'Alternative Title',
'http://purl.org/dc/terms/audience' => 'Audience',
'http://purl.org/dc/terms/available' => 'Date Available',
'http://purl.org/dc/terms/bibliographicCitation' => 'Bibliographic Citation',
'http://purl.org/dc/terms/conformsTo' => 'Conforms To',
'http://purl.org/dc/terms/contributor' => 'Contributor',
'http://purl.org/dc/terms/coverage' => 'Coverage',
'http://purl.org/dc/terms/created' => 'Created',
'http://purl.org/dc/terms/creator' => 'Creator',
'http://purl.org/dc/terms/date' => 'Date',
'http://purl.org/dc/terms/dateAccepted' => 'Date Accepted',
'http://purl.org/dc/terms/dateCopyrighted' => 'Date Copyrighted',
'http://purl.org/dc/terms/dateSubmitted' => 'Date Submitted',
'http://purl.org/dc/terms/description' => 'Description',
'http://purl.org/dc/terms/educationLevel' => 'Audience Education Level',
'http://purl.org/dc/terms/extent' => 'Extent',
'http://purl.org/dc/terms/format' => 'Format',
'http://purl.org/dc/terms/hasFormat' => 'Has Format',
'http://purl.org/dc/terms/hasPart' => 'Has Part',
'http://purl.org/dc/terms/hasVersion' => 'Has Version',
'http://purl.org/dc/terms/identifier' => 'Identifier',
'http://purl.org/dc/terms/instructionalMethod' => 'Instructional Method',
'http://purl.org/dc/terms/isFormatOf' => 'Is Format Of',
'http://purl.org/dc/terms/isPartOf' => 'Is Part Of',
'http://purl.org/dc/terms/isReferencedBy' => 'Is Referenced By',
'http://purl.org/dc/terms/isReplacedBy' => 'Is Replaced By',
'http://purl.org/dc/terms/isRequiredBy' => 'Is Required By',
'http://purl.org/dc/terms/issued' => 'Issued',
'http://purl.org/dc/terms/isVersionOf' => 'Is Version Of',
'http://purl.org/dc/terms/language' => 'Language',
'http://purl.org/dc/terms/license' => 'License',
'http://purl.org/dc/terms/mediator' => 'Mediator',
'http://purl.org/dc/terms/medium' => 'Medium',
'http://purl.org/dc/terms/modified' => 'Date Modified',
'http://purl.org/dc/terms/provenance' => 'Provenance',
'http://purl.org/dc/terms/publisher' => 'Publisher',
'http://purl.org/dc/terms/references' => 'References',
'http://purl.org/dc/terms/relation' => 'Relation',
'http://purl.org/dc/terms/replaces' => 'Replaces',
'http://purl.org/dc/terms/requires' => 'Requires',
'http://purl.org/dc/terms/rights' => 'Rights',
'http://purl.org/dc/terms/rightsHolder' => 'Rights Holder',
'http://purl.org/dc/terms/source' => 'Source',
'http://purl.org/dc/terms/spatial' => 'Spatial',
'http://purl.org/dc/terms/subject' => 'Subject',
'http://purl.org/dc/terms/tableOfContents' => 'Table Of Contents',
'http://purl.org/dc/terms/temporal' => 'Temporal Coverage',
'http://purl.org/dc/terms/title' => 'Title',
'http://purl.org/dc/terms/type' => 'Type',
'http://purl.org/dc/terms/valid' => 'Date Valid'
}
def initialize(params = {})
params.each do |k, v|
if respond_to?("#{k}=")
send "#{k}=", v
else
instance_variable_set "@#{k}", v
end
end
end
def label
LABELS[self.predicate] ? LABELS[self.predicate] : ''
end
end
<file_sep>/app/commands/update_role_command.rb
class UpdateRoleCommand < Command
def initialize(role, role_params, doing_user, remote_ip)
@role = role
@role_params = role_params
@doing_user = doing_user
@remote_ip = remote_ip
end
def execute
begin
raise "#{@doing_user.username} has insufficient privileges to "\
"update roles." unless @doing_user.has_permission?(Permission::ROLES_UPDATE)
@role.update!(@role_params)
rescue ActiveRecord::RecordInvalid => e
#Event.create(description: "Attempted to update role "\
#"\"#{@role.name},\" but failed: "\
#"#{@role.errors.full_messages[0]}",
# user: @doing_user, remote_ip: @remote_ip,
# event_level: EventLevel::DEBUG)
raise ValidationError, "Failed to update role \"#{@role.name}\": "\
"#{@role.errors.full_messages[0]}"
rescue => e
#Event.create(description: "Attempted to update role "\
#"\"#{@role.name},\" but failed: #{e.message}",
# user: @doing_user, remote_ip: @remote_ip,
# event_level: EventLevel::ERROR)
raise "Failed to update role \"#{@role.name}\": #{e.message}"
else
#Event.create(description: "Updated role \"#{@role.name}\"",
# user: @doing_user, remote_ip: @remote_ip)
end
end
def object
@role
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).
# Roles
roles = {}
roles[:admin] = Role.create!(key: 'admin', name: 'Administrators')
roles[:cataloger] = Role.create!(key: 'cataloger', name: 'Catalogers')
roles[:everybody] = Role.create!(key: 'everybody', name: 'Everybody')
# Permissions
Permission.create!(key: 'control_panel.access',
roles: [roles[:admin], roles[:cataloger]])
Permission.create!(key: 'roles.create',
roles: [roles[:admin]])
Permission.create!(key: 'roles.delete',
roles: [roles[:admin]])
Permission.create!(key: 'roles.update',
roles: [roles[:admin]])
Permission.create!(key: 'settings.update',
roles: [roles[:admin]])
Permission.create!(key: 'users.create',
roles: [roles[:admin]])
Permission.create!(key: 'users.delete',
roles: [roles[:admin]])
Permission.create!(key: 'users.update',
roles: [roles[:admin]])
Permission.create!(key: 'users.update_self',
roles: [roles[:admin], roles[:everybody]])
Permission.create!(key: 'users.disable',
roles: [roles[:admin]])
Permission.create!(key: 'users.enable',
roles: [roles[:admin]])
Permission.create!(key: 'users.view',
roles: [roles[:admin], roles[:cataloger]])
if Rails.env.development?
# Users
users = {}
users[:admin] = User.create!(
username: 'admin',
roles: [roles[:admin]])
users[:cataloger] = User.create!(
username: 'cataloger',
roles: [roles[:cataloger]])
users[:disabled] = User.create!(
username: 'disabled',
roles: [roles[:cataloger]])
end
<file_sep>/app/models/fedora/container.rb
module Fedora
##
# A container is a Fedora resource that may contain metadata and other
# resources but cannot be associated with a bytestream.
#
class Container < Resource
attr_reader :children
attr_accessor :web_id
##
# @param container_url URL of the parent container
# @param slug Optional URL slug
# @return Container
#
def self.create(container_url, slug = nil)
slug_url = slug ? "#{container_url}/#{slug}" : container_url
response = slug ? @@http.put(slug_url) : @@http.post(container_url)
find(response.header['Location'].first)
end
##
# @param uri Fedora resource URI
# @return Container
#
def self.find(uri)
response = @@http.get(uri, nil, { 'Accept' => 'application/ld+json' })
item = Container.new(fedora_url: uri)
item.fedora_json_ld = response.body
item
end
def initialize(params = {})
@children = []
super(params)
end
def fedora_json_ld=(json_ld)
super(json_ld)
# populate bytestreams
struct = JSON.parse(json_ld).select do |node|
node['@type'] and node['@type'].include?('http://www.w3.org/ns/ldp#RDFSource')
end
if struct[0]['http://www.w3.org/ns/ldp#contains']
struct[0]['http://www.w3.org/ns/ldp#contains'].each do |node|
@children << Bytestream.new(fedora_url: node['@id']) # TODO: make this either a Bytestream or Container
end
end
end
def make_indexable
url = "#{self.fedora_url}/fcr:metadata"
headers = { 'Content-Type' => 'application/sparql-update' }
body = 'PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> '\
'PREFIX indexing: <http://fedora.info/definitions/v4/indexing#> '\
'DELETE { } '\
'INSERT { '\
"<> indexing:hasIndexingTransformation \"#{Fedora::Repository::TRANSFORM_NAME}\"; "\
'rdf:type indexing:Indexable; } '\
'WHERE { }'
@@http.patch(url, body, headers)
end
end
end
<file_sep>/app/models/contentdm/dc_element.rb
module Contentdm
class DCElement < Element
URIS = [
'http://purl.org/dc/elements/1.1/contributor',
'http://purl.org/dc/elements/1.1/coverage',
'http://purl.org/dc/elements/1.1/creator',
'http://purl.org/dc/elements/1.1/date',
'http://purl.org/dc/elements/1.1/description',
'http://purl.org/dc/elements/1.1/format',
'http://purl.org/dc/elements/1.1/identifier',
'http://purl.org/dc/elements/1.1/language',
'http://purl.org/dc/elements/1.1/publisher',
'http://purl.org/dc/elements/1.1/relation',
'http://purl.org/dc/elements/1.1/rights',
'http://purl.org/dc/elements/1.1/source',
'http://purl.org/dc/elements/1.1/subject',
'http://purl.org/dc/elements/1.1/title',
'http://purl.org/dc/elements/1.1/type',
'http://purl.org/dc/terms/abstract',
'http://purl.org/dc/terms/accessRights',
'http://purl.org/dc/terms/accrualMethod',
'http://purl.org/dc/terms/accrualPeriodicity',
'http://purl.org/dc/terms/accrualPolicy',
'http://purl.org/dc/terms/alternative',
'http://purl.org/dc/terms/audience',
'http://purl.org/dc/terms/available',
'http://purl.org/dc/terms/bibliographicCitation',
'http://purl.org/dc/terms/conformsTo',
'http://purl.org/dc/terms/contributor',
'http://purl.org/dc/terms/coverage',
'http://purl.org/dc/terms/created',
'http://purl.org/dc/terms/creator',
'http://purl.org/dc/terms/date',
'http://purl.org/dc/terms/dateAccepted',
'http://purl.org/dc/terms/dateCopyrighted',
'http://purl.org/dc/terms/dateSubmitted',
'http://purl.org/dc/terms/description',
'http://purl.org/dc/terms/educationLevel',
'http://purl.org/dc/terms/extent',
'http://purl.org/dc/terms/format',
'http://purl.org/dc/terms/hasFormat',
'http://purl.org/dc/terms/hasPart',
'http://purl.org/dc/terms/hasVersion',
'http://purl.org/dc/terms/identifier',
'http://purl.org/dc/terms/instructionalMethod',
'http://purl.org/dc/terms/isFormatOf',
'http://purl.org/dc/terms/isPartOf',
'http://purl.org/dc/terms/isReferencedBy',
'http://purl.org/dc/terms/isReplacedBy',
'http://purl.org/dc/terms/isRequiredBy',
'http://purl.org/dc/terms/issued',
'http://purl.org/dc/terms/isVersionOf',
'http://purl.org/dc/terms/language',
'http://purl.org/dc/terms/license',
'http://purl.org/dc/terms/mediator',
'http://purl.org/dc/terms/medium',
'http://purl.org/dc/terms/modified',
'http://purl.org/dc/terms/provenance',
'http://purl.org/dc/terms/publisher',
'http://purl.org/dc/terms/references',
'http://purl.org/dc/terms/relation',
'http://purl.org/dc/terms/replaces',
'http://purl.org/dc/terms/requires',
'http://purl.org/dc/terms/rights',
'http://purl.org/dc/terms/rightsHolder',
'http://purl.org/dc/terms/source',
'http://purl.org/dc/terms/spatial',
'http://purl.org/dc/terms/subject',
'http://purl.org/dc/terms/tableOfContents',
'http://purl.org/dc/terms/temporal',
'http://purl.org/dc/terms/title',
'http://purl.org/dc/terms/type',
'http://purl.org/dc/terms/valid'
]
def namespace_prefix
self.namespace_uri.include?('/dc/terms') ? 'dcterms' : 'dc'
end
def namespace_uri
parts = URIS.select{ |u| u.include?(self.name) }.first.split('/')
parts[0..(parts.length - 2)].join('/') + '/'
end
end
end
<file_sep>/config/initializers/kumquat.rb
Kumquat::Application.kumquat_config =
YAML.load_file(File.join(Rails.root, 'config', 'kumquat.yml'))[Rails.env]
# create/update the Fedora indexing transformation needed by the application
Rails.logger.info 'Creating Fedora indexing transform (config/initializers/kumquat.rb)'
begin
Fedora::Repository.new.apply_indexing_transform
rescue HTTPClient::BadResponseError => e
Rails.logger.fatal "#{e.message} (is the Fedora URL correct in kumquat.yml?)"
exit
rescue => e
Rails.logger.fatal "#{e.message} (is Fedora running, and is its URL correct in kumquat.yml?)"
exit
end
<file_sep>/app/helpers/items_helper.rb
module ItemsHelper
##
# @param item Item
#
def triples_to_dl(item)
# collect triples into a hash of object (value) arrays keyed by predicate
triples = {}
item.triples.each{ |t| triples[t.predicate] = [] }
triples.keys.each do |k|
triples[k] = item.triples.select{ |t2| t2.predicate == k }.map{ |t2| t2.object }
end
dl = '<dl>'
triples.each do |predicate, objects|
next if predicate.include?('http://fedora.info/definitions/')
if objects.any?
term = Triple::LABELS.keys.include?(predicate) ?
Triple::LABELS[predicate] : predicate
dl += "<dt>#{term}</dt>"
objects.each do |object|
dl += "<dd>#{object}</dd>"
end
end
end
dl += '</dl>'
raw(dl)
end
end
<file_sep>/app/commands/command.rb
# Abstract command class in the command pattern, from which all commands
# should inherit.
class Command
# Executes the command, checking all relevant preconditions and raising an
# exception if anything goes wrong. Raised exception messages should be
# suitable for public consumption. Success/failure should be written to the
# event log.
def execute
raise NotImplementedError, 'Command must override execute method'
end
# Returns the object, if any, on which the command will or did act. This
# method exists to establish convention, but is optional. Some commands may
# operate on <> 1 object, in which case they might want to define their own
# getter(s) instead of this.
def object
nil
end
end
<file_sep>/app/models/contentdm/element.rb
module Contentdm
##
# Abstract class extended by DCElement and LocalElement.
#
class Element
attr_accessor :name
attr_accessor :value
def initialize(params = {})
params.each do |k, v|
if respond_to?("#{k}=")
send "#{k}=", v
else
instance_variable_set "@#{k}", v
end
end
end
def namespace_prefix
raise 'Subclasses must override namespace_prefix()'
end
def namespace_uri
raise 'Subclasses must override namespace_uri()'
end
def value=(value_)
@value = value_.strip.squeeze(' ').gsub('\t', '')
end
end
end
<file_sep>/app/models/item.rb
class Item
extend ActiveModel::Naming
extend Forwardable
delegate [:fedora_json_ld, :fedora_url, :triples, :uuid, :web_id] =>
:fedora_container
@@http = HTTPClient.new
attr_reader :children
attr_reader :fedora_container
attr_accessor :solr_representation
##
# @param uri Fedora resource URI
# @return Item
#
def self.find(uri)
Item.new(Fedora::Container.find(uri))
end
##
# @param uuid string
# @return Item
#
def self.find_by_uuid(uuid)
solr = RSolr.connect(url: Kumquat::Application.kumquat_config[:solr_url])
response = solr.get('select', params: { q: "uuid:#{uuid}" })
record = response['response']['docs'].first
item = Item.find(record['id'])
item.solr_representation = record
item
end
##
# @param web_id string
# @return Item
#
def self.find_by_web_id(web_id)
solr = RSolr.connect(url: Kumquat::Application.kumquat_config[:solr_url])
response = solr.get('select', params: { q: "web_id:#{web_id}" })
record = response['response']['docs'].first
item = nil
if record
item = Item.find(record['id'])
if item
item.solr_representation = record
end
end
item
end
def children
self.fedora_container.children.each{ |c| @children << Item.new(c) } unless
@children.any?
@children
end
def delete(also_tombstone = false)
self.fedora_container.delete(also_tombstone)
end
def initialize(fedora_container)
@children = []
@fedora_container = fedora_container
end
def persisted?
!self.fedora_container.nil?
end
def to_model
self
end
def to_param
self.web_id
end
def subtitle
t = self.triples.select do |e|
e.predicate.include?('http://purl.org/dc/terms/alternative')
end
t.first ? t.first.value : nil
end
##
# @see subtitle
#
def title
t = self.triples.select do |e|
e.predicate.include?('http://purl.org/dc/elements/1.1/title')
end
t.first ? t.first.value : 'Untitled'
end
end
<file_sep>/app/assets/javascripts/admin/server.js
var ServerStatusMonitor = function() {
var refresh_timer;
var refresh = function() {
console.log('Refreshing server status...');
$('.kq-dynamic-status').each(function() {
var status = $(this).find('.kq-service-status:first');
var check_url = status.attr('data-check');
$.ajax({
url: check_url,
data: {},
complete: function(xhr) {
if (xhr.status == 200) {
status.addClass('label-success').
removeClass('label-danger').removeClass('hidden').
text('Online');
}
},
error: function(xhr, statusText, err) {
status.addClass('label-danger').
removeClass('label-success').removeClass('hidden').
text('Offline');
}
});
});
};
this.start = function() {
refresh();
refresh_timer = setInterval(refresh, 8000);
};
this.stop = function() {
console.log('Clearing server status refresh timer');
clearInterval(refresh_timer);
};
};
var monitor;
var ready = function() {
if ($('body#server').length) {
monitor = new ServerStatusMonitor();
monitor.start();
}
};
var teardown = function() {
if ($('body#server').length && monitor) {
monitor.stop();
}
};
$(document).ready(ready);
$(document).on('page:load', ready);
$(document).on('page:before-change', teardown);
<file_sep>/app/controllers/admin/server_controller.rb
module Admin
class ServerController < ControlPanelController
def index
end
##
# Responds to GET /admin/server/image-server-status with either HTTP 200
# or 503
#
def image_server_status
http = HTTPClient.new
begin
response = http.get(Kumquat::Application.kumquat_config[:loris_url])
if response.body.include?('Internet Imaging Protocol Server')
render text: 'online'
else
render text: 'offline', status: 503
end
rescue
render text: 'offline', status: 503
end
end
##
# Responds to GET /admin/server/repository-status with either HTTP 200 or
# 503
#
def repository_status
http = HTTPClient.new
begin
response = http.get(Kumquat::Application.kumquat_config[:fedora_url])
if response.status == 200
render text: 'online'
else
render text: 'offline', status: 503
end
rescue
render text: 'offline', status: 503
end
end
##
# Responds to GET /admin/server/search-server-status with either HTTP 200
# or 503
#
def search_server_status
solr = RSolr.connect(url: Kumquat::Application.kumquat_config[:solr_url])
begin
solr.get('select', params: { q: '*:*', start: 0, rows: 1 })
rescue RSolr::Error::Http
render text: 'offline', status: 503
else
render text: 'online'
end
end
##
# Responds to PATCH /admin/server/update-index
#
def update_index
http = HTTPClient.new
url = Kumquat::Application.kumquat_config[:solr_url].chomp('/') +
'/update?commit=true'
response = http.get(url)
if response.status == 200
flash['success'] = 'Index updated.'
else
flash['error'] = response.body
end
redirect_to :back
end
end
end
|
7ff7623f11706759f19f76b4dda1f500218d7a48
|
[
"Markdown",
"JavaScript",
"Ruby"
] | 39 |
Ruby
|
medusa-project/kumquat-f4
|
3540271d2106cb1da3b5bd042a7c24df3244c164
|
d3b7b8640264b93294c65b10136223d6baa5654d
|
refs/heads/main
|
<repo_name>RVSAa/stopwatch-using-tkinter<file_sep>/link.py
https://repl.it/@RVSAditya/stopwatch
<file_sep>/README.md
# stopwatch-using-tkinter
python stopwatch using the module tkinter
|
d61eb68170425aade8372713bd1c00756f2bda82
|
[
"Markdown",
"Python"
] | 2 |
Python
|
RVSAa/stopwatch-using-tkinter
|
79a724c782cc2a655a0630884fbd4e320091aae9
|
136663c824a65aea5f42f578f794b73f87b1c073
|
refs/heads/master
|
<file_sep>void setup() {
// put your setup code here, to run once:
const int LED1 = 32;
const int LED2 = 30;
const int LED3 = 31;
pinMode(LED1,OUTPUT);
pinMode(LED2,OUTPUT);
pinMode(LED3,OUTPUT);
digitalWrite(LED1,HIGH);
digitalWrite(LED2,HIGH);
digitalWrite(LED3,HIGH);
}
void loop() {
// put your main code here, to run repeatedly:
}
<file_sep>from gpiozero import Button
from time import sleep
button1 = Button(3)
button2 = Button(2)
while True:
if button1.is_pressed:
print("Power up")
if button2.is_pressed:
print("Power down")
sleep(0.1)<file_sep>// defines pins numbers
const int pulse = 3;
const int dirPin = 4;
const int enPin = 5;
const long revs = 15000;
const int microStep = 1;
void setup() {
Serial.begin(9600);
// Sets the two pins as Outputs
pinMode(pulse,OUTPUT);
pinMode(dirPin,OUTPUT);
pinMode(enPin,OUTPUT);
digitalWrite(enPin,LOW);
}
void loop() {
digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction
// 1 Full clockwise rev, full step mode
Serial.println(revs*microStep);
for(int x = 0; x < revs; x++) {
digitalWrite(pulse,HIGH);
delayMicroseconds(600);
digitalWrite(pulse,LOW);
delayMicroseconds(600);
}
delay(1000); // One second delay
Serial.println("Switching!");
digitalWrite(dirPin,LOW); //Changes the rotations direction
// Counter clockwise rev
for(int x = 0; x < revs; x++) {
digitalWrite(pulse,HIGH);
delayMicroseconds(600);
digitalWrite(pulse,LOW);
delayMicroseconds(600);
}
delay(1000);
}
<file_sep>import pygatt
adapter = pygatt.GATTToolBackend()
try:
adapter.start()
device = adapter.connect('B4:52:A9:1A:A7:E0')
print("connected? Device: ")
print(device)
value = device.char_write_handle(0x0012,bytearray([32,73,43,74,10]))
print(value)
input("shut down?")
finally:
adapter.stop()<file_sep> // defines pins numbers
const int trigPin = A11;
const int echoPin = A12;
int ultra;
const int inverterPower = A6;
const int BLE_power = 8;
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
pinMode(BLE_power,OUTPUT);
digitalWrite(BLE_power,HIGH);
pinMode(inverterPower,OUTPUT);
digitalWrite(inverterPower, HIGH);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}
void loop() {
// read from port 1, send to port 0:
if (Serial1.available()) {
char inByte = Serial1.read();
Serial.print((char)inByte);
}
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
ultra = digitalRead(echoPin);
Serial.print("Ultrasound Out: ");
Serial.println(ultra);
}
<file_sep>void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial1.begin(9600);
while(!serial){}
Serial.println("Ready");
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial1.available()){
char data = Serial1.read();
Serial.print(data);
}
}
<file_sep># Team 7: Emerson Wants to Play Baseball
Emerson is a 12 year old girl with cerebral palsy. As a result, she has limited motor controls.
This project is an undertaking to give emerson the ability to play catch with her mom and friends despite her condition.
We are building a remote controlled baseball tossing device which would give emerson the ability to change the direction of her toss,
adjust the power and slightly modify the angle of her toss.
<file_sep>void setup() {
Serial.begin(9600);
Serial1.begin(9600);
pinMode(8,OUTPUT);
digitalWrite(8,HIGH);
}
void loop() {
// read from port 0, send to port 1:
if (Serial.available()) {
int inByte = Serial.read();
Serial.println((char)inByte);
Serial1.print(inByte, DEC);
}
// read from port 1, send to port 0:
if (Serial1.available()) {
char inByte = Serial1.read();
Serial.print((char)inByte);
}
}
<file_sep>#!/bin/bash
sudo gatttool -i hci0 -b B4:52:A9:1A:A7:E0 --char-write-req -a 0x0012 -n 0x4A4A4A
|
507d52390f301c7f33851b720cacb63958379bfa
|
[
"Markdown",
"Python",
"C++",
"Shell"
] | 9 |
C++
|
a-folabi/senior-design
|
4587fa0e193ea547bd0882699cc4581535e62f1c
|
f879ec29e82df06931aac5f4dec5785c9e073a08
|
refs/heads/master
|
<file_sep># Opus Tools Downloader
A Python script which downloads the latest build of Opus Tools from [AppVeyor](https://ci.appveyor.com/project/rillian/opus-tools).<file_sep>import urllib.request
import json
import zipfile
import os
import re
import shutil
class OpusTools:
work_dir = os.path.dirname(os.path.realpath(__file__))
url = 'https://ci.appveyor.com/api/projects/rillian/opus-tools/'
dl_url = (url + 'artifacts/opus-tools.zip?job='
+ urllib.parse.quote('Configuration: Release; Platform: x64'))
def json_data(self):
response = urllib.request.urlopen(self.url)
data = response.read()
return {'vers': json.loads(data)['build']['version'],
'date': json.loads(data)['build']['updated'][:10]}
def paths(self):
dir_name = 'opus-tools_' + self.json_data()['vers']
file_name = dir_name + '.zip'
dir_path = os.path.join(self.work_dir, dir_name)
zip_path = os.path.join(self.work_dir, file_name)
return {'dir': dir_path, 'zip': zip_path}
def zip_download(self):
zip_response = urllib.request.urlopen(self.dl_url)
zip_data = zip_response.read()
with open(self.paths()['zip'], 'wb') as file:
file.write(zip_data)
def zip_extract(self):
zip_file = zipfile.ZipFile(self.paths()['zip'], 'r')
zip_file.extractall(self.paths()['dir'])
zip_file.close()
os.remove(self.paths()['zip'])
def if_current(self):
return os.path.isdir(self.paths()['dir'])
def remove_prev(self):
for root, dirs, files in os.walk(self.work_dir, topdown=False):
for name in dirs:
if bool(re.match(r'^.+\\opus-tools_\d+.\d+.\d+$', os.path.join(root, name))):
shutil.rmtree(os.path.join(root, name))
def download(self):
vers = self.json_data()['vers']
date = self.json_data()['date']
if self.if_current():
print(f'Your version is current: {vers}')
else:
self.remove_prev()
print(f'Downloading build version: {vers} ({date})')
self.zip_download()
self.zip_extract()
new = OpusTools()
new.download()
|
1f25eb6ec0779e9bbaf78757d4227893d0920f2c
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
iamalexei/opustools-downloader
|
879383c4efa94b970fa93441a19a66bbba0a422e
|
d31e69510f7525f66cf911f8468bc7d9f20ec737
|
refs/heads/master
|
<file_sep>apply plugin: 'java'
apply plugin: 'application'
sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
if (!hasProperty('mainClass')) {
ext.mainClass = 'ru.no3utuff4uk.Main'
}
repositories {
mavenCentral()
}
dependencies {
compile 'org.projectlombok:lombok:1.16.18'
compile group: 'org.apache.poi', name: 'poi', version: '3.17'
compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.17'
}
<file_sep>package ru.no3utuff4uk.converter;
import java.io.IOException;
public interface PTEConverter {
public void convert() throws IOException;
}
<file_sep>package ru.no3utuff4uk.converter;
class PTEConverterImplTest {
}<file_sep>//plugins {
// id 'io.franzbecker.gradle-lombok' version '1.10'
//}
apply plugin: 'java'
apply plugin: 'idea'
//apply plugin: 'io.franzbecker.gradle-lombok'
sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
task runApp(type: JavaExec) {
classpath sourceSets.main.runtimeClasspath
main = "app.PTEConverterApplication"
}
repositories {
mavenCentral()
jcenter()
}
dependencies {
compile project(':PTEConverter')
compile 'org.projectlombok:lombok:1.16.18'
testCompile group: 'junit', name: 'junit', version: '4.10'
}
<file_sep>package ru.no3utuff4uk.converter;
import javafx.concurrent.Task;
import lombok.Cleanup;
import lombok.Getter;
import lombok.Synchronized;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import ru.no3utuff4uk.helper.Status;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class PTEConverterImpl extends Task<Status> implements PTEConverter{
/**
* Файл исходного изображения
*/
@Getter
private File inputPicture;
/**
* Файл с результатом преобразования
*/
@Getter
private File outputFile;
/**
* Размер стороны ячейки
*/
private Integer cellSize;
public PTEConverterImpl(File inputPicture, File outputFile, Integer cellSize) {
this.inputPicture = inputPicture;
this.outputFile = outputFile;
this.cellSize = cellSize;
}
@Override
public void convert() throws IOException {
BufferedImage image = ImageIO.read(inputPicture);
XSSFWorkbook workbook = new XSSFWorkbook();
// HSSFWorkbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet(inputPicture.getName());
sheet.setDefaultColumnWidth(1);
sheet.setDefaultRowHeight((short) 1);
sheet.setZoom(10);
HashMap<Integer, XSSFCellStyle> styles = new HashMap<>();
AtomicLong progress = new AtomicLong(0);
long maxProgress = image.getHeight() * image.getWidth();
updateProgress(progress.longValue(), maxProgress);
List<Row> rows = IntStream.range(0, image.getHeight()).mapToObj(y -> sheet.createRow(y)).collect(Collectors.toList());
rows.parallelStream().forEach((Row row) -> {
// long rowStart = System.currentTimeMillis();
for (int x = 0; x < image.getWidth(); x++) {
Cell cell = row.createCell(x);
int color = image.getRGB(x, row.getRowNum()) | 0x000F0F0F;
XSSFCellStyle style;
if (!styles.containsKey(color)) {
style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(new XSSFColor(new Color(image.getRGB(x, row.getRowNum()))));
styles.put(color, style);
} else {
style = styles.get(color);
}
// cell.setCellValue(Integer.toString(image.getRGB(x, y), 16));
cell.setCellStyle(style);
updateProgress(progress.incrementAndGet(), maxProgress);
// System.out.println("kek " + progress);
}
// System.out.println("Row " + row.getRowNum() + " преобразована за " + ((double)(System.currentTimeMillis() - rowStart)/1000));
});
sheet.setActiveCell(new CellAddress("A1"));
System.out.println("Преобразование завершено!");
// for(int y = 0; y < image.getHeight(); y++) {
// Row row = sheet.getRow(y);
// for(int x = 0; x < image.getWidth(); x++) {
// Cell cell = row.createCell(x);
// XSSFCellStyle style;
// if(!styles.containsKey(image.getRGB(x, y))) {
// style = workbook.createCellStyle();
// style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// style.setFillForegroundColor(new XSSFColor(new Color(image.getRGB(x, y))));
// styles.put(image.getRGB(x, y), style);
// } else {
// style = styles.get(image.getRGB(x, y));
// }
//// cell.setCellValue(Integer.toString(image.getRGB(x, y), 16));
// cell.setCellStyle(style);
//
// updateProgress(++progress, maxProgress);
//// System.out.println("kek " + progress);
// }
// }
@Cleanup
FileOutputStream fos =new FileOutputStream(outputFile);
workbook.write(fos);
}
@Override
public Status call() throws Exception {
try {
convert();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Строитель для задачи конвертации изображения в Excel файл
*/
public static class Builder {
@Getter
private File inputPicture;
@Getter
private File outputFile;
@Getter
private Integer cellSize = 50;
public Builder setInputPicture(String path) {
return setInputPicture(new File(path));
}
public Builder setInputPicture(File picture) {
if(picture == null) {
return this;
}
if(!picture.exists() || !picture.isFile()) {
throw new IllegalArgumentException("Некорректный путь к изображению");
}
if(!picture.getName().matches("[^\\s]+(\\.(?i)(jpg|png|gif|bmp))$")) {
throw new IllegalArgumentException("Файл не является изображением");
}
inputPicture = picture;
return this;
}
public Builder setOutputFile(String path) {
return setOutputFile(new File(path));
}
public Builder setOutputFile(File outputFile) {
this.outputFile = outputFile;
return this;
}
public Builder setCellSize(Integer size) {
if(size <= 0) {
throw new IllegalArgumentException("Размер ячейки не может быть меньше или равным 0");
}
if(size > 100){
throw new IllegalArgumentException("Размер ячейки не может быть больше, чем 100px");
}
cellSize = size;
return this;
}
/**
* Построение преобразователя по заданным параметрам
* @return Преобразователь изображения в excel файл
* @throws IllegalStateException
*/
public PTEConverterImpl build() throws IllegalStateException {
if(inputPicture == null) {
throw new IllegalStateException("Не задано изображение");
}
if(outputFile == null) {
throw new IllegalStateException("Не задан файл с результатом преобразования");
}
return new PTEConverterImpl(inputPicture, outputFile, cellSize);
}
}
}
<file_sep>rootProject.name = 'PictureToExcelConverter'
include 'PTEConverter'
<file_sep>rootProject.name = 'PTEConverter'
<file_sep># PictureToExcelConverter
Преобразует картинки в таблицы excel. Зачем? ¯ \ _ (ツ) _ / ¯
Для запуска выполните команду: gradle runApp
|
bd03035229c8dc5a78d89af250a958a90aed5e3b
|
[
"Markdown",
"Java",
"Gradle"
] | 8 |
Gradle
|
no3utuff4uk/PictureToExcelConverter
|
1d03924d16ce5ad0b6d556899a653999c108c576
|
fba487fbc3f1d3c0b20295e4d6e1cd837530d9d4
|
refs/heads/main
|
<repo_name>ndojalui/constructors<file_sep>/README.TXT
PROJECT TITLE: Constructors - Luigj Ndoja
PURPOSE OF PROJECT: To test multiple classes such as a class that simulates a car, a heater, and roach population growth
HOW TO START THIS PROJECT: Press run and follow on screan instructions
AUTHOR: <NAME>
Good Job, much much improved =)
10K, 10A, 9T, 10C<file_sep>/RoachPopulation.java
/**
* Roach Population class, simulations growth of roach population in a kitchen
*
* @author <NAME>
*
*/
public class RoachPopulation
{
// instance variables - replace the example below with your own
private int populationSize;
// constructer with starting pop input
public RoachPopulation(int startPop){
if (startPop < 0){ // sets negative values to positive
startPop *=-1;
}
populationSize = startPop; //sets population size to input population
}
// method doubles population size
public void growth(){
populationSize *=2;
}
// method reduces population size by 10%
public void spray(){
populationSize-= populationSize*0.1;
}
// method returns population size
public int getSize(){
return populationSize;
}
}
|
18000fab3000bb6882da1ce0d88a79810c708dc0
|
[
"Java",
"Text"
] | 2 |
Text
|
ndojalui/constructors
|
8a616684b8b426b6b6b6c3aded82a90433e124ae
|
b13f1b3979cf8fd19d9607caef484d5ae2e78313
|
refs/heads/master
|
<repo_name>killown/scripts<file_sep>/color-picker
#!/usr/bin/env python3
import sys
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
import xerox
picker = Gtk.ColorSelectionDialog("Color Picker")
if len(sys.argv) >= 2:
color = Gdk.color_parse(sys.argv[1])
if color:
picker.get_color_selection().set_current_color(color)
if picker.run() == getattr(Gtk, 'RESPONSE_OK', Gtk.ResponseType.OK):
color = picker.get_color_selection().get_current_color()
r, g, b = [int(c / 256) for c in [color.red, color.green, color.blue]]
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
hexcolor = "#{:02x}{:02x}{:02x}".format(r, g, b).upper()
xerox.copy(hexcolor)
<file_sep>/tomaragua.sh
#!/bin/bash
while true; do
notify-send "Você precisa tomar água agora!"
sleep 3600
done
<file_sep>/gist-gui
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
import subprocess
import os
def run_gist(description, file_content, filename):
file_path = os.path.join("/tmp/", filename)
with open(filename, 'w') as f:
f.writelines(file_content)
f.close()
outputCMD = subprocess.Popen(
['gist', '-d', description, filename], stdout=subprocess.PIPE)
class send_to_gist(Gtk.Window):
def __init__(self):
super(send_to_gist, self).__init__()
self.set_size_request(250, 200)
self.set_position(Gtk.WindowPosition.CENTER)
self.connect("destroy", Gtk.main_quit)
self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
self.set_title("Send to Gist")
self.description = Gtk.Entry()
self.description.set_text("Description")
self.description_label = Gtk.Label('Gist Description')
self.filename = Gtk.Entry()
self.filename.set_text("filename.py")
self.filename_label = Gtk.Label('File name .ext')
self.settext = Gtk.Button("Send to Gist")
self.settext.connect("clicked", self.on_gist_description)
self.settext.connect("destroy", Gtk.main_quit)
self.entry = Gtk.Entry()
self.entry.set_text("Hello World")
# adjust position
fix = Gtk.Fixed()
fix.put(self.description_label, 5, 5)
fix.put(self.description, 5, 25)
fix.put(self.filename_label, 5, 60)
fix.put(self.filename, 5, 80)
fix.put(self.settext, 5, 120)
fix.set_halign(Gtk.Align.CENTER)
fix.set_valign(Gtk.Align.CENTER)
self.add(fix)
self.show_all()
def on_gist_description(self, entry):
description = self.description.get_text()
filename = self.filename.get_text()
file_content = self.clipboard.wait_for_text()
run_gist(description, file_content, filename)
self.destroy()
send_to_gist()
Gtk.main()
<file_sep>/dialgen.py
#!/usr/bin/env python3
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__author__ = "<NAME>"
__license__ = "GPL"
__version__ = "1.0"
__email__ = "<EMAIL>"
__status__ = "Production"
import textwrap
import sys
import urllib
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('PangoCairo', '1.0')
gi.require_version('GdkPixbuf', '2.0')
gi.require_version('Pango', '1.0')
from gi.repository import GdkPixbuf, Pango, Gtk, PangoCairo
import cairo
import os
import shutil
import json
import sqlite3
import getpass
try:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
except ImportError:
print('Python pillow was not found, pip install pillow')
exit()
user = getpass.getuser()
from optparse import OptionParser
import subprocess
dialtext = 'DialText'
imcolor = '#F93939'
tcolor = '#ffffff'
shadowcolor = "#383c4a"
def fc_list():
outputCMD = subprocess.Popen(['fc-list'], stdout=subprocess.PIPE)
fclist = outputCMD.stdout.readlines()
fontlistdict = {}
for i in fclist:
fontname = str(i).split(':')[1]
fontext = str(i).split(':')[0].partition("b'")[2:][0].split("/")[-1]
fontlistdict.update({fontname: fontext})
return fontlistdict
fontlist = fc_list()
def set_font(size):
if os.path.exists('/usr/share/fonts/TTF/selawkb.ttf'):
return ImageFont.truetype('/usr/share/fonts/TTF/selawkb.ttf', size)
if os.path.exists(
'/usr/share/fonts/ttf-noto-fonts-cros-ib/Arimo-Bold.ttf'):
return ImageFont.truetype(
'/usr/share/fonts/ttf-noto-fonts-cros-ib/Arimo-Bold.ttf', size)
if os.path.exists('/usr/share/fonts/TTF/DejaVuSans.ttf'):
return ImageFont.truetype('/usr/share/fonts/TTF/DejaVuSans.ttf', size)
return None
fontsize = 75
parser = OptionParser()
parser.add_option(
"--update",
dest="update",
action="store_false",
help="uptate all dials, close vivaldi before update")
vivaldistable = os.path.join("/home/" + user + "/.config/vivaldi/Default/")
vivaldisnapshot = os.path.join("/home/" + user +
"/.config/vivaldi-snapshot/Default/")
vivalddir = "/"
if os.path.exists(vivaldistable):
vivalddir = vivaldistable
if os.path.exists(vivaldisnapshot):
vivalddir = vivaldisnapshot
topSites_path = os.path.join(vivalddir, "Top Sites")
bookmark_path = os.path.join(vivalddir, "Bookmarks")
customThumbs_path = os.path.join("/home/" + user +
"/.local/share/vivaldithumbs/")
if not os.path.exists(customThumbs_path):
os.makedirs(customThumbs_path)
def get_pid(name):
outputCMD = subprocess.Popen(
['pidof', 'vivaldi-bin'], stdout=subprocess.PIPE)
return outputCMD.stdout.readlines()
def load_speeddial(file_path):
"""
Load the bookmark entries from Vivaldi's speed dial and return as
dictionary
"""
# read bookmark file
with open(file_path, encoding="UTF-8") as jfile:
Bookmarks = json.load(jfile)
# access speed dial
dials = [{
x["id"]: x["name"]
for x in Bookmarks["roots"]["bookmark_bar"]["children"][i]["children"]
if x["type"] == "url"
} for i in range(len(Bookmarks["roots"]["bookmark_bar"]["children"]))]
speeddial = {}
for d in dials:
speeddial.update(d)
return speeddial
def load_thumbs(dir_path):
"""
Load custom thumbnails in specified directory and return as dictionary
"""
thumbs = os.listdir(dir_path)
return {
x[0]: dir_path + "_".join(x)
for x in [y.split("_") for y in thumbs]
}
def update_thumbs(topSites_path, Bookmarks, thumbnails):
"""
Replace thumbnails where thumbnail id matches bookmark id and print results
"""
updated = []
not_found = []
# open database
conn = sqlite3.connect(topSites_path)
cur = conn.cursor()
# replace if match
for key in Bookmarks.keys():
if key in thumbnails.keys():
with open(thumbnails[key], "rb") as bfile:
pic = bfile.read()
sql = "UPDATE thumbnails SET thumbnail=? WHERE url=?"
cur.execute(sql, (pic, "http://bookmark_thumbnail/" + str(key)))
conn.commit()
updated.append(key)
else:
not_found.append(key)
conn.close()
Bookmarks = load_speeddial(bookmark_path)
custom_thumbnails = load_thumbs(customThumbs_path)
def updated_thumbs(topSites_path, Bookmarks, thumbnails):
updated = {}
for key in Bookmarks.keys():
if key in thumbnails.keys():
updated.update({key: Bookmarks[key]})
return updated
def not_updated_thumbs(topSites_path, Bookmarks, thumbnails):
not_found = {}
for key in Bookmarks.keys():
if key in thumbnails.keys():
pass
else:
not_found.update({key: Bookmarks[key]})
if not_found:
return not_found
def save_thumb(Bookmarks, filename):
for key in Bookmarks.keys():
if Bookmarks[key] in filename or Bookmarks[key] in filename.lower(
) or Bookmarks[key] in filename.capitalize():
thumbdial = os.path.join(customThumbs_path + key + '_' + Bookmarks[
key] + '.png')
thumbtemp = os.path.join(customThumbs_path + Bookmarks[key] +
'.png')
if os.path.exists(thumbdial):
os.remove(thumbdial)
img = Image.open(thumbtemp)
img = img.resize((440, 360), Image.BILINEAR)
img.save(thumbdial)
thumb_filters(thumbtemp, img)
custom_thumbnails = load_thumbs(customThumbs_path)
def set_thumb(filename):
print("Python Script for replacing thumbnails in Vivaldi Speedial")
global customThumbs_path
if not customThumbs_path[-1] in "/\\":
customThumbs_path += "/"
# validate paths
if not os.path.isfile(bookmark_path):
print("\nERROR: Vivaldis bookmark file wasn't found under the path "
"'{}'!".format(bookmark_path))
elif not os.path.isfile(topSites_path):
print("\nERROR: Vivaldis 'Top Sites' file wasn't found under the path "
"'{}'!".format(topSites_path))
elif not os.path.isdir(customThumbs_path):
print("\nERROR: '{}' is no valid directory!".format(customThumbs_path))
# start script
else:
# load files
Bookmarks = load_speeddial(bookmark_path)
custom_thumbnails = load_thumbs(customThumbs_path)
save_thumb(Bookmarks, filename)
# create backup
bkp = os.path.join(customThumbs_path + "Top Sites")
if os.path.exists(bkp):
os.remove(bkp)
shutil.copy(topSites_path, customThumbs_path)
print("\nCreated backup of 'Top Sites' in '{}'".format(bkp))
update_thumbs(topSites_path, Bookmarks, custom_thumbnails)
def tohex(c):
# Convert to hex string
# little hack to fix bug
s = [
'#', hex(int(c[0] * 256))[2:].zfill(2),
hex(int(c[1] * 256))[2:].zfill(2), hex(int(c[2] * 256))[2:].zfill(2)
]
for item in enumerate(s):
if item[1] == '100':
s[item[0]] = 'ff'
return ''.join(s)
def thumb_filters(filename, image):
smoother = image.filter(ImageFilter.SMOOTH_MORE)
smoother.save(filename)
def create_thumb(self):
# color from selector
c = imcolor
d = tcolor
imagecolor = imcolor
textcolor = tcolor
# convert the code to hex
if c != "#F93939":
imagecolor = tohex(
(c.red / 65536.0, c.green / 65536.0, c.blue / 65536.0))
if d != "#ffffff":
textcolor = tohex(
(d.red / 65536.0, d.green / 65536.0, d.blue / 65536.0))
# create an empity thumb and set the size
MAX_W, MAX_H = 400, 360
im = Image.new('RGB', (MAX_W, MAX_H), imagecolor)
draw = ImageDraw.Draw(im)
# set position of the text
current_h, pad = 120, 50
current_hs, pad = 125, 50
# decrease the size of the font if the text is too long
if len(dialtext) > 10:
current_h, pad = 100, 10
current_hs, pad = 100, 10
global shadowcolor
# text shadow effects
if imagecolor == "#000000":
shadowcolor = "#727991"
global font_desc
if 'font_desc' in globals():
font = ImageFont.truetype(font_desc, fontsize)
fontshadow = ImageFont.truetype(font_desc, fontsize + 2)
else:
font = set_font(fontsize)
fontshadow = set_font(fontsize - 2)
# draw the text
text = textwrap.wrap(dialtext, width=15)
for line in text:
w, h = draw.textsize(line, font=font)
# draw the shadow
draw.text(
((MAX_W - w) / 2, current_hs), line, font=fontshadow, fill=shadowcolor)
# now draw the text over it
draw.text(
((MAX_W - w) / 2, current_h), line, fill=textcolor, font=font)
current_h += h + pad
current_hs += h + pad
global thumbfile
thumbfile = (dialtext + '.png')
global thumbcpath
thumbcpath = os.path.join(customThumbs_path + thumbfile)
im.save(thumbcpath)
thumb_filters(thumbcpath, im)
update_image(self)
def update_image(self):
self.image.set_from_pixbuf(
GdkPixbuf.Pixbuf.new_from_file(thumbcpath))
set_thumb(dialtext)
class PyApp(Gtk.Window):
def __init__(self):
super(PyApp, self).__init__()
self.set_size_request(720, 450)
# self.set_position(Gtk.WIN_POS_CENTER)
self.connect("destroy", Gtk.main_quit)
self.set_title("Thumbnail Generator")
self.text = Gtk.Entry()
self.text.set_text("Dial Text")
self.fontsize = Gtk.Entry()
self.fontsize.set_text("75")
self.fontsize.set_width_chars(3)
self.image = Gtk.Image()
self.set_dial_option_label = Gtk.Label("Use 'update thumbnail' to save the thumb.")
self.chagefontlabel = Gtk.Label("Change Font")
self.fontsizelabel = Gtk.Label("Font Size")
titles_updated_store = Gtk.ListStore(int, str)
titles_not_updated_store = Gtk.ListStore(int, str)
fontsize_store = Gtk.ListStore(int, str)
dial_store = Gtk.ListStore(int, str)
font_store = Gtk.ListStore(int, str)
n = 1
for i in range(10, 150, 5):
fontsize_store.append([n, str(i)])
n += 1
outputCMD = subprocess.Popen(['fc-list'], stdout=subprocess.PIPE)
out = outputCMD.stdout.readlines()
n = 1
for i in dict(updated_thumbs(topSites_path, Bookmarks, custom_thumbnails)).values():
print(i, 'updated')
titles_updated_store.append([n, i])
n += 1
for i in dict(not_updated_thumbs(topSites_path, Bookmarks, custom_thumbnails)).values():
print(i, 'not updated')
titles_not_updated_store.append([n, i])
n += 1
n = 1
duplicated = []
for i in sorted(i for i in out):
fontname = str(i).split(':')[1]
if len(fontname) < 25 and fontname not in duplicated:
font_store.append([n, fontname])
duplicated.append(fontname)
n += 1
self.dial_notupdated_text = Gtk.Label("Not Updated dial Titles")
self.dial_updated_text = Gtk.Label("Updated dial Titles")
self.dialcombo_notupdated = Gtk.ComboBox.new_with_model_and_entry(titles_not_updated_store)
self.dialcombo_notupdated.connect("changed", self.on_dial)
self.dialcombo_notupdated.set_entry_text_column(1)
self.dialcombo_updated = Gtk.ComboBox.new_with_model_and_entry(titles_updated_store)
self.dialcombo_updated.connect("changed", self.on_dial)
self.dialcombo_updated.set_entry_text_column(1)
self.fontsize_combo = Gtk.ComboBox.new_with_model_and_entry(fontsize_store)
self.fontsize_combo.connect("changed", self.on_fontsize)
self.fontsize_combo.set_entry_text_column(1)
self.fontsize_combo.set_wrap_width(10)
self.fontchange_combo = Gtk.ComboBox.new_with_model_and_entry(font_store)
self.fontchange_combo .connect("changed", self.on_fontchange)
self.fontchange_combo .set_entry_text_column(1)
self.update_all_dials = Gtk.Button("Update All Dials")
self.update_all_dials.connect("clicked", self.on_update_all_dials)
self.textcolor = Gtk.Button("Select Text Color")
self.textcolor.connect("clicked", self.on_tcolor)
self.update_thumb_button = Gtk.Button("Update Thumbnail")
self.update_thumb_button.connect("clicked", self.on_update_dial)
self.settext = Gtk.Button("Set Text")
self.settext.connect("clicked", self.on_dialtext)
self.shadowcolor = Gtk.Button("Set Shadow Color")
self.shadowcolor.connect("clicked", self.on_shadowncolor)
self.imgcolor = Gtk.Button("Select Background Color")
self.imgcolor.connect("clicked", self.on_imcolor)
fix = Gtk.Fixed()
fix.put(self.update_thumb_button, 10, 40)
fix.put(self.dial_notupdated_text, 10, 80)
fix.put(self.dialcombo_notupdated, 10, 100)
fix.put(self.dial_updated_text, 10, 140)
fix.put(self.dialcombo_updated, 10, 160)
fix.put(self.set_dial_option_label, 5, 10)
fix.put(self.image, 310, 20)
fix.put(self.imgcolor, 10, 200)
fix.put(self.textcolor, 10, 240)
fix.put(self.shadowcolor, 10, 280)
fix.put(self.chagefontlabel, 10, 320)
fix.put(self.fontchange_combo, 10, 340)
fix.put(self.fontsizelabel, 10, 380)
fix.put(self.fontsize_combo, 10, 400)
fix.put(self.update_all_dials, 580, 400)
self.add(fix)
self.show_all()
create_thumb(self)
def on_fontsize(self, size):
tree_iter = size.get_active_iter()
if tree_iter != None:
model = size.get_model()
row_id, number = model[tree_iter][: 2]
global fontsize
fontsize = int(number)
else:
entry = combo.get_child()
print("Entered: %s" % entry.get_text())
create_thumb(self)
def on_fontchange(self, combo):
tree_iter = combo.get_active_iter()
if tree_iter != None:
model = combo.get_model()
row_id, name = model[tree_iter][:2]
global font_desc
font_desc = fontlist[name]
print("Selected: ID=%d, name=%s" % (row_id, fontlist[name]))
else:
entry = combo.get_child()
print("Entered: %s" % entry.get_text())
create_thumb(self)
def on_update_all_dials_info(self, title="Update Info"):
dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
Gtk.ButtonsType.OK, "Updated")
dialog.format_secondary_text(
"All Dials Updated.")
dialog.run()
dialog.destroy()
def on_update_dial(self, title="Update Info"):
create_thumb(self)
dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
Gtk.ButtonsType.OK, "Updated")
dialog.format_secondary_text(
"Dial Updated.")
dialog.run()
dialog.destroy()
def on_update_all_dials(self, widget):
set_thumb('update')
self.on_update_all_dials_info()
def on_dial(self, combo):
tree_iter = combo.get_active_iter()
if tree_iter != None:
model = combo.get_model()
row_id, name = model[tree_iter][:2]
global dialtext
dialtext = name
print("Selected: ID=%d, name=%s" % (row_id, name))
else:
entry = combo.get_child()
print("Entered: %s" % entry.get_text())
create_thumb(self)
def on_imcolor(self, widget):
global imcolor
csd = Gtk.ColorSelectionDialog('foobar')
csd.run()
imcolor = csd.get_color_selection().get_current_color()
csd.destroy()
create_thumb(self)
def on_tcolor(self, widget):
global tcolor
csd = Gtk.ColorSelectionDialog('foobar')
csd.run()
tcolor = csd.get_color_selection().get_current_color()
csd.destroy()
create_thumb(self)
def on_dialtext(self, widget):
global dialtext
dialtext = self.text.get_text()
create_thumb(self)
def on_shadowncolor(self, widget):
global shadowcolor
csd = Gtk.ColorSelectionDialog('foobar')
csd.run()
c = csd.get_color_selection().get_current_color()
shadowcolor = tohex(
(c.red / 65536.0, c.green / 65536.0, c.blue / 65536.0))
csd.destroy()
create_thumb(self)
class VivaldiIsRunning(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="MessageDialog Example")
box = Gtk.Box(spacing=6)
self.add(box)
dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
Gtk.ButtonsType.OK, "Vivaldi is running?")
dialog.format_secondary_text(
"you can't use this program while vivaldi is running.")
dialog.run()
dialog.destroy()
exit()
def vivaldi_running():
if not get_pid("vivaldi-bin"):
return True
else:
win = VivaldiIsRunning()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
print("you can't use this option while vivaldi is running")
exit()
# if __name__ == "__main__":
# only set the thumb in the speed dial if --setdial is found
args, a = parser.parse_args()
if args.update is not None:
if vivaldi_running():
set_thumb('update')
exit()
# not allow to start if vivaldi is running
if vivaldi_running():
PyApp()
Gtk.main()
set_thumb(dialtext)
<file_sep>/atom-toggle
#!/usr/bin/env python3
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__author__ = "<NAME>"
__license__ = "GPL"
__email__ = "<EMAIL>"
import subprocess
app_name = "atom"
app_name_wmctrl = "atom.Atom"
outputCMD = subprocess.Popen(['xdotool', 'getactivewindow'], stdout=subprocess.PIPE)
activewindow = outputCMD.stdout.readlines()[0].decode('utf-8').strip()
outputCMD = subprocess.Popen(['xdotool', 'getwindowname', activewindow], stdout=subprocess.PIPE)
windowname = outputCMD.stdout.readlines()
for app in windowname:
name = app_name.encode('utf-8')
#subprocess.Popen(['notify-send', name, app.strip()])
if name in app.strip() or name.capitalize() in app.strip():
subprocess.Popen(['xdotool', 'windowminimize', activewindow])
else:
outputCMD = subprocess.Popen(['wmctrl', '-x', '-a', app_name_wmctrl])
<file_sep>/resize-image
#!/usr/bin/env python
from easygui import *
import sys
import os
from PIL import Image
size = enterbox(msg='Enter the image size, example: 800x600', title=' ', default='', strip=True)
filename = sys.argv[-1]
width = int(size.split('x')[0])
height = int(size.split('x')[1])
img = Image.open(filename)
img = img.resize((width, height), Image.BILINEAR)
image = os.path.split(filename)[-1]
img.save(os.path.join('resized-' + image))
<file_sep>/pulsemenu
#!/usr/bin/env python3
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__author__ = "<NAME>"
__license__ = "GPL"
__email__ = "<EMAIL>"
import subprocess
def get_pid(name):
outputCMD = subprocess.Popen(
['pidof', name], stdout=subprocess.PIPE)
return outputCMD.stdout.readlines()
if get_pid('pavucontrol'):
subprocess.Popen(
['killall', '-9', 'pavucontrol'], stdout=subprocess.PIPE)
else:
subprocess.Popen(
['pavucontrol', '-m'], stdout=subprocess.PIPE)
<file_sep>/thumbgen
#!/usr/bin/env python3
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__author__ = "<NAME>"
__license__ = "GPL"
__version__ = "1.0"
__email__ = "<EMAIL>"
__status__ = "Production"
import textwrap
import sys
import operator
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('PangoCairo', '1.0')
gi.require_version('GdkPixbuf', '2.0')
gi.require_version('Pango', '1.0')
from gi.repository import GdkPixbuf, Pango, Gtk, PangoCairo
import cairo
import os
import shutil
import json
import getpass
try:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
except ImportError:
print('Python pillow was not found, pip install pillow')
exit()
user = getpass.getuser()
from optparse import OptionParser
import subprocess
image_name = 'Hello World'
background_color = '#F93939'
text_color = '#ffffff'
text_shadow_color = "#383c4a"
image_tmp = '/tmp/image_name.png'
image_size = '247x154'
text_width = 70
def font_cache_list():
outputCMD = subprocess.Popen(['fc-list'], stdout=subprocess.PIPE)
fclist = outputCMD.stdout.readlines()
fontlistdict = {}
for i in fclist:
fontname = str(i).split(':')[1]
fontext = str(i).split(':')[0].partition("b'")[2:][0].split("/")[-1]
fontlistdict.update({fontname: fontext})
return fontlistdict
fontlist = font_cache_list()
def set_font(size):
if os.path.exists('/usr/share/fonts/TTF/selawkb.ttf'):
return ImageFont.truetype('/usr/share/fonts/TTF/selawkb.ttf', size)
if os.path.exists(
'/usr/share/fonts/ttf-noto-fonts-cros-ib/Arimo-Bold.ttf'):
return ImageFont.truetype(
'/usr/share/fonts/ttf-noto-fonts-cros-ib/Arimo-Bold.ttf', size)
if os.path.exists('/usr/share/fonts/TTF/DejaVuSans.ttf'):
return ImageFont.truetype('/usr/share/fonts/TTF/DejaVuSans.ttf', size)
return None
fontsize = 40
def save_image(Bookmarks, filename):
for key in Bookmarks.keys():
if Bookmarks[key] in filename or Bookmarks[key] in filename.lower(
) or Bookmarks[key] in filename.capitalize():
imagedial = os.path.join(customimages_path + key + '_' + Bookmarks[
key] + '.png')
imagetemp = os.path.join(customimages_path + Bookmarks[key] +
'.png')
if os.path.exists(imagedial):
os.remove(imagedial)
img = Image.open(imagetemp)
img = img.resize((440, 360), Image.BILINEAR)
img.save(imagedial)
set_image_filters(imagedial, img)
custom_images = load_images(customimages_path)
def convert_to_hex(c):
s = [
'#', hex(int(c[0] * 256))[2:].zfill(2),
hex(int(c[1] * 256))[2:].zfill(2), hex(int(c[2] * 256))[2:].zfill(2)
]
for item in enumerate(s):
if item[1] == '100':
s[item[0]] = 'ff'
return ''.join(s)
def set_image_filters(filename, image):
smoother = image.filter(ImageFilter.SMOOTH_MORE)
smoother.save(filename)
def create_image(self, filepath, image_size, text_width):
# color from selector
global background_color
global text_color
c = background_color
d = text_color
# convert the code to hex
print(c)
if type(c) != str:
background_color = convert_to_hex(
(c.red / 65536.0, c.green / 65536.0, c.blue / 65536.0))
if type(d) != str:
text_color = convert_to_hex(
(d.red / 65536.0, d.green / 65536.0, d.blue / 65536.0))
# create an empity image and set the size
if 'x' in image_size:
MAX_W, MAX_H = [int(i) for i in image_size.split('x')]
else:
MAX_W, MAX_H = 400, 360
im = Image.new('RGB', (MAX_W, MAX_H), background_color)
draw = ImageDraw.Draw(im)
# set position of the text
current_h, pad = MAX_H * 40 / 100, 10
current_hs, pad = MAX_H * 40 / 100, 10
# decrease the size of the font if the text is too long
text = textwrap.wrap(image_name, width=text_width)
global text_shadow_color
# text shadow effects
if background_color == "#000000":
text_shadow_color = "#000000"
global font_desc
if 'font_desc' in globals():
font = ImageFont.truetype(font_desc, fontsize)
fontshadow = ImageFont.truetype(font_desc, fontsize)
else:
font = set_font(fontsize)
fontshadow = set_font(fontsize)
for line in text:
w, h = draw.textsize(line, font=font)
# draw the shadow
draw.text(
((MAX_W - w) / 2, current_hs), line, font=fontshadow, fill=text_shadow_color)
# now draw the text over it
draw.text(
((MAX_W - w) / 2, current_h), line, fill=text_color, font=font)
current_h += h + pad
current_hs += h + pad
if '.png' not in filepath:
filepath = filepath + '.png'
im.save(filepath)
set_image_filters(filepath, im)
update_image(self, filepath)
def update_image(self, filepath):
self.image.set_from_pixbuf(
GdkPixbuf.Pixbuf.new_from_file(filepath))
class imageGen(Gtk.Window):
def __init__(self):
super(imageGen, self).__init__()
self.set_size_request(720, 450)
self.set_position(Gtk.WindowPosition.CENTER)
self.connect("destroy", Gtk.main_quit)
self.set_title("SpeedDial Image Creator")
self.fontsize = Gtk.Entry()
self.fontsize.set_text("75")
self.fontsize.set_width_chars(3)
self.image = Gtk.Image()
self.chagefontlabel = Gtk.Label("Change Font")
self.fontsizelabel = Gtk.Label("Font Size")
titles_updated_store = Gtk.ListStore(int, str)
titles_not_updated_store = Gtk.ListStore(int, str)
fontsize_store = Gtk.ListStore(int, str)
dial_store = Gtk.ListStore(int, str)
font_store = Gtk.ListStore(int, str)
n = 1
# populate fontsize store
for i in range(10, 150, 5):
fontsize_store.append([n, str(i)])
n += 1
# load font list
outputCMD = subprocess.Popen(['fc-list'], stdout=subprocess.PIPE)
fclist = outputCMD.stdout.readlines()
n = 1
# parse font list to get only the font name
duplicated = []
for i in sorted(i for i in fclist):
fontname = str(i).split(':')[1]
if len(fontname) < 25 and fontname not in duplicated:
font_store.append([n, fontname])
duplicated.append(fontname)
n += 1
# design widgets
self.fontsize_combo = Gtk.ComboBox.new_with_model_and_entry(fontsize_store)
self.fontsize_combo.connect("changed", self.on_fontsize)
self.fontsize_combo.set_entry_text_column(1)
self.fontsize_combo.set_wrap_width(10)
self.fontchange_combo = Gtk.ComboBox.new_with_model_and_entry(font_store)
self.fontchange_combo .connect("changed", self.on_fontchange)
self.fontchange_combo .set_entry_text_column(1)
self.text_color = Gtk.Button("Select Text Color")
self.text_color.connect("clicked", self.on_text_color)
self.ok_image_name = Gtk.Button("Ok")
self.ok_image_name.connect("clicked", self.on_image_name)
self.ok_image_size = Gtk.Button("Ok")
self.ok_image_size.connect("clicked", self.on_image_size)
self.ok_text_width = Gtk.Button("Ok")
self.ok_text_width.connect("clicked", self.on_text_width)
self.save_image_button = Gtk.Button("Save")
self.save_image_button.connect("clicked", self.on_file_clicked)
self.settext = Gtk.Button("Set Text")
self.settext.connect("clicked", self.on_image_name)
self.text_shadow_color = Gtk.Button("Set Shadow Color")
self.text_shadow_color.connect("clicked", self.on_shadow_color)
self.imgcolor = Gtk.Button("Select Background Color")
self.imgcolor.connect("clicked", self.on_background_color)
self.image_name = Gtk.Entry()
self.image_name.set_text("Hello World")
self.image_size = Gtk.Entry()
self.image_size.set_text("400x360")
self.text_width = Gtk.Entry()
self.text_width.set_text("25")
# adjust position
fix = Gtk.Fixed()
fix.put(self.save_image_button, 10, 20)
fix.put(self.image_name, 10, 80)
fix.put(self.ok_image_name, 180, 80)
fix.put(self.image_size, 10, 120)
fix.put(self.ok_image_size, 180, 120)
fix.put(self.text_width, 10, 160)
fix.put(self.ok_text_width, 180, 160)
fix.put(self.image, 310, 40)
fix.put(self.imgcolor, 10, 200)
fix.put(self.text_color, 10, 240)
fix.put(self.text_shadow_color, 10, 280)
fix.put(self.chagefontlabel, 10, 320)
fix.put(self.fontchange_combo, 10, 340)
fix.put(self.fontsizelabel, 10, 380)
fix.put(self.fontsize_combo, 10, 400)
self.add(fix)
self.show_all()
create_image(self, image_tmp, image_size, text_width)
def on_fontsize(self, size):
tree_iter = size.get_active_iter()
if tree_iter != None:
model = size.get_model()
row_id, number = model[tree_iter][: 2]
global fontsize
fontsize = int(number)
else:
entry = combo.get_child()
create_image(self, image_tmp, image_size, text_width)
def on_fontchange(self, combo):
tree_iter = combo.get_active_iter()
if tree_iter != None:
model = combo.get_model()
row_id, name = model[tree_iter][:2]
global font_desc
font_desc = fontlist[name]
else:
entry = combo.get_child()
create_image(self, image_tmp, image_size, text_width)
def on_background_color(self, widget):
global background_color
csd = Gtk.ColorSelectionDialog('Background Color')
csd.run()
background_color = csd.get_color_selection().get_current_color()
csd.destroy()
create_image(self, image_tmp, image_size, text_width)
def on_text_color(self, widget):
global text_color
csd = Gtk.ColorSelectionDialog('Text Color')
csd.run()
text_color = csd.get_color_selection().get_current_color()
csd.destroy()
create_image(self, image_tmp, image_size, text_width)
def on_image_name(self, widget):
global image_name
image_name = self.image_name.get_text()
create_image(self, image_tmp, image_size, text_width)
def on_image_size(self, widget):
global image_size
image_size = self.image_size.get_text()
create_image(self, image_tmp, image_size, text_width)
def on_text_width(self, widget):
global text_width
if self.text_width.get_text().isdigit():
text_width = int(self.text_width.get_text())
create_image(self, image_tmp, image_size, text_width)
def on_shadow_color(self, widget):
global text_shadow_color
csd = Gtk.ColorSelectionDialog('foobar')
csd.run()
c = csd.get_color_selection().get_current_color()
text_shadow_color = convert_to_hex(
(c.red / 65536.0, c.green / 65536.0, c.blue / 65536.0))
csd.destroy()
create_image(self, image_tmp, image_size, text_width)
def add_filters(self, dialog):
filter_png = Gtk.FileFilter()
filter_png.set_name("PNG")
filter_png.add_pattern("*.png")
filter_png.add_mime_type("image/png")
dialog.add_filter(filter_png)
def on_file_clicked(self, widget):
dialog = Gtk.FileChooserDialog("Please choose a file", self,
Gtk.FileChooserAction.SAVE,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
dialog.set_current_name(image_name)
self.add_filters(dialog)
response = dialog.run()
if response == Gtk.ResponseType.OK:
print("Open clicked")
print("File selected: " + dialog.get_filename())
create_image(self, dialog.get_filename(), image_size, text_width)
elif response == Gtk.ResponseType.CANCEL:
print("Cancel clicked")
dialog.destroy()
if __name__ == "__main__":
imageGen()
Gtk.main()
<file_sep>/randomword-rare
#!/usr/bin/env python2
import random
import subprocess
import os
import getpass
user = getpass.getuser()
import time
def ranrom_rare_english():
infile=os.path.join("/home/" + user + "/Documents/rare-words.txt")
lines = open(infile, 'r').readlines()
lines_set = set(lines)
out = open(infile, 'w')
for line in lines_set:
out.write(line)
out.close()
englishword = random.choice(open(infile).read().split('\n'))
traduzida = subprocess.Popen(["trans", ":pt-br", "-b", englishword], stdout=subprocess.PIPE)
traduzida = traduzida.stdout.readlines()[0]
filename="/tmp/rareword.txt"
if os.path.exists(filename):
os.remove(filename)
tmp = open('/tmp/rareword.txt', 'w')
tmp.write(englishword)
print englishword,":", traduzida
ranrom_rare_english()
<file_sep>/git-new
#!/bin/sh
repo_name=$1
commit_msg=$2
test -z $repo_name && echo "Repo name required." 1>&2 && exit 1
test -z $commit_msg && echo "Commit msg required." 1>&2 && exit 1
git init
git add .
git remote set-url origin <EMAIL>:/$1.git
git commit -m "$2"
hub create
git push origin master
<file_sep>/randomword
#!/usr/bin/python2
import random
import subprocess
infile = "/home/neo/Documents/words.txt"
englishword = random.choice(open(infile).read().split('\n'))
traduzida = subprocess.Popen(["trans", ":pt-br", "-b", englishword], stdout=subprocess.PIPE)
traduzida = traduzida.stdout.readlines()[0]
print englishword, ":", traduzida
<file_sep>/newfile
#!/bin/sh
file=$(zenity --file-selection --filename=$1/newfile --save)
if [ "$?" = "0" ]; then
touch "$file"
fi
<file_sep>/english-copy
#!/bin/bash
zenity --question --ok-label=Sim --cancel-label=Não --text="Deseja Adicionar palavra(s) na base de dados de inglês?"
if [ $? = 0 ]; then
echo $(xsel -b) >> ~/Documents/rare-words.txt
else
exit
fi
<file_sep>/notify-send.sh
eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)"
DISPLAY=:1 su $USER -c "/usr/bin/notify-send 'my message'"
<file_sep>/bpaste
#!/bin/bash
zenity --question --ok-label=Sim --cancel-label=Não --text="Deseja criar um bpaste do texto copiado?"
if [ $? = 0 ]; then
wgetpaste -s bpaste -x -C
else
exit
fi
|
946e8cc53e17d2a3aa05778e46880cf4c1318513
|
[
"Python",
"Shell"
] | 15 |
Python
|
killown/scripts
|
026eedef9b36d44c46c2b3c65e93408139e754c0
|
cc2e850b231563266fc82378b2e6b3563fee171f
|
refs/heads/master
|
<file_sep># Canvas Hide Old Courses
Really basic QOL extension to hide old course on Canvas LMS. Frequently Professors forget to mark a class as finished, so the course stays in your current enrollment listing. This chrome extension identifies these courses and moves them visually to the the past enrollments. This makes no effect on the actual Canvas database, it is just a HTML visual effect.
This is not on the Chrome WebStore, it is too niche for anyone but me. If you want to use it, download this folder and load the extension in Developer Mode as an Unpacked Extension.
<file_sep>
function getRows(table) {
let rows = table.querySelectorAll("tbody tr");
rows = Array.from(rows).map(e => {return new Row(e)});
return rows;
}
function removeRow(table, row) {
let tbody = table.querySelector("tbody");
tbody.removeChild(row);
}
function addRow(table, row) {
let tbody = table.querySelector("tbody");
tbody.prepend(row)
}
function getSemester() {
let d = new Date();
//determine the year
let y = d.getFullYear();
//determine the semester, Spring, Summer or Fall
let m = d.getMonth();
let s = "";
if(m >= 0 && m <= 5) s = "Spring";
else if(m >= 6 && m <= 7) s = "Summer";
else if(m >= 8 && m <= 11) s = "Fall";
return y + " " + s;
}
//is the row the same semester as the current one
function isSameSemester(row, sem) {
return row.term.toLowerCase() === sem.toLowerCase();
}
class Row {
constructor(domObj) {
this.domObj = domObj;
this.name = this._getName(this.domObj);
this.hasFav = this._isFavorite(this.domObj);
//term is year followed by optional Spring, Summer, Fall
this.term = this._getTerm(this.domObj);
}
_getName(row) {
let name_td = row.querySelector("td.course-list-course-title-column");
let name_a = name_td.querySelector("a");
if(name_a) return name_a.innerText;
else return "";
}
//determine if a row is favorite or not
_isFavorite(row) {
let star_td = row.querySelector("td.course-list-star-column");
if(star_td.querySelector(".course-list-favorite-icon.icon-star")) return true;
else return false;
}
_getTerm(row) {
let term_td = row.querySelector("td.course-list-term-column");
let term_raw = term_td.innerText;
//get year and first word
let m = term_raw.match(/(\d+)[\s]+([a-zA-Z0-9\-_]+)/i);
let term = ""
if(m) {
let year = m[1];
let semester = m[2];
if(semester.match(/Spring/i)) semester = "Spring";
else if(semester.match(/Summer/i)) semester = "Summer";
else if(semester.match(/Fall/i)) semester = "Fall";
else semester = "";
term = year + " " + semester;
}
return term;
}
}
function applyFilter() {
let my_course_table = document.body.querySelector("#my_courses_table");
let past_enrollments_table = document.body.querySelector("#past_enrollments_table")
let rows = getRows(my_course_table);
let curSem = getSemester();
//we want to keep all favs and all that belong in current semester
let toBeMovedToPast = rows.filter(row => {
return ! (row.hasFav || isSameSemester(row, curSem))
});
toBeMovedToPast.forEach(row => {
removeRow(my_course_table, row.domObj);
addRow(past_enrollments_table, row.domObj)
});
}
document.addEventListener("DOMContentLoaded", (event) => {
applyFilter()
});
|
17ac279e478a04f4bec13b72c78f06b8d91cdaf3
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
jacob-abraham/CanvasHideOldCourses
|
340b88468f215e08bc1a1d9ef2ad4260ff17130f
|
7f17b239ccb9e54edcc3417d0226d09130909c3a
|
refs/heads/master
|
<repo_name>luckymore/vue-multipage-boilerplate<file_sep>/vue.config.js
const glob = require('glob')
const path = require('path')
const PAGES_PATH = path.resolve(__dirname, './src/pages')
const pages = {}
glob.sync(PAGES_PATH + '/*').forEach(filepath => {
let pageName = path.basename(filepath).split('.')
// if(/\.(js|vue)$/.test(pageName)) {
// }
// if (pageName[1]) pageName = pageName[0]
pageName = pageName[0].toLocaleLowerCase()
pages[pageName] = {
entry: filepath,
filename: `${pageName}.html`,
chunks: ['chunk-vendors', 'chunk-common', pageName]
}
})
// console.log(JSON.stringify(pages))
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? 'http://aaa.com/aaa' : '/dev',
pages
}
|
e67f2d9a9cbcf25d28bdd3839ccaac0db3ec2a78
|
[
"JavaScript"
] | 1 |
JavaScript
|
luckymore/vue-multipage-boilerplate
|
0ce6442cf345dbdbaab1001d18a395b67bcf039a
|
e3595d5ce391644907203c8d648c5260bd008eba
|
refs/heads/master
|
<file_sep>def sumBetween(x, y):
total = 0
for i in range (x + 1,y):
total = total + i
return total
print(sumBetween(1,4))
<file_sep>#DO NOT TAMPER WITH THIS FILE
#ANY EDITS YOU MAKE TO THIS FILE WILL BE SAVED TO YOUR PUBLIC GITHUB HISTORY
#TAMPERING WITH THIS FILE WILL BE OBVIOUS AND WILL RESULT IN A ZERO
import main;
import datetime;
year = 2021
month = 11
day = 19
def test_code():
assert main.sumBetween(1,2) == 0, "x = 1 y = 2 failed"
assert main.sumBetween(3,7) == 15, "x = 3 y = 7 failed"
assert main.sumBetween(0,2) == 1, "x = 0 y = 1 failed"
def test_late():
assert datetime.datetime.now() < datetime.datetime(year, month, day + 1, 4, 0), "Submitted Late"
<file_sep># **SumBetween**
## **Assignment Description**
Create a function called sumBetween() that returns the sum of all numbers between two given variables x and y. Do not include x and y in the calculation.
## **Examples**
>sumBetween(5,7)
6
>sumBetween(5,10)
30
>sumBetween(1,2)
0
## **Limitations**
1 for loop
0 if
0 else
## **Hints**
in range(x,y) includes x and excludes y
## **Concepts**
Unit 1, Unit 2, for looops
---
## **How to complete this assignment**
In order to complete this assignment, you will need to write your code in the main.py file.
This assignment will automatically be tested and graded upon completion.
Once you submit your work, you can see if your code passed or failed by going to the "Actions" page of your github repository for this assignment. It may take a few minutes for the test to finish running. A red X means that it failed. A green check means that your assignment successfully passed and you are finished.
To submit your work, run these commands in the terminal:
>git add .
git commit -m "*Title of Assignment* try #"
git push
There is no limitation for the number of times you may submit.
Email me with any questions you may have about completing this assigment
<EMAIL>
|
7473316e2aec11b0fb85bad41ecf34c5dec755c9
|
[
"Markdown",
"Python"
] | 3 |
Python
|
Introduction-to-Programming-OSOWSKI/3-1-sumbetween-IsaacYantes23
|
8c30d9ec9e4cc8a239e5cca30df21c726500f9a9
|
7a8b31c0e7a236be01808a25f6eab2ccbb011ce2
|
refs/heads/master
|
<file_sep># Understanding Scope
### Recommended Reading
1. https://scotch.io/tutorials/understanding-scope-in-javascript
2. https://blog.bitsrc.io/understanding-scope-and-scope-chain-in-javascript-f6637978cf53
3. https://codeburst.io/javascript-learn-understand-scope-f53d6592c726
4. https://blog.codeanalogies.com/2017/11/22/how-javascript-variable-scoping-is-just-like-multiple-levels-of-government/
5. https://medium.com/@ashcoca/scopes-in-javascript-a-simple-and-visual-explanation-1427a55c29fa
### Recommended Videos
1. https://youtu.be/SBwoFkRjZvE - Javascript is Weird - Scopes
2. https://youtu.be/iJKkZA215tQ - Javascript Scope, Local vs Global
### Additional Resources
1. Udacity Course - Scopes (Lesson 1) - https://classroom.udacity.com/courses/ud015
2. A tool for visualizing Execution Context, Hoisting, Closures, and Scopes in JavaScript -- https://tylermcginnis.com/javascript-visualizer/
### Scope Examples
```javascript
function add2(x) {
return function (y) {
return x+y;
}
}
console.log(add2(5)(2)); // 7 we are pre-passing a variable to the nested function
```
```javascript
function a() {
var x = 1;
function y() {
var y = 2;
return x + y;
}
console.log(y); // undefined, you can't access y here
console.log(y()) // 3
}
```
```javascript
function a() {
var x = 1;
function y() {
y = 2; // var keyword omitted giving global scope
return x + y;
}
console.log(y); // 2 global scope access is granted to y
console.log(y()) // 3
}
```
### Scopes Adventure!
> Try to follow along with this adventure! Paste it into a snippet and try running it and see if you can understand why it works!
```javascript
// once upon a time, there was a princess
var Princess = function() {
// who rode around her world on a unicorn, battled dragons, encountered talking animals, and many other fantastical things.
var unicorn = {
name: 'Sparkles'
};
var dragons = [
'A green one with purple wings',
'A mean black one who breathed fire',
'A fluffy white one that looked like a dog'
];
var talkingAnimals = {
squirrel: "Hello!"
};
// and lived in a wonderful world full of adventures
var adventures = [
'My unicorn ' + unicorn.name + ' had a baby!',
'I fought ' + dragons.length + ' dragons!',
'I met a talking squirrel who said "' + talkingAnimals.squirrel + '"'
];
// but she would always have to return back to her dull world of chores and grown-ups
return {
// and she would often tell them of her latest amazing adventure as a princess
story: function() {
return adventures.pop();
}
};
};
// but all they could see is a little girl
var littleGirl = new Princess();
window.console.log(littleGirl);
// telling stories about magic and fantasy
window.console.log(littleGirl.story());
window.console.log(littleGirl.story());
window.console.log(littleGirl.story());
```<file_sep>// *Step 1 - Find what is in var hidden
// mystery is run with the input of 3, the return value is mystery2
// hidden contains scope of ...
// secret = 4;
// input = 5 (the 3 from the input then the +2 from the expression on line 10)
var hidden = function mystery2 ( multiplier ) {
multiplier *= 5;
return 4 * multiplier;
}
// *Step 2 - Find what is in var jumble
// var jumble contains the return value of mystery3, what is returned in mystery3?
var jumble = function mystery4( bonus ){
return param(6) + bonus;
}
// *Step 3 - Find the Value of Result
var result = jumble( 2 );
// pass 2 into 'bonus'
function mystery4( 2 ) {
return param(6) + 2
}
// uh oh? what is the value of param?
// param is the paramter passed to mystery3
// but wait? we already passed a parameter to mystery3 when we defined Jumble
var jumble = mystery3( hidden );
// hidden contains
var hidden = function mystery2( multiplier ) {
multiplier *= input;
return secret * multiplier;
}
// So we just replace the param with hidden, since that is already passed to mystery3
// Ultimatley the (6) is the value of the paramter multiplier
var jumble = function mystery4( 2 ) {
return hidden(6) + 2;
}
//You probably still remember that 'hidden' was nothing else,
//but our version of the mystery2 function, which is run here with
//6 as an argument. In this case, hidden becomes:
var hidden = function mystery2( 6 ) {
return 6 * 5 * 4;
}
// hidden returns 120, then look back into jumble, we still have to add 2, the final answer is 122<file_sep>/*
Problem #1:
Create a calculator that takes in an array of numbers and will add, subtract, multiply or divide the values of the
passed in array depending on the method called.
Notes:
Your solution should be able to handle more than two numbers.
Sample output:
var myCalc = new Calculator();
myCalc.add([1, 2]) // returns 3
myCalc.multiply([5, 4]) // returns 20
myCalc.subtract([5, 4, 1]) // returns 0
Constraints:
The divisor will always be a non zero integer.
*/
function Calculator() {
this.add = function(input){
// YOUR CODE HERE
};
this.multiply = function(input){
// YOUR CODE HERE
};
this.subtract = function(input){
// YOUR CODE HERE
};
this.divide = function(input){
// YOUR CODE HERE
};
};
/*
Problem #2:
*/<file_sep># Understanding Execution Context
### Recommended Reading
1. https://blog.bitsrc.io/understanding-execution-context-and-execution-stack-in-javascript-1c9ea8642dd0
2. https://tylermcginnis.com/ultimate-guide-to-execution-contexts-hoisting-scopes-and-closures-in-javascript/
3. https://www.valentinog.com/blog/context/
### Recommended Videos
1. https://youtu.be/FJNRmUdLlfw
2. https://youtu.be/W8AeMrVtFLY - Call stack
### Additional Resources
1. https://tylermcginnis.com/javascript-visualizer/ -- A tool for visualizing Execution Context, Hoisting, Closures, and Scopes in JavaScript
### Execution Context Examples
Look at the code below and try to predict what will be logged on each of the 6 lines
```javascript
var myString = "I'm outside";
function f() {
console.log(myString); // 2
var myString = "I'm in function";
console.log(myString); // 3
for (var i = 0; i < 1; ++i) {
var myString = "I'm in for";
console.log(myString); // 4
}
console.log(myString); // 5
}
console.log(myString); // 1
f();
console.log(myString); // 6
```
Once you've made a prediction scroll down to see the actual results
.
.
.
```
1. "I'm outside"
2. undefined
3. "I'm in function"
4. "I'm in for"
5. "I'm in for"
6. "I'm outside
```
From: https://weeklywebwisdom.com/2017/09/08/javascript-execution-context-and-scope/<file_sep># Underbar Reference Solutions
Reference solutions for the Underbar I and II sprints of the HREXT program at Hack Reactor.<file_sep># Git Resources
**Why do we use Git?**
Say you're working on a paper. You write five paragraphs. Then your friend comes along later, and writes another five paragraphs. Then you edit a few paragraphs, and your friend edits a few more paragraphs.
At the end of it, there are some issues, but its hard to coordinate who edited what and when, so what do you do?
**Version Control with GIT**
With a system like GIT, you would first create the file on the GIT server, and add your changes. Then, you commit those changes to the repository, which will basically say 'Hey, this file exists and looks like this.'
Then, your friend checks out that repo, pulling the latest changes. He adds some stuff, then commits to the repo. The repo says 'Hey, this file exists and is different from the previous version, so we will save it as version 2.'
So on and so forth. The GIT repo allows you and your friend to make edits and keep the changes sort of sequential, so if your friend messes up at #5, you can say 'GIT, please check out #4' and you can get back to fixing things. Each commit has an owner, so you know who did what. And you can compare Version X to Version Y, and see what has changed, making it easier to spot what new changes have been made.
**Branches**
GIT also allows you to branch. So you and your friend are on version 10 of the doc, but you want to try something new. Your friend wants to continue, so you create a branch called 'MyNewIdea' and start working on that. This is now a separate path of writing, while your friend continues on the original, which is usually considered the master.
### Additional Reading
1. https://pixelpioneers.co/blog/2017/git-basics-explained-by-designing-a-new-car
2. https://blog.thoughtram.io/git/rebase-book/2015/02/10/understanding-branches-in-git.html
<file_sep>/*
Write a function that takes the number of times the callback needs to be called before
being executed as the first parameter and the callback as the second parameter
Example Output:
var called = function() {
console.log('hello');
};
var afterCalled = calledWhenReady(3, called);
afterCalled(); // -> nothing is printed
afterCalled(); // -> nothing is printed
afterCalled(); // -> 'hello' is printed
*/
function calledWhenReady(timesBefore, callback) {
// YOUR CODE HERE
};<file_sep># Resources for Tricky Topics
**Recommended Study Order**
1. Git
2. Returns
3. Scopes
4. Closures
5. Execution Context
6. Async<file_sep>(function() {
'use strict';
window._ = {};
// Returns whatever value is passed as the argument. This function doesn't
// seem very useful, but remember it--if a function needs to provide an
// iterator when the user does not pass one in, this will be handy.
_.identity = function(val) {
return val;
};
/**
* COLLECTIONS
* ===========
*
* In this section, we'll have a look at functions that operate on collections
* of values; in JavaScript, a 'collection' is something that can contain a
* number of values--either an array or an object.
*
*
*/
// Return an array of the first n elements of an array. If n is undefined,
// return just the first element.
_.first = function(array, n) {
// If n is not defined, just return the first element.
if (n === undefined) {
return array[0];
}
// If n is defined we can use slice to return the correct n elements.
return array.slice(0, n);
};
// Like first, but for the last elements. If n is undefined, return just the
// last element.
_.last = function(array, n) {
// Similar to above, if n is undefined we'll just return the last element.
if (n === undefined) {
return array[array.length -1];
}
// We'll return the entire array if n is greater than the length of the entire array.
if (n > array.length) {
return array;
}
// Otherwise we'll just return the last n elements
return array.slice(array.length - n, array.length);
};
// Call iterator(value, key, collection) for each element of collection.
// Accepts both arrays and objects.
//
// Note: _.each does not have a return value, but rather simply runs the
// iterator function over each item in the input collection.
_.each = function(collection, iterator) {
// We need to check if our collection is an object or an array
if (Array.isArray(collection)) {
for (var i = 0; i < collection.length; i++) {
// Iterator takes in 3 arguments, see underbar docs for more info
iterator(collection[i], i, collection);
}
} else {
// We can safely assume if it's not an array then our collection is an object
for (var key in collection) {
iterator(collection[key], key, collection);
}
};
// No need to return anything!
};
// Returns the index at which value can be found in the array, or -1 if value
// is not present in the array.
_.indexOf = function(array, target){
// Iterate through our array
for (var i = 0; i < array.length; i++) {
// Check if each index is our target, if it is, return that index
if (array[i] === target) {
return i;
}
};
// If we complete our loop without finding our target, we return -1
return -1;
};
// Return all elements of an array that pass a truth test.
_.filter = function(collection, test) {
var truthyValues = [];
// We can use _.each to iterate!
_.each(collection, function(value) {
// We'll run the filter test over the current iteration, then push it to our output array if it passes
if (test(value)) {
truthyValues.push(value);
}
});
return truthyValues;
//* Basic for loop solution for reference
// for (var i = 0; i < collection.length; i++) {
// if (test(collection[i])) {
// truthyValues.push(collection[i])
// }
// };
// return truthyValues;
};
// Return all elements of an array that don't pass a truth test.
_.reject = function(collection, test) {
var falsyValues = [];
_.each(collection, function(value) {
if (!test(value)) {
falsyValues.push(value);
}
});
return falsyValues;
};
// Produce a duplicate-free version of the array.
_.uniq = function(array, isSorted, iterator) {
// See the hint above on the _.identity problem to get an idea of why we need this line below!
iterator = iterator || _.identity;
var uniqValues = {};
_.each(array, function(value) {
var newValue = iterator(value);
if (uniqValues[newValue] === undefined) {
uniqValues[newValue] = value;
}
});
// Uncomment to take a look at what's being stored in our uniqValues object!
// console.log(uniqValues)
// We need to output an array
var results = [];
for (var key in uniqValues) {
results.push(uniqValues[key])
};
return results;
};
// Return the results of applying an iterator to each element.
_.map = function(collection, iterator) {
// We don't want to modify the input so we'll declare a new array
var mappedArr = [];
// Iterate over each value in the collection. We could use a for loop but let's use _.each instead
_.each(collection, function(value, index, collection) {
// Apply the iterator function to each value and push it to the mapped array
mappedArr.push(iterator(value, index, collection));
});
return mappedArr;
};
/*
* TIP: map is really handy when you want to transform an array of
* values into a new array of values. _.pluck() is solved for you
* as an example of this.
*/
// Takes an array of objects and returns and array of the values of
// a certain property in it. E.g. take an array of people and return
// an array of just their ages
_.pluck = function(collection, key) {
// TIP: map is really handy when you want to transform an array of
// values into a new array of values. _.pluck() is solved for you
// as an example of this.
/* START SOLUTION */
return _.map(collection, function(element) {
return element[key];
});
/* END SOLUTION */
};
// Reduces an array or object to a single value by repetitively calling
// iterator(accumulator, item) for each item. accumulator should be
// the return value of the previous iterator call.
//
// You can pass in a starting value for the accumulator as the third argument
// to reduce. If no starting value is passed, the first element is used as
// the accumulator, and is never passed to the iterator. In other words, in
// the case where a starting value is not passed, the iterator is not invoked
// until the second element, with the first element as its second argument.
//
_.reduce = function(collection, iterator, accumulator) {
// Remember _.reduce should work with objects AND arrays!
var isAcc = true;
if (arguments.length === 2) {
isAcc = false;
};
_.each(collection, function(value) {
// If there is no accumulator
if (!isAcc) {
// Set the accumulator to the current value
accumulator = value;
isAcc = true;
} else {
accumulator = iterator(accumulator, value);
}
});
return accumulator;
};
_.findIndex = function(array, iterator) {
for (var i = 0; i < array.length; i++) {
// If the current iteration passes our predicate test we return that index
if (iterator(array[i])) {
return i;
}
};
// If nothing in our array passes the test then we'll return -1
return -1;
};
// Determine if the array or object contains a given value (using `===`).
_.contains = function(collection, target) {
// TIP: Many iteration problems can be most easily expressed in
// terms of reduce(). Here's a freebie to demonstrate!
/* START SOLUTION */
return _.reduce(collection, function(wasFound, item) {
if (wasFound) {
return true;
}
return item === target;
}, false);
/* END SOLUTION */
};
// Determine whether all of the elements match a truth test.
_.every = function(collection, iterator) {
// TIP: Try re-using reduce() here.
/* START SOLUTION */
iterator = iterator || _.identity;
return _.reduce(collection, function(accumulator, item) {
if (!iterator(item)) {
accumulator = false;
}
return accumulator;
}, true);
/* END SOLUTION */
};
// Determine whether any of the elements pass a truth test. If no iterator is
// provided, provide a default one
_.some = function(collection, iterator) {
// TIP: There's a very clever way to re-use every() here.
iterator = iterator || _.identity;
return !_.every(collection, function(item) {
return !iterator(item);
});
// If this is confusing try walking through it with this example:
// Collection = [2, 4, 6]; Iterator = isEven test
// What happens each step of the way? What if the collection is [2, 4, 5, 6]?
};
/**
* OBJECTS
* =======
*
* In this section, we'll look at a couple of helpers for merging objects.
*/
// Extend a given object with all the properties of the passed in
// object(s).
//
// Example:
// var obj1 = {key1: "something"};
// _.extend(obj1, {
// key2: "something new",
// key3: "something else new"
// }, {
// bla: "even more stuff"
// }); // obj1 now contains key1, key2, key3 and bla
_.extend = function(obj) {
// The first argument is our target obj that we want to merge into
var targetObj = arguments[0];
// Let's loop through the arguments to find our other objects
for (var i = 1; i < arguments.length; i++) {
// We can give our current object a name just to make things more readable
var currentObj = arguments[i];
// Then we'll loop through all the keys in the currentObj and add them to our targetObj
for (var key in currentObj) {
targetObj[key] = currentObj[key];
}
};
return targetObj;
};
// Like extend, but doesn't ever overwrite a key that already
// exists in obj
_.defaults = function(obj) {
/* START SOLUTION */
var targetObj = arguments[0];
for (var i = 1; i < arguments.length; i++) {
var currentObj = arguments[i];
for (var key in currentObj) {
if (targetObj[key] === undefined) {
targetObj[key] = currentObj[key];
}
}
};
return targetObj;
/* END SOLUTION */
};
/**
* FUNCTIONS
* =========
*
* Now we're getting into function decorators, which take in any function
* and return out a new version of the function that works somewhat differently
*/
// Return a function that can be called at most one time. Subsequent calls
// should return the previously returned value.
_.once = function(func) {
// TIP: These variables are stored in a "closure scope" (worth researching),
// so that they'll remain available to the newly-generated function every
// time it's called.
/* START SOLUTION */
// We'll use this var to keep track of whether or not our fn has run yet
var hasRun = false;
var results;
return function() {
if (!hasRun) {
// Ex: We can use apply to ensure that the [2, 4, 6] are passed in -> _.once(isEven([2, 4, 6]))
results = func.apply(this, arguments);
hasRun = true;
}
return results;
};
/* END SOLUTION */
};
// Memorize an expensive function's results by storing them. You may assume
// that the function only takes primitives as arguments.
// memoize could be renamed to oncePerUniqueArgumentList; memoize does the
// same thing as once, but based on many sets of unique arguments.
//
// _.memoize should return a function that, when called, will check if it has
// already computed the result for the given argument and return that value
// instead if possible.
_.memoize = function(func) {
/* START SOLUTION */
var memo = {};
return function() {
// We can stringify the arguments to allow for obj comparison
var args = JSON.stringify(arguments);
// If the fn has NOT been run with these arguments, we'll run it and store the results
if (!memo[args]) {
memo[args] = func.apply(this, arguments);
}
return memo[args];
};
/* END SOLUTION */
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
//
// The arguments for the original function are passed after the wait
// parameter. For example _.delay(someFunction, 500, 'a', 'b') will
// call someFunction('a', 'b') after 500ms
_.delay = function(func, wait) {
/* START SOLUTION */
// We can convert the arguments obj into an array and slice the arguments we need
var args = Array.from(arguments).slice(2)
setTimeout(function() {
func.apply(this, args);
}, wait);
/* END SOLUTION */
};
/**
* ADVANCED COLLECTION OPERATIONS
* ==============================
*/
// Randomizes the order of an array's contents.
//
// TIP: This function's test suite will ask that you not modify the original
// input array. For a tip on how to make a copy of an array, see:
// http://mdn.io/Array.prototype.slice
_.shuffle = function(array) {
/* START SOLUTION */
var copyArr = array.slice();
var shuffled = [];
// We can use a helper function to get a random Index!
var getRandomIndex = function(max) {
return Math.floor(Math.random() * Math.floor(max));
};
while (copyArr.length > 0) {
var randomItem = getRandomIndex(copyArr.length);
shuffled.push(copyArr[randomItem]);
// Remove the random item from our copyArr
copyArr.splice(randomItem, 1);
};
return shuffled;
/* END SOLUTION */
};
/**
* ADVANCED
* =================
*
* Note: This is the end of the pre-course curriculum. Feel free to continue,
* but nothing beyond here is required.
*/
// Calls the method named by functionOrKey on each value in the list.
// Note: You will need to learn a bit about .apply to complete this.
_.invoke = function(collection, functionOrKey, args) {
/* START SOLUTION */
return _.map(collection, function(item) {
// Check to see if it's a function or a key
if (typeof functionOrKey === 'function') {
return functionOrKey.apply(item, args);
} else {
// If it's a key...
return item[functionOrKey].apply(item, args);
}
});
/* END SOLUTION */
};
// Sort the object's values by a criterion produced by an iterator.
// If iterator is a string, sort objects by that property with the name
// of that string. For example, _.sortBy(people, 'name') should sort
// an array of people by their name.
_.sortBy = function(collection, iterator) {
/* START SOLUTION */
if (typeof iterator === 'function') {
return collection.sort(function(a, b) {
return iterator(a) - iterator(b);
});
} else {
return collection.sort(function(a, b) {
return a[iterator] - b[iterator];
});
}
/* END SOLUTION */
};
// Zip together two or more arrays with elements of the same index
// going together.
//
// Example:
// _.zip(['a','b','c','d'], [1,2,3]) returns [['a',1], ['b',2], ['c',3], ['d',undefined]]
_.zip = function() {
/* START SOLUTION */
var maxLength = 0;
var results = [];
// First let's find the length of the longest input array
_.each(arguments, function(item) {
if (item.length > maxLength) {
maxLength = item.length;
}
});
for (var i = 0; i < maxLength; i++) {
var currentValsAtIndex = [];
// For each index we loop through the arguments and push the current values at that index to an array
_.each(arguments, function(val) {
currentValsAtIndex.push(val[i]);
})
// Then we'll push that array to our result array
results.push(currentValsAtIndex);
}
return results;
/* END SOLUTION */
};
// Takes a multidimensional array and converts it to a one-dimensional array.
// The new array should contain all elements of the multidimensional array.
//
// Hint: Use Array.isArray to check if something is an array
_.flatten = function(nestedArray, result) {
/* START SOLUTION */
var depthCount = 0;
// We can use a helper function to find out how deep our nestedArray is!
var checkDepth = function(array) {
for (var i = 0; i < nestedArray.length; i++) {
// If we find a nested array as we iterate we increment our depthCount and run checkDepth on the array
if (Array.isArray(array[i])) {
depthCount += 1;
checkDepth(array[i]);
}
};
};
checkDepth(nestedArray);
// Once we know how deep the nested arrays go we can use the native array flat method
return nestedArray.flat(depthCount);
/* END SOLUTION */
};
// Takes an arbitrary number of arrays and produces an array that contains
// every item shared between all the passed-in arrays.
_.intersection = function() {
/* START SOLUTION */
var results = [];
// We can compare the values in the other arrays to our first array
var firstArr = arguments[0];
var otherArrays = Array.from(arguments).slice(1);
// Iterate through each item and each other array
_.each(firstArr, function(item) {
// We can use this boolean to keep track of whether an item is present in all arrays
var isPresentInAll = false;
_.each(otherArrays, function(arr) {
if (arr.includes(item)) {
isPresentInAll = true;
}
});
if (isPresentInAll) {
results.push(item);
}
});
return results;
/* END SOLUTION */
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
/* START SOLUTION */
var results = [];
var firstArr = arguments[0];
var otherArrays = Array.from(arguments).slice(1);
_.each(firstArr, function(item) {
var isItemPresent = false;
_.each(otherArrays, function(arr) {
if (arr.includes(item)) {
isItemPresent = true;
}
});
if (!isItemPresent) {
results.push(item);
}
});
return results;
/* END SOLUTION */
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. See the Underbar readme for extra details
// on this function.
//
// Note: This is difficult! It may take a while to implement.
_.throttle = function(func, wait) {
/* START SOLUTION */
// We'll use this hasRun var to keep track of whether the func has run or not.
var hasRun = false;
// We can use this helper function to reset the hasRun flag
var resetHelper = function() {
hasRun = false;
};
return function() {
if (!hasRun) {
hasRun = true;
// Use setTimeout to run the resetHelper after the wait
setTimeout(resetHelper, wait);
return func();
}
};
/* END SOLUTION */
};
}());
<file_sep># Scopes, Closures and keyword 'this' Practice Problems
All problems are contained within /src
<file_sep>/*
Implement a magic dictionary with buildDict, and search methods.
For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary.
For the method search, you'll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built.
Example 1:
Input: buildDict(["hello", "leetcode"]), Output: Null
Input: search("hello"), Output: False
Input: search("hhllo"), Output: True
Input: search("hell"), Output: False
Input: search("leetcoded"), Output: False
*/
var MagicDictionary = function() {
this.dict = {};
};
MagicDictionary.prototype.buildDict = function(words) {
for (var i = 0; i < words.length; i++) {
this.dict[words[i].length]
}
};
MagicDictionary.prototype.search = function(word) {
};<file_sep># Understanding Async
Understanding how asynchronous functions can affect your code in javascript can be tricky. Let's try to first understand the difference between **blocking** and **non-blocking** code.
1. Blocking aka synchronous code
This is the code you're likely most used to seeing at this point. Blocking or synchronous code waits for one action to complete before moving on and executing the next line of code.
2. Non-Blocking aka asynchronous code
Non-Blocking code simply doesn't block execution execution of subsequent lines of code. Operations are performed independent of other system operations.
Think of Blocking as if you're waiting for someone to join you on a date. Until they arrive, you just wait indefinitely. Non-Blocking on the other hand is like you invited someone to join you, but you aren't sure if they're going to come so you keep busy doing other things instead of simply waiting around.
### Recommended Reading
1. http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/
2. https://medium.com/dailyjs/asynchronous-adventures-in-javascript-understanding-the-event-loop-fc6f968d5f72
### Recommended Videos
1. https://youtu.be/YxWMxJONp7E - Part 1 of Series on Async
2. https://youtu.be/8aGhZQkoFbQ - Event Loop Explained
3. https://youtu.be/6MXRNXXgP_0 - Updated version of above
## Common Questions/Issues
1. What does it mean when people say Javascript runs on a single thread?
Essentially this means that one command can be processed at a time in Javascript.
2. What are the pros/cons of single threads vs multi-threads and other options?
* Synchronous/single thread: You handle one request at a time, each in turn. pros: simple. cons: any one request can hold up all the other requests
* Fork a new process: you start a new process to handle each request. pros: easy cons: does not scale well, hundreds of connections means hundreds of processes. fork() is the Unix programmer's hammer. Because it's available, every problem looks like a nail. It's usually overkill
* Threads: Start a new thread to handle each request. pros: easy, and kinder to the kernel than using fork, since threads usually have much less overhead cons: your machine may not have threads, and threaded programming can get very complicated very fast, with worries about controlling access to shared resources.
3. How does Javascript get around the limitations of running on a single thread?
By using something called the **event-loop** see Recommended Reading/Videos above for more information
<file_sep>// Note that these are just one of many possible solutions!
// Provided for reference, please try to solve the problem on your own before reviewing this!
function Calculator() {
this.add = function(input){
return function() {
var result = input[0];
for (var i = 1; i < input.length; i++) {
result = result + input[i];
};
return result;
}();
};
this.multiply = function(input){
return function() {
var result = input[0];
for (var i = 1; i < input.length; i++) {
result = result * input[i];
};
return result;
}();
};
// Instead of writing more repetitive code like above let's try use a helper function to save time!
// When you notice your code is repetitive it can be a good idea to try and refactor!
this.subtract = function(input){
return operation(input, function(result, input) {
return result - input;
});
};
this.divide = function(input){
return operation(input, function(result, input) {
return result / input;
});
};
function operation(input, operator) {
var result = input[0];
for(var i = 1; i < input.length; i++){
result = operator(result, input[i]);
};
return result;
};
};<file_sep># Understanding Returns
The basics of return statements:
1. Every function in Javascript returns undefined unless *otherwise specified*
2. Return statements end function execution
3. Return statements return a value to the function caller
### Recommended Reading
1. https://codeburst.io/javascript-what-is-the-return-statement-97d8b11a1a0c - Expands on above basics w/ examples
2. https://hackernoon.com/some-thoughts-on-the-return-statement-9d99771f2838
### Recommended Videos
1. https://youtu.be/AdQcd3sKGC8 - The Return Statment
2. https://youtu.be/qRnUBiTJ66Y - Functions and Returns
3. https://youtu.be/gdGmpTcNZXQ - Beginners Return Statement Tutorial
### Return Example
> You have 10 + 2 + 5 + 3 written on a whiteboard and you want to solve it. How do you do this?
> You start with the first operation, 10 + 2. That's 12, so you wipe 10 + 2 off the board and replace it with the number 12. Now the whiteboard reads 12 + 5 + 3. So you do it again: 12 + 5 = 17, so you wipe off 12 + 5 and replace it with the result, 17. Now it says 17 + 3. Well that's 20, so you wipe it off again and just write 20, the result.
> Makes sense? Now imagine instead the board reads:
```javascript
add(10, 2) + add(5, 3)
```
> This is the exact same thing. add is a function, and it takes two arguments, the numbers to add together. When it's calculated the result, the text "add(10, 2)" will be wiped off the board and be replaced by that result. This function would be written:
```javascript
function add(num1, num2) {
return num1 + num2;
}
```
> and after running it the whiteboard would read: 12 + 8. The keyword return means *this function is done, now place this value at the point where it was called.* When a function completes, it is wiped off the whiteboard, and whatever was returned by it is written in its place.
> Now let's look at this and try to imagine the same thing:
```javascript
function Food() {
return "strawberry";
}
myFave = Food();
```
> If I say console.log(myFave()) what do you think will get logged? Well, Food() will be executed. It will complete, and because "strawberry" is returned, that last line essentially becomes
```javascript
myFave = "strawberry"
```
### Common Questions/Issues
1. What happens when you put a return statement inside of a for loop?
> A return statement will stop the execution of your for loop and return a value (if specified). This is a common mistake people make using return statements inside of a loop. As soon as your for loop hits that first return, it's going to exit the loop. If you need to store a value but want to continue looping, try exploring other options instead of using a return statement.<file_sep>describe("Calculator", function() {
var calculator;
beforeEach(function() {
calculator = new Calculator();
});
describe("Arithmetic operations on an input array", function() {
it("creates a new Calculator", function() {
expect(calculator).not.to.equal(null);
});
it("should add numbers", function() {
expect(calculator.add([1, 0])).to.equal(1);
expect(calculator.add([5, 6])).to.equal(11);
expect(calculator.add([1,2,3])).to.equal(6);
});
it("should multiply numbers", function() {
expect(calculator.multiply([1, 2])).to.equal(2);
expect(calculator.multiply([5, 6, 7])).to.equal(210);
expect(calculator.multiply([5, 0, 6])).to.equal(0);
});
it("should subtract numbers", function() {
expect(calculator.subtract([3, 2])).to.equal(1);
expect(calculator.subtract([5, 4, 1])).to.equal(0);
});
it("should divide numbers", function() {
expect(calculator.divide([10, 2, 5])).to.equal(1);
expect(calculator.divide([40, 2])).to.equal(20);
expect(calculator.divide([0, 2])).to.equal(0);
});
});
});
describe("calledWhenReady function", function() {
var called = function() {
return 5;
};
it("should not return anything when called fewer than the designated # of times", function() {
var afterCalled = calledWhenReady(3, called);
expect(afterCalled()).to.equal(undefined);
});
it("should return a value when called more than the designated # of times", function() {
var afterCalled = calledWhenReady(3, called);
afterCalled();
afterCalled();
expect(afterCalled()).to.equal(5);
});
});
describe("createBase function", function() {
var addTen = createBase(10);
it("should use closure to solve the problem", function() {
expect(typeof(addTen)).to.equal('function');
});
it("should return the sum of the base number and the passed in value", function() {
var result = addTen(7);
expect(result).to.equal(17);
});
});<file_sep># Reference Solutions, Practice Problems and More
**In this Repo:**
### Reference Solutions
> Solutions for Hack Reactor Extended Sprints
1. Underbar Part I & II
2. Recursion Koans
### Study Resources
> Information, Recommended Reading, Videos, Frequently Asked Questions, Examples and Explanations on the following:
1. Closures
2. Scopes
3. Execution Context
4. Async
5. Return Statments
6. Git
### Toy Problems
> Practice problems, worksheets, all complete with a full testing suite and specrunner, reference solutions and explanations covering the following topics:
1. Scopes
2. Closures
3. Keyword 'this'
Good luck and happy coding!<file_sep>/*
This problem is a little different. You won't be coding anything, your goal is
to follow along with what's happening in this already built function. This
problem will test your understanding of scopes and closures.
Note: There are no spec tests for this problem.
DO NOT CHANGE ANYTHING!!
GOAL: Find the value of the *result* variable
*/
var hidden = mystery(3);
var jumble = mystery3(hidden);
var result = jumble(2);
function mystery ( input ){
var secret = 4;
input += 2;
function mystery2 ( multiplier ) {
multiplier *= input;
return secret * multiplier;
};
return mystery2;
};
function mystery3 ( param ){
function mystery4 ( bonus ){
return param(6) + bonus;
};
return mystery4;
};<file_sep># Recursion Prompts
Reference Solutions for the Recursion Koans sprint for HREXT<file_sep># Understanding Closure
### Reading Resources:
1. https://css-tricks.com/javascript-scope-closures/
2. https://medium.freecodecamp.org/javascript-closures-explained-by-mailing-a-package-4f23e9885039 -- My favorite
3. https://prettydiff.com/2/guide/closure_with_jsscope.xhtml
4. https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch1.md
5. https://medium.com/@samkwon521/eli5-closures-c0018a23e3c5
### Recommended Videos
1. https://youtu.be/ZqGFKcCcO-Y
2. https://youtu.be/71AtaJpJHw0
3. https://youtu.be/O312eN5J2bc -- Multi-Part Series, In-Depth
### Additional Resources
1. Why global state/variables are bad and alternatives -- https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil/148154#148154
2. Udacity Course - Closures (Lesson 2) -- https://classroom.udacity.com/courses/ud015
3. A tool for visualizing Execution Context, Hoisting, Closures, and Scopes in JavaScript -- https://tylermcginnis.com/javascript-visualizer/
4. Python Tutor - A tool to watch your code as it executes (be sure to change the language to JavaScript!) -- http://www.pythontutor.com/live.html
## Common Questions
**1. Why are closures so important?**
> Closures have a few advantages. One is that variables contained in closure scope don't pollute the global namespace which can help prevent collisions with other libraries or parts of your app.
> Think about this: Local variables are defined and used within a function, whereas global variables are defined for the function window. In short, until the code terminates, global variables will be present, lurking in the background, using memory. Although variables storing little data won’t be too critical, if you store a lot of data in it it’ll choke your bandwidth and definitely threaten the page efficiency. Too much data stored as cache slows the speed of your browser, resulting in high latency. Caches are a website’s data that are stored and used when you revisit the site time and again.
**2. What's a practical use for closures in the real world?**
> Suppose you wanted to count the number of times a user clicked on a button on your webpage. To do this you'd trigger a function onClick event for the button to update the count of the variable.
> Let's consider some of the ways we could accomplish this.
1. You could use a *global variable* and a function to increase the counter
```javascript
var counter = 0;
function updateClickCount() {
++counter;
// do something with counter
}
```
> But the problem here is any script on the page can change the counter without calling updateClickCount().
2. What if we declared the variable inside our function?
```javascript
function updateClickCount() {
var counter = 0;
++counter;
// do something with counter
}
```
> But now every time we call updateClickCount we're resetting the counter variable!
3. Ok, well how about a *nested function*?
Nested functions have access to the scope that's above them. In this example updateClickCount can access the counter variable that's contained in the countWrapper scope.
```javascript
function countWrapper() {
var counter = 0;
function updateClickCount() {
++counter;
// do something with counter
}
updateClickCount();
return counter;
}
```
> We're close, but we can't access the updateClickCount function from the outside, and we still need to figure out how to execute counter = 0 only once and not everytime.
4. Let's try using closure with a self invoking function (IIFE)
```javascript
var updateClickCount=(function(){
var counter = 0;
return function(){
++counter;
// do something with counter
}
})();
```
> Let's take a look at how this works. First of all the self invoking function runs only once. It set's the counter to 0 and returns a function expression. This way updateClickCount becomes a function! And it still has access to the counter variable stored in it's parent's scope. We've created a private variable that is protected by the scope of the anonymous function and it can only be changed when we call UpdateClickCount!
Here's an expanded example of the above code
```javascript
<script>
var updateClickCount=(function(){
var counter=0;
return function(){
++counter;
document.getElementById("spnCount").innerHTML=counter;
}
})();
</script>
<html>
<button onclick="updateClickCount()">click me</button>
<div> you've clicked
<span id="spnCount"> 0 </span> times!
</div>
</html>
```
> Please note: While a closure doesn't need to be a self-invoking function (IIFE), it can be. When a closure is self invoking (i.e. immediately called by adding () after the function), this means the return value is immediately calculated, rather than the function being returned and the return value being calculated later once the function is invoked.
> A closure can be any function within another function, and its key characteristic is that it has access to the scope of the parent function including it's variables and methods.
|
eb898ea0db108a5646065d285c2af38f9e8a25cd
|
[
"Markdown",
"JavaScript"
] | 19 |
Markdown
|
Ashcoca/HiR-Special-Repos
|
34e4c9cc82e950ae93bcdad7217f5c875da4d0b9
|
34d254a53fd65e8af782c1cb5b1cc7785bcacb6d
|
refs/heads/dev
|
<file_sep>import styles from './styles';
import React, { Component } from 'react';
import { View, Text, Button, Image } from 'react-native';
import { List, ListItem } from 'react-native-elements';
import ViewToggler from '../../components/ViewToggler';
class GroupsScreen extends Component {
state = {
groups: [
{
title: 'Northcoders',
img:
'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg'
},
{
title: 'FunRun',
img: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg'
}
]
};
static navigationOptions = ({ navigation }) => {
return {
header: null
};
};
onPress = (event, title) => {
const { navigate } = this.props.navigation;
const groupName = 'Trackeroo - ' + title;
navigate('HomeScreen', { title: 'Home', groupName });
};
postNewGroup = newGroup => {
this.setState(currentState => {
return { groups: [...currentState.groups, newGroup] };
});
};
render() {
const { groups } = this.state;
console.log(groups);
return (
<View style={styles.groups}>
{/* <Image source={require('./fabio.jpg')} style={styles.backgroundImage} /> */}
<Text style={styles.text}>Your current groups: </Text>
{groups.map(group => {
return (
<ListItem
key={group.title}
title={group.title}
bottomDivider
rightTitle="View Group"
onPress={event => this.onPress(event, group.title)}
leftAvatar={{ source: { uri: group.img } }}
/>
// <Button
// key={group.title}
// title={group.title}
// onPress={event => this.onPress(event, group.title)}
// />
);
})}
<ViewToggler item="group" postNewGroup={this.postNewGroup} />
</View>
);
}
}
export default GroupsScreen;
<file_sep>import React, { useState, useContext } from "react";
import { FlatList, View, Button } from "react-native";
import { ListItem } from "react-native-elements";
import Typography from "./Typography";
import { followUser } from "../api";
import UserContext from "../context/UserContext";
const UsersList = ({ users }) => {
const { user } = useContext(UserContext);
return (
<FlatList
keyExtractor={item => item.username}
data={users}
renderItem={({ item }) => {
const { username } = item;
return (
<View>
<Typography>{username}</Typography>
<Button
onPress={async () => {
try {
console.log(username, user.username)
await followUser(username, user.username);
} catch (err) {
console.log(err);
}
}}
title="Follow"
/>
</View>
);
}}
/>
);
};
export default UsersList;
<file_sep>import styles from './styles';
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import ToggleButton from '../../components/ToggleButton';
class LeaderBoardScreen extends Component {
// static navigationOptions = ({ navigation }) => {
// return {
// title: navigation.getParam('title'),
// headerLeft: (
// <ToggleButton navigation={navigation} />)
// }
// };
render() {
return (
<View style={styles.container}>
<ToggleButton navigation={this.props.navigation} />
<Text>This is the LeaderBoard</Text>
</View>
);
}
}
export default LeaderBoardScreen;<file_sep>import styles from "./styles";
import React, { Component, useState, useEffect, useContext } from "react";
import {
Text,
View,
TextInput,
TouchableOpacity,
KeyboardAvoidingView,
ScrollView,
Alert,
Image,
Header,
AsyncStorage
} from "react-native";
import * as api from "../../api";
import { withNavigation } from "react-navigation";
import Typography from "../../components/Typography";
import { Input, Button } from "react-native-elements";
import UserContext from "../../context/UserContext";
const LoginScreen = ({ navigation }) => {
const [state, setState] = useState({
username: "",
password: "",
validUser: false,
error: null
});
const { user, setUser } = useContext(UserContext);
const checkLogin = async () => {
const { navigate } = navigation;
try {
const token = await api.getToken();
if (token) {
api.setAuthorizationHeader(token);
console.log("rsss", user);
const username = await AsyncStorage.getItem("username");
const actualUser = await api.getUser(username);
console.log("actual", actualUser);
setUser(actualUser);
navigate("HomeScreen");
}
} catch (err) {
console.log(err);
}
};
const handleChange = (event, inputType) => {
const { text } = event.nativeEvent;
usernameRule = /^[a-zA-Z0-9]+$/;
passwordRule = /(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?!.*[!?/[/@#" {}()<>£%+='$:;%^&*])(?=.{8,})/;
if (inputType === "password") {
if (passwordRule.test(text)) {
console.log("password is valid");
setState({ ...state, [inputType]: text });
} else {
console.log("password is invalid");
Alert.alert('Incorrect Password', "Password should contain at least 8 characters, including 1 number and 1 capital letter", [
{
text: 'Cancel',
onPress: () => console.log("Cancel Pressed"),
style: "cancel"
},
{
text: 'Ok',
onPress: () => console.log("Ok Pressed"),
}
], { cancelable: false })
}
}
if (inputType === "username") {
if (usernameRule.test(text)) {
console.log("username is valid");
setState({ ...state, [inputType]: text });
} else console.log("username is invalid");
}
};
const handleSubmit = async () => {
const { username, password, validUser } = state;
const { navigate } = navigation;
if (!password) {
}
try {
const user = await api.login(username, password);
console.log("got a users", user);
setUser(user);
await AsyncStorage.setItem("username", user.username);
navigate("HomeScreen", {
username,
password
});
} catch (error) {
console.log(username, password);
console.log("in catch block");
console.log(error);
}
};
useEffect(() => {
checkLogin();
}, []);
const { navigate } = navigation;
const { username, password, error, usernameValid, passwordValid } = state;
if (error) return <Text>{error}</Text>;
return (
<KeyboardAvoidingView style={styles.container} behavior='padding' enabled>
<View style={styles.container}>
<Text style={styles.text}>彡TᖇᗩᑕK•ᗩ•ᖇOO</Text>
<Image source={require("./rubyroo.png")} style={styles.backgroundImage} />
<Typography style={styles.signInText}>ᒪOG Iᑎ</Typography>
<Input
placeholder="USERNAME"
inputStyle={{
color: 'gold'
}}
placeholderTextColor="white"
onEndEditing={event => handleChange(event, 'username')}
name="username"
labelStyle={{ color: 'black' }}
containerStyle={{
backgroundColor: '#202020',
width: 300,
borderRadius: 5,
marginTop: 5,
height: 43
}}
/>
<Input
style={{ color: 'gold' }}
inputStyle={{
color: 'gold'
}}
placeholder="<PASSWORD>"
placeholderTextColor="white"
name="password"
onEndEditing={event => handleChange(event, 'password')}
labelStyle={{ color: 'black' }}
containerStyle={{
backgroundColor: '#202020',
width: 300,
borderRadius: 5,
marginTop: 5,
height: 43
}}
/>
<Typography style={styles.bottomText}>
Password must be 8 characters long
</Typography>
<TouchableOpacity>
<Button
buttonStyle={{
backgroundColor: '#FF8000'
}}
style={styles.button}
titleStyle={{ color: 'black' }}
color="black"
title="SIGᑎ Iᑎ"
onPress={handleSubmit}
/>
<TouchableOpacity>
<Typography
onPress={() =>
navigate("PasswordResetScreen", { title: "Forgot Password" })
}
>
FORGOT PASSWORD
</Typography>
</TouchableOpacity>
</TouchableOpacity>
<TouchableOpacity>
<Typography onPress={handleSubmit}>SIGN IN</Typography>
</TouchableOpacity>
<TouchableOpacity>
<Typography
onPress={() => navigate("RegisterScreen", { title: "SIGN UP" })}
>
DON'T HAVE A ACCOUNT?
</Typography>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
};
export default withNavigation(LoginScreen);
<file_sep>import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-between',
// alignItems: 'center',
// width: 200
// top: 30
},
backgroundImage: {
flex: 1,
width: null,
height: null,
resizeMode: 'cover'
}
});
export default styles;
<file_sep># trackeroo-client
### Setting up Environment Variables
In the root of the project, create an `environment.js` file and add the following:
```
import Constants from "expo-constants";
const apiUrl = "your-api-url";
const webSocketUrl =
"your-websocket-url";
const ENV = {
dev: {
apiUrl,
webSocketUrl
},
prod: {
apiUrl,
webSocketUrl
}
};
const getEnvVars = (env = Constants.manifest.releaseChannel) => {
if (__DEV__) {
return ENV.dev;
} else if (env === "staging") {
return ENV.staging;
} else if (env === "prod") {
return ENV.prod;
}
};
export default getEnvVars;
```
<file_sep>import RunScreen from "./RunScreen";
export default RunScreen;
<file_sep>import React, { useState } from "react";
import { Stopwatch } from "react-native-stopwatch-timer";
import { View, TouchableOpacity } from "react-native";
import { Button } from "react-native-elements";
import Typography from "./Typography";
const StopWatch = ({ isRunning, shouldResetStopWatch, onReset }) => {
console.log(shouldResetStopWatch, "<- reset");
return (
<View
style={{
flex: 1,
display: "flex",
flexDirection: "column",
alignContent: "flex-end"
}}
>
<TouchableOpacity
style={{
backgroundColor: "#121212",
alignItems: "flex-end",
paddingRight: 20
}}
disabled={isRunning}
onPress={onReset}
>
<Typography fontSize={12} color="error">
RESET
</Typography>
</TouchableOpacity>
<Stopwatch
start={isRunning}
options={options}
reset={shouldResetStopWatch}
/>
</View>
);
};
const options = {
container: {
backgroundColor: "#121212",
alignItems: "flex-end",
paddingRight: 20
},
text: {
fontSize: 30,
color: "#FFF"
}
};
export default StopWatch;
<file_sep>import React, { Component } from 'react';
import { Text, View, Button, TextInput } from 'react-native';
import styles from '../screens/Groups/styles';
class GroupCreator extends Component {
state = {
groupName: '',
groupDescription: ''
}
handleChange = (event, inputType) => {
const { text } = event.nativeEvent
this.setState({ [inputType]: text })
}
handleSubmit = () => {
console.log(this.props)
const { postNewGroup } = this.props
const { groupName } = this.state;
postNewGroup({ title: groupName })
this.setState({
groupName: ''
})
}
render() {
return (
<View>
<Text> New Group Details :</Text>
<TextInput placeholder='name' onEndEditing={(event) => this.handleChange(event, 'groupName')} name='groupName' style={styles.inputStyle}
/>
<TextInput placeholder='description' name='groupDescription' onEndEditing={(event) => this.handleChange(event, 'groupDescription')} style={styles.inputStyle}
/>
<Button title="Create!" onPress={this.handleSubmit} />
</View>
);
}
}
export default GroupCreator;<file_sep>
import FollowingScreen from "./FollowingScreen";
export default FollowingScreen;
<file_sep>import React, { Component } from 'react';
import { Button } from 'react-native';
import { DrawerActions } from 'react-navigation-drawer';
class ToggleButton extends Component {
render() {
const { navigation } = this.props
return (
<Button title="=" onPress={() => navigation.dispatch(DrawerActions.toggleDrawer())} />
);
}
}
export default ToggleButton;<file_sep>import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
bottom: 10
},
padLeft: {
paddingLeft: 16
},
padRight: {
paddingRight: 16
},
groups: {
flex: 1,
backgroundColor: 'black',
justifyContent: 'center',
color: 'white'
},
backgroundImage: {
flex: 1,
width: null,
height: null,
resizeMode: 'cover'
},
text: {
color: 'white',
fontSize: 20,
justifyContent: 'center'
}
});
export default styles;
<file_sep>import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#18dcff'
},
button: {
paddingTop: 15,
paddingBottom: 5
},
logo: {
width: 200,
height: 200
},
reset: {
flex: 1,
backgroundColor: 'black',
justifyContent: 'center',
alignItems: 'center',
color: 'white'
}
});
export default styles;
<file_sep>import RegisterScreen from "../screens/Register";
import LoginScreen from "../screens/Login";
import PasswordResetScreen from "../screens/PasswordReset";
import GroupsScreen from "../screens/Groups";
// import AuthLoadingScreen from '../screens/AuthLoading';
import { createStackNavigator } from "react-navigation-stack";
import { createAppContainer, createSwitchNavigator } from "react-navigation";
import TabNavigator from "./TabNavigator";
const AuthStack = createStackNavigator(
{
LoginScreen,
RegisterScreen,
PasswordResetScreen
},
{
headerMode: "none",
navigationOptions: {
headerVisible: false
}
}
);
const AppContainer = createAppContainer(
createSwitchNavigator(
{
TabNavigator,
AuthStack
},
{
initialRouteName: "AuthStack"
}
)
);
export default AppContainer;
<file_sep>import React, { Component } from 'react';
import {
View,
Button,
Text,
FlatList,
StyleSheet,
SafeAreaView
} from 'react-native';
import { ListItem } from 'react-native-elements';
//import Typography from './Typography';
class UserList extends Component {
state = {
users: [
{ name: 'John' },
{ name: 'Hannah' },
{ name: 'Than' },
{ name: 'Tim' }
]
};
keyExtractor = item => String(item.name);
renderItem = ({ item }) => <ListItem title={item.name} />;
render() {
const { users } = this.state;
// console.log(users);
return (
<SafeAreaView style={styles.container}>
<Text>This is UserList Screen</Text>
<FlatList
data={users.name}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
/>
<Button title="+" />
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'column',
flex: 1
},
text: {
fontSize: 25,
color: 'red',
marginLeft: 7
}
});
export default UserList;
<file_sep>import React, { useState, useContext, useEffect } from "react";
import { View } from "react-native";
import { Button } from "react-native-elements";
import Typography from "../../components/Typography";
import * as api from "../../api";
import AlternativeMap from "../../components/AlternativeMap";
import AlternativeStopWatch from "../../components/AlternativeStopWatch";
import styles from "../MapView/SharedStyles";
import UserContext from "../../context/UserContext";
const RunScreen = () => {
//whether running
//
const [isRunning, setIsRunning] = useState(false);
const [endTime, setEndTime] = useState(null);
const [completedRun, setCompletedRun] = useState(false);
const [resetRun, setResetRun] = useState(false);
const [run, setRun] = useState({});
const [runToUpdate, setRunToUpdate] = useState(false);
const [shouldResetStopWatch, setShouldResetStopWatch] = useState(false);
const { user } = useContext(UserContext);
const handleStartRun = async () => {
//make request here
try {
const startTime = Date.now().toString();
console.log("type", typeof startTime);
console.log(startTime);
const run = await api.startRun(user.username, startTime);
console.log("run that came back", run);
setRun(run);
} catch (err) {
console.log(err);
}
};
const handleUpdateRun = async stats => {
try {
if (run.run_id) {
await api.updateRun({
...stats,
run_id: run.run_id,
username: user.username
});
}
} catch (err) {
console.log(err);
}
};
const handleEndRun = async (
averageSpeed,
distanceTravelled,
stringedCoords
) => {
//patch request with rest of run data and username?
const finish_time = Date.now().toString();
const updatedRun = {
// latitude: location.coords.latitude,
// longitude: location.coords.longitude,
finish_time,
average_speed: averageSpeed,
total_distance: distanceTravelled,
coordinates: stringedCoords,
username: user.username,
run_id: run.run_id
};
await api.endRun(updatedRun);
//send this to server
};
const updateActivityStatus = async (boolean, time) => {
setIsRunning(boolean);
if (boolean === true) {
await handleStartRun(time);
} else {
setEndTime(Date.now());
}
};
const collectFinalRunData = async (
averageSpeed,
distanceTravelled,
stringedCoords
) => {
await handleEndRun(averageSpeed, distanceTravelled, stringedCoords);
};
const onResetPress = boolean => {
console.log(boolean, "<--- reset watch?");
setResetRun(boolean);
};
const toggleRun = async () => {
if (!isRunning) {
setShouldResetStopWatch(true);
await handleStartRun();
} else {
setShouldResetStopWatch(false);
}
setShouldResetStopWatch(false);
setIsRunning(!isRunning);
};
return (
<View>
<AlternativeMap
isRunning={isRunning}
collectFinalRunData={collectFinalRunData}
resetRun={resetRun}
onReset={() => setShouldResetStopWatch(true)}
onResetPress={onResetPress}
onUpdateRun={handleUpdateRun}
shouldResetStopWatch={shouldResetStopWatch}
/>
<View style={{ position: "absolute", bottom: 50, right: 20 }}>
<Button
raised
onPress={toggleRun}
title={isRunning ? "Stop" : "Start"}
textStyle={{
color: isRunning ? "#ce93d8" : "#FFFFFF"
}}
buttonStyle={{
backgroundColor: isRunning ? "#ff8c00" : "#ce93d8",
width: 70,
height: 70,
borderRadius: 35
}}
/>
</View>
</View>
);
};
export default RunScreen;
<file_sep>import React from "react";
import { View, Platform, StatusBar } from "react-native";
const styles = {
paddingTop: StatusBar.currentHeight,
backgroundColor: "#121212",
flex: 1
};
const Layout = ({ children }) => {
return <View style={styles}>{children}</View>;
};
export default Layout;
<file_sep>import React, { Component, useState, useContext } from "react";
import {
Platform,
Text,
View,
StyleSheet,
TouchableHighlight,
Dimensions
} from "react-native";
import Constants from "expo-constants";
import * as Location from "expo-location";
import * as Permissions from "expo-permissions";
import MapView, { Marker, Polyline } from "react-native-maps";
import RunInfo from "./RunInfo";
import RunInfoNumeric from "./RunInfoNumeric";
import haversine from "haversine";
import styles from "../screens/MapView/SharedStyles";
import pick from "lodash.pick";
import Typography from "./Typography";
import RunsContext from "../context/RunsContext";
const SingleRunnersMap = ({ navigation }) => {
const { run_id } = navigation.state.params;
const { runs } = useContext(RunsContext);
const [isMapTrue, setIsMapTrue] = useState(false);
const onMapLayout = () => {
setIsMapTrue(true);
};
const run = runs.find(r => r.run_id === run_id);
console.log("WEBSOCKET RUNNAAA", run);
return run ? (
<View style={{ display: "flex", flexDirection: "column" }}>
<MapView
onLayout={onMapLayout}
style={{
height: Dimensions.get("window").height - 50,
width: Dimensions.get("window").width
}}
showsUserLocation={true}
followsUserLocation={true}
initialRegion={{
latitude: 53.486653,
longitude: -2.240088,
latitudeDelta: 0.02,
longitudeDelta: 0.02
}}
>
{isMapTrue && (
<Marker
coordinate={{
latitude: run.latitude,
longitude: run.longitude
}}
title="Start"
/>
)}
{run.coordinates && (
<Polyline
strokeWidth={5}
coordinates={JSON.parse(run.coordinates).run}
/>
)}
</MapView>
</View>
) : null;
};
export default SingleRunnersMap;
// export default class SingleRunnersMap extends Component {
// state = {
// isMapTrue: false
// };
// render() {
// const { isMapTrue } = this.state;
// const run = JSON.stringify(this.props.navigation.getParam("run", "NO-run"));
// }
// }
<file_sep>import React from "react";
import HomeScreen from "../screens/Home";
import MapView from "../screens/MapView";
import FeedScreen from "../screens/Feed";
import FollowingScreen from "../screens/Following";
import RunScreen from "../screens/Run";
import RewardsScreen from "../screens/Rewards";
import SingleRunnersMap from "../components/SingleRunnersMap";
import { MaterialIcons } from "@expo/vector-icons";
import { createBottomTabNavigator } from "react-navigation-tabs";
import { createStackNavigator } from "react-navigation-stack";
const Home = createStackNavigator(
{
HomeScreen,
MapView
},
{
headerMode: "none",
navigationOptions: {
headerVisible: false
}
}
);
const Feed = createStackNavigator(
{
FeedScreen,
SingleRunnersMap
},
{
headerMode: "none",
navigationOptions: {
headerVisible: false
}
}
);
const TabNavigator = createBottomTabNavigator(
{
Home: Home,
Feed: Feed,
Run: RunScreen,
Members: FollowingScreen,
Rewards: RewardsScreen
},
{
tabBarOptions: {
tabStyle: {
paddingVertical: 4
},
style: {
backgroundColor: "rgba(255,255,255,0.07)",
height: 56,
borderTopColor: "transparent"
},
activeTintColor: "#ce93d8",
inactiveTintColor: "rgba(255,255,255,0.7)"
},
defaultNavigationOptions: ({ navigation }) => ({
header: null,
tabBarIcon: ({ focused, horizontal, tintColor }) => {
const { routeName } = navigation.state;
let IconComponent = MaterialIcons;
let iconName;
if (routeName === "Home") {
iconName = "home";
}
if (routeName === "Run") {
iconName = "track-changes";
}
if (routeName === "Feed") {
iconName = "rss-feed";
}
if (routeName === "Members") {
iconName = "people";
}
if (routeName === "Rewards") {
iconName = "star";
}
return <IconComponent name={iconName} size={24} color={tintColor} />;
}
})
}
);
export default TabNavigator;
<file_sep>import React, { Component } from "react";
import { View, Dimensions, StyleSheet } from "react-native";
import * as Location from "expo-location";
import * as Permissions from "expo-permissions";
import MapView, { Marker, Polyline } from "react-native-maps";
import haversine from "haversine";
import styles from "../screens/MapView/SharedStyles";
import pick from "lodash.pick";
import Typography from "./Typography";
import AlternativeStopWatch from "./AlternativeStopWatch";
import StopWatch from "./StopWatch";
///this doesn't quite work yet, need to pass in markers correctly to polyline
const boxStyle = {
display: "flex",
flexDirection: "column",
justifyContent: "center",
paddingVertical: 10,
paddingLeft: 20
};
export default class AlternativeMap extends Component {
state = {
errorMessage: null,
// ownRunObjects: [],
// watchID: null,
isMapTrue: false,
routeCoordinates: [],
distanceTravelled: 0,
prevLatLng: {},
currentSpeed: 0,
allSpeeds: []
};
async componentDidUpdate(prevProps) {
const { isRunning, totalTime, collectFinalRunData } = this.props;
if (prevProps.isRunning !== this.props.isRunning) {
if (isRunning) {
this._getLocationAsync();
}
if (!isRunning) {
this.location.remove();
const { routeCoordinates, distanceTravelled, allSpeeds } = this.state;
const averageSpeed = this.calcAveSpeed(allSpeeds);
const stringedCoords = JSON.stringify({ run: routeCoordinates });
await collectFinalRunData(
averageSpeed,
distanceTravelled,
stringedCoords
);
}
}
if (prevProps.shouldResetStopWatch !== this.props.shouldResetStopWatch) {
this.setState({
routeCoordinates: [],
distanceTravelled: 0,
prevLatLng: {},
currentSpeed: 0,
allSpeeds: []
});
}
}
getPosition = async location => {
const { routeCoordinates, distanceTravelled, allSpeeds } = this.state;
const newLatLngs = {
latitude: location.coords.latitude,
longitude: location.coords.longitude
};
const positionLatLngs = pick(location.coords, ["latitude", "longitude"]);
console.log("speeds", allSpeeds, this.calcAveSpeed(allSpeeds));
const speed = location.coords.speed;
const updatedRun = {
latitude: location.coords.latitude,
longitude: location.coords.longitude,
average_speed: this.calcAveSpeed(allSpeeds),
total_distance: distanceTravelled,
coordinates: JSON.stringify({
run: routeCoordinates.concat(positionLatLngs)
})
};
const { onUpdateRun } = this.props;
console.log("up", onUpdateRun, updatedRun);
await onUpdateRun(updatedRun);
//also add run_id and username
this.setState({
routeCoordinates: routeCoordinates.concat(positionLatLngs),
// ownRunObjects: [...this.state.ownRunObjects, location],
distanceTravelled: distanceTravelled + this.calcDistance(newLatLngs),
prevLatLng: newLatLngs,
currentSpeed: speed,
allSpeeds: [...this.state.allSpeeds, speed]
});
};
_getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== "granted") {
this.setState({
errorMessage: "Permission to access location was denied"
});
}
this.location = await Location.watchPositionAsync(
{ enableHighAccuracy: true, timeInterval: 1000, distanceInterval: 0.1 },
this.getPosition
);
};
calcDistance(newLatLng) {
const { prevLatLng } = this.state;
return haversine(prevLatLng, newLatLng) || 0;
}
calcAveSpeed(speedsArray) {
if (speedsArray.length > 0) {
return speedsArray.reduce((a, b) => a + b) / speedsArray.length;
} else {
return 0;
}
}
onMapLayout = () => {
this.setState({ isMapTrue: true });
};
render() {
const { routeCoordinates, distanceTravelled, currentSpeed } = this.state;
const {
isRunning,
updateActivityStatus,
onReset,
shouldResetStopWatch
} = this.props;
const { onResetPress } = this.props;
// const { isRunning } = this.state;
let text = "Waiting..";
if (this.state.errorMessage) {
text = this.state.errorMessage;
} else if (this.state.location) {
text = JSON.stringify(this.state.location);
}
return (
<View style={{ display: "flex", flexDirection: "column" }}>
<MapView
onLayout={this.onMapLayout}
style={{
height: Dimensions.get("window").height - 50,
width: Dimensions.get("window").width
}}
showsUserLocation={true}
followsUserLocation={true}
initialRegion={{
latitude: 53.486653,
longitude: -2.240088,
latitudeDelta: 0.02,
longitudeDelta: 0.02
}}
>
{this.state.isMapTrue && routeCoordinates.length > 0 && (
<Marker
coordinate={{
latitude: routeCoordinates[0].latitude,
longitude: routeCoordinates[0].longitude
}}
title="Start"
/>
)}
{this.state.isMapTrue &&
routeCoordinates.length > 0 &&
isRunning === false && (
<Marker
coordinate={{
latitude: routeCoordinates.slice(-1)[0].latitude,
longitude: routeCoordinates.slice(-1)[0].longitude
}}
title="Finish"
/>
)}
{this.state.isMapTrue && (
<Polyline strokeWidth={5} coordinates={routeCoordinates} />
)}
</MapView>
<View
style={{
flex: 1,
display: "flex",
flexDirection: "row",
alignItems: "center",
position: "absolute",
top: 0,
left: 0,
backgroundColor: "#121212",
width: Dimensions.get("window").width
}}
>
<View style={boxStyle}>
<Typography color="secondary" fontSize={12}>
Speed:
</Typography>
<View
style={{
flex: 1,
display: "flex",
flexDirection: "row",
alignItems: "flex-end"
}}
>
<Typography color="accent" fontSize={30}>
{(currentSpeed * ((60 * 60) / 1000)).toFixed(1)}
</Typography>
<View style={{ marginBottom: 5, marginLeft: 5 }}>
<Typography fontSize={12} color="primary">
km/h
</Typography>
</View>
</View>
</View>
<View style={boxStyle}>
<Typography fontSize={12} color="secondary">
Distance:
</Typography>
<View
style={{
flex: 1,
display: "flex",
flexDirection: "row",
alignItems: "flex-end"
}}
>
<Typography color="accent" fontSize={30}>
{distanceTravelled.toFixed(2)}
</Typography>
<View style={{ marginBottom: 5, marginLeft: 5 }}>
<Typography fontSize={12} color="primary">
km
</Typography>
</View>
</View>
</View>
{/* <AlternativeStopWatch
updateActivityStatus={updateActivityStatus}
onResetPress={onResetPress}
/> */}
<StopWatch
shouldResetStopWatch={shouldResetStopWatch}
onReset={onReset}
isRunning={isRunning}
/>
</View>
</View>
);
}
}
<file_sep>import React from "react";
import { View } from "react-native";
import { Text, Button, Icon } from "react-native-elements";
import Typography from "./Typography";
import TimeAgo from "javascript-time-ago";
import en from "javascript-time-ago/locale/en";
TimeAgo.addLocale(en);
const timeAgo = new TimeAgo("en-US");
const RewardItem = ({ rewardObj, rewardClaimed, selectedIndex, user }) => {
const { challenge, reward, reward_id, winner } = rewardObj;
console.log(rewardObj, '<----')
console.log(typeof (user.cumulative_distance), user.cumulative_distance, '<---- user')
console.log(typeof (challenge), challenge, '<---- challenge')
handlePress = async () => {
await rewardClaimed(reward_id, user.username)
}
return (
<View
style={{
backgroundColor: 'rgba(255,255,255,0.05)',
paddingHorizontal: 20,
paddingVertical: 16,
marginBottom: 16,
flex: 1,
flexWrap: 'wrap',
flexDirection: 'row',
justifyContent: 'space-between'
}}
>
<View style={{ flex: 1 }}>
{selectedIndex === 0 && (
<Icon
name="star"
type="Font-Awesome"
color="green"
iconStyle={{ paddingRight: 15 }}
/>
)}
{selectedIndex === 1 && (
<Icon
name="star"
type="Font-Awesome"
color="grey"
iconStyle={{ paddingRight: 15 }}
/>
)}
<View
style={{
flex: 1,
flexDirection: 'row',
backgroundColor: 'rgba(255,255,255,0.01)',
justifyContent: "space-evenly"
}}>
<View>
<Typography fontWeight={400} color="secondary">Challenge:</Typography>
<Typography fontWeight={400} color="secondary">Reward:</Typography>
{selectedIndex === 1 && <Typography fontWeight={400} style={{ color: "green" }}>Winner:</Typography>}
</View>
<View style={{ flex: 1, alignItems: "flex-end" }}>
<Typography fontWeight={400} color="secondary">
{challenge} km
</Typography>
<Typography fontWeight={400} color="secondary">
{reward}
</Typography>
{selectedIndex === 1 && <Typography fontWeight={400} style={{ color: "green" }}>{winner.S}</Typography>}
</View>
</View>
{selectedIndex === 0 && user.cumulative_distance >= challenge && <Button title="CLAIM" onPress={handlePress} titleStyle={{ color: 'black', fontSize: 14 }}
buttonStyle={{
paddingLeft: 15,
paddingRight: 15,
backgroundColor: 'rgb(255, 128, 0)'
}} type="outline" />}
{selectedIndex === 0 && user.cumulative_distance < challenge && <Button title="CLAIM" onPress={handlePress} disabled={true} titleStyle={{ color: 'black', fontSize: 14 }}
buttonStyle={{
paddingLeft: 15,
paddingRight: 15,
backgroundColor: 'grey'
}} type="outline" />
}
</View>
</View>
);
};
export default RewardItem;<file_sep>import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'grey'
},
button: {},
wholeContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
map: {
// ...StyleSheet.absoluteFillObject
height: 200,
width: 350,
left: 0,
top: 0,
bottom: 0,
flex: 0
},
button: {
position: 'absolute',
top: 5
},
signup_button: {
color: 'black'
},
register: {
flex: 1,
backgroundColor: 'black',
justifyContent: 'center',
alignItems: 'center',
color: 'white'
},
button: {
paddingTop: 15,
paddingBottom: 5
},
backgroundImage: {
flex: 1,
alignSelf: 'stretch',
width: undefined,
height: undefined,
justifyContent: 'center',
alignItems: 'center'
},
input: {
backgroundColor: 'rgb(128,128,0.6)',
alignItems: 'center',
justifyContent: 'center'
}
});
export default styles;
<file_sep>import React, { Component } from "react";
import { Text, View, Button, Dimensions } from "react-native";
import { Stopwatch } from "react-native-stopwatch-timer";
import styles from "../screens/MapView/SharedStyles";
class AlternativeStopWatch extends Component {
state = {
isStopwatchStart: false,
timerDuration: 90000,
resetStopwatch: false,
startTime: 0,
isRunning: false,
resetPressed: true
};
startWatch = async () => {
const { updateActivityStatus, onResetPress } = this.props;
const startTime = new Date().getTime();
this.setState(
{
resetStopwatch: false,
isRunning: true,
startTime,
resetPressed: false
},
async () => {
await updateActivityStatus(this.state.isRunning, this.state.startTime);
onResetPress(this.state.resetStopwatch);
}
);
// await onStart();
};
stopStopWatch = () => {
const { updateActivityStatus } = this.props;
const endTime = new Date().getTime();
// console.log(startTime, endTime);
// const totalTime = endTime - startTime;
// console.log(totalTime);
this.setState(
{
resetStopwatch: false,
isRunning: false
},
() => {
updateActivityStatus(this.state.isRunning, endTime);
}
);
};
resetStopwatch = () => {
const { onResetPress } = this.props;
this.setState(
{ isStopwatchStart: false, resetStopwatch: true, resetPressed: true },
() => {
onResetPress(this.state.resetStopwatch);
}
);
};
getFormattedTime = time => {
// console.log(time)
this.currentTime = time;
};
render() {
const { isRunning, resetPressed } = this.state;
return (
<View
style={{
flex: 1,
display: "flex",
flexDirection: "row",
justifyContent: "flex-end"
}}
>
<Stopwatch
laps
start={this.state.isRunning}
//To start
reset={this.state.resetStopwatch}
//To reset
options={options}
// //options for the styling
getTime={this.getFormattedTime}
/>
<View style={{ position: "absolute", bottom: 0 }}>
{isRunning === false && (
<Button
title="START RUN"
onPress={this.startWatch}
disabled={resetPressed === false}
/>
)}
</View>
{isRunning && (
<Button title="FINISH RUN" onPress={this.stopStopWatch} />
)}
<Button
disabled={isRunning}
title="RESET"
onPress={this.resetStopwatch}
/>
</View>
);
}
}
const options = {
container: {
backgroundColor: "#121212",
alignItems: "flex-end",
paddingRight: 20
},
text: {
fontSize: 30,
color: "#FFF"
}
};
export default AlternativeStopWatch;
<file_sep>import React from "react";
const RunsContext = React.createContext({ runs: [], addRuns: () => {} });
export const RunsProvider = RunsContext.Provider;
export const RunsConsumer = RunsContext.Consumer;
export default RunsContext;
<file_sep>import React, { Component } from "react";
import { SafeAreaView } from "react-navigation";
import ToggleButton from '../../components/ToggleButton'
import MapView, { Marker, Polyline } from 'react-native-maps';
import Constants from 'expo-constants';
import styles from './styles';
import { Text, View, Button } from 'react-native';
export class PersonalProfileScreen extends Component {
state = {
isMapTrue: false,
showSpecificRun: false,
specificRun: '',
pastRuns: [
[{ latitude: 53.192014, longitude: -2.895863 }, { latitude: 53.191860, longitude: -2.895772 }, { latitude: 53.191799, longitude: -2.895954 }, { latitude: 53.191941, longitude: -2.896062 }, { latitude: 53.191899, longitude: -2.896346 }, { latitude: 53.191867, longitude: -2.896635 }, { latitude: 53.191876, longitude: -2.896807 }],
[{ latitude: 53.192240, longitude: -2.896228 }, { latitude: 53.192223, longitude: -2.896571 }, { latitude: 53.192211, longitude: -2.896850 }, { latitude: 53.192420, longitude: -2.896915 }, { latitude: 53.192516, longitude: -2.896700 }, { latitude: 53.192397, longitude: -2.896657 }, { latitude: 53.192342, longitude: -2.897178 }]]
}
onMapLayout = () => {
this.setState({ isMapTrue: true })
}
onPress = (event, runNumber) => {
console.log(event, runNumber)
if (runNumber === 'all') {
this.setState({ showSpecificRun: false, specificRun: '' })
}
else {
this.setState({ showSpecificRun: true, specificRun: runNumber })
}
}
render() {
const { navigation } = this.props;
const { pastRuns, showSpecificRun, specificRun, isMapTrue } = this.state;
return (
<SafeAreaView style={styles.wholeContainer}>
<ToggleButton style={styles.button} navigation={navigation} />
<MapView onLayout={this.onMapLayout}
style={styles.map}
showsUserLocation
followsUserLocation
initialRegion={{
latitude: 53.190959,
longitude: -2.864260,
latitudeDelta: 0.02,
longitudeDelta: 0.02
}}>
{showSpecificRun === false && isMapTrue &&
<View>
<Polyline coordinates={[{ latitude: 53.192014, longitude: -2.895863 }, { latitude: 53.191860, longitude: -2.895772 }, { latitude: 53.191799, longitude: -2.895954 }, { latitude: 53.191941, longitude: -2.896062 }, { latitude: 53.191899, longitude: -2.896346 }, { latitude: 53.191867, longitude: -2.896635 }, { latitude: 53.191876, longitude: -2.896807 }]} strokeWidth={5}
/>
<Polyline coordinates={[{ latitude: 53.192240, longitude: -2.896228 }, { latitude: 53.192223, longitude: -2.896571 }, { latitude: 53.192211, longitude: -2.896850 }, { latitude: 53.192420, longitude: -2.896915 }, { latitude: 53.192516, longitude: -2.896700 }, { latitude: 53.192397, longitude: -2.896657 }, { latitude: 53.192342, longitude: -2.897178 }]} strokeWidth={5}
/>
</View>
}
{showSpecificRun === true && isMapTrue && specificRun === 'run1' &&
<Polyline coordinates={[{ latitude: 53.192014, longitude: -2.895863 }, { latitude: 53.191860, longitude: -2.895772 }, { latitude: 53.191799, longitude: -2.895954 }, { latitude: 53.191941, longitude: -2.896062 }, { latitude: 53.191899, longitude: -2.896346 }, { latitude: 53.191867, longitude: -2.896635 }, { latitude: 53.191876, longitude: -2.896807 }]} strokeWidth={5}
/>
}
{showSpecificRun === true && isMapTrue && specificRun === 'run2' &&
<Polyline coordinates={[{ latitude: 53.192240, longitude: -2.896228 }, { latitude: 53.192223, longitude: -2.896571 }, { latitude: 53.192211, longitude: -2.896850 }, { latitude: 53.192420, longitude: -2.896915 }, { latitude: 53.192516, longitude: -2.896700 }, { latitude: 53.192397, longitude: -2.896657 }, { latitude: 53.192342, longitude: -2.897178 }]} strokeWidth={5}
/>
}
</MapView>
<Button title='RUN 1' onPress={(event) => this.onPress(event, 'run1')} />
<Button title='RUN 2' onPress={(event) => this.onPress(event, 'run2')} />
<Button title='View all' onPress={(event) => this.onPress(event, 'all')} />
</SafeAreaView>
);
}
}
export default PersonalProfileScreen;
// const styles = StyleSheet.create({
// container: {
// flex: 1,
// alignItems: 'center',
// justifyContent: 'center',
// paddingTop: Constants.statusBarHeight,
// backgroundColor: '#ecf0f1',
// },
// paragraph: {
// margin: 24,
// fontSize: 18,
// textAlign: 'center',
// },
// });<file_sep>import LeaderBoardScreen from "./LeaderBoardScreen";
export default LeaderBoardScreen;
<file_sep>import styles from './styles';
import React, { Component } from 'react';
import { View, TextInput, TouchableOpacity, Image } from 'react-native';
import { Input, Text, Button } from 'react-native-elements';
class PasswordResetScreen extends Component {
static navigationOptions = ({ navigation }) => {
return {
title: navigation.getParam('title'),
headerStyle: {
backgroundColor: '#61469C'
}
};
};
state = {
username: ''
};
handleChange = () => {
this.setState;
};
render() {
return (
<View style={styles.reset}>
{/* <Image style={styles.logo} source={require('./oops.png')} /> */}
<Text style={{ color: 'white', paddingBottom: 30 }} h4>
Enter Username
</Text>
<Input
placeholder="username:"
inputStyle={{ color: 'white' }}
placeholderTextColor="white"
onEndEditing={event => this.handleChange(event, 'username')}
/>
<TouchableOpacity>
<Button
style={styles.button}
title="Recover"
onPress={this.handleSubmit}
></Button>
</TouchableOpacity>
</View>
);
}
}
export default PasswordResetScreen;
<file_sep>import RegisterScreen from "./RegisterScreen";
export default RegisterScreen;
<file_sep>import MapScreen from "./MapScreen";
export default MapScreen;
<file_sep>import LoginScreen from "./LoginScreen";
export default LoginScreen;
<file_sep>import React, { useContext } from "react";
import { Text } from "react-native";
import FontContext from "../context/FontContext";
const colors = {
primary: "rgba(255,255,255,1)",
secondary: "rgba(255,255,255,0.7)",
tertiary: "rgba(255,255,255,0.5)",
accent: "#ce93d8",
error: "#ff8c00"
};
const fonts = {
400: "open-sans-regular",
600: "open-sans-semibold",
700: "open-sans-bold"
};
const Typography = ({
fontWeight,
color,
fontSize,
letterSpacing,
mb,
...rest
}) => {
const hasFontLoaded = useContext(FontContext);
return hasFontLoaded ? (
<Text
style={{
fontSize: fontSize || 14,
color: colors[color] || colors.primary,
fontFamily: fonts[fontWeight] || fonts[400]
}}
{...rest}
/>
) : null;
};
export default Typography;
<file_sep>import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
import GroupCreator from './GroupCreator'
import RewardCreator from './RewardCreator'
class ViewToggler extends Component {
state = {
isShowingForm: false,
messageToggle: true
}
handlePress = () => {
const { isShowingForm, messageToggle } = this.state;
this.setState({ isShowingForm: !isShowingForm, messageToggle: !messageToggle });
};
updateIsShowing = (boolean) => {
this.setState({ isShowingForm: boolean, messageToggle: !boolean })
}
render() {
const { isShowingForm, messageToggle } = this.state;
const { postNewGroup, item, postNewReward } = this.props;
return (
<View>
<Button titleStyle={{ color: 'black', fontSize: 14 }}
buttonStyle={{
paddingLeft: 15,
paddingRight: 15,
backgroundColor: 'rgb(255, 128, 0)'
}} type="outline" onPress={this.handlePress} title={messageToggle === true ? `+Add ${item}` : "Hide Form"}>
</Button>
{(isShowingForm) && (item === 'group') && <GroupCreator postNewGroup={postNewGroup} />}
{(isShowingForm) && (item === 'reward') && <RewardCreator postNewReward={postNewReward} />}
</View>
);
}
}
export default ViewToggler;
|
dfd7ef307c64f85af97d2eefbb58baf0fb523076
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 32 |
JavaScript
|
hannahw1ll1ams/trackeroo-client
|
f4fd6187c16967290993c464659598bd9b0e88c7
|
6f4c3b9c72639b2a6f412d02cb655a55c2b4e503
|
refs/heads/master
|
<repo_name>Fer2929/MiContentProvider<file_sep>/app/src/main/java/com/example/micontentprovider/MainActivity.java
package com.example.micontentprovider;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public static final String TAG_MAIN = MainActivity.class.getSimpleName();
public static final int NOMBRE_EDIT = 99;
private RecyclerView recyclerView;
private AsignaturaAdapter adapter;
//TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//textView = (TextView) findViewById(R.id.textView);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
adapter = new AsignaturaAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
/*public void onClickBotones(View view) {
String queryUri = Contract.CONTENT_URI.toString();
Log.d(TAG_MAIN, queryUri);
String[] projection = new String[]{Contract.CONTENT_PATH};
String selectionClause;
String selectionArgs[];
switch (view.getId()) {
case R.id.btn_mostrar_primera:
// SELECT * FROM asignatura WHERE ASIGNATURA_ID = 0
selectionClause = Contract.ASIGNATURA_ID + " = ?";
selectionArgs = new String[]{"0"};
//textView.append("\n Boton1.");
break;
case R.id.btn_mostrar_todos:
selectionClause = null;
selectionArgs = null;
//textView.append("\n Boton2.");
break;
default:
selectionClause = null;
selectionArgs = null;
}
Cursor cursor = getContentResolver().query(
Uri.parse(queryUri),
projection,
selectionClause,
selectionArgs,
null
);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
do {
String asignatura = cursor.getString(columnIndex);
textView.append(asignatura + "\n");
} while (cursor.moveToNext());
} else {
textView.append("No existen asignaturas.");
}
} else {
textView.append("No existen Asignaturas.");
}
}*/
}
|
7adb97e6e18ff346e7fbf81ec8b9843245c10790
|
[
"Java"
] | 1 |
Java
|
Fer2929/MiContentProvider
|
f72d05f7e4eff62982bc297ac7a60848159a44ea
|
b0f27260a2da1884392cbd7f6bdba58da4de39ca
|
refs/heads/master
|
<file_sep>#!/usr/bin/env ruby
# encoding: utf-8
require "nokogiri"
require "open-uri"
require "./data/manga-titles-1349253256-size-3549"
require "./data/manga-items-1349106078-size-50591"
require "./settings"
#Manga_titles标题列表
#Manga_items卷集列表
#比较标题列表和现有item列表
#更新现有item列表
#
#
def compare_item(new_titles,old_items,has_count)
data_end=Hash.new
count = 0
if old_items==nil&&has_count==nil
add_items new_titles
else
new_titles.each_key do |key|
if old_items[key] == nil
count += 1
data = add_items(new_titles,key,old_items,has_count)
data_end = data[:data]
count = data[:count]
end
end
end
make_file(data_end,count)
p "新增#{count}部漫画"
end
#获取3级树子项数目,现有数据漫画卷树
def get_count_3 tree
count = 0
tree.each_key do |key|
len = tree[key][:child].size
if len==1
count += 1
else
count += (len-1)
end
end
p ""
p "现共有#{count}卷漫画"
p ""
count
end
#生成新的卷数据
def add_items(new_titles,key,old_items,has_count)
count = has_count||0
if old_items !=nil
data = old_items
data[key] = new_titles[key].clone
data[key][:child] = Hash.new
else
data[key][:child] = Hash.new
end
page = Nokogiri::HTML(open DOMAIN+data[key][:url])
p "#{'-'*20}"
p "漫画名称:#{key}"
p "抓取地址:#{DOMAIN+data[key][:url]}"
p "现计#{count}卷"
p "#{'-'*20}"
page.css(".subBookList a").each do |link|
if link[:href] =~ /comic/
p link[:title]
count = count+1
data[key][:child][link[:title]] = {url:link[:href]}
end
end
p "完成!一共#{data.size}部#{count}卷"
{data:data,count:count}
end
def make_file(data,count)
open("data/manga-items-#{Time.now.to_i}-size-#{count}.rb","w") do |file|
file << "#!/usr/bin/env ruby\n# encoding: utf-8\nManga_items=#{data}"
end
end
compare_item(Manga_titles,Manga_items,get_count_3(Manga_items))
<file_sep>#!/usr/bin/env ruby
# encoding: utf-8
# author Tiankui
# email <EMAIL>
#
DOMAIN='http://imanhua.com'
ALL_PAGES='http://imanhua.com/all.html'
MANGA_ITEMS='./data/manga-items-1349258275-size-48385'
MANGA_TITLES='./data/manga-titles-1349253256-size-3549'
<file_sep>#!/usr/bin/env ruby
# encoding: utf-8
require "./data/manga-items-1349258275-size-48385"
require "./manga-items"
def title_strip manga_list
data = {}
#trip 3th of tree
manga_list.each_key do |key|
data[key.to_s.strip]=Marshal.load(Marshal.dump(manga_list[key]))
end
manga_list.each_key do |key|
manga_list[key][:child].each_key do |k|
data[key.to_s.strip][:child].delete k
data[key.to_s.strip][:child][k.to_s.strip]=manga_list[key][:child][k]
end
end
data
end
data = title_strip Manga_items
data.each_key do |key|
data[key][:child].each_key{|a| p a}
end
make_file(data,get_count_3(data))
<file_sep>#!/usr/bin/env ruby
# encoding: utf-8
require "nokogiri"
require "open-uri"
require "./settings"
def make_title_list
manga_list=Hash.new#构造树
page = Nokogiri::HTML.parse(open(ALL_PAGES), nil, "gb2312")#抓取目录页面
#page = Nokogiri::HTML.parse(open('./index.html'),nil,"gb2312")
page.css("h3+ul a").each do |link|
if link[:href]=~/comic/ && link[:href].size<14
#link['href']URI link['title']漫画名称 link['rel']封面
manga_list[link[:title]] = {url:link[:href],rel:link['rel']}
end
end
#add 死神
manga_list[:死神] = {url:'/comic/120/',rel:'http://i1.imanhua.com/Cover/2011-10/sishen.jpg'}
manga_list
end
data = make_title_list
open("data/manga-titles-#{Time.now.to_i}-size-#{data.size}.rb","w") do |file|
file << "#!/usr/bin/env ruby\n# encoding: utf-8\nManga_titles=#{data}"
end
puts "漫画目录抓取完毕,共计#{data.size}部"
puts "文件名:manga-titles-#{Time.now.to_i}-size-#{data.size}"
<file_sep>#!/usr/bin/env ruby
# encoding: utf-8
require "anemone"
require "./settings"
Anemone.crawl DOMAIN do |anemone|
anemone.on_every_page do |page|
#if /\/conmic\//=~page.url
p page.url
#end
end
end
|
8a2da5c783b855c8995ae9a6983d716d9da361bc
|
[
"Ruby"
] | 5 |
Ruby
|
Tbxhs/manga-spider
|
ffad56e90604ccf756c4db0b63bc13be6c0e2627
|
b6322337590d2947530dd36ff74050611c86dda4
|
refs/heads/master
|
<file_sep>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup() {
ofSetFrameRate(60);
ofBackground(39);
ofSetWindowTitle("Insta");
ofSetLineWidth(3);
}
//--------------------------------------------------------------
void ofApp::update() {
}
//--------------------------------------------------------------
void ofApp::draw() {
vector<ofPoint> points;
points.push_back(ofPoint(0, 0));
points.push_back(ofPoint(ofGetWidth(), ofGetHeight()));
points.push_back(ofPoint(0, ofGetHeight()));
points.push_back(ofPoint(ofGetWidth(), 0));
int deg_span = 1;
int color_start = 0;
int color_end = 120;
ofSetColor(239);
for (int i = 0; i < points.size(); i++) {
ofPushMatrix();
ofTranslate(points[i]);
for (int radius = 150; radius <= 380; radius += 15) {
int start_deg = i * 90;
for (int deg = start_deg; deg < start_deg + 360; deg += deg_span) {
int value = (ofGetFrameNum() * 2 + deg + radius) % 360;
if (value > color_start && value < color_end) {
ofPoint start = ofPoint(radius * cos(deg * DEG_TO_RAD), radius * sin(deg * DEG_TO_RAD));
ofPoint end = ofPoint(radius * cos((deg + deg_span) * DEG_TO_RAD), radius * sin((deg + deg_span) * DEG_TO_RAD));
ofDrawLine(start, end);
}
}
}
ofPopMatrix();
}
}
//--------------------------------------------------------------
int main() {
ofSetupOpenGL(720, 720, OF_WINDOW);
ofRunApp(new ofApp());
}
|
f120a685fef372659a378b91fe6ace83c1179876
|
[
"C++"
] | 1 |
C++
|
junkiyoshi/Insta20180608
|
b94d7a6cde5b3e2bc977873de4422cb02e6c21f9
|
dfe59b3d76110e457f65f7e118aeb1530acd5b21
|
refs/heads/m
|
<repo_name>daneal2u/android_vendor_du<file_sep>/caf-vendorsetup.sh
add_lunch_combo du_bacon-userdebug
add_lunch_combo du_clark-userdebug
add_lunch_combo du_dlx-userdebug
add_lunch_combo du_find7s-userdebug
add_lunch_combo du_lux-userdebug
add_lunch_combo du_m7-userdebug
add_lunch_combo du_m7vzw-userdebug
add_lunch_combo du_m8-userdebug
add_lunch_combo du_oneplus3-userdebug
add_lunch_combo du_Z00T-userdebug
<file_sep>/config/packages.mk
# DU Utils Library
PRODUCT_PACKAGES += \
org.dirtyunicorns.utils
# Required packages
PRODUCT_PACKAGES += \
CellBroadcastReceiver \
Development \
SpareParts
# Optional packages
PRODUCT_PACKAGES += \
Basic \
CalendarWidget \
Chromium \
DU-About \
DUCertified \
LatinIME \
LockClock \
OmniSwitch \
PhaseBeam
# Extra tools
PRODUCT_PACKAGES += \
openvpn \
e2fsck \
mke2fs \
tune2fs \
mount.exfat \
fsck.exfat \
mkfs.exfat
# Stagefright FFMPEG plugin
ifeq ($(BOARD_USES_QCOM_HARDWARE),true)
PRODUCT_PACKAGES += \
libstagefright_soft_ffmpegadec \
libstagefright_soft_ffmpegvdec \
libFFmpegExtractor \
libnamparser
endif
<file_sep>/vendorsetup.sh
add_lunch_combo du_angler-userdebug
add_lunch_combo du_bullhead-userdebug
add_lunch_combo du_dragon-userdebug
add_lunch_combo du_flo-userdebug
add_lunch_combo du_flounder-userdebug
add_lunch_combo du_hammerhead-userdebug
add_lunch_combo du_mako-userdebug
add_lunch_combo du_shamu-userdebug
add_lunch_combo du_shieldtablet-userdebug
|
5f28c4ec57c76d207c7b9da8e565b6023e4af8c2
|
[
"Makefile",
"Shell"
] | 3 |
Shell
|
daneal2u/android_vendor_du
|
58a0adfa15fce1834573b9c5a5a222e4f5f025bf
|
31100728348e52bdff77362e8d9845ea8c5c0466
|
refs/heads/master
|
<file_sep>(function () {
let properties = {
showProperties: function () {
let elem = document.getElementById('properties');
elem.style.display = 'block';
closeOtherWindows(elem);
let propertiesData = this.properties;
document.getElementById('namePropertyVal').value = propertiesData.taskName;
document.getElementById('requiredTimePropertyVal').value = propertiesData.requiredTime;
document.getElementById('timeSpentPropertyVal').value = propertiesData.timeSpent;
document.getElementById('taskColorPropertyVal').value = propertiesData.taskColor;
document.getElementById('descriptionPropertyVal').value = propertiesData.description;
let select = document.getElementsByTagName('select')[1];
setBgColorOfSelect.call(select);
// Removing event listeners so button can be dynamically bound to task properties
let saveButton = document.getElementById('saveEdit'),
newButton = saveButton.cloneNode(true);
saveButton.parentNode.replaceChild(newButton, saveButton);
newButton.addEventListener('click', properties.saveEdit.bind(this));
},
hideProperties: function () {
let elem = document.getElementById('properties');
elem.style.display = 'none';
let input = document.getElementById('properties').getElementsByTagName('input')[0];
if (!input.hasAttribute('disabled')) {
properties.enterLeaveEditMode();
properties.showHideButtons();
}
},
editProperties: function () {
this.currentProperties = {
taskName: document.getElementById('namePropertyVal').value,
requiredTime: document.getElementById('requiredTimePropertyVal').value,
timeSpent: document.getElementById('timeSpentPropertyVal').value,
taskColor: document.getElementById('taskColorPropertyVal').value,
description: document.getElementById('descriptionPropertyVal').value,
};
document.getElementById('exitEditMode').addEventListener('click', properties.revertChanges.bind(this));
properties.enterLeaveEditMode();
properties.showHideButtons();
},
saveEdit: function () {
let taskLowerChildren = this.getElementsByClassName('taskLower')[0].getElementsByTagName('div');
this.properties.taskName = document.getElementById('namePropertyVal').value;
this.properties.requiredTime = document.getElementById('requiredTimePropertyVal').value;
this.properties.timeSpent = document.getElementById('timeSpentPropertyVal').value;
this.properties.taskColor = document.getElementById('taskColorPropertyVal').value;
this.properties.description = document.getElementById('descriptionPropertyVal').value;
this.getElementsByClassName('taskUpper')[0].innerHTML = this.properties.taskName;
taskLowerChildren[0].innerHTML = `🕐 ${this.properties.requiredTime}m`;
this.querySelector('.progressTextVal').innerHTML = `${this.properties.timeSpent}m`;
this.querySelector('.singleTaskContent').style.backgroundColor = this.properties.taskColor;
document.getElementById('properties').style.display = 'none';
properties.showHideButtons();
properties.enterLeaveEditMode();
confirmSaved();
},
enterLeaveEditMode: function () {
let prop = document.getElementById('properties'),
inputs = prop.getElementsByTagName('input'),
taskColorSelect = prop.getElementsByTagName('select')[0],
textArea = prop.getElementsByTagName('textarea')[0];
if (inputs[0].hasAttribute('disabled')) {
for (let input of inputs) {
input.removeAttribute('disabled');
}
taskColorSelect.removeAttribute('disabled');
textArea.removeAttribute('disabled');
} else {
for (let input of inputs) {
input.setAttribute('disabled', 'disabled')
}
taskColorSelect.setAttribute('disabled', 'disabled');
textArea.setAttribute('disabled', 'disabled');
}
},
showHideButtons: function () {
let buttons = document.getElementById('buttons').getElementsByTagName('button');
for (let i = 0; i < buttons.length; i++) {
buttons[i].classList.toggle('show');
buttons[i].classList.toggle('hide');
}
},
revertChanges: function () {
document.getElementById('namePropertyVal').value = this.currentProperties.taskName;
document.getElementById('requiredTimePropertyVal').value = this.currentProperties.requiredTime;
document.getElementById('timeSpentPropertyVal').value = this.currentProperties.timeSpent;
document.getElementById('taskColorPropertyVal').value = this.currentProperties.taskColor;
document.getElementById('descriptionPropertyVal').value = this.currentProperties.description;
let select = document.getElementById('taskColorPropertyVal');
select.style.backgroundColor = select.value;
}
}
let taskCreation = {
createTask: function () {
// Task structure
let task = this.createDiv(),
dropSpace = this.createDiv(),
singleTaskContent = this.createDiv(),
taskUpper = this.createDiv(),
taskLower = this.createDiv(),
requiredTimeDiv = this.createDiv(),
timeSpentDiv = this.createDiv(),
deleteDiv = this.createDiv(),
deleteTopLine = this.createDiv(),
deleteBottomLine = this.createDiv(),
progressBarSymbol = this.createDiv(),
progressFilledSide = this.createDiv(),
progressEmptySide = this.createDiv(),
progressVal = this.createDiv(),
editTask = document.querySelector('.hamburgerMenu').cloneNode(true),
container = document.getElementsByClassName('tasks')[this.indexOfContainer];
let values = {
taskName: document.querySelector('#taskName').value || 'Task',
requiredTime: document.querySelector('#requiredTime').value,
timeSpent: document.querySelector('#timeSpent').value,
taskColor: document.querySelector('#taskColor').value,
description: document.querySelector('#taskDescription').value
};
task.className = 'task';
singleTaskContent.style.backgroundColor = values.taskColor;
task.setAttribute('draggable', 'true');
editTask.addEventListener("click", properties.showProperties.bind(task));
editTask.classList.add('hamburgerInsideTask');
task.addEventListener('dragstart', dragEvents.dragStart);
task.addEventListener('dragend', dragEvents.dragEnd);
dropSpace.className = 'dropSpace';
dropSpace.addEventListener('drop', dragEvents.dragDropBefore);
dropSpace.addEventListener('dragenter', dragEvents.dragEnter);
dropSpace.addEventListener('dragover', dragEvents.dragOver);
dropSpace.addEventListener('dragleave', dragEvents.dragLeave);
singleTaskContent.className = 'singleTaskContent';
task.appendChild(dropSpace);
task.appendChild(singleTaskContent);
singleTaskContent.appendChild(taskUpper);
singleTaskContent.appendChild(taskLower);
singleTaskContent.appendChild(deleteDiv);
taskUpper.className = 'taskUpper';
taskUpper.innerHTML = values.taskName;
taskLower.appendChild(requiredTimeDiv);
taskLower.appendChild(timeSpentDiv);
taskLower.className = 'taskLower';
deleteDiv.className = 'hideButton';
deleteDiv.addEventListener('click', taskDeletion.showDeleteTask);
deleteDiv.appendChild(deleteTopLine);
deleteDiv.appendChild(deleteBottomLine);
deleteTopLine.className = 'topLine line';
deleteBottomLine.className = 'bottomLine line';
requiredTimeDiv.innerHTML = `🕐 ${values.requiredTime}m`;
progressBarSymbol.className = 'progressBarSymbol';
progressBarSymbol.appendChild(progressEmptySide);
progressBarSymbol.appendChild(progressFilledSide);
progressFilledSide.className = 'filledSide';
progressEmptySide.className = 'emptySide';
timeSpentDiv.className = 'timeSpent';
timeSpentDiv.appendChild(progressBarSymbol);
progressVal.innerHTML = `${values.timeSpent}m`;
progressVal.className = 'progressTextVal';
timeSpentDiv.appendChild(progressVal);
singleTaskContent.appendChild(editTask);
container.appendChild(task);
task.properties = values;
this.taskMaker.querySelector('#taskName').value = '';
this.taskMaker.querySelector('#requiredTime').value = settings.defaultSettings.defaultRequiredTime;
this.taskMaker.querySelector('#timeSpent').value = 0;
this.taskMaker.querySelector('#taskColor').value = settings.defaultSettings.defaultTaskColor;
this.taskMaker.querySelector('#taskDescription').value = '';
setBgColorOfSelect.call(document.getElementById('taskColor'));
},
createDiv: function () {
return document.createElement('div');
},
addTask: function (indexOfContainer) {
this.indexOfContainer = indexOfContainer;
let columnName = document.getElementsByClassName('taskHeaderText')[indexOfContainer].innerHTML;
this.taskMaker = document.querySelector('#taskMaker');
closeOtherWindows(this.taskMaker);
document.getElementById('taskMakerHeader').innerHTML = `Add task for ${columnName}`;
if (this.taskMaker.style.display === 'block') {
this.closeTaskMaker.call(this);
}
// Resetting input values of Task Creator
this.taskMaker.querySelector('#taskName').value = '';
this.taskMaker.querySelector('#requiredTime').value = settings.defaultSettings.defaultRequiredTime;
this.taskMaker.querySelector('#timeSpent').value = 0;
this.taskMaker.querySelector('#taskColor').value = settings.defaultSettings.defaultTaskColor;
this.taskMaker.querySelector('#taskDescription').value = '';
this.taskMaker.style.display = 'block';
document.querySelector('#createTask').addEventListener('click', this.createTask);
document.querySelector('#createTaskAndClose').addEventListener('click', this.createTask);
document.querySelector('#createTaskAndClose').addEventListener('click', this.closeWindow);
let select = document.getElementsByTagName('select')[0];
setBgColorOfSelect.call(select);
},
closeTaskMaker: function () {
document.querySelector('#taskMaker').style.display = 'none';
document.querySelector('#createTask').removeEventListener('click', this.createTask);
document.querySelector('#createTaskAndClose').removeEventListener('click', this.createTask);
document.querySelector('#createTaskAndClose').removeEventListener('click', this.closeWindow);
},
closeWindow: function () {
let popup = findAncestor(this, 'popup');
popup.style.display = 'none';
}
};
let settings = {
defaultSettings: {
defaultRequiredTime: 25,
defaultTaskColor: 'chocolate',
showAddButtons: false,
defaultSeparatorColor: 'green'
},
showSettings: function () {
let settingsDiv = document.getElementById('settings');
document.getElementById('defaultTaskColor').value = settings.defaultSettings.defaultTaskColor;
document.getElementById('defaultRequiredTime').value = settings.defaultSettings.defaultRequiredTime;
document.getElementById('showAddButtons').value = settings.defaultSettings.showAddButtons;
document.getElementById('separatorColor').value = settings.defaultSettings.defaultSeparatorColor;
setBgColorOfSelect.call(document.getElementById('separatorColor'));
setBgColorOfSelect.call(document.getElementById('defaultTaskColor'));
settingsDiv.style.display = 'block';
closeOtherWindows(settingsDiv);
},
hideSettings: function () {
let settingsDiv = document.getElementById('settings');
settingsDiv.style.display = 'none';
},
saveSettings: function () {
let showAddButtons = document.getElementById('showAddButtons').value,
showAddButtonsValue = convertToBoolean(showAddButtons);
settings.toggleShowAddButtons(showAddButtonsValue);
settings.setColorOfSeparator();
settings.defaultSettings.defaultTaskColor = document.getElementById('defaultTaskColor').value;
settings.defaultSettings.defaultRequiredTime = document.getElementById('defaultRequiredTime').value;
settings.defaultSettings.showAddButtons = document.getElementById('showAddButtons').value;
settings.defaultSettings.defaultSeparatorColor = document.getElementById('separatorColor').value;
confirmSaved();
},
toggleShowAddButtons: function (doIShow) {
let addButtons = document.getElementsByClassName('addTask');
for (let i = 0; i < addButtons.length; i++) {
if (doIShow) {
if (!addButtons[i].classList.contains('alwaysShow')) {
addButtons[i].classList.add('alwaysShow');
}
} else {
addButtons[i].classList.remove('alwaysShow');
}
}
},
setColorOfSeparator: function () {
let lines = document.getElementsByClassName('separatingLine'),
color = document.getElementById('separatorColor').value;
for (let i = 0; i < lines.length; i++) {
lines[i].style.backgroundColor = color;
}
}
};
let taskDeletion = {
showDeleteTask: function () {
let elem = document.getElementById('confirmClosed');
elem.style.display = 'block'
closeOtherWindows(elem);
if (elem.querySelector('.singleTaskContent')) {
elem.removeChild(elem.querySelector('.singleTaskContent'));
document.getElementById('confirmClosedYes').removeEventListener('click', taskDeletion.confirmClosedYesBound);
document.getElementById('confirmClosedNo').removeEventListener('click', taskDeletion.hideConfirmWindow)
}
// Need to overwrite function with bind expression so it can be dinamically added and removed from this function
taskDeletion.confirmClosedYesBound = taskDeletion.confirmClosedYes.bind(this);
let buttonSection = document.getElementById('confirmClosedButtonSection'),
singleTaskContent = this.parentNode,
taskView = singleTaskContent.cloneNode(true);
taskView.removeChild(taskView.querySelector('.hideButton'));
taskView.removeChild(taskView.querySelector('.hamburgerInsideTask'));
taskView.classList.add('clonedTask');
elem.insertBefore(taskView, buttonSection);
document.getElementById('confirmClosedYes').addEventListener('click', taskDeletion.confirmClosedYesBound);
document.getElementById('confirmClosedNo').addEventListener('click', taskDeletion.hideConfirmWindow);
},
confirmClosedYes: function () {
document.getElementById('confirmClosedYes').removeEventListener('click', taskDeletion.confirmClosedYesBound);
document.getElementById('confirmClosedNo').removeEventListener('click', taskDeletion.hideConfirmWindow);
let task = this.parentNode.parentNode;
task.parentNode.removeChild(task);
taskDeletion.hideConfirmWindow();
},
hideConfirmWindow: function () {
document.getElementById('confirmClosedYes').removeEventListener('click', taskDeletion.confirmClosedYesBound);
document.getElementById('confirmClosedNo').removeEventListener('click', taskDeletion.hideConfirmWindow);
let elem = document.getElementById('confirmClosed'),
appendedTask = elem.getElementsByClassName('singleTaskContent')[0];
if (appendedTask) {
elem.removeChild(appendedTask);
}
elem.style.display = 'none';
}
}
let dragEvents = {
dragStart: function (event) {
event.dataTransfer.dropEffect = 'move';
this.style.opacity = '0.4';
let id = String(Math.random());
event.target.setAttribute('id', id);
event.dataTransfer.setData('text', event.target.getAttribute('id'));
},
dragEnd: function () {
this.style.opacity = '1.0';
let columns = document.getElementsByClassName('tasks'),
spaces = document.getElementsByClassName('dropSpace');
[].forEach.call(columns, function (column) {
column.classList.remove('over');
});
[].forEach.call(spaces, function (space) {
space.classList.remove('over');
});
},
dragDrop: function (event) {
event.preventDefault();
event.stopPropagation();
let elemId = event.dataTransfer.getData('text'),
draggedElem = document.getElementById(elemId),
targetClasses = event.target.classList;
// Prevents dropping items inside of other tasks
if (!targetClasses.contains('tasks') && !targetClasses.contains('dropSpace')) {
let parentColumn = findAncestor(event.target, 'tasks');
parentColumn.appendChild(draggedElem);
} else {
event.target.appendChild(draggedElem);
}
},
dragDropBefore: function (event) {
event.preventDefault();
event.stopPropagation();
let elemId = event.dataTransfer.getData('text'),
elem = document.getElementById(elemId),
dropSpace = event.target,
parentColumn = findAncestor(dropSpace, 'tasks'),
nextTask = findAncestor(dropSpace, 'task'),
transitionProperty = dropSpace.style.transition;
// Makes tasks go back to place immediately when dragging is done
dropSpace.style.webkitTransition = 'none';
dropSpace.style.mozTransition = 'none';
dropSpace.style.oTransition = 'none';
dropSpace.style.transition = 'none';
parentColumn.insertBefore(elem, nextTask);
setTimeout(function () {
dropSpace.style.webkitTransition = transitionProperty;
dropSpace.style.mozTransition = transitionProperty;
dropSpace.style.oTransition = transitionProperty;
dropSpace.style.transition = transitionProperty;
}, 0);
},
dragOver: function (event) {
event.preventDefault();
event.stopPropagation();
return false;
},
dragEnter: function () {
this.classList.add('over');
},
dragLeave: function (event) {
if (event.target.classList) {
if (event.target.classList.contains('tasks') || event.target.classList.contains('dropSpace')) {
this.classList.remove('over');
}
}
}
};
let firefoxFixes = {
setTextToSelectOptions: function () {
// Firefox has a bug where option elements' background colors don't change appropriately
// Fixing by writing plain color's name's into options elements
let separatorColor = document.getElementById('separatorColor'),
separatorColorOptions = separatorColor.getElementsByTagName('option');
[].forEach.call(separatorColorOptions, function (option) {
let uppered = option.value[0].toUpperCase() + option.value.substr(1, option.value.length - 1);
option.innerHTML = uppered;
});
let selectedOption = separatorColor.options[separatorColor.selectedIndex];
selectedOption.innerHTML = '';
selectedOption.style.display = 'none';
separatorColor.addEventListener('change', function () {
let selectedOption = this.options[this.selectedIndex];
// Not allowing to display option's innerhtml when this option is selected (cosmetic value)
[].forEach.call(this.options, function (option) {
if (option !== selectedOption) {
option.innerHTML = option.value;
option.style.display = 'block';
}
});
selectedOption.innerHTML = '';
selectedOption.style.display = 'none';
});
}
}
// Converts 'false' to false, 'true' to true
function convertToBoolean(text) {
return text !== 'false';
}
function setBgColorOfSelect() {
this.style.backgroundColor = this.value;
}
function findAncestor(el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
function closeOtherWindows(popup) {
let allWindows = document.getElementsByClassName('popup');
for (let i = 0; i < allWindows.length; i++) {
if (popup !== allWindows[i]) {
allWindows[i].style.display = 'none';
}
}
}
function confirmSaved() {
let saved = document.getElementsByClassName('saved')[0];
saved.style.webkitTransition = 'none';
saved.style.mozTransition = 'none';
saved.style.oTransition = 'none';
saved.style.transition = 'none';
saved.style.opacity = '1';
setTimeout(function () {
saved.style.webkitTransition = 'opacity 1s ease 2s';
saved.style.mozTransition = 'opacity 1s ease 2s';
saved.style.oTransition = 'opacity 1s ease 2s';
saved.style.transition = 'opacity 1s ease 2s';
saved.style.opacity = '0';
}, 0);
}
window.onload = function () {
const FIREFOX = /Firefox/i.test(navigator.userAgent);
if (FIREFOX) {
firefoxFixes.setTextToSelectOptions();
}
let elems = document.getElementsByClassName('addTask'),
selects = document.getElementsByTagName('select');
for (let i = 0; i < elems.length; i++) {
elems[i].addEventListener('click', function () {
taskCreation.addTask(i);
});
}
[].forEach.call(selects, function (select) {
select.addEventListener('change', setBgColorOfSelect);
setBgColorOfSelect.call(select)
});
let taskColumns = document.getElementsByClassName('tasks');
for (var i = 0; i < taskColumns.length; i++) {
taskColumns[i].addEventListener('drop', dragEvents.dragDrop);
taskColumns[i].addEventListener('dragenter', dragEvents.dragEnter);
taskColumns[i].addEventListener('dragover', dragEvents.dragOver);
taskColumns[i].addEventListener('dragleave', dragEvents.dragLeave);
}
document.querySelector('#propertiesCloseButton').addEventListener('click', properties.hideProperties);
taskCreation.createTask = taskCreation.createTask.bind(taskCreation);
document.querySelector('#taskMakerCloseButton').addEventListener('click', taskCreation.closeTaskMaker.bind(taskCreation));
document.getElementById('editButton').addEventListener('click', properties.editProperties);
document.getElementById('exitEditMode').addEventListener('click', properties.editProperties);
document.getElementById('showSettings').addEventListener('click', settings.showSettings);
document.getElementById('hideSettings').addEventListener('click', settings.hideSettings);
document.getElementById('hideConfirmWindow').addEventListener('click', taskDeletion.hideConfirmWindow);
document.getElementById('settingsSave').addEventListener('click', settings.saveSettings);
};
}());<file_sep>Try online! https://jakub-leszczynski.github.io/To-do-App/
Organize your day with simple task manager!
|
fe142ba08859705d1c616bca64eed32bf3c734ba
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
BlackM0le/To-do-App
|
bdc3d3ca1b9d76c753c5303e66c25d59fedbfe50
|
80fb40253b259ea1c8bfc428f1193efd987abae7
|
refs/heads/master
|
<repo_name>confirmdev/CS50-2014<file_sep>/pset2/initials.c
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
// Prompt Line to input
string s = GetString(); //Get input
printf("%c", toupper(s[0]));
for (int i = 0, n = strlen(s); i < n; i++)
{
if ( s[i] == ' ' )
{char u = toupper(s[i += 1]);
printf("%c", u);
}
}
printf("\n");
return 0;
if ( s != NULL ) // Sanity Check to see if there was an input
{
printf("You didnt type in the blinking prompt\n");
return 1;
}
}
<file_sep>/pset1/greedy.c
#include <stdio.h>
#include <cs50.h>
#include<math.h>
int main(void)
{
//Declare all amounts - Quaters, Dimes, Nickels and Pennies values.
float quaters = 0.25;
float dimes = 0.10;
float nickels = 0.05;
float pennies = 0.01;
// Prompt line to enter amount value.
printf("Enter the amount of change owed: ");
float change = GetFloat(); //Input change
int x = 0;
// Sanity check for less than zero.
if (change <= 0)
{
printf("\nYou entered an invalid change\n"); //Invalid change when change is negative or zero
}
while ( change > 0 )
{
if ( change >= quaters) //If change > Quaters
{
change = change - quaters; //Subtract the value of the Quaters already printed
x++;
}
else if ( change >= dimes ) //If change > Dimes
{
change = change - dimes;
x++;
}
else if ( change >= nickels) //If change > Nickels
{
change = change - nickels;
x++;
}
else if (change >= pennies) //If change > Pennies
{
change = change - pennies;
x++;
}
else
{
change = roundf(change);
}
}
printf("%i\n", x );
}
<file_sep>/pset1/mario.c
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int i, j, k;
printf("Height: ");
int height = GetInt();
if (height > 0 && height <= 23)
{
for ( i = 0; i < height; i++)
{
for ( j = 0; j < ( height - i -1 ); j++)
{printf(" ");}
for ( k = 0; k < ( i + 2); k++)
{
printf("#");
}
printf("\n");
}
}
else
{
printf("\nThe value you entered is invalid. \n");
return 1;
}
}
<file_sep>/pset3/find/helpers.c
/**
* helpers.c
*
* Computer Science 50
* Problem Set 3
*
* Helper functions for Problem Set 3.
*/
#include <cs50.h>
#include <stdio.h>
#include "helpers.h"
/**
* Returns true if value is in array of n values, else false.
*/
bool search(int value, int values[], int n)
{
if (n < 1) // Lets cover situations when our n may be less than 1, Defensive Programming.
{
return false;
}
sort(values, n); // Sort the values first. We need to sort before we can do Binary Search.
// Implements a BINARY searching algorithm.
int min = 0;
int max = n-1;
while (max >= min)
{
int mid = (min + max)/2; // Mid is our max added to min then divided by 2.
if (max == min) // If the array only has one number, check that number.
{
if (value == values[n-1])
return true;
}
if (max == 1) // If the array only has two numbers, check both
{
if (value == values[1])
return true;
if (value == values[0])
return true;
}
if (value == values[mid]) // If number is at mid.
return true;
else if (value < values[mid])
{
max = mid - 1; //search left
}
else
{
min = mid + 1; //search right
}
}
return false; //return false if(nothing found).
}
/**
* Sorts array of n values.
*/
void sort(int values[ ], int n)
{
// Bubble sort algorithm implementation.
// Needs to min off as true to keep track of swaps or nothing will happen.
int swaps = true;
// Sorting while loop. If no swaps are made swaps will remain false.
while (swaps == true)
{
int temp;
swaps = false;
for (int i = 0; i < (n-1); i++)
{
if (values[i] > values[i+1]) //If Greater than the next
{ //swap
temp = values[i + 1];
values[i + 1] = values[i];
values[i] = temp;
swaps = true;
}
}
}
}
<file_sep>/pset2/caesar.c
// Pset2 Caesar Cypher
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[]) // Accepting command at the Terminal
{
if (argc != 2) // Verifying the input at the command-line to be exactly 2
{
printf("Please Enter the valid command-line argument\n"); // Message yelled if argc isnt 2
return 1;
}
else
{
int k = atoi(argv[1]); // converting argv[1] into an int and assigning it to key
if ( k < 0)
{
printf("Please Enter a positive integer as key\n");
}
string p = GetString();
for ( int i = 0, n = strlen(p); i < n; i ++)
{
if ( islower(p[i]) && (p[i] >= 'a' && p[i] <= 'z')) // Condition to encrypt lower case letters
{
char c;
c = (p[i] + k - 'a') % 26 + 'a'; // Encryption of lower case letters
printf("%c", c );
}
else if ( isupper(p[i]) && (p[i] >= 'A' && p[i] <= 'Z')) // Condition to encrypt upper case letters
{ // Else if our char is upper case, also encrypt
int x;
x = (p[i] + k -'A') % 26 + 'A'; // Encrypt upper case letters and then print it
printf("%c", x);
}
else // Leaving-out symbols and numbers
{ // Non-Alphabetics remain unchanged.
printf("%c", p[i]);
}
}
printf("\n"); // New Line
return 0;
}
}
<file_sep>/pset3/find/helpers linear.c
/**
* helpers.c
*
* Computer Science 50
* Problem Set 3
*
* Helper functions for Problem Set 3.
*/
#include <cs50.h>
#include "helpers.h"
/**
* Returns true if value is in array of n values, else false.
*/
// TODO: implement a searching algorithm
// search(needle, haystack, size)
bool search(int needle, int values[], int size)
{
for( int i = 0; i < size; i++)
{
if( values[i] == needle )
{
return false;
}
return i;
}
return false;
}
/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{ // Implementation of Bubble Sort
// TODO: implement an O(n^2) sorting algorithm
for (int i = 0; i < n; i++)
{
int temp = values[i];
int j = i;
while (j > 0 && values[j-1] > temp)
{
values[j] = values[j-1];
j = j-1;
values[j] = temp;
}
}
}
<file_sep>/pset2/vigenere.c
// Pset2 Vigenere Cypher
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[]) // Accepting command at the Terminal
{
if (argc != 2) // Verifying the input at the command-line to be exactly 2
{
printf("Please Enter the valid command-line argument\n"); // Message yelled if argc isnt 2
return 1;
}
else
{
string key =(argv[1]); // argv[1] assigned as key
int m = strlen(argv[1]);
printf("Enter your plain text: ");
string p = GetString();
for ( int i = 0, n = strlen(p); i < n; i ++)
{
if ( islower(p[i]) && (p[i] >= 'a' && p[i] <= 'z')) // Condition to encrypt lower case letters
{
int g = i % (m+1);
printf("%i", g);
char c;
if ( isupper(key[g]))
{
int k = key[g] - 'A';
c = (p[i] + k - 97) % 26 + 97; // Encryption of lower case letters
printf("%c", c );
}
else
{
int k = key[g] - 'a';
c = (p[i] + k - 97) % 26 + 97; // Encryption of lower case letters
printf("%c", c );
}
}
else if ( isupper(p[i]) && (p[i] >= 'A' && p[i] <= 'Z') ) // Condition to encrypt upper case letters
{
int g = i % (m+1);
printf("%i", g);
if ( isupper(key[g]))
{
int k = key[g] - 'A';
char x;
x = (p[i] + k -65) % 26 + 65; // Encrypt upper case letters and then print it
printf("%c", x);
}
else
{
int k = key[g] - 'a';
char x;
x = (p[i] + k -65) % 26 + 65; // Encrypt upper case letters and then print it
printf("%c", x);
}
}
else if( p[i] == ' ')
{
printf(" ");
continue;
}
else // Leaving-out symbols and numbers
{
printf("%c", p[i]);
}
}
printf("\n"); // New Line
return 0;
}
}
<file_sep>/pset3/find/helpers error.c
/**
* helpers.c
*
* Computer Science 50
* Problem Set 3
*
* Helper functions for Problem Set 3.
*/
#include <cs50.h>
#include "helpers.h"
/**
* Returns true if value is in array of n values, else false.
*/
// TODO: implement a searching algorithm
// search(needle, haystack, size)
int min = 0, max, size;
max = size;
int findMid(min, max)
{
return (min + max) / 2;
}
bool search(int needle, int haystack[], int size)
{
sort(int haystack[], int size)
if(max < min)
return -1;
else
sort(haystack, size);
int mid = findMid(min, max);
if(haystack[mid] < needle)
{ printf("Haystack[mid] : %i < needle : %i", haystack[mid], needle);
min = mid +=1;
search(needle, haystack, size);
}
else if( haystack[mid] > needle)
{
printf("Haystack[mid] : %i > needle : %i", haystack[mid], needle);
size = mid -= 1;
search(needle, haystack, size);
}
else
{printf("mid: %i", mid);
return mid;}
}
/**
* Sorts array of n values.
*/
void sort(int haystack, int size)
{ // Implementation of Bubble Sort
// TODO: implement an O(n^2) sorting algorithm
int swaps = true;
for (int i = 0; i < size; i++)
{
int sorthelper = haystack[i];
int j = i;
while (j > 0 && haystack[j-1] > sorthelper)
{
haystack[j] = haystack[j-1];
j = j-1;
haystack[j] = sorthelper;
}
}
}
<file_sep>/README.md
# CS50-2014
An introduction to the intellectual enterprises of computer science and the art of programming. CS50 by Harvard University. This course was completed in 2015 and has since been updated.
Note that the new updates to the course were not taken, neither are the problem sets updated!
|
fbd63c189b839b3e6f69b61b4aa1ece1f863f7cf
|
[
"Markdown",
"C"
] | 9 |
C
|
confirmdev/CS50-2014
|
406a5673e4169bdb5a82b33fb228aea5179bfe5c
|
82aad380e304c439c5fd580de1c9c75421ab44ad
|
refs/heads/master
|
<file_sep>import pyttsx3
import datetime
import speech_recognition as sr
from tkinter import messagebox
import tkinter as tk
import gtts
import random
import os
import wikipedia
import webbrowser
#----------- documentation ---------------------
# first we have to open the terminal from below options
# then we have to type this commands in the same order one by one
#----------- commands ---------------------------
# pip install wikipedia
# pip install pywin32
# pip install pipwin
# pipwin install pyaudio
# ------------------------------------------------
engine = pyttsx3.init("sapi5")
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[0].id)
def speak(audio, toBeSaved=False):
if(toBeSaved):
rand = random.randrange(1, 100000)
tts = gtts.gTTS(audio)
tts.save("{}{}.mp3".format(str(audio).replace(" ", "_"), rand))
os.startfile("{}{}.mp3".format(str(audio).replace(" ", "_"), rand))
else:
engine.say(audio)
engine.runAndWait()
def reply(queryFromResult):
query = str(queryFromResult).lower()
if ("how are you" in query):
speak("I am fine, Nice to meet you")
elif ("wikipedia" in query):
query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences=2)
speak("According to wikipedia")
speak(results)
elif ("open google" in query):
speak("opening google")
webbrowser.open("google.com")
elif ("open youtube" in query):
speak("opening youtube")
webbrowser.open("youtube.com")
elif ("open facebook" in query):
speak("opening facebook")
webbrowser.open("facebook.com")
def onStart():
hour = int(datetime.datetime.now().hour)
if(hour>=0 and hour<=12):
engine.say("Good morning")
engine.runAndWait()
elif(hour>12 and hour<=16):
engine.say("Good afternoon")
engine.runAndWait()
elif(hour>16 and hour<=19):
engine.say("Good evening")
engine.runAndWait()
else:
engine.say("Hope, your day was great!")
engine.runAndWait()
engine.say("How can I help you?")
engine.runAndWait()
#
notClickedListen = True
def listenToUser(btn):
global notClickedListen
if(notClickedListen):
onStart()
notClickedListen = False
btn.configure(background="#2b18d8")
btn.configure(text="Listening.......")
r = sr.Recognizer()
with sr.Microphone() as source:
print("listening")
r.energy_threshold = 200
r.pause_threshold = 1
audio = r.listen(source)
try:
query = r.recognize_google(audio, language="en-IN")
reply(query)
btn.configure(background="#d8d106")
btn.configure(text="Listen")
except Exception as e:
print(e)
btn.configure(background="#d8d106")
btn.configure(text="Listen")
messagebox.showerror(
title="Error",
message='''Some error occurred,\n
please try gain later'''
)
#
# speak("Hi, How are you")
top = tk.Tk()
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
font10 = "-family {Segoe UI} -size 13 -weight bold -slant " \
"roman -underline 0 -overstrike 0"
font9 = "-family {Courier New} -size 15 -weight bold -slant " \
"roman -underline 0 -overstrike 0"
top.geometry("553x180")
top.title("Jarvis")
top.configure(background="#add2d6")
Entry1 = tk.Entry(top)
Entry1.place(relx=0.054, rely=0.111,height=34, relwidth=0.893)
Entry1.configure(background="white")
Entry1.configure(disabledforeground="#a3a3a3")
Entry1.configure(font=font9)
Entry1.configure(foreground="#000000")
Entry1.configure(insertbackground="black")
Entry1.configure(width=494)
Button1 = tk.Button(top, command = lambda:speak(Entry1.get(), False))
Button1.place(relx=0.054, rely=0.389, height=33, width=236)
Button1.configure(activebackground="#ececec")
Button1.configure(activeforeground="#000000")
Button1.configure(background="#ccd829")
Button1.configure(disabledforeground="#a3a3a3")
Button1.configure(foreground="#000000")
Button1.configure(highlightbackground="#d9d9d9")
Button1.configure(highlightcolor="black")
Button1.configure(pady="0")
Button1.configure(text='''Speak''')
Button1.configure(width=236)
menubar = tk.Menu(top,font="TkMenuFont",bg=_bgcolor,fg=_fgcolor)
top.configure(menu = menubar)
Button1_1 = tk.Button(top, command = lambda:speak(Entry1.get(), True))
Button1_1.place(relx=0.506, rely=0.389, height=33, width=246)
Button1_1.configure(activebackground="#ececec")
Button1_1.configure(activeforeground="#000000")
Button1_1.configure(background="#ccd829")
Button1_1.configure(disabledforeground="#a3a3a3")
Button1_1.configure(foreground="#000000")
Button1_1.configure(highlightbackground="#d9d9d9")
Button1_1.configure(highlightcolor="black")
Button1_1.configure(pady="0")
Button1_1.configure(text='''Save and play''')
Button1_1.configure(width=246)
Button2 = tk.Button(top, command = lambda: listenToUser(Button2))
Button2.place(relx=0.054, rely=0.667, height=33, width=496)
Button2.configure(activebackground="#ececec")
Button2.configure(activeforeground="#000000")
Button2.configure(background="#d8d106")
Button2.configure(disabledforeground="#a3a3a3")
Button2.configure(font=font10)
Button2.configure(foreground="#fff")
Button2.configure(highlightbackground="#d9d9d9")
Button2.configure(highlightcolor="black")
Button2.configure(pady="0")
Button2.configure(text='''Listen''')
Button2.configure(width=496)
top.mainloop()
|
1167c4655b32e752f573649a44d0bf5ca2f08807
|
[
"Python"
] | 1 |
Python
|
00440022/JarvisProject
|
628fd060c717f349a81ca300026d408cfca5b35d
|
759109851c9f595bdaaee4c2e35ef37c4a072316
|
refs/heads/master
|
<file_sep>import React from 'react';
import styled from 'styled-components';
const Button = styled.button`
background: transparent;
border-radius: 3px;
border: 2px solid #3b4049;
color: white;
margin-right: 1em;
padding: 0.5em 1.5em;
&.active {
background-color: #3b4049
color: white;
font-weight: 600;
}
`;
const Container = styled.div`
display: flex;
justify-content: flex-start !important;
`;
export const Filter = ({filterList, selectedFilterType}) => {
const filter = (type) => {
return () => {
filterList(type)
}
};
return (
<Container>
<Button className={`${selectedFilterType === 'all' ? 'active' : ''}`}
onClick={filter('all')}>All</Button>
<Button className={`${selectedFilterType === 'active' ? 'active' : ''}`}
onClick={filter('active')}>Active</Button>
<Button className={`${selectedFilterType === 'completed' ? 'active' : ''}`}
onClick={filter('completed')}>Completed</Button>
</Container>
)
};
<file_sep>import React from "react";
import AddTodo from "./AddTodo";
import { Filter } from "./Filter";
import TodoList from "./TodoList";
import styled from "styled-components";
const TodosWrapper = styled.div`
max-width: 500px;
display: flex;
flex-direction: column;
`;
class ListWrapper extends React.PureComponent {
constructor (props) {
super(props);
this.state = {
toggled: false,
filterType: 'all',
filteredItems: []
}
}
toggle = () => {
this.setState({toggled: !this.state.toggled})
};
filterList = (type) => {
this.setState({filterType: type})
};
componentDidMount () {
const { getListItems, list } = this.props;
const items = getListItems(list);
this.setState({items})
}
render() {
const { createTodo, toggleComplete, list, getListItems } = this.props;
const { toggled, filteredItems, filterType } = this.state;
const items = getListItems(list, filterType);
return (
<div className="listWrapper">
<div onClick={this.toggle}>
<span>{list}</span>
<span>
<i className={`fa fa-angle-${toggled ? 'up' : 'down'}`}/>
</span>
</div>
{
toggled && <TodosWrapper>
<AddTodo listName={list} onAddTodo={createTodo} />
<Filter selectedFilterType={filterType} filterList={this.filterList}/>
<TodoList listName={list} items={filteredItems.length ? filteredItems : items} toggleComplete={toggleComplete} />
</TodosWrapper>
}
</div>
)
}
}
export default ListWrapper;
|
4a55627ae33da0f62c62f13b8f6e247c0cd2bb0b
|
[
"JavaScript"
] | 2 |
JavaScript
|
hakvahan/react-todo
|
e1862b0f75f60508ce838f21d32349ced735b27e
|
c531af8239cf9d4aac6212365cd444dd91e38053
|
refs/heads/master
|
<file_sep>//
// InputeTextItem.swift
// VirtualCycling
//
// Created by <NAME> on 2020/05/30.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
struct InputeTextItem {
let placeholder: String
var isSecure = false
}
<file_sep>/**
* @file IndoorBike.ino
* @brief VirtualCycling エアロバイク側モジュール
* @author <NAME>
* @date 2020/05/30
*/
#include <M5Stack.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
// オーディオジャックと接続したPIN
const int PIN = 5;
// BLE設定
const char *localName = "VirtualCycling";
const char *serviceUUID = "edeccb55-86b6-4ef2-8711-9cb7c0d3f6a0";
const char *characteristicUUID = "b44924cc-83d8-4376-81f5-6b80e5654768";
// 通知用のBLEキャラクタリスティック
BLECharacteristic *characteristic;
// BLEの端末接続状態
bool isDeviceConnected = false;
// 回転数
int count = 0;
// 現在の表示値
char countValue[6];
/**
* M5Stackのセットアップ
*/
void setup(){
M5.begin();
// PINをプルアップに設定
pinMode(PIN, INPUT_PULLUP);
// BLEの初期化
initializeBLE();
M5.Lcd.setTextColor(WHITE);
// 回転数
M5.Lcd.drawString("00000", 80, 90, 7);
}
/**
* M5Stackのループ
*/
void loop() {
M5.update();
int value = digitalRead(PIN);
if (value == LOW) {
// エアロバイクを回転すると通電する
count += 1;
updateCount();
if (isDeviceConnected) {
notify();
}
delay(200);
}
}
/**
* BLEのコールバック
*/
class ServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
isDeviceConnected = true;
}
void onDisconnect(BLEServer* pServer) {
isDeviceConnected = false;
// 一定時間待ってからアドバタイジングを再開
delay(500);
pServer->startAdvertising();
}
};
/**
* BLEを初期化します
*/
void initializeBLE() {
// デバイスを作成
BLEDevice::init(localName);
// サーバーを作成
BLEServer* server = BLEDevice::createServer();
server->setCallbacks(new ServerCallbacks());
// サービスを作成
BLEService* service = server->createService(serviceUUID);
// 通知用のキャラクタリスティックを作成
characteristic = service->createCharacteristic(
characteristicUUID,
BLECharacteristic::PROPERTY_NOTIFY
);
characteristic->addDescriptor(new BLE2902());
// サービスを開始
service->start();
// アドバタイジングを開始
server->getAdvertising()->start();
}
/**
* 距離の表示を更新します
*/
void updateCount() {
char buffer[6];
sprintf(buffer, "%05d", count);
if (strcmp(countValue, buffer) != 0) {
strncpy(countValue, buffer, 6);
M5.Lcd.fillRoundRect(80, 90, 160, 110, 10, BLACK);
M5.Lcd.drawString(countValue, 80, 90, 7);
}
}
/**
* BLEで回転を送信します
*/
void notify() {
char json[24];
sprintf(json, "{\"delta\": %lu}", millis());
characteristic->setValue(json);
characteristic->notify();
Serial.println(json);
}
<file_sep>//
// ContentViewModel.swift
// VirtualCycling
//
// Created by <NAME> on 2020/05/30.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import Combine
/// コンテンツビューのビューモデル
class ContentViewModel: ObservableObject {
/// サイクルメーター
var meter: CycleMeter
/// WebViewのモデル
var webViewModel: WebViewModel
/// 画面に表示する経過時刻
@Published var time = "00:00";
/// 画面に表示する距離
@Published var distance = "0.00";
/// 画面に表示する消費カロリー
@Published var calorie = "0.0";
/// 画面に表示する回転数
@Published var cycle = "0";
/// 画面に表示する顔の傾き
@Published var face = "0.0";
/// Combineのキャンセル
private var cancellables = [AnyCancellable]()
/// ビューモデルの初期化
init(meter: CycleMeter, webViewModel: WebViewModel) {
self.meter = meter
self.webViewModel = webViewModel
// 経過時間
meter.$duration.sink { (value) in
let minutes = value / 1000 / 60
let seconds = (value - (6000 * minutes)) / 1000
self.time = String(format: "%02d:%02d", Int(minutes), Int(seconds))
}
.store(in: &cancellables)
// 距離
meter.$distance.sink { (value) in
self.distance = String(format: "%0.2f", value)
}
.store(in: &cancellables)
// 消費カロリー
meter.$calorie.sink { (value) in
self.calorie = String(format: "%0.1f", value)
}
.store(in: &cancellables)
// 回転数
meter.$count.sink { (value) in
self.cycle = String(format: "%d", Int(value))
}
.store(in: &cancellables)
// 顔の傾き
FaceTracking.shared.$roll
.throttle(for: .milliseconds(500), scheduler: RunLoop.main, latest: true).sink { (value) in
self.face = String(format: "%0.4f", value)
// rollが0以外の場合は左右に方向移動
if value < 0 {
self.webViewModel.evalute(javaScript: "right();")
} else if 0 < value {
self.webViewModel.evalute(javaScript: "left();")
}
}
.store(in: &cancellables)
// エアロバイクからの回転通知
BLEClient.shared.$model.sink { (model) in
guard let model = model else { return }
if let _ = model.delta {
// 移動
meter.count += 1.0
self.webViewModel.evalute(javaScript: "move();")
}
}
.store(in: &cancellables)
}
/// Jumpボタン押下時の処理
func jump() {
self.webViewModel.evalute(javaScript: "jump();")
}
}
<file_sep>//
// CycleMeter.swift
// VirtualCycling
//
// Created by <NAME> on 2020/05/30.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Combine
import Foundation
/// サイクルメーター
class CycleMeter: ObservableObject {
/// 1回転あたりの距離
static let perDistance = 0.006
/// 1回転あたりの消費カロリー
static let perCalorie = 0.12
/// 経過時間
@Published var duration = 0.0;
/// 距離
@Published var distance = 0.0;
/// 消費カロリー
@Published var calorie = 0.0;
/// 回転数
@Published var count = 0.0;
/// アイドル時間
private var iduleDuration = 3000.0
/// 毎秒呼ばれるタイマー
private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
/// Combineのキャンセル
private var cancellables = [AnyCancellable]()
/// 初期化
init() {
timer.sink { [weak self] _ in
guard let self = self else { return }
if self.iduleDuration < 3000 {
// アイドル時間が3秒以内なら継続と判定、経過時間を加算
self.duration += 1000
}
self.iduleDuration += 1000
}
.store(in: &cancellables)
$count.dropFirst().sink { [weak self] value in
guard let self = self else { return }
// アイドル時間をリセット
self.iduleDuration = 0
// 距離と消費カロリーを加算
self.distance += CycleMeter.perDistance
self.calorie += CycleMeter.perCalorie
}
.store(in: &cancellables)
}
}
<file_sep>//
// InputTextPanel.swift
// VirtualCycling
//
// Created by <NAME> on 2020/05/30.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
struct InputTextPanel: Identifiable {
var id = UUID().uuidString
let message: String
let items: [InputeTextItem]
let handler: ([String]?) -> Void
}
<file_sep>//
// ContentView.swift
// VirtualCycling
//
// Created by <NAME> on 2020/05/30.
// Copyright © 2020 <NAME>. All rights reserved.
//
import SwiftUI
/// コンテンツビュー
struct ContentView: View {
/// 各種情報表示. 距離や消費カロリーなどを非表示にする場合は false
@State var showInfo = true
/// ビューモデル
@ObservedObject var viewModel: ContentViewModel
/// 各種情報表示
var info: some View {
GeometryReader { proxy in
VStack () {
Text(self.viewModel.time)
.foregroundColor(.white)
HStack(spacing: 8) {
Text(self.viewModel.distance)
.foregroundColor(.white)
.frame(width: 40, alignment: .trailing)
Text("km")
.foregroundColor(.white)
.frame(width: 40, alignment: .leading)
}
HStack(spacing: 8) {
Text(self.viewModel.calorie)
.foregroundColor(.white)
.frame(width: 40, alignment: .trailing)
Text("cal")
.foregroundColor(.white)
.frame(width: 40, alignment: .leading)
}
HStack(spacing: 8) {
Text(self.viewModel.cycle)
.foregroundColor(.white)
.frame(width: 40, alignment: .trailing)
Text("cycle")
.foregroundColor(.white)
.frame(width: 40, alignment: .leading)
}
Text(self.viewModel.face)
.foregroundColor(.white)
}
.frame(width: proxy.size.width, height: proxy.size.height, alignment: .topLeading)
.offset(x: 16, y: 16)
}
.opacity(showInfo ? 1 : 0)
}
/// ジャンプボタン
var jumpButton: some View {
GeometryReader { proxy in
Button(action: self.viewModel.jump) {
Image(systemName: "arrow.right.arrow.left.circle")
.font(.largeTitle)
.foregroundColor(.white)
}
.frame(width: proxy.size.width, height: proxy.size.height, alignment: .bottomLeading)
.offset(x: 16, y: -26)
}
.opacity(showInfo ? 1 : 0)
}
var body: some View {
// iPad Proの解像度でストリートビューにリクエストを出し続けると数回のリクエストでエラーになるため
// 600x420をベースに拡大表示する
GeometryReader { proxy in
WebView(viewModel: self.viewModel.webViewModel)
.frame(width: 600, height: 420)
.transformEffect(CGAffineTransform(scaleX: (proxy.size.width / 600), y: (proxy.size.height / 420)))
.overlay(self.info)
.overlay(self.jumpButton)
.offset(CGSize(width: -1 * ((proxy.size.width - 600) / 2), height: -1 * ((proxy.size.height - 420) / 2)))
}
}
// MARK: - テキスト入力パネル
private func showInputTextPanel(_ panel: InputTextPanel?) {
guard let panel = panel else {
return
}
// 入力フィールド付きのアラートはSwiftUIでは非対応のため
// 従来通りUIAlertControllerを使用する
let alertController = UIAlertController(title: panel.message, message: nil, preferredStyle: .alert)
panel.items.forEach { item in
alertController.addTextField { (textField) in
textField.placeholder = item.placeholder
textField.isSecureTextEntry = item.isSecure
}
}
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: { action in
let values = alertController.textFields?.map { $0.text ?? "" }
panel.handler(values)
}))
alertController.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .default, handler: { action in
panel.handler(nil)
}))
mostFrontViewController().present(alertController, animated: true, completion: nil)
}
private func mostFrontViewController() -> UIViewController {
// 最前面にあるViewControllerを探す
let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first ?? UIApplication.shared.keyWindow!
var viewController = keyWindow.rootViewController!
while(viewController.presentedViewController != nil) {
viewController = viewController.presentedViewController!
}
return viewController
}
}
// MARK: - プレビュー
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(viewModel: .init(meter: CycleMeter(), webViewModel: WebViewModel()))
}
}
<file_sep>//
// WebViewModel.swift
// VirtualCycling
//
// Created by <NAME> on 2020/05/30.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Combine
import WebKit
/// WebViewのモデル
class WebViewModel: ObservableObject {
@Published var webView = WKWebView()
@Published var showActivity = false
@Published var prgress: Float = 0
@Published var panel: Panel?
@Published var inputTextPanel: InputTextPanel?
private var observers = [NSKeyValueObservation]()
/// 初期化
public init() {
observeWebViewStates(\.estimatedProgress)
observeWebViewStates(\.title)
observeWebViewStates(\.url)
observeWebViewStates(\.canGoBack)
observeWebViewStates(\.canGoForward)
}
/// KVO
private func observeWebViewStates<Value>(_ keyPath: KeyPath<WKWebView, Value>) {
observers.append(webView.observe(keyPath, options: .prior) { (_, _) in
self.objectWillChange.send()
})
}
/// JavaScriptを実行する
func evalute(javaScript: String) {
webView.evaluateJavaScript(javaScript) { (response, error) in
if let error = error {
print(error)
return
}
}
}
}
<file_sep>//
// SceneDelegate.swift
// VirtualCycling
//
// Created by <NAME> on 2020/05/30.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// FaceTrackingを開始
FaceTracking.shared.initialize()
// BLEを開始
BLEClient.shared.initialize()
let contentView = ContentView(viewModel: .init(meter: CycleMeter(), webViewModel: WebViewModel()))
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
}
<file_sep>//
// WebView.swift
// VirtualCycling
//
// Created by <NAME> on 2020/05/30.
// Copyright © 2020 <NAME>. All rights reserved.
//
import SwiftUI
import WebKit
/// WKWebViewのSwiftUIラッパー
struct WebView: UIViewRepresentable {
@ObservedObject var viewModel: WebViewModel
func makeCoordinator() -> WebView.Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> WKWebView {
let url = Bundle.main.url(forResource: "index", withExtension: "html")!
let uiView = viewModel.webView
uiView.uiDelegate = context.coordinator
uiView.navigationDelegate = context.coordinator
uiView.loadFileURL(url, allowingReadAccessTo: url)
uiView.scrollView.contentInsetAdjustmentBehavior = .never
return uiView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
}
// MARK: - Coordinator Classs
class Coordinator: NSObject {
private var view: WebView
init(_ view: WebView) {
self.view = view
}
}
}
// MARK: - WebView Navigation delegate
extension WebView.Coordinator: WKNavigationDelegate {
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
decisionHandler(.allow)
}
// MARK: - Autholication Challenges
public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic {
// Show alert dialog
let message = String(format: NSLocalizedString("Log in to %@", comment: ""), webView.url?.host ?? "site")
let items = [
InputeTextItem(placeholder: "User Name"),
InputeTextItem(placeholder: "Password", isSecure: true),
]
view.viewModel.inputTextPanel = InputTextPanel(message: message, items: items, handler: { (values) in
if let values = values {
let credential = URLCredential(user: values[0],
password: values[1],
persistence: .forSession)
completionHandler(.useCredential, credential)
} else {
completionHandler(.cancelAuthenticationChallenge, nil)
}
})
return
}
completionHandler(.performDefaultHandling, nil)
}
// MARK: - Reacting to Errors
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
if (error as NSError).code == NSURLErrorCancelled {
return
}
view.viewModel.panel = Panel(message: error.localizedDescription, type: .alert({}))
}
public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
if (error as NSError).code == NSURLErrorCancelled {
return
}
view.viewModel.panel = Panel(message: error.localizedDescription, type: .alert({}))
}
}
// MARK: - WebView UI delegate
extension WebView.Coordinator: WKUIDelegate {
// MARK: - Creating a Web View
public func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if navigationAction.targetFrame?.isMainFrame != true {
webView.load(navigationAction.request)
}
return nil
}
// MARK: - Displaying UI Panels
public func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
view.viewModel.panel = Panel(message: message, type: .alert(completionHandler))
}
public func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
view.viewModel.panel = Panel(message: message, type: .confirm(completionHandler))
}
public func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
let items = [InputeTextItem(placeholder: "Enter Text")]
view.viewModel.inputTextPanel = InputTextPanel(message: prompt, items: items, handler: { (values) in
completionHandler(values?.first)
})
}
}
<file_sep>//
// Panel.swift
// VirtualCycling
//
// Created by <NAME> on 2020/05/30.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
struct Panel: Identifiable {
enum PanelType {
case alert(() -> Void)
case confirm((Bool) -> Void)
}
var id = UUID().uuidString
let message: String
let type: PanelType
}
<file_sep>//
// FaceTracking.swift
// VirtualCycling
//
// Created by <NAME> on 2020/05/30.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import AVKit
import Vision
/// 顔検出
class FaceTracking: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
// メイン部分のコードはAppleのサンプルを流用
var session: AVCaptureSession?
var videoDataOutput: AVCaptureVideoDataOutput?
var videoDataOutputQueue: DispatchQueue?
var captureDevice: AVCaptureDevice?
var captureDeviceResolution: CGSize = CGSize()
private var detectionRequests: [VNDetectFaceRectanglesRequest]?
private var trackingRequests: [VNTrackObjectRequest]?
lazy var sequenceRequestHandler = VNSequenceRequestHandler()
@Published var roll = 0.0
// MARK: - シングルトンの初期化
static let shared = FaceTracking()
override private init() {
}
func initialize() {
self.session = self.setupAVCaptureSession()
self.prepareVisionRequest()
self.session?.startRunning()
}
// MARK: AVCapture 初期化
fileprivate func setupAVCaptureSession() -> AVCaptureSession? {
let captureSession = AVCaptureSession()
do {
let inputDevice = try self.configureFrontCamera(for: captureSession)
self.configureVideoDataOutput(for: inputDevice.device, resolution: inputDevice.resolution, captureSession: captureSession)
return captureSession
} catch {
print(error)
}
// Tear down AV capture
self.videoDataOutput = nil
self.videoDataOutputQueue = nil
return nil
}
fileprivate func highestResolution420Format(for device: AVCaptureDevice) -> (format: AVCaptureDevice.Format, resolution: CGSize)? {
var highestResolutionFormat: AVCaptureDevice.Format? = nil
var highestResolutionDimensions = CMVideoDimensions(width: 0, height: 0)
for format in device.formats {
let deviceFormat = format as AVCaptureDevice.Format
let deviceFormatDescription = deviceFormat.formatDescription
if CMFormatDescriptionGetMediaSubType(deviceFormatDescription) == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange {
let candidateDimensions = CMVideoFormatDescriptionGetDimensions(deviceFormatDescription)
if (highestResolutionFormat == nil) || (candidateDimensions.width > highestResolutionDimensions.width) {
highestResolutionFormat = deviceFormat
highestResolutionDimensions = candidateDimensions
}
}
}
if highestResolutionFormat != nil {
let resolution = CGSize(width: CGFloat(highestResolutionDimensions.width), height: CGFloat(highestResolutionDimensions.height))
return (highestResolutionFormat!, resolution)
}
return nil
}
fileprivate func configureFrontCamera(for captureSession: AVCaptureSession) throws -> (device: AVCaptureDevice, resolution: CGSize) {
let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .front)
if let device = deviceDiscoverySession.devices.first {
if let deviceInput = try? AVCaptureDeviceInput(device: device) {
if captureSession.canAddInput(deviceInput) {
captureSession.addInput(deviceInput)
}
if let highestResolution = self.highestResolution420Format(for: device) {
try device.lockForConfiguration()
device.activeFormat = highestResolution.format
device.unlockForConfiguration()
return (device, highestResolution.resolution)
}
}
}
throw NSError(domain: "ViewController", code: 1, userInfo: nil)
}
fileprivate func configureVideoDataOutput(for inputDevice: AVCaptureDevice, resolution: CGSize, captureSession: AVCaptureSession) {
let videoDataOutput = AVCaptureVideoDataOutput()
videoDataOutput.alwaysDiscardsLateVideoFrames = true
// Create a serial dispatch queue used for the sample buffer delegate as well as when a still image is captured.
// A serial dispatch queue must be used to guarantee that video frames will be delivered in order.
let videoDataOutputQueue = DispatchQueue(label: "com.example.apple-samplecode.VisionFaceTrack")
videoDataOutput.setSampleBufferDelegate(self, queue: videoDataOutputQueue)
if captureSession.canAddOutput(videoDataOutput) {
captureSession.addOutput(videoDataOutput)
}
videoDataOutput.connection(with: .video)?.isEnabled = true
if let captureConnection = videoDataOutput.connection(with: AVMediaType.video) {
if captureConnection.isCameraIntrinsicMatrixDeliverySupported {
captureConnection.isCameraIntrinsicMatrixDeliveryEnabled = true
}
}
self.videoDataOutput = videoDataOutput
self.videoDataOutputQueue = videoDataOutputQueue
self.captureDevice = inputDevice
self.captureDeviceResolution = resolution
}
func exifOrientationForDeviceOrientation(_ deviceOrientation: UIDeviceOrientation) -> CGImagePropertyOrientation {
switch deviceOrientation {
case .portraitUpsideDown:
return .rightMirrored
case .landscapeLeft:
return .downMirrored
case .landscapeRight:
return .upMirrored
default:
return .leftMirrored
}
}
func exifOrientationForCurrentDeviceOrientation() -> CGImagePropertyOrientation {
return exifOrientationForDeviceOrientation(UIDevice.current.orientation)
}
// MARK: Visionのリクエストを送信
fileprivate func prepareVisionRequest() {
let faceDetectionRequest = VNDetectFaceRectanglesRequest(completionHandler: { (request, error) in
if error != nil {
print("FaceDetection error: \(String(describing: error)).")
}
guard let faceDetectionRequest = request as? VNDetectFaceRectanglesRequest,
let results = faceDetectionRequest.results as? [VNFaceObservation] else {
return
}
DispatchQueue.main.async {
for observation in results {
// 顔のrollを取得
self.roll = observation.roll?.doubleValue ?? 0.00
}
}
})
// Start with detection. Find face, then track it.
self.detectionRequests = [faceDetectionRequest]
self.sequenceRequestHandler = VNSequenceRequestHandler()
}
// MARK: AVCaptureVideoDataOutputSampleBuffer デリゲート
public func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
var requestHandlerOptions: [VNImageOption: AnyObject] = [:]
let cameraIntrinsicData = CMGetAttachment(sampleBuffer, key: kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, attachmentModeOut: nil)
if cameraIntrinsicData != nil {
requestHandlerOptions[VNImageOption.cameraIntrinsics] = cameraIntrinsicData
}
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
print("Failed to obtain a CVPixelBuffer for the current output frame.")
return
}
let exifOrientation = self.exifOrientationForCurrentDeviceOrientation()
let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer,
orientation: exifOrientation,
options: requestHandlerOptions)
do {
guard let detectRequests = self.detectionRequests else {
return
}
try imageRequestHandler.perform(detectRequests)
} catch let error as NSError {
NSLog("Failed to perform FaceRectangleRequest: %@", error)
}
}
}
<file_sep>//
// BLEClient.swift
// VirtualCycling
//
// Created by <NAME> on 2020/05/30.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import CoreBluetooth
/// BLEクライアント
class BLEClient: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
/// ローカルネーム
private let kLocalName = "VirtualCycling"
/// セントラルマネージャー
private var centralManager: CBCentralManager!
/// ペリフェラル
private var peripheral: CBPeripheral!
/// BLE経由で受信したモデル
@Published var model: IndoorBike?
// MARK: - シングルトンの初期化
static let shared = BLEClient()
override private init() {
}
func initialize() {
centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)
}
// MARK: - CBCentralManager デリゲート
func centralManagerDidUpdateState(_ central: CBCentralManager) {
guard central.state == .poweredOn else {
return
}
// BLEに接続したらペリフェラルのスキャンを開始
centralManager.scanForPeripherals(withServices: nil, options: nil)
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
guard let localName = advertisementData[CBAdvertisementDataLocalNameKey] as? String,
localName == kLocalName else {
return
}
// ペリフェラルを見つけたらインスタンスを保持
self.peripheral = peripheral
// ペリフェラルに接続
centralManager.stopScan()
centralManager.connect(peripheral, options: nil)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
// ペリフェラルに接続したらサービスを検索
peripheral.delegate = self
peripheral.discoverServices(nil)
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
self.peripheral = nil
// ペリフェラルから切断した場合は、再度ペリフェラルのスキャンを開始
centralManager.scanForPeripherals(withServices: nil, options: nil)
}
// MARK: - CBPeripheral デリゲート
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if let error = error {
print(error)
return
}
// サービスに接続したらキャラクタリスティックを検索
peripheral.services?.forEach { (service) in
peripheral.discoverCharacteristics(nil, for: service)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let error = error {
print(error)
return
}
// キャラクタリスティックを発見したら通知の受信を設定
service.characteristics?.forEach({ (characteristic) in
peripheral.setNotifyValue(true, for: characteristic)
})
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
print(error)
return
}
guard let value = characteristic.value else {
return
}
do {
// 通知を受信したらJSONとしてパース
model = try JSONDecoder().decode(IndoorBike.self, from: value)
} catch {
print(error)
}
}
}
<file_sep># バーチャルサイクリング
[](https://opensource.org/licenses/MIT)
市販のエアロバイクで仮想サイクリングを実現するためのアプリ一式です。

以下の機材とアプリから構成されています。
* エアロバイク用 回転数取得機材 (M5Stack製)
* エアロバイク用 回転数送信用アプリ
* iOS用 ストリートビュー表示アプリ
エアロバイクにM5Stackで作成した簡易的な機材を接続することで、iOSアプリで表示したストリートビューとエアロバイクの回転が連動できるようになります。
エアロバイク用アプリとiOS用アプリ間ではBluetoothを使用してデータを連携します。
## :warning: 注意事項
- このアプリは電気信号等を制御するため、使用機材に予期せぬ損害を与える可能性があります。
もしも損害が発生した場合、エアロバイクの通常の使用方法とは異なるためメーカー保証の対象外となります。
- このアプリはGoogleストリートビューを使用するため、動作にはGoogle Cloud PlatformのAPI Keyが必要です。
APIの使用分に対して料金が発生するため、Googleの利用規約、料金設定をご確認ください。
- 記載されている機材等は開発時に使用したものを記載してあります。それらの機材での動作を保証するものではありません。
- これらのリスクを十分にご理解頂いた上で、自己責任においてご利用ください。
## 構成図

## エアロバイク用機材の作成
### 使用機材
* [アルインコ コンフォートバイクⅡ](https://www.alinco.co.jp/product/fitness/detail/id=4175)
* [M5Stack Basic](https://www.switch-science.com/catalog/3647/)
* [SideBB for M5Stack(ブレッドボード)](https://www.switch-science.com/catalog/4098/)
* [3.5mm オーディオジャック](https://www.switch-science.com/catalog/619/)
* [ジャンパワイヤ](https://www.switch-science.com/catalog/314/)
### 作成手順
1. M5Stackのボトムを外し、代わりにSideBBを接続します
2. SideBBに回線図を参考ににオーディオジャック、ジャンパワイヤを設置します
3. Arudiono IDEなどを使用して、M5Stackに[IndoorBike.ino](IndoorBike/IndoorBike.ino)をインストールします
| 回路図 |
| :-------------: |
|  |
| オーディオジャックの左右のピンとGND、5番を接続します |
### 設置手順
1. エアロバイク備え付けのモニターに接続されているオーディオケーブルを外します
2. 外したケーブルを、作成したメーターのオーディオジャックに接続します
| オーディオケーブル位置 |
| :-------------: |
|  |
| 接続例 |
| :-------------: |
|  |
## iOS用アプリの作成
### 要求環境
- iOS 13.5
- Xcode 11.5
- Swift 5.0
### ビルド&実行手順
1. [Google Cloud Platform Console](https://cloud.google.com/console/)からAPI Keyを発行します。以下のAPIを有効化してください。
- Maps JavaScript API
- Geocoding API
2. [index.html](iOS/VirtualCycling/www/index.html)をテキストエディタで開き、`YOUR_API_KEY` を取得したAPI Keyに書き換えます。
```html
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initialize
```
3. Xcodeで[VirtualCycling.xcodeproj](iOS/VirtualCycling.xcodeproj)を開きます。
4. Runボタンを押してアプリを実行します。
## 使用方法
1. エアロバイク側のアプリを起動します
2. iOS端末側のアプリを起動します
3. エアロバイクを回転すると、iOSアプリ側のストリートビューが移動します
**方向を変える**
顔を左右に傾けることで、方向を変更することができます。
**現在座標を変える**
左下のジャンプボタンを押すと、ストリートビューの現在座標が変わります。
## 作成者
<NAME> – <EMAIL>
## ライセンス
このプロジェクトはMITライセンスです。詳細は [ライセンス](LICENSE) ファイルを参照してください。
## 謝辞
このアプリを作成するにあたり、以下の記事・ライブラリを参照いたしました。
* [Aerocraft](https://github.com/mizucoffee/Aerocraft)
* [【フィットネスバイク】のインターネットを作る!!:Qiita](https://qiita.com/ie4/items/130308793444bd98179f)
* [M5Stack Bluetooth LE通信テスト](https://github.com/FromF/M5Stack-Color-BluetoothLE)
<file_sep>//
// IndoorBike.swift
// VirtualCycling
//
// Created by <NAME> on 2020/05/30.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
/// エアロバイク側機材との通信モデル
struct IndoorBike: Codable {
/// 前回の回転時刻からの差分 (ms)
var delta: Int?
}
|
3dc0fc1bcf94b7605e60dc62082cbf67c900fbfe
|
[
"Swift",
"C++",
"Markdown"
] | 14 |
Swift
|
watanabetoshinori/VirtualCycling
|
e42299fb71182c68d764b3fa0c00261d9b1eb24f
|
dc7449aaa3609ef17609f24cdff8a0a4f44e5dfd
|
refs/heads/master
|
<file_sep>/**************************
* Includes
*
**************************/
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include "glut.h"
#include "glaux.h"
/**************************
* Function Declarations
*
**************************/
LRESULT CALLBACK WndProc (HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam);
void EnableOpenGL (HWND hWnd, HDC *hDC, HGLRC *hRC);
void DisableOpenGL (HWND hWnd, HDC hDC, HGLRC hRC);
GLfloat xrot; // deklarasi rotasi x
GLfloat yrot; // deklarasi rotasi y
GLfloat zrot; // deklarasi rotasi z
GLuint texture[1]; // digunakan untuk menampung 1 gambar
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
AUX_RGBImageRec *LoadBMP(char *Filename) // fungsi menampilkan gambar
{
FILE *File=NULL;
if (!Filename)
{
return NULL;
}
File=fopen(Filename,"r"); // digunakan untuk membaca file
if (File)
{
fclose(File);
return auxDIBImageLoad(Filename); // jika gambar ada tampilkan gambar
}
return NULL;
}
int LoadGLTextures() // fungsi menampilkan gambar dan Convert ke Textures
{
int Status=FALSE;
AUX_RGBImageRec *TextureImage[11]; // membuat temporary untuk menyimpan gambar
memset(TextureImage,0,sizeof(void *)*1);
if (TextureImage[0]=LoadBMP("GAMBAR.bmp")) //pengambilan data gambar (256X256)
{
Status=TRUE;
glGenTextures(1, &texture[0]);
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}
if (TextureImage[1]=LoadBMP("JamDinding.bmp")) //pengambilan data gambar (256X256)
{
Status=TRUE;
glGenTextures(1, &texture[1]);
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texture[1]);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[1]->sizeX, TextureImage[1]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[1]->data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}
if (TextureImage[2]=LoadBMP("ac.bmp")) //pengambilan data gambar (256X256)
{
Status=TRUE;
glGenTextures(1, &texture[2]);
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texture[2]);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[2]->sizeX, TextureImage[2]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[2]->data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}
if (TextureImage[3]=LoadBMP("asset/lantai-1.bmp")) //pengambilan data gambar untuk lantai
{
Status=TRUE;
glGenTextures(1, &texture[3]);
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texture[3]);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[3]->sizeX, TextureImage[3]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[3]->data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}
if (TextureImage[4]=LoadBMP("asset/dinding-1.bmp")) //pengambilan data gambar untuk dinding kiri
{
Status=TRUE;
glGenTextures(1, &texture[4]);
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texture[4]);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[4]->sizeX, TextureImage[4]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[4]->data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}
if (TextureImage[5]=LoadBMP("asset/dinding-2.bmp")) //pengambilan data gambar untuk dinding kiri
{
Status=TRUE;
glGenTextures(1, &texture[5]);
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texture[5]);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[5]->sizeX, TextureImage[5]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[5]->data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}
if (TextureImage[6]=LoadBMP("asset/dinding-3.bmp")) //pengambilan data gambar untuk dinding kiri
{
Status=TRUE;
glGenTextures(1, &texture[6]);
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texture[6]);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[6]->sizeX, TextureImage[6]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[6]->data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}
if (TextureImage[7]=LoadBMP("asset/dinding-3.bmp")) //pengambilan data gambar untuk dinding kiri
{
Status=TRUE;
glGenTextures(1, &texture[7]);
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texture[7]);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[7]->sizeX, TextureImage[7]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[7]->data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}
if (TextureImage[8]=LoadBMP("Kelompok.bmp")) //pengambilan data gambar untuk dinding kiri
{
Status=TRUE;
glGenTextures(1, &texture[8]);
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texture[8]);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[8]->sizeX, TextureImage[8]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[8]->data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}
if (TextureImage[9]=LoadBMP("Kelompok2.bmp")) //pengambilan data gambar untuk dinding kiri
{
Status=TRUE;
glGenTextures(1, &texture[9]);
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texture[9]);
glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[9]->sizeX, TextureImage[9]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[9]->data);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}
}
void kubusNormal() {
glBegin(GL_QUADS);
// Muka depan
glNormal3f( 0.0f, 0.0f, 1.0f); // Normal menuju Anda
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 1 (depan)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 2 (depan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (depan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 4 (depan)
// Muka belakang
glNormal3f( 0.0f, 0.0f,-1.0f); // Normal meninggalKan Anda
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (belakang)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 2 (belakang)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 3 (belakang)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 4 (belakang)
// Muka Atas
glNormal3f( 0.0f, 1.0f, 0.0f); // Normal berarah atas
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 1 (atas)
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 2 (atas)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (atas)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 4 (atas)
// Muka bawah
glNormal3f( 0.0f,-1.0f, 0.0f); // Normal berarah bawah
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (bawah)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 2 (bawah)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 3 (bawah)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 4 (bawah)
// Muka kanan
glNormal3f( 1.0f, 0.0f, 0.0f); // Normal berarah ke kanan
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 1 (kanan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 2 (kanan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (kanan)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 4 (kanan)
// Muka kiri
glNormal3f(-1.0f, 0.0f, 0.0f); // Normal berarah ke kiri
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (kiri)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 2 (kiri)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 3 (kiri)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 4 (kiri)
glEnd();
}
void kubusRuangan() {
glBindTexture(GL_TEXTURE_2D, texture[4]); //menampilkan citra
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
// Muka belakang
glNormal3f( 0.0f, 0.0f,-1.0f); // Normal meninggalKan Anda
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (belakang)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 2 (belakang)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 3 (belakang)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 4 (belakang)
glEnd();
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[7]); //menampilkan citra
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
// Muka Atas
glNormal3f( 0.0f, 1.0f, 0.0f); // Normal berarah atas
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 1 (atas)
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 2 (atas)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (atas)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 4 (atas)
glEnd();
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[3]); //menampilkan citra
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
// Muka bawah
glNormal3f( 0.0f,-1.0f, 0.0f); // Normal berarah bawah
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (bawah)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 2 (bawah)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 3 (bawah)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 4 (bawah)
glEnd();
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[6]); //menampilkan citra
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
// Muka kanan
glNormal3f( 1.0f, 0.0f, 0.0f); // Normal berarah ke kanan
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 1 (kanan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 2 (kanan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (kanan)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 4 (kanan)
glEnd();
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[5]); //menampilkan citra
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
// Muka kiri
glNormal3f(-1.0f, 0.0f, 0.0f); // Normal berarah ke kiri
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (kiri)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 2 (kiri)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 3 (kiri)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 4 (kiri)
glEnd();
glDisable(GL_TEXTURE_2D);
}
void kubusTekstur()
{
glBindTexture(GL_TEXTURE_2D, texture[0]);
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
// Muka depan
glNormal3f( 0.0f, 0.0f, 1.0f); // Normal menuju Anda
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 1 (depan)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 2 (depan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (depan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 4 (depan)
// Muka belakang
glNormal3f( 0.0f, 0.0f,-1.0f); // Normal meninggalKan Anda
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (belakang)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 2 (belakang)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 3 (belakang)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 4 (belakang)
// Muka Atas
glNormal3f( 0.0f, 1.0f, 0.0f); // Normal berarah atas
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 1 (atas)
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 2 (atas)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (atas)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 4 (atas)
// Muka bawah
glNormal3f( 0.0f,-1.0f, 0.0f); // Normal berarah bawah
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (bawah)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 2 (bawah)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 3 (bawah)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 4 (bawah)
// Muka kanan
glNormal3f( 1.0f, 0.0f, 0.0f); // Normal berarah ke kanan
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 1 (kanan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 2 (kanan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (kanan)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 4 (kanan)
// Muka kiri
glNormal3f(-1.0f, 0.0f, 0.0f); // Normal berarah ke kiri
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (kiri)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 2 (kiri)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 3 (kiri)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 4 (kiri)
glEnd();
glDisable(GL_TEXTURE_2D);
// Akhir kode yang diambil dari bukunya Suyoto
//******************************************************
}
void kubusJamTekstur()
{
glBindTexture(GL_TEXTURE_2D, texture[1]); //menampilkan citra
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
// Muka depan
glNormal3f( 0.0f, 0.0f, 1.0f); // Normal menuju Anda
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 1 (depan)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 2 (depan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (depan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 4 (depan)
// Muka belakang
glNormal3f( 0.0f, 0.0f,-1.0f); // Normal meninggalKan Anda
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (belakang)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 2 (belakang)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 3 (belakang)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 4 (belakang)
// Muka Atas
glNormal3f( 0.0f, 1.0f, 0.0f); // Normal berarah atas
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 1 (atas)
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 2 (atas)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (atas)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 4 (atas)
// Muka bawah
glNormal3f( 0.0f,-1.0f, 0.0f); // Normal berarah bawah
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (bawah)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 2 (bawah)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 3 (bawah)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 4 (bawah)
// Muka kanan
glNormal3f( 1.0f, 0.0f, 0.0f); // Normal berarah ke kanan
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 1 (kanan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 2 (kanan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (kanan)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 4 (kanan)
// Muka kiri
glNormal3f(-1.0f, 0.0f, 0.0f); // Normal berarah ke kiri
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (kiri)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 2 (kiri)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 3 (kiri)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 4 (kiri)
glEnd();
glDisable(GL_TEXTURE_2D);
// Akhir kode yang diambil dari bukunya Suyoto
//******************************************************
}
void kubusAcTekstur()
{
glBindTexture(GL_TEXTURE_2D, texture[2]); //menampilkan citra
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
// Muka kanan
glNormal3f( 1.0f, 0.0f, 0.0f); // Normal berarah ke kanan
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 1 (kanan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 2 (kanan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (kanan)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 4 (kanan)
glEnd();
glDisable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
// Muka depan
glNormal3f( 0.0f, 0.0f, 1.0f); // Normal menuju Anda
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 1 (depan)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 2 (depan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (depan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 4 (depan)
// Muka belakang
glNormal3f( 0.0f, 0.0f,-1.0f); // Normal meninggalKan Anda
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (belakang)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 2 (belakang)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 3 (belakang)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 4 (belakang)
// Muka Atas
glNormal3f( 0.0f, 1.0f, 0.0f); // Normal berarah atas
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 1 (atas)
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 2 (atas)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (atas)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 4 (atas)
// Muka bawah
glNormal3f( 0.0f,-1.0f, 0.0f); // Normal berarah bawah
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (bawah)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 2 (bawah)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 3 (bawah)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 4 (bawah)
// Muka kiri
glNormal3f(-1.0f, 0.0f, 0.0f); // Normal berarah ke kiri
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (kiri)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 2 (kiri)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 3 (kiri)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 4 (kiri)
glEnd();
// Akhir kode yang diambil dari bukunya Suyoto
//******************************************************
}
void lemari() {
// Untuk bahan objek kubus sisi belakang
GLfloat bahan_ambient0[]= {1.0f, 0.77f, 0.3f, 0.8f};
GLfloat bahan_diffuse0[] = {1.0f, 0.7f, 0.3f, 0.8f};
GLfloat bahan_specular0[] = {1.0f, 0.7f, 0.3f, 0.8f};
GLfloat bahan_shininess0[] = {10.0f};
// Untuk bahan objek kubus sisi kiri
GLfloat bahan_ambient1[]= {1.0f, 0.77f, 0.3f, 0.8f};
GLfloat bahan_diffuse1[] = {1.0f, 0.7f, 0.3f, 0.8f};
GLfloat bahan_specular1[] = {1.0f, 0.7f, 0.3f, 0.8f};
GLfloat bahan_shininess1[] = {10.0f};
// Untuk bahan objek kubus sisi kanan
GLfloat bahan_ambient2[]= {1.0f, 0.77f, 0.3f, 0.8f};
GLfloat bahan_diffuse2[] = {1.0f, 0.7f, 0.3f, 0.8f};
GLfloat bahan_specular2[] = {1.0f, 0.7f, 0.3f, 0.8f};
GLfloat bahan_shininess2[] = {10.0f};
// Untuk bahan objek kubus sisi atas
GLfloat bahan_ambient3[]= {1.0f, 0.77f, 0.3f, 0.8f};
GLfloat bahan_diffuse3[] = {1.0f, 0.7f, 0.3f, 0.8f};
GLfloat bahan_specular3[] = {1.0f, 0.7f, 0.3f, 0.8f};
GLfloat bahan_shininess3[] = {10.0f};
glBegin(GL_QUADS);
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient0);
glMaterialfv(GL_FRONT, GL_DIFFUSE, bahan_diffuse0);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular0);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess0);
// Muka belakang
glNormal3f( 0.0f, 0.0f,-1.0f); // Normal meninggalKan Anda
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (belakang)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 2 (belakang)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 3 (belakang)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 4 (belakang)
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient1);
glMaterialfv(GL_FRONT, GL_DIFFUSE, bahan_diffuse1);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular1);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess1);
// Muka Atas
glNormal3f( 0.0f, 1.0f, 0.0f); // Normal berarah atas
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 1 (atas)
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 2 (atas)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (atas)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 4 (atas)
// Muka bawah
glNormal3f( 0.0f,-1.0f, 0.0f); // Normal berarah bawah
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (bawah)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 2 (bawah)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 3 (bawah)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 4 (bawah)
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient2);
glMaterialfv(GL_FRONT, GL_DIFFUSE, bahan_diffuse2);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular2);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess2);
// Muka kanan
glNormal3f( 1.0f, 0.0f, 0.0f); // Normal berarah ke kanan
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 1 (kanan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 2 (kanan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (kanan)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 4 (kanan)
// Muka kiri
glNormal3f(-1.0f, 0.0f, 0.0f); // Normal berarah ke kiri
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (kiri)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 2 (kiri)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 3 (kiri)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 4 (kiri)
glEnd();
}
void kubusFiguraKananTekstur()
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[8]); //menampilkan citra
glBegin(GL_QUADS);
// Muka kanan
glNormal3f( 1.0f, 0.0f, 0.0f); // Normal berarah ke kanan
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 1 (kanan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 2 (kanan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (kanan)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 4 (kanan)
glEnd();
glDisable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
// Muka depan
glNormal3f( 0.0f, 0.0f, 1.0f); // Normal menuju Anda
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 1 (depan)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 2 (depan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (depan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 4 (depan)
// Muka belakang
glNormal3f( 0.0f, 0.0f,-1.0f); // Normal meninggalKan Anda
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (belakang)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 2 (belakang)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 3 (belakang)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 4 (belakang)
// Muka Atas
glNormal3f( 0.0f, 1.0f, 0.0f); // Normal berarah atas
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 1 (atas)
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 2 (atas)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (atas)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 4 (atas)
// Muka bawah
glNormal3f( 0.0f,-1.0f, 0.0f); // Normal berarah bawah
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (bawah)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 2 (bawah)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 3 (bawah)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 4 (bawah)
// Muka kiri
glNormal3f(-1.0f, 0.0f, 0.0f); // Normal berarah ke kiri
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (kiri)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 2 (kiri)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 3 (kiri)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 4 (kiri)
glEnd();
// Akhir kode yang diambil dari bukunya Suyoto
//******************************************************
}
void kubusFiguraKiriTekstur()
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[9]); //menampilkan citra
glBegin(GL_QUADS);
// Muka kanan
glNormal3f( 1.0f, 0.0f, 0.0f); // Normal berarah ke kanan
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 1 (kanan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 2 (kanan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (kanan)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 4 (kanan)
glEnd();
glDisable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
// Muka depan
glNormal3f( 0.0f, 0.0f, 1.0f); // Normal menuju Anda
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 1 (depan)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 2 (depan)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (depan)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 4 (depan)
// Muka belakang
glNormal3f( 0.0f, 0.0f,-1.0f); // Normal meninggalKan Anda
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (belakang)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 2 (belakang)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 3 (belakang)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 4 (belakang)
// Muka Atas
glNormal3f( 0.0f, 1.0f, 0.0f); // Normal berarah atas
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 1 (atas)
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 2 (atas)
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (atas)
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 4 (atas)
// Muka bawah
glNormal3f( 0.0f,-1.0f, 0.0f); // Normal berarah bawah
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (bawah)
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 2 (bawah)
glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 3 (bawah)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 4 (bawah)
// Muka kiri
glNormal3f(-1.0f, 0.0f, 0.0f); // Normal berarah ke kiri
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, -1.0f); // Titik 1 (kiri)
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f); // Titik 2 (kiri)
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f); // Titik 3 (kiri)
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f); // Titik 4 (kiri)
glEnd();
// Akhir kode yang diambil dari bukunya Suyoto
//******************************************************
}
void FotoKelompokKanan()
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[7]); //menampilkan citra
glBegin(GL_QUADS);
glNormal3f( 1.0f, 0.0f, 0.0f); // Normal berarah ke kanan
glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Titik 1 (kanan)
glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Titik 2 (kanan)
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // Titik 3 (kanan)
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Titik 4 (kanan)
glEnd();
glDisable(GL_TEXTURE_2D);
}
//******************************************************
// Awal kode yang diambil dari bukunya Suyoto
void Inisialisasi(int lebar, int tinggi)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
glClearAccum(0.0, 0.0, 0.0, 0.0);
glViewport (0, 0, lebar, tinggi);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ( );
gluPerspective(60.0, (GLfloat) lebar/(GLfloat) tinggi, 1.0, 20.0);
glMatrixMode (GL_MODELVIEW);
LoadGLTextures();
// hidupkan pencahayaan
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
//glShadeModel (GL_FLAT);
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
}
// Akhir kode yang diambil dari bukunya Suyoto
//******************************************************
/**************************
* WinMain
*
**************************/
int WINAPI
WinMain (HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int iCmdShow)
{
WNDCLASS wc;
HWND hWnd;
HDC hDC;
HGLRC hRC;
MSG msg;
BOOL bQuit = FALSE;
// Untuk bahan objek teko
GLfloat bahan_ambient0[]= {1.0f, 0.0f, 0.0f, 1.0f};
GLfloat bahan_diffuse0[] = {1.0f, 0.0f, 0.0f, 1.0f};
GLfloat bahan_specular0[] = {1.0f, 0.0f, 0.0f, 1.0f};
GLfloat bahan_shininess0[] = {10.0f};
// Untuk bahan objek torus
GLfloat bahan_ambient1[]= {0.0f, 1.0f, 0.0f, 1.0f};
GLfloat bahan_diffuse1[] = {0.0f, 1.0f, 0.0f, 1.0f};
GLfloat bahan_specular1[] = {0.0f, 1.0f, 0.0f, 1.0f};
GLfloat bahan_shininess1[] = {10.0f};
// Untuk bahan objek bola
GLfloat bahan_ambient2[]= {0.0f, 0.0f, 1.0f, 1.0f};
GLfloat bahan_diffuse2[] = {0.0f, 0.0f, 1.0f, 1.0f};
GLfloat bahan_specular2[] = {0.0f, 0.0f, 1.0f, 1.0f};
GLfloat bahan_shininess2[] = {10.0f};
// Untuk bahan objek kubus
GLfloat bahan_ambient3[]= {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat bahan_diffuse3[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat bahan_specular3[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat bahan_shininess3[] = {10.0f};
// Untuk Pencahayaan
GLfloat IntensitasCahaya0[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat PosisiCahaya0[]={0.0f,6.0f,5.0f, 1.0f};
GLfloat PosisiCahaya1[]={-10.0f,0.0f,-10.0f, 1.0f};
GLfloat PosisiCahaya2[]={15.0f,10.0f,-9.0f, 0.0f};
/* register window class */
wc.style = CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor (NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH) GetStockObject (BLACK_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = "TF-UAJY";
RegisterClass (&wc);
/* create main window */
hWnd = CreateWindow (
"TF-UAJY", "UAS_8141_8193_8240_8332",
WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE,
0, 0, 1024, 768,
NULL, NULL, hInstance, NULL);
/* enable OpenGL for the window */
EnableOpenGL (hWnd, &hDC, &hRC);
//******************************************************
// Awal kode yang diambil dari bukunya Suyoto
Inisialisasi(1024, 768);
// Akhir kode yang diambil dari bukunya Suyoto
//******************************************************
/* program main loop */
while (!bQuit)
{
/* check for messages */
if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
{
/* handle or dispatch messages */
if (msg.message == WM_QUIT)
{
bQuit = TRUE;
}
else
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
}
else
{
/* OpenGL animation code goes here */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//******************************************************
// Awal kode yang diambil dari bukunya Suyoto
//glColor3f (0, 0, 1);
//bahan untuk teko
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient0);
glMaterialfv(GL_FRONT, GL_DIFFUSE, bahan_diffuse0);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular0);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess0);
glLightfv(GL_LIGHT0, GL_DIFFUSE, IntensitasCahaya0);
glLightfv(GL_LIGHT0, GL_POSITION, PosisiCahaya0);
glPushMatrix( );
glTranslatef (-0.3, -2.2f, -6.0f);
glScalef(0.3f, 0.3f, 0.3f);
glRotatef(yrot+20,0.0f,1.0f,0.0f);
glutSolidTeapot(0.8f );
glPopMatrix( );
//bahan untuk torus
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient1);
glMaterialfv(GL_FRONT, GL_DIFFUSE, bahan_diffuse1);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular1);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess1);
//glutSolidTorus ( innerRadius , outerRadius , nsides , rings )
glPushMatrix( );
glTranslatef (0.4f, -2.2f, -6.0f);
glScalef(0.3f, 0.3f, 0.3f);
glRotatef(yrot,0.0f,1.0f,0.0f);
glutSolidTorus(0.3f, 0.5f, 200, 200);
glPopMatrix( );
//bahan untuk bola
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient3);
glMaterialfv(GL_FRONT, GL_DIFFUSE, bahan_diffuse1);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular2);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess1);
//glutSolidSphere ( radius , slices , stacks )
glPushMatrix( );
glTranslatef (-1.0f, -2.2f, -6.0f);
glScalef(0.2f, 0.2f, 0.2f);
glRotatef (90, 1, 0, 0);
glutSolidSphere(1.0f, 200, 200);
glPopMatrix( );
//bahan untuk kubus
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient3);
glMaterialfv(GL_FRONT, GL_DIFFUSE, bahan_diffuse3);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular3);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess3);
//kubusTekstur()
glPushMatrix( );
glTranslatef (1.1f, -2.2f, -6.0f);
glScalef(0.2f, 0.2f, 0.2f);
//glRotatef(180,1.0f,0.0f,0.0f);
glRotatef(yrot,0.0f,1.0f,0.0f);
//glRotatef(zrot,0.0f,0.0f,1.0f);
kubusTekstur();
glPopMatrix( );
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient0);
glMaterialfv(GL_FRONT, GL_DIFFUSE, bahan_diffuse2);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular0);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess0);
glPushMatrix();
glTranslatef (0.0f, -2.8f, -6.7f);
glScalef(1.7f, 0.2f, 1.0f);
glRotatef (43, 0, 1, 0);
kubusNormal();
glPopMatrix();
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient3);
glMaterialfv(GL_FRONT, GL_DIFFUSE,bahan_diffuse3);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular3);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess3);
glLightfv(GL_LIGHT0, GL_DIFFUSE, IntensitasCahaya0);
glLightfv(GL_LIGHT0, GL_POSITION, PosisiCahaya2);
glPushMatrix();
glTranslatef(0.0f, 0.5f, -10.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(6.0f, 4.0f, 5.0f);
kubusRuangan();
glPopMatrix();
//JAM
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient3);
glMaterialfv(GL_FRONT, GL_DIFFUSE, bahan_diffuse3);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular3);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess3);
glLightfv(GL_LIGHT0, GL_DIFFUSE, IntensitasCahaya0);
glLightfv(GL_LIGHT0, GL_POSITION, PosisiCahaya0);
glPushMatrix( );
glTranslatef (0.0f, 3.5f, -14.99f);
glScalef(0.7f, 0.7f, 0.f);
//glRotatef(180,1.0f,0.0f,0.0f);
//glRotatef(zrot,0.0f,0.0f,1.0f);
kubusJamTekstur();
glPopMatrix( );
//AC 1
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient3);
glMaterialfv(GL_FRONT, GL_DIFFUSE, bahan_diffuse3);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular3);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess3);
glPushMatrix( );
glTranslatef (-5.95f, 3.0f, -11.0f);
glScalef(0.4f, 0.7f, 2.3f);
glRotatef (0.0f, 0.0f, 1.0f, 0.0f);
kubusAcTekstur();
glPopMatrix( );
//AC 2
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient3);
glMaterialfv(GL_FRONT, GL_DIFFUSE, bahan_diffuse3);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular3);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess3);
glPushMatrix( );
glTranslatef (5.95f, 3.0f, -11.0f);
glScalef(0.4f, 0.7f, 2.3f);
glRotatef (180.0f, 0.0f, 1.0f, 0.0f);
kubusAcTekstur();
glPopMatrix( );
//Lemari
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient1);
glMaterialfv(GL_FRONT, GL_DIFFUSE,bahan_diffuse1);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular1);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess1);
glLightfv(GL_LIGHT0, GL_DIFFUSE, IntensitasCahaya0);
glLightfv(GL_LIGHT0, GL_POSITION, PosisiCahaya2);
glPushMatrix();
glTranslatef(-4.2f, -2.6f, -14.00f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-3.4f, -2.6f, -14.00f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-2.6f, -2.6f, -14.00f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-1.8f, -2.6f, -14.00f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-1.0f, -2.6f, -14.00f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-0.2f, -2.6f, -14.00f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(0.6f, -2.6f, -14.00f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(1.4f, -2.6f, -14.00f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(2.2f, -2.6f, -14.00f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(3.0f, -2.6f, -14.00f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
//atas
glPushMatrix();
glTranslatef(-4.2f, -1.0f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-3.4f, -1.0f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-2.6f, -1.0f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-1.8f, -1.0f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-1.0f, -1.0f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-0.2f, -1.0f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(0.6f, -1.0f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(1.4f, -1.0f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(2.2f, -1.0f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(3.0f, -1.0f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
//atas lv2
//atas
glPushMatrix();
glTranslatef(-4.2f, 0.6f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-3.4f, 0.6f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-2.6f, 0.6f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-1.8f, 0.6f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-1.0f, 0.6f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(-0.2f, 0.6f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(0.6f, 0.6f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(1.4f, 0.6f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(2.2f, 0.6f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
glPushMatrix();
glTranslatef(3.0f, 0.6f, -14.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(0.4f, 0.8f, 0.6f);
lemari();
glPopMatrix();
//Foto Kanan
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient3);
glMaterialfv(GL_FRONT, GL_DIFFUSE,bahan_diffuse3);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular3);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess3);
glLightfv(GL_LIGHT0, GL_DIFFUSE, IntensitasCahaya0);
glLightfv(GL_LIGHT0, GL_POSITION, PosisiCahaya1);
glPushMatrix( );
glTranslatef (5.95f, 1.0f, -11.0f);
glScalef(0.05f, 1.0f, -2.0f);
glRotatef (180.0f, 0.0f, 1.0f, 0.0f);
kubusFiguraKananTekstur();
glPopMatrix( );
//Foto Kiri
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient3);
glMaterialfv(GL_FRONT, GL_DIFFUSE,bahan_diffuse3);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular3);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess3);
glLightfv(GL_LIGHT0, GL_DIFFUSE, IntensitasCahaya0);
glLightfv(GL_LIGHT0, GL_POSITION, PosisiCahaya1);
glPushMatrix( );
glTranslatef (-5.95f, 0.8f, -11.0f);
glScalef(0.05f, 1.0f, -2.0f);
glRotatef (0.0f, 0.0f, 1.0f, 0.0f);
kubusFiguraKiriTekstur();
glPopMatrix( );
/*
//Wallpaper KANAN
glMaterialfv(GL_FRONT, GL_AMBIENT, bahan_ambient3);
glMaterialfv(GL_FRONT, GL_DIFFUSE,bahan_diffuse3);
glMaterialfv(GL_FRONT, GL_SPECULAR, bahan_specular3);
glMaterialfv(GL_FRONT, GL_SHININESS, bahan_shininess3);
glLightfv(GL_LIGHT0, GL_DIFFUSE, IntensitasCahaya0);
glLightfv(GL_LIGHT0, GL_POSITION, PosisiCahaya2);
glPushMatrix();
glTranslatef(0.0f, 0.5f, -11.0f);
glRotatef(0.0, 0.0f, 1.0f ,0.0f);
glScalef(6.0f, 4.0f, -4.0f);
FotoKelompokKanan();
glPopMatrix();
*/
xrot+=0.3f; //Mengatur arah putaran object
yrot+=0.2f; //Mengatur arah putaran object
zrot+=0.4f; //Mengatur arah putaran object
// Akhir kode yang diambil dari bukunya Suyoto
//******************************************************
SwapBuffers (hDC);
}
}
/* shutdown OpenGL */
DisableOpenGL (hWnd, hDC, hRC);
/* destroy the window explicitly */
DestroyWindow (hWnd);
return msg.wParam;
}
/********************
* Window Procedure
*
********************/
LRESULT CALLBACK
WndProc (HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
return 0;
case WM_CLOSE:
PostQuitMessage (0);
return 0;
case WM_DESTROY:
return 0;
case WM_KEYDOWN:
switch (wParam)
{
case VK_ESCAPE:
PostQuitMessage(0);
return 0;
}
return 0;
default:
return DefWindowProc (hWnd, message, wParam, lParam);
}
}
/*******************
* Enable OpenGL
*
*******************/
void
EnableOpenGL (HWND hWnd, HDC *hDC, HGLRC *hRC)
{
PIXELFORMATDESCRIPTOR pfd;
int iFormat;
/* get the device context (DC) */
*hDC = GetDC (hWnd);
/* set the pixel format for the DC */
ZeroMemory (&pfd, sizeof (pfd));
pfd.nSize = sizeof (pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
iFormat = ChoosePixelFormat (*hDC, &pfd);
SetPixelFormat (*hDC, iFormat, &pfd);
/* create and enable the render context (RC) */
*hRC = wglCreateContext( *hDC );
wglMakeCurrent( *hDC, *hRC );
}
/******************
* Disable OpenGL
*
******************/
void
DisableOpenGL (HWND hWnd, HDC hDC, HGLRC hRC)
{
wglMakeCurrent (NULL, NULL);
wglDeleteContext (hRC);
ReleaseDC (hWnd, hDC);
}
<file_sep># uas-grafika-komputer
Ujian Akhir Semester untuk mata kuliah Grafika Komputer.
|
196e0a67821f4d651c3f2e48526f82e9cc69a31c
|
[
"Markdown",
"C++"
] | 2 |
C++
|
wasoffsatyadara/uas-grafika-komputer
|
e38f57c76c7aa9fecad4669415042603641502ae
|
17ed7681e8363aa42ce3ff0658389c555a628d11
|
refs/heads/master
|
<file_sep>
import java.util.HashSet;
public class Curso {
String nombre;
String cod;
public Curso(String nombre, String cod){
}
Profesor profesor;
HashSet<Estudiante> estudiantes = new HashSet<Estudiante>();
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getCod() {
return cod;
}
public void setCod(String cod) {
this.cod = cod;
}
public Profesor getProfesor() {
return profesor;
}
public void setProfesor(Profesor profesor) {
this.profesor = profesor;
}
//********************************************************
public void setEstudiantes(Estudiante estudiante){
estudiantes.add(estudiante);
}
}
<file_sep>
import java.util.HashSet;
public class Departamento {
String nombre;
public Departamento(Universidad universidad) {
this.universidad = universidad;
}
Universidad universidad;
HashSet <Profesor> profesores = new HashSet <Profesor>();
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
// public Universidad getUniversidad() {
// return universidad;
// }
//
// public void setUniversidad(Universidad universidad) {
// this.universidad = universidad;
// }
public void setProfesor(Profesor profesor){
profesores.add(profesor);
}
}
<file_sep>
import java.util.HashSet;
public class Estudiante {
String nombre;
String cod;
public Estudiante(String nombre, String cod){
this.nombre = nombre;
this.cod = cod;
}
HashSet <Curso> cursos = new HashSet <Curso>();
Universidad universidad;
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getCod() {
return cod;
}
public void setCod(String cod) {
this.cod = cod;
}
public Universidad getUniversidad() {
return universidad;
}
public void setUniversidad(Universidad universidad) {
this.universidad = universidad;
}
//*******************************************
public void setcurso(Curso curso){
cursos.add(curso);
}
}
<file_sep>
import java.util.HashSet;
public class Profesor {
String nombre;
String cod;
Departamento departamento;
HashSet <Curso> cursos = new HashSet <Curso>();
// **** Constructor *****
public Profesor (String nombre){
this.nombre = nombre;
}
// **** Get y Set *******
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getCod() {
return cod;
}
public void setCod(String cod) {
this.cod = cod;
}
public Departamento getDepartamento() {
return departamento;
}
public void setDepartamento(Departamento departamento) {
this.departamento = departamento;
}
//***************************************************************
public void setCurso(Curso curso){
cursos.add(curso);
}
}
<file_sep>
import java.util.HashSet;
/**
*
* @author: YO
*/
public class Universidad {
String nombre;
public Universidad(String nombre){
this.nombre = nombre;
}
HashSet<Departamento> departamentos = new HashSet<Departamento>();
HashSet<Estudiante> estudiantes = new HashSet <Estudiante>();
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public void setDepartamentos(Departamento departamento){
departamentos.add(departamento);
}
public void setEstudiantes(Estudiante estudiante){
estudiantes.add(estudiante);
}
}
|
4af617dd82e9dfeb2782dd141dee0a984ffa701f
|
[
"Java"
] | 5 |
Java
|
wildelgad/Ejemplo01RelacionEntreClasesJAVA
|
7a54bb9796c958afc6e2197310ad18d7d8396924
|
cfae81b51ef01e4d46b2a272e1cbfb36c8f09ae7
|
refs/heads/master
|
<file_sep>let googleButton = document.getElementById('google-button');
let googleInput = document.getElementById('input-google')
let parsedData;
let btn;
function searchGoogleBook() {
let req = new XMLHttpRequest();
googleInput = document.getElementById('input-google').value;
// console.log('inne')
let bookUrl = 'https://www.googleapis.com/books/v1/volumes?q=' + googleInput;
console.log(bookUrl);
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
console.log('händer det nått?')
parsedData = JSON.parse(req.responseText);
console.log(parsedData);
showGoogleBooks();
}
else {
console.log('gick inte bra, körs igen kanske?')
}
}
req.open('GET', bookUrl, true);
req.send();
}
function showGoogleBooks() {
removeChildren(viewListOfBooks);
// console.log('kommer vi till Show?')
for (let i = 0; i < parsedData.items.length; i++) {
// console.log(parsedData + 'i show');
let createLi = document.createElement('li');
createLi.className = 'google-li';
createLi.innerHTML = parsedData.items[i].volumeInfo.title + ', ' + parsedData.items[i].volumeInfo.authors;
let btn = document.createElement('button');
btn.className = 'google-add-button';
btn.innerHTML = 'add';
btn.id = i;
createLi.appendChild(btn);
viewListOfBooks.appendChild(createLi);
btn.addEventListener('click', addGoogleBooks);
}
}
function addGoogleBooks() {
console.log('inne i add google book')
console.log("target id", event.target);
let book = `https://www.forverkliga.se/JavaScript/api/crud.php?key=${key}&op=insert&title=${parsedData.items[event.target.id].volumeInfo.title}&author=${parsedData.items[event.target.id].volumeInfo.authors}`;
console.log(parsedData);
let req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
bookslistparsed = JSON.parse(req.responseText);
if (bookslistparsed.status != 'error') {
console.log(bookslistparsed);
googleInput.value = '';
showElementStatus.style.color = '#A2BC55';
showElementStatus.innerHTML = 'Book Added To List'
setTimeout(function () {
showElementStatus.innerHTML = '';
showElementStatus.style.color = '#fff';
}, 3000);
getBooks();
}
else {
addGoogleBooks();
}
}
}
req.open('GET', book);
req.send();
}
googleButton.addEventListener('click', searchGoogleBook);
|
b75200a53b1eef0a02acd724355de49bdf3b85a8
|
[
"JavaScript"
] | 1 |
JavaScript
|
gorrew/books-API-project
|
74acbe96142d47e5862716a8ebcee59bdcac4f18
|
edd76c635492dbdff92f4a4be3c859e589aa2aed
|
refs/heads/master
|
<file_sep>var sys = require('sys');
sys.debug("> 1 <");
process.nextTick(function () {
sys.debug("> 2 <");
});
sys.debug("> 3 <");
<file_sep>require 'rack'
@concurrent = []
run lambda {|env|
@concurrent << '*'
puts "---> #{status}"
result = db_query()
puts "<--- #{status}"
@concurrent.pop
[200, {'Content-Type' => 'text/plain'}, [result]]
}
# Simulate a slow DB query
def db_query
sleep 1
"hello world\n"
end
def status
"#{Time.now.strftime("%H:%M:%S ")} #{@concurrent.join}"
end
<file_sep>var events = require('events'),
sys = require('sys');
function doSomethingAsynchronously() {
var promise = new events.EventEmitter;
process.nextTick(function () {
promise.emit("success", "Good night.");
});
return promise;
}
var promise = doSomethingAsynchronously();
promise.addListener("success", function (msg) {
sys.puts(msg);
});
promise.addListener("error", function (msg) {
sys.log("error: " + msg);
});
<file_sep>!SLIDE
# node.js
> evented I/O for V8 JavaScript
!SLIDE bullets incremental transition=scrollHorz
# what is node?
* Server-side JavaScript done right.
* Runs on V8
* An environment for developing high-performance web services
* Evented TCP stack
* Not a framework
!SLIDE bullets left transition=scrollHorz
# why node?
* Web applications spend most of their time doing I/O
* JavaScript is the language of the web
!SLIDE transition=scrollHorz
# V8 #
!SLIDE bullets incremental transition=scrollHorz
# V8
* Google's open source JavaScript engine.
* Developed by <NAME>.
* Fast: compiles JavaScript to machine code.
* Implements most of ECMAScript 5.
!SLIDE center transition=scrollHorz
## Lars Bak

!SLIDE transition=scrollHorz
# ECMAScript 5
!SLIDE transition=scrollHorz
### ECMAScript 5
## Safe prototype extension
@@@ javascript
Object.defineProperty(Object.prototype, "forEach", {
value: function (callback) {
var keys = Object.keys(this);
for (var i = 0, key; i < keys.length; i++) {
key = keys[i];
callback.call(this, key, this[key]);
}
}
});
!SLIDE transition=scrollHorz
### ECMAScript 5
## Access to the hidden prototypes
@@@ javascript
Object.getPrototypeOf([]) // Array
[].__proto__ // Array
[].__proto__.__proto__ // Object
!SLIDE transition=scrollHorz
### ECMAScript 5
## Basic prototypal inheritance
@@@ javascript
var o = Object.create({ foo: 42 });
o.bar = "bah";
Object.keys(o) // ["bar"]
o.foo // 42
o.__proto__ // { foo: 42 }
!SLIDE bullets transition=scrollHorz
# node.js #
!SLIDE bullets transition=scrollHorz
### node.js
## Event-driven programming
* Asynchronous I/O
* Callbacks
!SLIDE transition=scrollHorz
### node.js
## Common.js module system
@@@ javascript
var sys = require("sys");
sys.puts("hello world");
!SLIDE transition=scrollHorz
### node.js
## Common.js module system
@@@ javascript
require.paths // ["./lib", ...]
__dirname // this dirname
__filename // this filename
!SLIDE transition=scrollHorz
### node.js
## Simple HTTP server
@@@ javascript
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type':'text/plain'
});
response.end('Hello World\n');
}).listen(8000);
!SLIDE transition=scrollHorz
# Event-driven programming
!SLIDE transition=scrollHorz
@@@ javascript
setTimeout(function () {
// Do something after 1 second
}, 1000);
!SLIDE transition=scrollHorz
@@@ javascript
process.nextTick(function () {
// Do something asynchronously
});
!SLIDE transition=scrollHorz
## Async error handling
@@@ javascript
process.addListener('uncaughtException',
function (err) {
// Handle exception
});
!SLIDE transition=scrollHorz
## Async signal handling
@@@ javascript
process.addListener('SIGINT', function (err) {
// Handle Ctrl-C
});
!SLIDE transition=scrollHorz
# modules #
!SLIDE transition=scrollHorz
# file-system module #
@@@ javascript
require('fs');
!SLIDE bullets transition=scrollHorz
## modules
# fs
* one-to-one mapping with unix commands
* most functions have a synchronous version
!SLIDE transition=scrollHorz
## Asynchronous file stat
@@@ javascript
fs.stat("path/to/file", function (err, res) {
if (res) {
// Handle success
} else {
// Handle error
}
});
!SLIDE transition=scrollHorz
## Synchronous file stat
@@@ javascript
var res = fs.statSync("path/to/file");
if (res) {
// Handle success
} else {
// Handle error
}
!SLIDE transition=scrollHorz
# Example
## `cat`
!SLIDE transition=scrollHorz
# Example
## Sync vs Async
!SLIDE transition=scrollHorz
# Thanks
!SLIDE transition=scrollHorz
# `http://nodejs.org`
!SLIDE transition=scrollHorz
# @cloudhead
## <NAME>
## http://github.com/cloudhead/node-intro
!SLIDE transition=scrollHorz
# Questions?
|
77835692baeea1f8c1355a84c5ac76f17a5a209e
|
[
"JavaScript",
"Ruby",
"Markdown"
] | 4 |
JavaScript
|
adityapooniya/node-intro
|
7c96d3012d79813d4e7eb3429f507c9e3796daa0
|
1db2527534e0035c54e10ddb5941a7655b120500
|
refs/heads/master
|
<repo_name>vivi2053/JinrouGame<file_sep>/backend/user.py
class User(object):
def __init__(self, name, idx):
self.name = user_name
self.user_idx = idx
self.role = None
self.is_alive = True
def vote(self):
pass
def act_at_night(self, game, username):
self.role.act_at_night(game, username, target)
<file_sep>/backend/game.py
import random
from user import User
MORNING = 0
NIGHT = 1
class Game(object):
"""Game object
Has property and methods to control game.
"""
def __init__(self, code):
self.code = code
self.day = 0
self.turn = MORNING
self.users = {}
self.roles = []
self.num_werewolf = 0
self.visible_matrix = None
def start_game(self):
num_user = len(self.users)
self.generate_role()
self.allocate_role_to_users()
self.visible_matrix = [[int(i==j) for i in range(num_user)] for j in range(num_user)]
def _exchange_role(self, src_user, tgt_user):
tmp = self.users[src_user].role
self.users[src_user].role = self.users[tgt_user].role
self.users[tgt_user].role = tmp
def _visualize_user(self, src_user, tgt_user):
src_idx, tgt_idx = self.users[src_user].user_idx, self.users[tgt_user].user_idx
self.visible_matrix[src_idx][tgt_idx] = True
def add_user(self, username):
"""Add user to users property
Args:
username (str): username
"""
user = User(username, len(self.users))
self.users[username] = user
def generate_role(self, num_members):
"""Generate roles
Generate roles according to the number of users
Args:
num_members: number of users
"""
pass
def allocate_role_to_users(self):
"""Allocate roles to users
Allocate roles to users. This method has to be done after add_user and generate_role.
"""
shuffled_roles = random.sample(self.roles, len(self.roles))
for u, r in zip(self.users.values(), self.roles):
u.role = r
self.num_werewolf += int(not r.is_human)
def check_finish(self):
"""Check is_finish
Check the game is finished. This method has to be called in the morning and after voting.
"""
num_alive_human = 0
for u in self.users.values():
num_alive_human += int(u.is_alive and u.role.is_human)
return num_alive_human <= self.num_werewolf
def kill_selected_user(self, username):
"""Kill selected user
Kill selected user. User selected must be alive. If the user is already killed, raise assertion error.
"""
assert username in self.users, "Not found user %s" % username
assert self.users[username].is_alive, "User %s is already killed." % username
self.users[username].is_alive = False
def act_at_night(self, username, target):
self.users[username].act_at_night(self, target)
<file_sep>/backend/api.py
import string
import random
from pathlib import Path
from flask import Flask, render_template, request, redirect, url_for, session
code_candidate = list(string.ascii_letters) + list(string.digits)
static_folder = Path.cwd()
app = Flask(__name__, template_folder=str(static_folder / "template"), static_folder=str(static_folder / "static"))
app.secret_key = 'A0Zr9foijaoe090'
@app.route("/", methods=['GET', "POST"])
def top_page():
if request.method == "POST":
select_time = request.form.get("select_time")
select_member = request.form.get("select_member")
session['room'] = ''.join(random.choices(code_candidate, k=4))
return redirect(url_for("admin_wait", room_id=session["room"]))
return render_template('home.html')
@app.route("/<room_id>/game-start")
def admin_wait(room_id):
return render_template("admin_wait.html")
@app.route("/<room_id>", methods=["GET"])
def main(room_id):
if "username" in session:
print("Hello " + str(session['username']))
return render_template('home.html')
return redirect(url_for('login', room_id=room_id))
@app.route('/<room_id>/login', methods=['POST'])
def login(room_id):
session['username'] = request.form['username']
return redirect(url_for('main', room_id=room_id))
@app.route('/<room_id>/vote', methods=['POST'])
def vote(room_id):
"""Recieve voting result
Args:
result: {'from': 'username1', 'to': 'username2'}
"""
print(request.json['from'], request.json['to'])
return redirect(url_for('main', room_id=room_id))
@app.route('/<room_id>/night_action', methods=['POST'])
def night_action(room_id):
"""Recieve night action
Args:
result: {'from': 'username1', 'to': 'username2'}
"""
return redirect(url_for('main', room_id=room_id))
@app.route('/<room_id>/login', methods=['GET'])
def login_view(room_id):
return """
<form action="" method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
"""
if __name__ == "__main__":
print(str((static_folder / "template").resolve()))
print(str(Path.cwd()))
app.run(host="0.0.0.0", port="5000")
<file_sep>/Dockerfile
FROM python:3.6
ADD . /code
WORKDIR /code
RUN pip install --upgrade pip
RUN pip install flask
CMD ["python", "backend/api.py"]
<file_sep>/static/js/admin_wait.js
// var this.timer = setInterval(function foo(){};, 10000);
var timer = [];
function changeColor(){
// if (type)
timer.push(setInterval(randColor, 100));
}
function randColor(){
code = '#' + addColorCode('');
// console.log(code);
document.body.style.background = code;
}
function addColorCode(cur_code){
var num = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'];
one_code = num[Math.floor(Math.random()*16)];
cur_code+=one_code;
if (cur_code.length==6){
return cur_code;
}
else{
return addColorCode(cur_code);
}
}
let chg_btn = document.getElementById("change");
chg_btn.onclick = changeColor;
function stopChange(){
for (var i = 0; i < timer.length; i++) {
clearInterval(timer[i]);
}
document.body.style.background = '#99cc00';
}
let stop_btn = document.getElementById("stop");
stop_btn.onclick = stopChange;
counter=0;
setInterval(incPeople, 2000);
function incPeople(){
// console.log("running");
counter++;
partLabel = document.getElementById("joined");
partLabel.innerHTML = counter;
}
<file_sep>/README.md
# JinrouGame
## Docker
### Build docker
```
docker-compose build
docker-compose up
```
### Access web application
Please access `localhost:5000`
<file_sep>/backend/role.py
class Role(object):
def __init__(self):
self.is_human = True
def act_at_night(self, game, username):
pass
class Citizen(Role):
def __init__(self):
super(Citizen, self).__init__()
self.name = "citizen"
class Prophet(Role):
def __init__(self):
super(Prophet, self).__init__()
def act_at_night(self, game, username, target):
game._exchange_role(username, target)
class Werewolf(Role):
def __init(self):
super(Werewolf, self).__init__()
|
9a6fa1ee63f1c40f371ffe695c2df2f26b2acc05
|
[
"JavaScript",
"Python",
"Dockerfile",
"Markdown"
] | 7 |
Python
|
vivi2053/JinrouGame
|
40a33606ca34ec61f2c16188e7524ee13e5e7f3f
|
fbb20909895be2a94c56427716231ed6e2e89a46
|
refs/heads/master
|
<repo_name>violet-anima/github-avatar-downloader<file_sep>/download_avatars.js
var request = require('request');
var GITHUB_USER = "violet-anima";
var GITHUB_TOKEN = "4b487cdc5c9222b32abecbe0e6a395f5f859de13";
var repoOwner = process.argv[2];
var repoName = process.argv[3];
console.log('Welcome to the GitHub Avatar Downloader!!');
if (!repoOwner || !repoName) {
throw 'Please provide a repo owner and repo name. Eg: e.g "node download_avatar.js violet-anima finstagram"';
} else {
// Github API endpoint
function getRepoContributors(repoOwner, repoName, cb) {
var requestURL = 'https://'+ GITHUB_USER + ':' + GITHUB_TOKEN +
'@api.github.com/repos/' + repoOwner + '/' + repoName + '/contributors';
// HTTP request to get contributors and User-Agent forbidden request bypass
request.get({
url: requestURL,
headers: {
"User-Agent": "GitHub Avatar Downloader - Student Project"
}
}, cb)
}
function printResponse(err, res, body) {
if(err) {
console.log("Error has been made!", error);
}
var parsedResults = JSON.parse(body);
// targeting avatar urls to save to avatar folder
for (var arr in parsedResults) {
var avatarUrl = parsedResults[arr]["avatar_url"];
downloadImageByURL(avatarUrl, `avatar/${arr}.jpg`);
}
}
var fs = require("fs");
function downloadImageByURL(url, filePath) {
// HTTP request to get images
request.get(url)
.on("error", function(err) {
console.log("Error has been made!");
throw err;
})
.on("response", function (response) {
console.log("Image(s) downloading.");
})
.on("end", function (){
console.log("Download has ended.")
})
.pipe(fs.createWriteStream(filePath));
}
getRepoContributors(repoOwner, repoName, printResponse);
}
|
d00327c696cadd5836fc2d1d04bc851a5efbe508
|
[
"JavaScript"
] | 1 |
JavaScript
|
violet-anima/github-avatar-downloader
|
702b1844b6ecdf634976b09c3cb56ba3a06188ac
|
dbb96fa447a509484b05bfd0ff1904a697a31874
|
refs/heads/master
|
<file_sep>using DB_Helper;
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 insaSystem
{
public partial class Insa04AwardInfo : Form, IForm
{
DBOracle_Helper oHelper;
public InsaManagement InsaManagement { get; set; }
string BtnCheck = "";
public Insa04AwardInfo()
{
InitializeComponent();
}
public void DataGridView_Double_clicked()
{
}
private void TextboxClear()
{
award_organ.Text = "";
award_pos.Text = "";
award_dept.Text = "";
award_inout.Text = "";
award_no.Text = "";
award_type.Text = "";
award_content.Text = "";
award_kind.Text = "";
award_date.Format = DateTimePickerFormat.Custom;
}
public void Btn_insert_clicked()
{
if (bas_empno_award.Text == "")
{
MessageBox.Show("입력할 사원정보를 선택하세요");
}
else
{
TextboxClear();
MessageBox.Show("상벌사항 입력을 시작합니다.");
InsaManagement.btncheck.Text = "A_I";
InsaManagement.Mode = "BlockIUD";
}
}
private void CallingEmployeeAwdInfo()
{
if (bas_empno_award.Text == "")
{
MessageBox.Show("조회할 사원정보를 선택하세요");
return;
}
InsaManagement.Mode = "BlockIUD";
string awd_sql = "";//sql문 작성해야함
DataTable AwdInfo = oHelper.GetData(awd_sql);
foreach (DataRow Row in AwdInfo.Rows)
{
if (Row == null)
{
MessageBox.Show("등록되어있지 않는 상벌정보입니다.");
return;
}
//불러들일 정보
}
}
public void Btn_update_clicked()
{
CallingEmployeeAwdInfo();
BtnCheck = "A_U";
}
public void Btn_delete_clicked()
{
CallingEmployeeAwdInfo();
BtnCheck = "A_D";
//button1.Text = "Form2(삭제버튼)";
//this.textBox1.Text = MainForm.textBox1.Text;
}
public void Btn_check_clicked()
{
//button1.Text = "Form2(삭제버튼)";
//this.textBox1.Text = MainForm.textBox1.Text;
}
public void Btn_cancel_clicked()
{
if (BtnCheck == "A_I")
{
if (MessageBox.Show("취소하시면 입력하신 정보가 모두 저장되지 않습니다. 취소하시겠습니까?", "취소", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("취소되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
//bas_empno.Focus();
InsaManagement.Mode = "BlockIUD";
return;
}
InsaManagement.Mode = "BlockCC";
}
if (BtnCheck == "A_U")
{
if (MessageBox.Show("수정을 취소합니다.", "취소", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("취소되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
//bas_empno.Focus();
InsaManagement.Mode = "BlockIUD";
return;
}
InsaManagement.Mode = "BlockCC";
}
if (BtnCheck == "A_D")
{
if (MessageBox.Show("데이터 삭제가 취소되었습니다 . 취소하시겠습니까?", "취소", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("취소되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
//bas_empno.Focus();
InsaManagement.Mode = "BlockIUD";
return;
}
InsaManagement.Mode = "BlockCC";
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Oracle.ManagedDataAccess.Client;
using System.Data.SqlClient;
namespace insaSystem
{
public partial class SearchDeptForm : Form
{
OracleConnection pgOraConn;
OracleCommand pgOraCmd;
OracleDataReader rd;
SqlDataAdapter adapter = null;
SqlConnection conn = null;
String dbIp = "192.168.3.11";
String dbName = "ORA7";
String dbId = "EDU";
String dbPw = "<PASSWORD>";
Insa01BaseInfo frm1;
#region 나가기, 최대화, 리스토어, 최소화 Btn Control
//-----------나가기----------
private void exitbtn_Click(object sender, EventArgs e)
{
this.Close();
}
//-----------최소화----------
private void minimizarbtn_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
#endregion
public SearchDeptForm(Insa01BaseInfo frm2)
{
InitializeComponent();
frm1 = frm2;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
dataGridView1.RowHeadersVisible = false;
pgOraConn = new OracleConnection($"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST={dbIp})(PORT=1522)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME={dbName})));User ID={dbId};Password={<PASSWORD>};Connection Timeout=30;");
pgOraConn.Open();
}
private void deptSearch_Click(object sender, EventArgs e)
{
var sql = "select dept_code, dept_name from thrm_dept_psy where dept_edate is null and dept_name like '" + idept.Text + "%'";
//MessageBox.Show(sql);
OracleCommand cmd = new OracleCommand();
cmd.Connection = pgOraConn;
cmd.CommandText = sql;
OracleDataReader rd = cmd.ExecuteReader();
int cnt = 0;
while (rd.Read())
{
//MessageBox.Show(rd["bas_empno"].ToString());
dataGridView1.Rows.Add(rd["dept_code"].ToString(), rd["dept_name"].ToString());
cnt++;
}
}
private void Form2_Load(object sender, EventArgs e)
{
this.FormBorderStyle = FormBorderStyle.FixedSingle;
dataGridView1.Columns.Add("dept_code", "부서코드");
dataGridView1.Columns.Add("dept_name", "부서명");
}
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var tmp1 = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
var tmp2 = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
frm1.jinguy(tmp1, tmp2);
Close();
}
}
}
<file_sep>using DB_Helper;
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 insaSystem
{
public partial class Insa03EduInfo : Form, IForm
{
DBOracle_Helper oHelper;
public InsaManagement InsaManagement { get; set; }
string BtnCheck = "";
public Insa03EduInfo()
{
InitializeComponent();
}
public void DataGridView_Double_clicked()
{
}
public void Btn_insert_clicked()
{
if (bas_empno_edu.Text == "")
{
MessageBox.Show("입력할 사원정보를 선택하세요");
}
else
{
TextboxClear();
MessageBox.Show("학력사항 입력을 시작합니다.");
InsaManagement.btncheck.Text = "E_I";
InsaManagement.Mode = "BlockIUD";
}
}
private void CallingEmployeeEduInfo()
{
if(bas_empno_edu.Text == "")
{
MessageBox.Show("조회할 사원정보를 선택하세요");
return;
}
InsaManagement.Mode = "BlockIUD";
string edu_sql = "";//sql문 작성해야함
DataTable EduInfo = oHelper.GetData(edu_sql);
foreach(DataRow Row in EduInfo.Rows)
{
if(Row == null)
{
MessageBox.Show("등록되어있지 않는 가족정보입니다.");
return;
}
//불러들일 정보
}
}
public void Btn_update_clicked()
{
CallingEmployeeEduInfo();
BtnCheck = "E_U";
}
public void Btn_delete_clicked()
{
CallingEmployeeEduInfo();
BtnCheck = "E_U";
}
public void Btn_check_clicked()
{
}
public void Btn_cancel_clicked()
{
if (BtnCheck == "E_I")
{
if (MessageBox.Show("취소하시면 입력하신 정보가 모두 저장되지 않습니다. 취소하시겠습니까?", "취소", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("취소되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
//bas_empno.Focus();
InsaManagement.Mode = "BlockIUD";
return;
}
InsaManagement.Mode = "BlockCC";
}
if (BtnCheck == "E_U")
{
if (MessageBox.Show("수정을 취소합니다.", "취소", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("취소되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
//bas_empno.Focus();
InsaManagement.Mode = "BlockIUD";
return;
}
InsaManagement.Mode = "BlockCC";
}
if (BtnCheck == "E_D")
{
if (MessageBox.Show("데이터 삭제가 취소되었습니다 . 취소하시겠습니까?", "취소", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("취소되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
//bas_empno.Focus();
InsaManagement.Mode = "BlockIUD";
return;
}
InsaManagement.Mode = "BlockCC";
}
}
private void TextboxClear()
{
edu_loe.Text = "";
edu_schnm.Text = "";
edu_dept.Text = "";
edu_grade.Text = "";
edu_degree.Text = "";
edu_last.Text = "";
edu_gra.Text = "";
edu_entdate.Format = DateTimePickerFormat.Custom;
edu_gradate.Format = DateTimePickerFormat.Custom;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DB_Helper;
using Oracle.ManagedDataAccess.Client;
namespace insaSystem
{
//시스템명 : 인사관리시스템
//단위업무명 : 인사기록관리
//프로그래머 : 박서윤
//public delegate void EventHandler(string userName); //델리게이트 선언
public partial class InsaLogin : Form
{
//db호출
DBOracle_Helper oHelper;
//public event EventHandler loginEventHandler;
public InsaLogin()
{
InitializeComponent();
}
private void InsaLogin_Load(object sender, EventArgs e)
{
//db호출
oHelper = new DBOracle_Helper();
}
#region Window 드래그 Control (마우스 핸들링)
//-----------필수 코드--------------
[DllImport("user32.DLL", EntryPoint = "ReleaseCapture")]
private extern static void ReleaseCapture();
[DllImport("user32.DLL", EntryPoint = "SendMessage")]
private extern static void SendMessage(System.IntPtr hwnd, int wmsg, int wparam, int lparam);
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, 0x112, 0xf012, 0);
}
private void panel2_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, 0x112, 0xf012, 0);
}
#endregion
#region 나가기, 최대화, 리스토어, 최소화 Btn Control
//-----------나가기----------
private void exitbtn_Click(object sender, EventArgs e)
{
this.Close();
}
//-----------최소화----------
//private void minimizarbtn_Click(object sender, EventArgs e)
//{
// this.WindowState = FormWindowState.Minimized;
//}
#endregion
#region Enter입력 이벤트
private void password_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
loginBtn_Click(sender, e);
}
}
private void username_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
loginBtn_Click(sender, e);
}
}
#endregion
#region ID, PW : Placeholder 초기화
private void password_Click(object sender, EventArgs e)
{
password.UseSystemPasswordChar = true;
password.Text = "";
}
private void username_Click(object sender, EventArgs e)
{
username.Text = "";
}
#endregion
#region Login 기능
private void loginBtn_Click(object sender, EventArgs e)
{
LoginHandler loginHandler = new LoginHandler();
if (ControlCheck())
{
if (loginHandler.LoginCheck(username.Text, password.Text))
{
string userName = username.Text;
//loginEventHandler(userName);
DialogResult = DialogResult.OK;
}
else
{
MessageBox.Show("로그인 정보가 정확하지 않습니다.", "알림", MessageBoxButtons.OK, MessageBoxIcon.Warning);
username.Clear();
password.Clear();
username.Focus();
}
}
}
//입력이 없을시
private bool ControlCheck()
{
if (String.IsNullOrEmpty(username.Text))
{
MessageBox.Show("아이디와 비밀번호를 입력해주세요", "알림", MessageBoxButtons.OK, MessageBoxIcon.Warning);
username.Focus();
return false;
}
else if (String.IsNullOrEmpty(password.Text))
{
MessageBox.Show("비밀번호를 입력해주세요", "알림", MessageBoxButtons.OK, MessageBoxIcon.Warning);
password.Focus();
return false;
}
return true;
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using insaSystem;
namespace insaSystem
{
static class Program
{
public static string Info { get; }
/// <summary>
/// 해당 애플리케이션의 주 진입점입니다.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new InsaManagement(0));
}
}
}<file_sep>using DB_Helper;
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 insaSystem
{
public partial class Insa06LicInfo : Form, IForm
{
DBOracle_Helper oHelper;
public InsaManagement InsaManagement { get; set; }
string BtnCheck = "";
public Insa06LicInfo()
{
InitializeComponent();
}
public void DataGridView_Double_clicked()
{
}
private void TextboxClear()
{
lic_code.Text = "";
lic_grade.Text = "";
lic_acqdate.Format = DateTimePickerFormat.Custom;
lic_organ.Text = "";
}
public void Btn_insert_clicked()
{
if (bas_empno_lic.Text == "")
{
MessageBox.Show("입력할 사원정보를 선택하세요");
}
else
{
TextboxClear();
MessageBox.Show("자격면허 입력을 시작합니다.");
InsaManagement.btncheck.Text = "L_I";
InsaManagement.Mode = "BlockIUD";
}
}
private void CallingEmployeeLicInfo()
{
if (bas_empno_lic.Text == "")
{
MessageBox.Show("조회할 사원정보를 선택하세요");
return;
}
InsaManagement.Mode = "BlockIUD";
string lic_sql = "";//sql문 작성해야함
DataTable LicInfo = oHelper.GetData(lic_sql);
foreach (DataRow Row in LicInfo.Rows)
{
if (Row == null)
{
MessageBox.Show("등록되어있지 않는 경력정보입니다.");
return;
}
//불러들일 정보
}
}
public void Btn_update_clicked()
{
CallingEmployeeLicInfo();
BtnCheck = "L_U";
}
public void Btn_delete_clicked()
{
CallingEmployeeLicInfo();
BtnCheck = "L_D";
//button1.Text = "Form2(삭제버튼)";
//this.textBox1.Text = MainForm.textBox1.Text;
}
public void Btn_check_clicked()
{
//button1.Text = "Form2(삭제버튼)";
//this.textBox1.Text = MainForm.textBox1.Text;
}
public void Btn_cancel_clicked()
{
if (BtnCheck == "L_I")
{
if (MessageBox.Show("취소하시면 입력하신 정보가 모두 저장되지 않습니다. 취소하시겠습니까?", "취소", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("취소되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
//bas_empno.Focus();
InsaManagement.Mode = "BlockIUD";
return;
}
InsaManagement.Mode = "BlockCC";
}
if (BtnCheck == "L_U")
{
if (MessageBox.Show("수정을 취소합니다.", "취소", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("취소되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
//bas_empno.Focus();
InsaManagement.Mode = "BlockIUD";
return;
}
InsaManagement.Mode = "BlockCC";
}
if (BtnCheck == "L_D")
{
if (MessageBox.Show("데이터 삭제가 취소되었습니다 . 취소하시겠습니까?", "취소", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("취소되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
//bas_empno.Focus();
InsaManagement.Mode = "BlockIUD";
return;
}
InsaManagement.Mode = "BlockCC";
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace insaSystem
{
public interface IForm
{
InsaManagement InsaManagement { get; set; }
//void Btn_query_clicked();
void DataGridView_Double_clicked();
void Btn_insert_clicked();
void Btn_update_clicked();
void Btn_delete_clicked();
void Btn_check_clicked();
void Btn_cancel_clicked();
}
}
<file_sep>using DB_Helper;
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 insaSystem
{
public partial class Insa02FamInfo : Form, IForm
{
DBOracle_Helper oHelper;
public InsaManagement InsaManagement { get; set; }
string BtnCheck = "";
public Insa02FamInfo()
{
InitializeComponent();
}
public void DataGridView_Double_clicked()
{
}
public void Btn_insert_clicked()
{
if (bas_empno_fam.Text == "")
{
MessageBox.Show("입력할 사원정보를 선택하세요");
return;
}
else
{
fam_rel.Focus();
MessageBox.Show("가족정보 입력을 시작합니다.");
fam_rel.Text = "";
fam_name.Text = "";
fam_bth.Text = "";
fam_ltg.Text = "";
fam_rel.Enabled = true;
fam_name.Enabled = true;
InsaManagement.btncheck.Text = "F_I";
InsaManagement.Mode = "BlockIUD";
}
}
private void CallingEmployeeFamInfo()
{
if (bas_empno_fam.Text == "")
{
MessageBox.Show("조회할 사원정보를 선택하세요");
//enablefalse 들어가야함
return;
}
InsaManagement.Mode = "BlockIUD";
string fam_sql = "select fam_empno, fam_codnms as fam_rel, fam_name, fam_bth, fam_ltg" +
" from thrm_bas_psy, " +
" thrm_fam_psy," +
" (select cd_grpcd, cd_code, cd_codnms as fam_codnms " +
" from tieas_cd_psy where cd_grpcd = 'REL') " +
" where bas_empno = fam_empno(+) and fam_rel = cd_code" +
" and bas_empno = '" + bas_empno_fam.Text + "'";
DataTable FamInfo = oHelper.GetData(fam_sql);
foreach (DataRow Row in FamInfo.Rows)
{
if (Row == null)
{
MessageBox.Show("등록되어있지 않는 가족정보입니다.");
return;
}
bas_empno_fam.Text = Row["fam_empno"] as string;
fam_rel_code.Text = Row["fam_rel"] as string;
fam_name.Text = Row["fam_name"] as string;
fam_bth.Text = Row["fam_bth"] as string;
fam_ltg.Text = Row["fam_ltg"] as string;
}
}
public void Btn_update_clicked()
{
CallingEmployeeFamInfo();
BtnCheck = "F_U";
}
public void Btn_delete_clicked()
{
CallingEmployeeFamInfo();
BtnCheck = "F_D";
}
public void Btn_check_clicked()
{
if (BtnCheck == "F_I")
{
int num = 0;
if (MessageBox.Show("입력된 가족사항을 저장하시겠습니까?", "가족사항", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//informationChecking();
if (num == 1)
{
return;
}
string SqlInsert = $"insert into THRM_FAM_PSY(fam_empno, fam_rel, fam_name, fam_bth, fam_ltg) values('" + bas_empno_fam.Text + "','" + fam_rel_code.Text + "','" + fam_name.Text + "', '" + fam_bth.Text + "','" + fam_ltg.Text + "')";
oHelper.SetData(SqlInsert);
InsaManagement.Mode = "BlockCC";
}
else
{
fam_bth.Focus();
//_falseTrue_Checking();
//checkCancelClose();
InsaManagement.Mode = "BlockIUD";
}
if (BtnCheck == "F_U")
{
if (MessageBox.Show("수정하시겠습니까?", "수정", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string SqlUpdate = $"update THRM_FAM_PSY set fam_bth='" + fam_bth.Text + "',fam_ltg='" + fam_ltg.Text + "' where fam_empno ='" + bas_empno_fam.Text + "' and fam_name= '" + fam_name.Text + "'";
//MessageBox.Show(sql1);
oHelper.SetData(SqlUpdate);
MessageBox.Show("수정되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
MessageBox.Show("수정이 취소되었습니다.");
InsaManagement.Mode = "BlockIUD";
return;
}
}
if (BtnCheck == "F_D")
{
if (MessageBox.Show("삭제하시겠습니까?", "삭제", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string SqlDelete = $"delete from THRM_BAS_PSY where fam_empno='" + bas_empno_fam.Text + "'";
oHelper.SetData(SqlDelete);
TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("삭제되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
MessageBox.Show("삭제가 취소되었습니다.");
fam_bth.Focus();
InsaManagement.Mode = "BlockIUD";
}
}
}
}
public void Btn_cancel_clicked()
{
if (InsaManagement.btncheck.Text == "F_I")
{
if (MessageBox.Show("취소하시면 입력하신 정보가 모두 저장되지 않습니다. 취소하시겠습니까?", "취소", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("취소되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
//bas_empno.Focus();
InsaManagement.Mode = "BlockIUD";
return;
}
InsaManagement.Mode = "BlockCC";
}
if (InsaManagement.btncheck.Text == "F_U")
{
if (MessageBox.Show("수정을 취소합니다.", "취소", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("취소되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
//bas_empno.Focus();
InsaManagement.Mode = "BlockIUD";
return;
}
InsaManagement.Mode = "BlockCC";
}
if (InsaManagement.btncheck.Text == "F_D")
{
if (MessageBox.Show("데이터 삭제가 취소되었습니다 . 취소하시겠습니까?", "취소", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
TextboxClear();
//InsabaseEnableFalse();
MessageBox.Show("취소되었습니다.");
InsaManagement.Mode = "BlockCC";
}
else
{
//bas_empno.Focus();
InsaManagement.Mode = "BlockIUD";
return;
}
InsaManagement.Mode = "BlockCC";
}
}
private void TextboxClear()
{
fam_rel.Text = "";
fam_rel_code.Text = "";
fam_name.Text = "";
fam_bth.Text = "";
fam_ltg.Text = "";
}
}
}
<file_sep>using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
using Oracle.ManagedDataAccess.Client;
using System.Runtime.InteropServices;
using DB_Helper;
using System.Data;
using System.Diagnostics;
namespace insaSystem
{
//시스템명 : 인사관리시스템
//단위업무명 : 인사기록관리
//프로그래머 : 박서윤
public partial class InsaManagement : Form
{
static public string Mode { get; set; }
public string getData;
//public Insa01BaseInfo Insa01BaseInfo { get; set; }
//public Insa02FamInfo Insa02FamInfo { get; set; }
//public Insa03EduInfo Insa03EduInfo { get; set; }
//public Insa04AwardInfo Insa04AwardInfo { get; set; }
//public Insa05CarInfo Insa05CarInfo { get; set; }
//public Insa06LicInfo Insa06LicInfo { get; set; }
//public Insa07ForlInfo Insa07ForlInfo { get; set; }
DBOracle_Helper oHelper;
int tabPageNum;
public InsaManagement(int tp)
{
InitializeComponent();
tabPageNum = tp;
}
public void frm_load(Form form)
{
form.TopLevel = false;
tabControl1.TabPages.Add(form.Text);
tabControl1.TabPages[tabControl1.TabPages.Count - 1].Controls.Add(form);
form.WindowState = System.Windows.Forms.FormWindowState.Maximized;
form.Show();
}
private void InsaMangement_Load(object sender, EventArgs e)
{
#region 프로그램 시작 시 확인, 취소버튼 Block
checkbtn.Enabled = false;
cancelbtn.Enabled = false;
checkbtn.BackColor = Color.LightGray;
cancelbtn.BackColor = Color.LightGray;
tabControl1.SelectedIndex = tabPageNum;
#endregion
#region 프로그램 시작 시 인사시스템 데이터 그리드뷰 기본 생성
sabunDataGridView.BackgroundColor = Color.White;
sabunDataGridView.Columns.Add("bas_empno", "사번");
sabunDataGridView.Columns.Add("bas_name", "성명");
sabunDataGridView.Columns.Add("cd_codnms", "직급");
sabunDataGridView.Columns.Add("dept_name", "부서");
#endregion
#region InsaManageMentContent Load
frm_load(new Insa01BaseInfo());
frm_load(new Insa02FamInfo());
frm_load(new Insa03EduInfo());
frm_load(new Insa04AwardInfo());
frm_load(new Insa05CarInfo());
frm_load(new Insa06LicInfo());
frm_load(new Insa07ForlInfo());
#endregion
}
//수정 및 connection 필요함
#region 사번테이블 EVENT CellMouseDoubleClick -- 통합
//인사기본 데이터 테이블 정보 더블클릭시 데이터 가져가기
private void sabunDataGridView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
Insa01BaseInfo Insa01BaseInfo = new Insa01BaseInfo();
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.sabunDataGridView.Rows[e.RowIndex];
getData = row.Cells["bas_empno"].Value.ToString();
IForm form = (IForm)tabControl1.SelectedTab.Controls[0];
form.InsaManagement = this;
form.DataGridView_Double_clicked();
}
////가족사항
//if (tabControl1.SelectedTab.TabIndex == 1)
//{
// DataGridViewRow row = this.sabunDataGridView.Rows[e.RowIndex];
// bas_empno_fam.Text = row.Cells["bas_empno"].Value.ToString();
// bas_name_fam.Text = row.Cells["bas_name"].Value.ToString();
// bas_pos_fam.Text = row.Cells["cd_codnms"].Value.ToString(); ;
// bas_dept_fam.Text = row.Cells["dept_name"].Value.ToString();
// famDataGridView.Rows.Clear();
// string searchsql = " select fam_codnms as fam_rel, fam_name, fam_bth, fam_ltg" +
// " from thrm_bas_psy, " +
// " thrm_fam_psy," +
// " (select cd_grpcd, cd_code, cd_codnms as fam_codnms " +
// " from tieas_cd_psy where cd_grpcd = 'REL') " +
// " where bas_empno = fam_empno(+) and fam_rel = cd_code" +
// " and bas_empno = '" + bas_empno_fam.Text + "'";
// try
// {
// OracleCommand cmd = new OracleCommand();
// cmd.Connection = pgOraConn;
// cmd.CommandText = searchsql;
// OracleDataReader rd2 = cmd.ExecuteReader();
// int cnt = 0;
// while (rd2.Read())
// {
// famDataGridView.Rows.Add(rd2["fam_rel"].ToString(), rd2["fam_name"].ToString(), rd2["fam_bth"].ToString(), rd2["fam_ltg"].ToString());
// cnt++;
// }
// }
// catch (Exception ex)
// {
// MessageBox.Show(ex.ToString());
// }
//}
////학력사항
//else if (tabControl1.SelectedTab.TabIndex == 2)
//{
// DataGridViewRow row = this.sabunDataGridView.Rows[e.RowIndex];
// bas_empno_edu.Text = row.Cells["bas_empno"].Value.ToString();
// bas_name_edu.Text = row.Cells["bas_name"].Value.ToString();
// bas_pos_edu.Text = row.Cells["cd_codnms"].Value.ToString(); ;
// bas_dept_edu.Text = row.Cells["dept_name"].Value.ToString();
// DateTimePicker dtp = new DateTimePicker();//해결필요함
// eduDataGridView.Rows.Clear();
// string searchsql = " select edu_empno, edu_loe, edu_endate, edu_gradate, edu_schnm, edu_dept, edu_degree, edu_grade, edu_gra, edu_last" +
// " from thrm_bas_psy," +
// " thrm_edu_psy" +
// " where bas_empno = edu_empno(+) " +
// " and bas_empno = '" + bas_empno_edu.Text + "'";
// MessageBox.Show("123123");
// try
// {
// OracleCommand cmd = new OracleCommand();
// cmd.Connection = pgOraConn;
// cmd.CommandText = searchsql;
// OracleDataReader rd3 = cmd.ExecuteReader();
// int cnt = 0;
// while (rd3.Read())
// {
// eduDataGridView.Rows.Add(rd3["edu_loe"].ToString(), rd3["edu_endate"].ToString(), rd3["edu_gradate"].ToString(), rd3["edu_schrm"].ToString(), rd3["edu_dept"].ToString(), rd3["edu_degree"].ToString(), rd3["edu_grade"].ToString(), rd3["edu_gra"].ToString());
// cnt++;
// }
// }
// catch (Exception ex)
// {
// MessageBox.Show(ex.ToString());
// }
//}
////상벌이력
//else if (tabControl1.SelectedTab.TabIndex == 3)
//{
//}
////경력사항
//else if (tabControl1.SelectedTab.TabIndex == 4)
//{
//}
////자격면허
//else if (tabControl1.SelectedTab.TabIndex == 5)
//{
//}
////외국어
//else if (tabControl1.SelectedTab.TabIndex == 6)
//{
//}
}
#endregion
//시스템 state control
#region 나가기, 최대화, 리스토어, 최소화 Btn Control
//-----------나가기----------
private void exitbtn_Click(object sender, EventArgs e)
{
this.Close();
}
//-----------최대화----------
private void maximizarbtn_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
restorebtn.Visible = true;
maximizarbtn.Visible = false;
}
//-----------리스토어----------
private void restorebtn_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
restorebtn.Visible = false;
maximizarbtn.Visible = true;
}
//-----------최소화----------
private void minimizarbtn_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
#endregion
#region Window 드래그 Control (마우스 핸들링)
//-----------필수 코드--------------
[DllImport("user32.DLL", EntryPoint = "ReleaseCapture")]
private extern static void ReleaseCapture();
[DllImport("user32.DLL", EntryPoint = "SendMessage")]
private extern static void SendMessage(System.IntPtr hwnd, int wmsg, int wparam, int lparam);
private void panel2_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, 0x112, 0xf012, 0);
}
#endregion
//사번검색
#region 사번검색(고정) -- 기본화면
//인사정보검색
private void insaSearch_Click(object sender, EventArgs e)
{
try
{
oHelper = new DBOracle_Helper();
sabunDataGridView.Rows.Clear();
string searchsql =
"select bas_empno, bas_name, bas_pos, cd_codnms, bas_dept, dept_name" +
" from thrm_bas_psy," +
" (select cd_grpcd, cd_code, cd_codnms from tieas_cd_psy where cd_grpcd = 'POS')," +
" thrm_dept_psy" +
" where bas_pos = cd_code" +
" and bas_dept = dept_code" +
" and bas_empno like '" + qry_empno.Text + "%'" +
" and bas_name like '" + qry_name.Text + "%'" +
" and dept_name like '" + qry_dept.Text + "%'" +
" order by bas_empno asc";
DataTable sabunSearch = oHelper.GetData(searchsql);
int cnt = 0;
foreach (DataRow item in sabunSearch.Rows)
{
sabunDataGridView.Rows.Add(item["BAS_EMPNO"].ToString(), item["BAS_NAME"].ToString(),
item["cd_codnms"].ToString(), item["dept_name"].ToString());
cnt++;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
#endregion
private void insertbtn_Click(object sender, EventArgs e)
{
IForm form = (IForm)tabControl1.SelectedTab.Controls[0];
form.InsaManagement = this;
form.Btn_insert_clicked();
BtnCotrol();
}
private void updatebtn_Click(object sender, EventArgs e)
{
IForm form = (IForm)tabControl1.SelectedTab.Controls[0];
form.InsaManagement = this;
form.Btn_update_clicked();
BtnCotrol();
}
private void deletebtn_Click(object sender, EventArgs e)
{
IForm form = (IForm)tabControl1.SelectedTab.Controls[0];
form.InsaManagement = this;
form.Btn_delete_clicked();
BtnCotrol();
}
private void checkbtn_Click(object sender, EventArgs e)
{
IForm form = (IForm)tabControl1.SelectedTab.Controls[0];
form.InsaManagement = this;
form.Btn_check_clicked();
MessageBox.Show(Mode);
BtnCotrol();
}
private void cancelbtn_Click(object sender, EventArgs e)
{
IForm form = (IForm)tabControl1.SelectedTab.Controls[0];
form.InsaManagement = this;
form.Btn_cancel_clicked();
BtnCotrol();
}
private void BtnIUDBlock()
{
insertbtn.Enabled = false;
updatebtn.Enabled = false;
deletebtn.Enabled = false;
checkbtn.Enabled = true;
cancelbtn.Enabled = true;
}
private void BtnIUDGray()
{
insertbtn.BackColor = Color.LightGray;
updatebtn.BackColor = Color.LightGray;
deletebtn.BackColor = Color.LightGray;
checkbtn.BackColor = Color.White;
cancelbtn.BackColor = Color.White;
}
private void BtnCCBlock()
{
insertbtn.Enabled = true;
updatebtn.Enabled = true;
deletebtn.Enabled = true;
checkbtn.Enabled = false;
cancelbtn.Enabled = false;
}
private void BtnCCGray()
{
insertbtn.BackColor = Color.White;
updatebtn.BackColor = Color.White;
deletebtn.BackColor = Color.White;
checkbtn.BackColor = Color.LightGray;
cancelbtn.BackColor = Color.LightGray;
}
private void BtnCotrol()
{
if (Mode == "BlockIUD")
{
BtnIUDGray();
BtnIUDBlock();
Mode = "";
}
if(Mode == "BlockCC")
{
BtnCCBlock();
BtnCCGray();
Mode = "";
}
}
}
}
<file_sep>using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace DB_Helper
{
public class DBOracle_Helper
{
string dbIp = "192.168.3.11";
string dbName = "ORA7";
string dbId = "EDU";
string dbPw = "<PASSWORD>";
public DBOracle_Helper()
{
}
public DBOracle_Helper(string _dbip, string _dbName, string _dbId, string _dbPw)
{
dbIp = _dbip;
dbName = _dbName;
dbId = _dbId;
dbPw = _dbPw;
}
//==========================================================================================================
public DataTable GetData(string query)
{
OracleConnection conn = GetConnection();
DataTable ret = new DataTable(); //DataTable 생성
try
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = query;
conn.Open();
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(ret);
conn.Close();
da.Dispose();
}
catch (Exception ex)
{
ret = null;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Dispose();
}
return ret;
}
//==========================================================================================================
public int SetData(string query)
{
int ret = 0;
OracleConnection conn = GetConnection();
try
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = query;
conn.Open();
ret = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
ret = -1;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Dispose();
}
return ret;
}
//===============================================================================================================
private OracleConnection GetConnection()
{
return new OracleConnection($"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST={dbIp})(PORT=1522)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME={dbName}))); User ID={dbId};Password={<PASSWORD>};Connection Timeout=30;");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
using System.Xml;
using System.Net;
namespace insaSystem
{
public partial class search_address : Form
{
int num;
string fix;
string mar;
String dbIp = "192.168.127.12";
String dbName = "ORA7";
String dbId = "EDU";
String dbPw = "<PASSWORD>";
string currentPage = "1"; //현재 페이지
string countPerPage = "1000"; //1페이지당 출력 갯수
string confmKey = "<KEY>"; //테스트 Key
string keyword = string.Empty;
string apiurl = string.Empty;
int count = 1;
Insa01BaseInfo ff;
public search_address(Insa01BaseInfo fm)
{
InitializeComponent();
ff = fm;
}
#region 나가기, 최대화, 리스토어, 최소화 Btn Control
//-----------나가기----------
private void exitbtn_Click(object sender, EventArgs e)
{
this.Close();
}
//-----------최소화----------
private void minimizarbtn_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
#endregion
public Insa01BaseInfo fom;
private void search_Click(object sender, EventArgs e)
{
if (addresstxt.Text == "")
{
MessageBox.Show("찾으시려는 동/읍/면을 먼저 입력해주세요");
return;
}
List<string> tm = new List<string>();
int tma;
DataTable table = new DataTable();
table.Columns.Add("우편번호", typeof(String));
table.Columns.Add("도로명주소", typeof(String));
table.Columns.Add("지번주소", typeof(String));
Find(addresstxt.Text, 1, 50, tm, out tma);
int i = 0;
while (i * 3 < 50)
{
i++;
try
{
table.Rows.Add(tm[i * 3 + 0], tm[i * 3 + 1], tm[i * 3 + 2]);
}
catch (Exception e1)
{
}
}
dataGridView1.DataSource = table;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
}
//* 공공데이터포털(http://www.data.go.kr) 오픈 API 이용
// [in] s : 검색어 (도로명주소[도로명/건물명] 또는 지번주소[동/읍/면/리])
// [in] p : 읽어올 페이지(1부터), l : 한 페이지당 출력할 목록 수(최대 50까지)
// [out] v[i*3 +0]=우편번호, v[i*3 +1]=도로명주소, v[i*3 +2]=지번주소, v.Count/3=표시할 목록 수
// [out] n : 검색한 전체 목록(우편번호) 개수
// 반환값 : 에러메시지, null == OK
public static string Find(string s, int p, int l, List<string> v, out int n)
{
n = 0;
try
{
HttpWebRequest rq = (HttpWebRequest)WebRequest.Create(
"http://openapi.epost.go.kr/postal/retrieveNewAdressAreaCdSearchAllService/retrieveNewAdressAreaCdSearchAllService/getNewAddressListAreaCdSearchAll"
+ "?ServiceKey=<KEY>2<KEY>%3D%3D" // 서비스키
+ "&countPerPage=" + l // 페이지당 출력될 개수를 지정(최대 50)
+ "¤tPage=" + p // 출력될 페이지 번호
+ "&srchwrd=" + HttpUtility.UrlPathEncode(s) // 검색어
);
rq.Headers = new WebHeaderCollection();
rq.Headers.Add("Accept-language", "ko");
bool bOk = false; // <successYN>Y</successYN> 획득 여부
s = null; // 에러 메시지
HttpWebResponse rp = (HttpWebResponse)rq.GetResponse();
XmlTextReader r = new XmlTextReader(rp.GetResponseStream());
while (r.Read())
{
if (r.NodeType == XmlNodeType.Element)
{
if (bOk)
{
if (r.Name == "zipNo" || // 우편번호
r.Name == "lnmAdres" || // 도로명 주소
r.Name == "rnAdres") // 지번 주소
{
v.Add(r.ReadString());
}
else if (r.Name == "totalCount") // 전체 검색수
{
int.TryParse(r.ReadString(), out n);
}
}
else
{
if (r.Name == "successYN")
{
if (r.ReadString() == "Y") bOk = true; // 검색 성공
}
else if (r.Name == "errMsg") // 에러 메시지
{
s = r.ReadString();
break;
}
}
}
}
r.Close();
rp.Close();
if (s == null)
{ // OK!
if (v.Count < 3)
s = "검색결과가 없습니다.";
}
}
catch (Exception e)
{
s = e.Message;
}
return s;
}
private void addresstxt_TextChanged(object sender, EventArgs e)
{
}
private void previousbtn_Click(object sender, EventArgs e)
{
if (count == 1)
{
return;
}
else
{
count--;
}
List<string> tm = new List<string>();
int tma;
DataTable table = new DataTable();
table.Columns.Add("우편번호", typeof(String));
table.Columns.Add("도로명주소", typeof(String));
table.Columns.Add("지번주소", typeof(String));
Find(addresstxt.Text, count, 50, tm, out tma);
int i = 0;
while (i * 3 < 50)
{
i++;
try
{
table.Rows.Add(tm[i * 3 + 0], tm[i * 3 + 1], tm[i * 3 + 2]);
}
catch (Exception e2)
{
}
}
dataGridView1.DataSource = table;
}
private void nextbtn_Click(object sender, EventArgs e)
{
count++;
List<string> tm = new List<string>();
int tma;
DataTable table = new DataTable();
table.Columns.Add("우편번호", typeof(String));
table.Columns.Add("도로명주소", typeof(String));
table.Columns.Add("지번주소", typeof(String));
Find(addresstxt.Text, count, 50, tm, out tma);
int i = 0;
while (i * 3 < 50)
{
i++;
try
{
table.Rows.Add(tm[i * 3 + 0], tm[i * 3 + 1], tm[i * 3 + 2]);
}
catch (Exception e1)
{
}
}
dataGridView1.DataSource = table;
}
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var adr_data1 = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
var adr_data2 = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
ff.getAddress(adr_data1, adr_data2);
Close();
}
private void search_address_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Data.SqlClient;
using Oracle.ManagedDataAccess.Client;
namespace insaSystem
{
public partial class InsaMain : Form
{
InsaLogin loginForm;
Form assist;
#region raindrops 초석, insa버튼 색깔 제어
//raindrops 초석
[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private extern static IntPtr CreateRoundRectRgn(int left, int top, int right, int bottom, int width, int height);
int[] rainSpeeds = { 1, 2, 2, 3, 2, 2, 1, 1 };
//insa버튼 색깔 제어
int on01 = 0; int on02 = 0; int on03 = 0; int on04 = 0; int on05 = 0;
#endregion
public InsaMain(string info)
{
#region raindrops 초석, 보조사이드바 숨기기
InitializeComponent();
//raindrops 초석
Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 7, 7));
timer1.Start();
//보조 사이드바 숨기기
assistVertical.Visible = false;
#endregion
}
#region 나가기, 최대화, 리스토어, 최소화 Btn Control
//-----------나가기----------
private void exitbtn_Click(object sender, EventArgs e)
{
Application.Exit();
}
//-----------최대화----------
private void maximizarbtn_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
restorebtn.Visible = true;
maximizarbtn.Visible = false;
}
//-----------리스토어----------
private void restorebtn_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
restorebtn.Visible = false;
maximizarbtn.Visible = true;
}
//-----------최소화----------
private void minimizarbtn_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
#endregion
#region Window 드래그 Control (마우스 핸들링)
//-----------필수 코드--------------
[DllImport("user32.DLL", EntryPoint = "ReleaseCapture")]
private extern static void ReleaseCapture();
[DllImport("user32.DLL", EntryPoint = "SendMessage")]
private extern static void SendMessage(System.IntPtr hwnd, int wmsg, int wparam, int lparam);
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
screenMouseDown();
}
private void label2_MouseDown(object sender, MouseEventArgs e)
{
screenMouseDown();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
screenMouseDown();
}
private void screenMouseDown()
{
ReleaseCapture();
SendMessage(this.Handle, 0x112, 0xf012, 0);
}
#endregion
#region Raindrop Control
private void timer1_Tick(object sender, EventArgs e)
{
//do animation
for (int i = 0; i < 8; i++)
{
switch (i)
{
case 0:
//animation for rain1;
pictureBox2.Location = new Point(pictureBox2.Location.X, pictureBox2.Location.Y + rainSpeeds[i]);
if (pictureBox2.Location.Y > panel7.Size.Height + pictureBox2.Size.Height)
{
pictureBox2.Location = new Point(pictureBox2.Location.X, 0 - pictureBox2.Size.Height);
}
break;
case 1:
//animation for rain2;
pictureBox3.Location = new Point(pictureBox3.Location.X, pictureBox3.Location.Y + rainSpeeds[i]);
if (pictureBox3.Location.Y > panel7.Size.Height + pictureBox3.Size.Height)
{
pictureBox3.Location = new Point(pictureBox3.Location.X, 0 - pictureBox3.Size.Height);
}
break;
case 2:
//animation for rain3;
pictureBox4.Location = new Point(pictureBox4.Location.X, pictureBox4.Location.Y + rainSpeeds[i]);
if (pictureBox4.Location.Y > panel7.Size.Height + pictureBox4.Size.Height)
{
pictureBox4.Location = new Point(pictureBox4.Location.X, 0 - pictureBox4.Size.Height);
}
break;
case 3:
//animation for rain4;
pictureBox5.Location = new Point(pictureBox5.Location.X, pictureBox5.Location.Y + rainSpeeds[i]);
if (pictureBox5.Location.Y > panel7.Size.Height + pictureBox5.Size.Height)
{
pictureBox5.Location = new Point(pictureBox5.Location.X, 0 - pictureBox5.Size.Height);
}
break;
case 4:
//animation for rain5;
pictureBox6.Location = new Point(pictureBox6.Location.X, pictureBox6.Location.Y + rainSpeeds[i]);
if (pictureBox6.Location.Y > panel7.Size.Height + pictureBox6.Size.Height)
{
pictureBox6.Location = new Point(pictureBox6.Location.X, 0 - pictureBox6.Size.Height);
}
break;
case 5:
//animation for rain6;
pictureBox7.Location = new Point(pictureBox7.Location.X, pictureBox7.Location.Y + rainSpeeds[i]);
if (pictureBox7.Location.Y > panel7.Size.Height + pictureBox7.Size.Height)
{
pictureBox7.Location = new Point(pictureBox7.Location.X, 0 - pictureBox7.Size.Height);
}
break;
case 6:
//animation for rain7;
pictureBox8.Location = new Point(pictureBox8.Location.X, pictureBox8.Location.Y + rainSpeeds[i]);
if (pictureBox8.Location.Y > panel7.Size.Height + pictureBox8.Size.Height)
{
pictureBox8.Location = new Point(pictureBox8.Location.X, 0 - pictureBox8.Size.Height);
}
break;
case 7:
//animation for rain8;
pictureBox9.Location = new Point(pictureBox9.Location.X, pictureBox9.Location.Y + rainSpeeds[i]);
if (pictureBox9.Location.Y > panel7.Size.Height + pictureBox9.Size.Height)
{
pictureBox9.Location = new Point(pictureBox9.Location.X, 0 - pictureBox9.Size.Height);
}
break;
}
}
}
#endregion
#region insa 버튼 color Control
//-------------MouseMove 및 MouseLeave시 컬러변화------------
//인사기초 정보
private void insa_baseBtn_MouseMove(object sender, MouseEventArgs e)
{
insa_baseBtn.ForeColor = Color.Black;
insa_baseBtn.BackColor = Color.WhiteSmoke;
insa_recordBtn.ForeColor = Color.White;
insa_recordBtn.BackColor = Color.CornflowerBlue;
insa_changeBtn.ForeColor = Color.White;
insa_changeBtn.BackColor = Color.CornflowerBlue;
insa_certificateBtn.ForeColor = Color.White;
insa_certificateBtn.BackColor = Color.CornflowerBlue;
insa_graphBtn.ForeColor = Color.White;
insa_graphBtn.BackColor = Color.CornflowerBlue;
}
private void insa_baseBtn_MouseLeave(object sender, EventArgs e)
{
}
//인사기록 관리
private void insa_recordBtn_MouseMove(object sender, MouseEventArgs e)
{
insa_recordBtn.ForeColor = Color.Black;
insa_recordBtn.BackColor = Color.WhiteSmoke;
insa_baseBtn.ForeColor = Color.White;
insa_baseBtn.BackColor = Color.CornflowerBlue;
insa_changeBtn.ForeColor = Color.White;
insa_changeBtn.BackColor = Color.CornflowerBlue;
insa_certificateBtn.ForeColor = Color.White;
insa_certificateBtn.BackColor = Color.CornflowerBlue;
insa_graphBtn.ForeColor = Color.White;
insa_graphBtn.BackColor = Color.CornflowerBlue;
}
private void insa_recordBtn_MouseLeave(object sender, EventArgs e)
{
}
//인사변동 관리
private void insa_changeBtn_MouseMove(object sender, MouseEventArgs e)
{
insa_changeBtn.ForeColor = Color.Black;
insa_changeBtn.BackColor = Color.WhiteSmoke;
insa_baseBtn.ForeColor = Color.White;
insa_baseBtn.BackColor = Color.CornflowerBlue;
insa_recordBtn.ForeColor = Color.White;
insa_recordBtn.BackColor = Color.CornflowerBlue;
insa_certificateBtn.ForeColor = Color.White;
insa_certificateBtn.BackColor = Color.CornflowerBlue;
insa_graphBtn.ForeColor = Color.White;
insa_graphBtn.BackColor = Color.CornflowerBlue;
}
private void insa_changeBtn_MouseLeave(object sender, EventArgs e)
{
}
//제증명서 발급
private void insa_certificateBtn_MouseMove(object sender, MouseEventArgs e)
{
insa_certificateBtn.ForeColor = Color.Black;
insa_certificateBtn.BackColor = Color.WhiteSmoke;
insa_baseBtn.ForeColor = Color.White;
insa_baseBtn.BackColor = Color.CornflowerBlue;
insa_recordBtn.ForeColor = Color.White;
insa_recordBtn.BackColor = Color.CornflowerBlue;
insa_changeBtn.ForeColor = Color.White;
insa_changeBtn.BackColor = Color.CornflowerBlue;
insa_graphBtn.ForeColor = Color.White;
insa_graphBtn.BackColor = Color.CornflowerBlue;
}
private void insa_certificateBtn_MouseLeave(object sender, EventArgs e)
{
}
//현황 및 통계
private void insa_graphBtn_MouseMove(object sender, MouseEventArgs e)
{
insa_graphBtn.ForeColor = Color.Black;
insa_graphBtn.BackColor = Color.WhiteSmoke;
insa_baseBtn.ForeColor = Color.White;
insa_baseBtn.BackColor = Color.CornflowerBlue;
insa_recordBtn.ForeColor = Color.White;
insa_recordBtn.BackColor = Color.CornflowerBlue;
insa_changeBtn.ForeColor = Color.White;
insa_changeBtn.BackColor = Color.CornflowerBlue;
insa_certificateBtn.ForeColor = Color.White;
insa_certificateBtn.BackColor = Color.CornflowerBlue;
}
private void insa_graphBtn_MouseLeave(object sender, EventArgs e)
{
}
private void White_ConflowerBlue()
{
insa_baseBtn.ForeColor = Color.White;
insa_baseBtn.BackColor = Color.CornflowerBlue;
insa_recordBtn.ForeColor = Color.White;
insa_recordBtn.BackColor = Color.CornflowerBlue;
insa_changeBtn.ForeColor = Color.White;
insa_changeBtn.BackColor = Color.CornflowerBlue;
insa_certificateBtn.ForeColor = Color.White;
insa_certificateBtn.BackColor = Color.CornflowerBlue;
insa_graphBtn.ForeColor = Color.White;
insa_graphBtn.BackColor = Color.CornflowerBlue;
}
private void panelContenedor_MouseMove(object sender, MouseEventArgs e)
{
if (assistVertical.Visible == false)
{
White_ConflowerBlue();
}
}
#endregion
#region insa버튼 기능 Control (미완성)
//인사기초정보(insa_base)
//=====================================================================
private void insa_baseBtn_Click(object sender, EventArgs e)
{
if (on01 == 0)
{
on01 = 1; on02 = 0; on03 = 0; on04 = 0; on05 = 0;
if (assist != null)
{
assist.Close();
}
if (this.assistVertical.Controls.Count > 0)
{
this.assistVertical.Controls.RemoveAt(0);
}
//보조 Bar 소환
assistVertical.Visible = true;
//메뉴 호출
Call_assistMenu(new MainMenubar01());
}
else
{
assist.Close();
assistVertical.Visible = false;
on01 = 0;
}
}
//=====================================================================
//인사기록관리(insa_record)
//=====================================================================
private void insa_recordBtn_Click(object sender, EventArgs e)
{
if (on02 == 0)
{
on01 = 0; on02 = 1; on03 = 0; on04 = 0; on05 = 0;
if (assist != null)
{
assist.Close();
}
if (this.assistVertical.Controls.Count > 0)
{
this.assistVertical.Controls.RemoveAt(0);
}
assistVertical.Visible = false;
//보조 Bar 소환
assistVertical.Visible = true;
//메뉴 호출
Call_assistMenu(new MainMenubar02());
}
else
{
assist.Close();
assistVertical.Visible = false;
on02 = 0;
}
}
//=====================================================================
//인사변동관리(insa_change)
//=====================================================================
private void insa_changeBtn_Click(object sender, EventArgs e)
{
if (on03 == 0)
{
on01 = 0; on02 = 0; on03 = 1; on04 = 0; on05 = 0;
if (assist != null)
{
assist.Close();
}
if (this.assistVertical.Controls.Count > 0)
{
this.assistVertical.Controls.RemoveAt(0);
}
assistVertical.Visible = false;
//보조 Bar 소환
assistVertical.Visible = true;
//메뉴 호출
Call_assistMenu(new MainMenubar03());
}
else
{
assist.Close();
assistVertical.Visible = false;
on03 = 0;
}
}
//=====================================================================
//제증명서발급(insa_certificate)
//=====================================================================
private void insa_certificateBtn_Click(object sender, EventArgs e)
{
if (on04 == 0)
{
on01 = 0; on02 = 0; on03 = 0; on04 = 1; on05 = 0;
if (assist != null)
{
assist.Close();
}
if (this.assistVertical.Controls.Count > 0)
{
this.assistVertical.Controls.RemoveAt(0);
//assist = null; // assist를 null로 만들어준다
}
assistVertical.Visible = false;
//보조 Bar 소환
assistVertical.Visible = true;
//메뉴 호출
Call_assistMenu(new MainMenubar04());
}
else
{
assist.Close();
assistVertical.Visible = false;
on04 = 0;
}
}
//=====================================================================
//현황및통계(insa_graph)
//=====================================================================
private void insa_graphBtn_Click(object sender, EventArgs e)
{
if (on05 == 0)
{
on01 = 0; on02 = 0; on03 = 0; on04 = 0; on05 = 1;
if (assist != null)
{
assist.Close();
}
if (this.assistVertical.Controls.Count > 0)
{
this.assistVertical.Controls.RemoveAt(0);
//assist = null; // assist를 null로 만들어준다
}
assistVertical.Visible = false;
//보조 Bar 소환
assistVertical.Visible = true;
//메뉴 호출
Call_assistMenu(new MainMenubar05());
}
else
{
assist.Close();
assistVertical.Visible = false;
on05 = 0;
}
}
//=====================================================================
#endregion
#region sideMenuBar 호출하기, 닫아주기 함수
//호출하기
private void Call_assistMenu(object FormCall)
{
if (this.assistVertical.Controls.Count > 0)
this.assistVertical.Controls.RemoveAt(0);
assist = FormCall as Form;
assist.TopLevel = false;
assist.Dock = DockStyle.Fill;
this.assistVertical.Controls.Add(assist);
this.assistVertical.Tag = assist;
assist.Show();
}
//닫아주기
private void Close_assistMenu(object FormClose)
{
Form assist_close = FormClose as Form;
assist_close.Close();
}
#endregion
#region 실시간 시간, 날짜 출력 함수
private void timechange_Tick(object sender, EventArgs e)
{
lblTimeToday.Text = DateTime.Now.ToString("hh:mm:ss");
lblDateToday.Text = DateTime.Now.ToLongDateString();
}
#endregion
#region 메뉴바가 켜져있을 때 중앙 패널을 눌렀을시 메뉴바 닫고 버튼 컬러 초기화
private void panelContenedor_Click(object sender, EventArgs e)
{
if (assist != null)
{
assist.Close();
assistVertical.Visible = false;
insa_baseBtn.BackColor = Color.CornflowerBlue;
insa_baseBtn.ForeColor = Color.White;
insa_recordBtn.BackColor = Color.CornflowerBlue;
insa_recordBtn.ForeColor = Color.White;
insa_changeBtn.BackColor = Color.CornflowerBlue;
insa_changeBtn.ForeColor = Color.White;
insa_certificateBtn.BackColor = Color.CornflowerBlue;
insa_certificateBtn.ForeColor = Color.White;
insa_graphBtn.BackColor = Color.CornflowerBlue;
insa_graphBtn.ForeColor = Color.White;
}
}
#endregion
private void InsaMain_Load(object sender, EventArgs e)
{
loginForm = new InsaLogin();//로그인폼 생성
switch (loginForm.ShowDialog())
{
case DialogResult.OK:
loginForm.Close();
break;
case DialogResult.Cancel:
Dispose();
break;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DB_Helper;
using System.Configuration;
using Oracle.ManagedDataAccess.Client;
using System.Diagnostics;
using System.Windows.Forms;
namespace insaSystem
{
class LoginHandler
{
DBOracle_Helper oHelper;
public bool LoginCheck(string id, string password)
{
try
{
oHelper = new DBOracle_Helper();
{
string sql = "select login_empno, login_password from thrm_login_psy where login_empno = '"+ id + "' and login_password = '" + password + "'";
DataTable loginInfo = oHelper.GetData(sql);
using (DataTableReader reader = new DataTableReader(loginInfo))
{
if (reader.HasRows)
{
return true;
}
}
}
}
catch (OracleException ex)
{
MessageBox.Show(ex.Message);
}
return false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace insaSystem
{
public partial class MainMenubar02 : Form
{
public MainMenubar02()
{
InitializeComponent();
}
#region 인사기록관리 border Color - White
private void panel5_Paint(object sender, PaintEventArgs e)
{
ControlPaint.DrawBorder(e.Graphics, this.panel5.ClientRectangle, Color.White, ButtonBorderStyle.Solid);
}
#endregion
#region 선택 메뉴로 들어가기 Control
private void InsaInput_Click(object sender, EventArgs e)
{
InsaManagement InsaManSys = new InsaManagement(0);
InsaManSys.ShowDialog();
}
private void InsaInquiry_Click(object sender, EventArgs e)
{
InsaManagement InsaManSys = new InsaManagement(7);
InsaManSys.ShowDialog();
}
#endregion
}
}
|
26f38eebb7e805a8cb857238ccc93b260fd58318
|
[
"C#"
] | 14 |
C#
|
SeoYoonP/insaSystem
|
0cf6e8d77f251f65d5953fe08ddcbfd5d70a028e
|
fa76f08a7ec62f80ad9db8cb7c2cfc26cc15f6d0
|
refs/heads/main_branch
|
<repo_name>shayella/url_shortener_django<file_sep>/shortener/migrations/0001_initial.py
# Generated by Django 3.1 on 2020-08-24 20:49
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ShortenURL',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('url', models.URLField(max_length=220)),
('shortcode', models.SlugField(max_length=250, unique=True)),
('updated', models.DateTimeField(auto_now=True)),
('timestamp', models.DateTimeField(auto_now_add=True)),
],
),
]
<file_sep>/shortener/management/commands/refreshcodes.py
from django.core.management.base import BaseCommand,CommandError
from shortener.models import ShortenURL
class Command(BaseCommand):
help = 'Refreshes all shortcodes for the ShortenURL objects'
def handle(self,*args,**options):
return ShortenURL.objects.refresh_shortcodes()
<file_sep>/analystics/templates/analystics/total_url_count.html
{%extends 'shortener/base.html'%}
{% block content%}
<section id="one">
{%include 'shortener/logo.html'%}
<div class="main style1">
<div class="container">
<div class="row gtr-150">
<div class="col-10 off-2 col-12-medium align-left">
<div class="major">
<h1 >Total URL Clicks</h1>
</div>
<h3> Count : </h3><h2> <strong> 0{{obj.clickevent.count}}</strong> </h2>
<p>This shows the number of clicks on Short URL: <strong> <a href="{{obj.get_short_url}}">{{obj.get_short_url}}</a> </strong> </p>
<p>Click here to <a id="track-url" href="{%url 'url_count'%}">track number of clicks of a different short URL</a> </p> <br>
<a id="create-url" href="{% url 'home'%}">Create another Short URL</a>
</div>
</div>
</div>
</div>
</section>
{%endblock%}
<file_sep>/analystics/views.py
from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponse
from .forms import URLCountForm
from shortener.models import ShortenURL
from django.conf import settings
# Create your views here.
URL_START_STRING = getattr(settings,"URL_START_STRING")
def url_count(request, shortcode=None):
if ShortenURL.objects.count() > 0:
sc_eg = ShortenURL.objects.first().shortcode
sc_eg = URL_START_STRING+'/'+sc_eg+'/'
else:
sc_eg = ""
if shortcode is None:
if request.method == 'GET':
form = URLCountForm();
return render(request,'analystics/url_count.html',{'form':form,'sc_eg':sc_eg})
elif request.method == 'POST':
form = URLCountForm(request.POST)
if form.is_valid():
short_url = form.cleaned_data.get('short_url')
if short_url.startswith(URL_START_STRING+'/'):
if short_url.endswith('/'):
sc = short_url.split('/')[-2]
else:
sc = short_url.split('/')[-1]
qs = ShortenURL.objects.filter(shortcode__iexact = sc)
if bool(qs) and qs.count()== 1:
obj = qs.first()
print(obj)
return render(request,'analystics/total_url_count.html',{'obj':obj,'sc_eg':sc_eg})
else:
return render(request,'analystics/url_count.html',{'form':form, 'not_exists':True,'sc_eg':sc_eg})
return render(request,'analystics/url_count.html',{'form':form, 'wrong_url':True,'sc_eg':sc_eg})
else:
obj = get_object_or_404(ShortenURL, shortcode = shortcode)
s_url = URL_START_STRING +'/'+ shortcode
return render(request,'analystics/total_url_count.html',{'obj':obj,'sc_eg':sc_eg})
<file_sep>/shortener/admin.py
from django.contrib import admin
# Register your models here.
from .models import ShortenURL
admin.site.register(ShortenURL)
<file_sep>/shortener/views.py
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.views import View
from .models import ShortenURL
from analystics.models import ClickEvent
from .forms import SubmitURLForm
# Create your views here.
def home(request):
if request.method == "GET":
form = SubmitURLForm()
return render(request, 'shortener/index.html', {'form':form})
if request.method == "POST":
form = SubmitURLForm(request.POST)
if form.is_valid():
print(form.cleaned_data)
new_url = form.cleaned_data.get('url')
obj = ShortenURL.objects.create(url=new_url)
created= True
context = { "obj": obj, "created":created,"form":form}
if created:
return render(request,'shortener/index.html',context)
else:
return render(request,'shortener/index.html',context)
context = {"form":form}
return render(request, 'shortener/index.html',context)
def shortenurl_redirect_view(request, shortcode= None):
# sc_url = "does not exist"
# qs = ShortenURL.objects.filter(shortcode__iexact = shortcode)
# if bool(qs) and qs.count()== 1:
# sc_url = qs.first().url
obj = get_object_or_404(ShortenURL, shortcode = shortcode)
print(ClickEvent.objects.create_event(obj))
return HttpResponseRedirect(obj.url)
<file_sep>/shortener/urls.py
from django.urls import path
from .views import shortenurl_redirect_view,home
urlpatterns = [
path('',home, name='home' ),
path('<slug:shortcode>/', shortenurl_redirect_view,name='shortenurl'),
]
<file_sep>/analystics/forms.py
from django import forms
from django.core.exceptions import ValidationError
class URLCountForm(forms.Form):
short_url = forms.URLField(label='Short URL',
widget=forms.URLInput(attrs={'placeholder': 'Enter your short URL'}))
<file_sep>/shortener/forms.py
from django import forms
my_default_errors = {
'required': 'This field is required',
'invalid': 'Invalid URL. Please enter a valid url'
}
class SubmitURLForm(forms.Form):
url = forms.URLField(label='',
widget=forms.URLInput(attrs={'placeholder': 'Paste long URL to shorten e.g. http:\\\\google.com'})
, error_messages = my_default_errors)
<file_sep>/shortener/utils.py
import random
import string
from django.conf import settings
SHORTCODE_MIN = getattr(settings,"SHORTCODE_MIN",6)
def code_generator(length, chars= string.ascii_lowercase + string.digits):
return ''.join(random.choices(chars,k=length))
def create_shortcode(instance,length=SHORTCODE_MIN):
new_shortcode = code_generator(length)
# print(instance)
# print(instance.__class__)
# print(instance.__class__.__name__)
ShortenURLClass = instance.__class__
sc_exists = ShortenURLClass.objects.filter(shortcode=new_shortcode).exists()
if sc_exists:
return create_shortcode(length)
return new_shortcode
<file_sep>/analystics/models.py
from django.db import models
from shortener.models import ShortenURL
# Create your models here.
class ClickEventManager(models.Manager):
def create_event(self,instance):
if isinstance(instance,ShortenURL):
obj,created = self.get_or_create(short_url=instance)
obj.count += 1
obj.save()
return obj.count
return None
class ClickEvent(models.Model):
short_url = models.OneToOneField(ShortenURL,on_delete=models.CASCADE,)
count = models.IntegerField(default = 0)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
objects = ClickEventManager()
def __str__(self):
return str(self.short_url)
<file_sep>/analystics/apps.py
from django.apps import AppConfig
class AnalysticsConfig(AppConfig):
name = 'analystics'
<file_sep>/analystics/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.url_count,name='url_count'),
path('<slug:shortcode>/',views.url_count,name='url_count')
]
<file_sep>/shortener/models.py
from django.db import models
from .utils import create_shortcode
from django.conf import settings
from django.urls import reverse
# Create your models here.
SHORTCODE_MAX = getattr(settings,"SHORTCODE_MAX",15)
URL_START_STRING = getattr(settings,"URL_START_STRING")
# You can make a model manager for this ShortenURL model like this:
class ShortenURLManager(models.Manager):
# You can override the manger methods e.g all or even make your own manager methods
def refresh_shortcodes(self):
qs = ShortenURL.objects.filter(id__gte=1)
new_codes_made = 0
for q in qs:
q.shortcode = create_shortcode(q)
print(q.shortcode)
q.save()
new_codes_made +=1
return "New codes made {}".format(new_codes_made)
class ShortenURL(models.Model):
url = models.URLField(max_length = 220, )
shortcode = models.SlugField(max_length = SHORTCODE_MAX,unique = True, blank=True)
updated = models.DateTimeField(auto_now = True)
timestamp = models.DateTimeField(auto_now_add =True)
# Attach the ShortenURLManager to the objects
objects = ShortenURLManager()
def save(self, *args, **kwargs):
if self.shortcode is None or self.shortcode == "":
self.shortcode = create_shortcode(self)
super(ShortenURL,self).save(*args,**kwargs)
def __str__(self):
return str(self.url)
def get_short_url(self):
url_path = reverse('shortenurl',kwargs={'shortcode':self.shortcode})
return URL_START_STRING+url_path
|
901c035c03fa8b9b8189f68c37c627e63ffeb883
|
[
"Python",
"HTML"
] | 14 |
Python
|
shayella/url_shortener_django
|
0fa23dae79351f98f1fcc421bee5b820d132eeef
|
da212b267c62f2ed0cbdd3d5ddd2731bdd2f0624
|
refs/heads/master
|
<repo_name>andrzejsliwa/production_ready_serverless_in_golang<file_sep>/README.md
# Production Ready Serverless in GoLang
Examples from [Production Ready Serverless](https://www.manning.com/livevideo/production-ready-serverless), made in Golang (Video Course is based on Node.js)
## Setup
```shell
[~]$ cd $GOPATH/src/github.com/andrzejsliwa
[~/go/src/github.com/andrzejsliwa]$ git clone <EMAIL>:andrzejsliwa/production_ready_serverless_in_golang.git
Cloning into 'production_ready_serverless_in_golang'...
remote: Counting objects: 10, done.
remote: Compressing objects: 100% (9/9), done.
remote: Total 10 (delta 0), reused 10 (delta 0), pack-reused 0
Receiving objects: 100% (10/10), done.
[~/go/src/github.com/andrzejsliwa]$ cd production_ready_serverless_in_golang
[master][~/go/src/github.com/andrzejsliwa/production_ready_serverless_in_golang]$
```
## Deployment
```shell
[master][~/go/src/github.com/andrzejsliwa/production_ready_serverless_in_golang]$ cd production_ready_serverless_in_golang
[master][~/go/src/github.com/andrzejsliwa/production_ready_serverless_in_golang/hello_manning]$ make
dep ensure
env GOOS=linux go build -ldflags="-s -w" -o bin/hello hello/main.go
[master][~/go/src/github.com/andrzejsliwa/production_ready_serverless_in_golang/hello_manning]$ sls deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (2.25 MB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
..........
Serverless: Stack update finished...
Service Information
service: hello-manning
stage: dev
region: us-west-1
stack: hello-manning-dev
api keys:
None
endpoints:
GET - https://*********.execute-api.us-west-1.amazonaws.com/dev/
functions:
hello: hello-manning-dev-hello
```
## Running
Open endpoint (from your console output, not from this file)
Example:
```shell
$ open https://*********.execute-api.us-west-1.amazonaws.com/dev/
```
## List of Examples
- hello_manning - simple api-gateway example with golang and serverless
- sam_local_with_localstack_and_dynamodb - simple example with using localstack and running on AWS SAM Local (with example test with mocking dynamodb)
- big_mouth - simple example how to render static html via api-gateway (as proof of concept for tutorial, for production I would consider using S3 build with CloudFront)
## Notes
- Serverless is using CloudFormation underhood for provisioning
- Currently Serverless is not supporting invoke on local for Golang (you can make it with `AWS SAM Local`)
- AWS Sam Local is running locally lambdas in docker images which are close to production in behaviour
- Together with AWS SAM Local you are able to run LocalStack to emulate resources locally
<file_sep>/sam_local_with_localstack_and_dynamo/main.go
package main
import (
"log"
"os"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/events"
"context"
)
func handleRequest(context context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
endpoint := os.Getenv("AWS_DYNAMODB_ENDPOINT")
fmt.Println("All env variables:")
for _, pair := range os.Environ() {
fmt.Println(pair)
}
sess, err := session.NewSession(&aws.Config{Endpoint: aws.String(endpoint)})
fmt.Println("ENDPOINT = ", endpoint)
if err != nil {
log.Fatal(err)
}
svc := dynamodb.New(sess)
return events.APIGatewayProxyResponse{
Body: fmt.Sprintf("%s", GetTableNames(svc)),
StatusCode: 200,
}, nil
}
func main() {
lambda.Start(handleRequest)
}
func GetTableNames(db dynamodbiface.DynamoDBAPI) []string {
out, err := db.ListTables(&dynamodb.ListTablesInput{})
if err != nil {
log.Fatal(err)
}
fmt.Println(out)
var tableNames []string
for _, name := range out.TableNames {
tableNames = append(tableNames, *name)
}
return tableNames
}
<file_sep>/hello_manning/hello/main.go
package main
import (
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/events"
"encoding/json"
)
type Response struct {
Message string `json:"message"`
}
func Handler(_ events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
body, err := json.Marshal(&Response{Message: "Hello Manning!!"})
if err != nil {
return events.APIGatewayProxyResponse{Body: "Unprocessable Entity", StatusCode: 422}, err
}
return events.APIGatewayProxyResponse{Body: string(body), StatusCode: 200}, nil
}
func main() {
lambda.Start(Handler)
}
<file_sep>/big-mouth/get-index/main.go
package main
import (
"github.com/aws/aws-lambda-go/lambda"
"github.com/gobuffalo/packr"
"github.com/aws/aws-lambda-go/events"
"context"
)
type Response struct {
Message string `json:"message"`
}
var html string
func handleRequest(context context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
return events.APIGatewayProxyResponse{
StatusCode: 200,
Body: html,
Headers: map[string]string{"Content-Type": "text/html; charset=UTF-8"},
}, nil
}
func main() {
box := packr.NewBox("../statics")
res, err := box.MustString("index.html")
if err != nil {
panic(err)
}
html = res
lambda.Start(handleRequest)
}
<file_sep>/sam_local_with_localstack_and_dynamo/Makefile
build:
GOOS=linux go build -o bin/main
chmod +x bin/main
start: build
AWS_DYNAMODB_ENDPOINT=http://172.17.0.4:4569 sam local start-api --docker-network localstack_default
localstack:
localstack start --docker<file_sep>/big-mouth/Makefile
.PHONY = clean build
all: build
clean: ## Clean build
rm -rf bin/*
packr clean
build: clean ## Build handler binary
dep ensure
packr
env GOOS=linux go build -o bin/get-index get-index/*.go
deploy: build ## Deploy function
sls deploy
help: ## This help-view
@printf "\033[36mHelp: \033[0m\n"
@grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36mmake %-20s\033[0m%s\n", $$1, $$2}'
<file_sep>/sam_local_with_localstack_and_dynamo/main_test.go
package main
import (
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
"github.com/stretchr/testify/assert"
)
type fakeDynamoDB struct {
dynamodbiface.DynamoDBAPI
payload []*string
}
func (f *fakeDynamoDB) ListTables(*dynamodb.ListTablesInput) (*dynamodb.ListTablesOutput, error) {
return &dynamodb.ListTablesOutput{
TableNames: f.payload,
}, nil
}
func TestGetTableNames(t *testing.T) {
dynamodb := &fakeDynamoDB{
payload: []*string{
aws.String("ala"),
aws.String("ma"),
aws.String("kota"),
},
}
actual := GetTableNames(dynamodb)
expected := []string{"ala", "ma", "kota"}
assert.EqualValues(t, expected, actual)
}
|
bdcc120a62ecf17da052211ccb7d60788063d888
|
[
"Markdown",
"Go",
"Makefile"
] | 7 |
Markdown
|
andrzejsliwa/production_ready_serverless_in_golang
|
9fe353ec93c0cf3e9c7aa18635fd0f1b052ab85b
|
81ff2e01915df490d4325d321fed52be560ab42e
|
refs/heads/master
|
<repo_name>dhruvindsd-dev/dhruvindsd-dev.github.io<file_sep>/sw.js
const cacheName = "assets";
const appFiles = [
"/static/css/bulma.min.css",
"/index.html",
"/images/icons/icon-72x72.png",
"/images/icons/icon-96x96.png",
"/images/icons/icon-128x128.png",
"/images/icons/icon-144x144.png",
"/images/icons/icon-152x152.png",
"/images/icons/icon-192x192.png",
"/images/icons/icon-384x384.png",
"/images/icons/icon-512x512.png",
];
self.addEventListener("install", (e) => {
console.log("[Service Worker] Install");
e.waitUntil(
caches.open(cacheName).then((cache) => {
console.log("[Service Worker] Caching all: app shell and content");
return cache.addAll(appFiles);
})
);
});
self.addEventListener("fetch", (e) => {
e.respondWith(
caches.match(e.request).then((r) => {
console.log("[Service Worker] Fetching resource: " + e.request.url);
return (
r ||
fetch(e.request).then(async (response) => {
const cache = await caches.open(cacheName);
console.log(
"[Service Worker] Caching new resource: " + e.request.url
);
cache.put(e.request, response.clone());
return response;
})
);
})
);
});
|
ee2b157c586d51c4fd6c9885a091d0c3b24681ca
|
[
"JavaScript"
] | 1 |
JavaScript
|
dhruvindsd-dev/dhruvindsd-dev.github.io
|
4705992b08e85c589eb6210c39a1b77cc96d7cfa
|
fa4ec46bca4b1940de048be0da937058a1acda5d
|
refs/heads/master
|
<repo_name>xThaid/asylum-app<file_sep>/app/src/main/java/com/thaid/asylum/api/APIRequest.java
package com.thaid.asylum.api;
import org.json.JSONException;
import org.json.JSONObject;
public abstract class APIRequest<T> {
private final String APIEndpoint;
protected JSONObject data;
public APIRequest(String APIEndpoint, JSONObject data) {
this.APIEndpoint = APIEndpoint;
this.data = data;
}
public APIRequest(String APIEndpoint) {
this(APIEndpoint, new JSONObject());
}
public String getAPIEndpoint() {
return APIEndpoint;
}
public JSONObject getData() {
return data;
}
public abstract T parseResponse(JSONObject json) throws JSONException;
}
<file_sep>/app/src/main/java/com/thaid/asylum/api/requests/Energy/GetHistoryEnergyDataRequest.java
package com.thaid.asylum.api.requests.Energy;
import com.thaid.asylum.api.APIRequest;
import org.joda.time.LocalDate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Locale;
public class GetHistoryEnergyDataRequest extends APIRequest<GetHistoryEnergyDataRequest.HistoryEnergyDataModel> {
private static final String API_ENDPOINT = "getHistoryEnergyData";
private static final String ENERGY_TOTAL = "energy_total";
private static final String ENERGY_GROUPED = "energy_grouped";
private static final String PRODUCTION = "production";
private static final String CONSUMPTION = "consumption";
private static final String IMPORT = "import";
private static final String EXPORT = "export";
private static final String STORE = "store";
private static final String USE = "use";
private static final String FROM_DATE = "from_date";
private static final String TO_DATE = "to_date";
private static final String GROUP_SPAN = "group_span";
public static final String DATE_PATTERN = "yyyy-MM-dd";
public static final String GROUP_SPAN_YEAR = "year";
public static final String GROUP_SPAN_MONTH = "month";
public static final String GROUP_SPAN_DAY = "day";
public static final String GROUP_SPAN_MINUTES = "minutes";
public static final LocalDate STARTING_DATE = new LocalDate(2018, 5, 21);
public GetHistoryEnergyDataRequest(LocalDate fromDate, LocalDate toDate, String groupSpan) throws JSONException{
super(API_ENDPOINT);
JSONObject postData = new JSONObject();
postData.put(FROM_DATE, fromDate.toString(DATE_PATTERN, Locale.US));
postData.put(TO_DATE, toDate.toString(DATE_PATTERN, Locale.US));
postData.put(GROUP_SPAN, groupSpan);
this.data = postData;
}
@Override
public HistoryEnergyDataModel parseResponse(JSONObject json) throws JSONException {
JSONObject energyTotalJson = json.getJSONObject(ENERGY_TOTAL);
JSONObject energyGroupedJson = json.getJSONObject(ENERGY_GROUPED);
//JSONObject records = json.getJSONObject("records");
HistoryEnergyGroup<Double> energyTotal = new HistoryEnergyGroup<>(
energyTotalJson.getDouble(PRODUCTION),
energyTotalJson.getDouble(CONSUMPTION),
energyTotalJson.getDouble(IMPORT),
energyTotalJson.getDouble(EXPORT),
energyTotalJson.getDouble(STORE),
energyTotalJson.getDouble(USE));
HistoryEnergyGroup<Double[]> energyGroup = new HistoryEnergyGroup<>(
JSONArrayToDoubleArray(energyGroupedJson.getJSONArray(PRODUCTION)),
JSONArrayToDoubleArray(energyGroupedJson.getJSONArray(CONSUMPTION)),
JSONArrayToDoubleArray(energyGroupedJson.getJSONArray(IMPORT)),
JSONArrayToDoubleArray(energyGroupedJson.getJSONArray(EXPORT)),
JSONArrayToDoubleArray(energyGroupedJson.getJSONArray(STORE)),
JSONArrayToDoubleArray(energyGroupedJson.getJSONArray(USE))
);
return new HistoryEnergyDataModel(energyTotal, energyGroup);
}
private Double[] JSONArrayToDoubleArray(JSONArray j) throws JSONException{
Double[] array = new Double[j.length()];
for(int i = 0; i < j.length(); i++)
array[i] = j.getDouble(i);
return array;
}
public class HistoryEnergyGroup<I> {
private I production;
private I consumption;
private I import_;
private I export;
private I store;
private I use;
public HistoryEnergyGroup(I production,
I consumption,
I import_,
I export,
I store,
I use){
this.production = production;
this.consumption = consumption;
this.import_ = import_;
this.export = export;
this.store = store;
this.use= use;
}
public I getProduction(){
return production;
}
public I getConsumption() {
return consumption;
}
public I getImport_(){
return import_;
}
public I getExport(){
return export;
}
public I getStore() {
return store;
}
public I getUse() {
return use;
}
}
public class HistoryEnergyDataModel{
private HistoryEnergyGroup<Double> energyTotal;
private HistoryEnergyGroup<Double[]> energyGroups;
public HistoryEnergyDataModel(HistoryEnergyGroup<Double> energyTotal, HistoryEnergyGroup<Double[]> energyGroups){
this.energyTotal = energyTotal;
this.energyGroups = energyGroups;
}
public HistoryEnergyGroup<Double> getTotalEnergy(){
return energyTotal;
}
public HistoryEnergyGroup<Double[]> getGroups(){
return energyGroups;
}
}
}
<file_sep>/app/src/main/java/com/thaid/asylum/api/requests/Blinds/BlindActionRequest.java
package com.thaid.asylum.api.requests.Blinds;
import com.thaid.asylum.Blinds.BlindsFragment;
import com.thaid.asylum.api.APINoDataOnResponseRequest;
public class BlindActionRequest extends APINoDataOnResponseRequest {
private static final String API_ENDPOINT = "blindAction";
public BlindActionRequest(BlindsFragment.BlindAction blindAction) {
super(API_ENDPOINT + "/" + blindAction.getBlind().getId() + "/" + blindAction.getAction().getId());
}
}
<file_sep>/app/src/main/java/com/thaid/asylum/SettingsFragment.java
package com.thaid.asylum;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.preference.EditTextPreference;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import java.util.Map;
public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences sharedPreferences;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
@Override
public void onResume() {
super.onResume();
sharedPreferences = getPreferenceManager().getSharedPreferences();
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
Map<String, ?> preferencesMap = sharedPreferences.getAll();
for (Map.Entry<String, ?> preferenceEntry : preferencesMap.entrySet()) {
Preference pref = findPreference(preferenceEntry.getKey());
if (pref instanceof EditTextPreference) {
updateSummary((EditTextPreference) pref);
}
}
}
@Override
public void onPause() {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);
if (pref instanceof EditTextPreference) {
updateSummary((EditTextPreference) pref);
}
}
private void updateSummary(EditTextPreference preference) {
preference.setSummary(preference.getText());
}
}
<file_sep>/app/src/main/java/com/thaid/asylum/MainActivity.java
package com.thaid.asylum;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.PreferenceManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.thaid.asylum.Blinds.BlindsFragment;
import com.thaid.asylum.Chart.ChartFragment;
import com.thaid.asylum.Energy.EnergyFragment;
import com.thaid.asylum.Energy.EnergyHistoryFragment;
import com.thaid.asylum.api.APIClient;
import com.thaid.asylum.api.APIError;
import com.thaid.asylum.api.ResponseListener;
import com.thaid.asylum.api.requests.GetUserInfoRequest;
public class MainActivity extends AppCompatActivity {
private EnergyFragment energyFragment;
private Fragment blindsFragment;
private Fragment meteoFragment;
private EnergyHistoryFragment energyHistoryFragment;
private FragmentManager fragmentManager;
private Fragment activeFragment;
private View container;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_energy:
fragmentManager.beginTransaction().hide(activeFragment).show(energyFragment).commit();
activeFragment = energyFragment;
energyFragment.startRequests();
return true;
case R.id.navigation_shutter:
fragmentManager.beginTransaction().hide(activeFragment).show(blindsFragment).commit();
activeFragment = blindsFragment;
energyFragment.stopRequests();
return true;
case R.id.navigation_meteo:
fragmentManager.beginTransaction().hide(activeFragment).show(meteoFragment).commit();
activeFragment = meteoFragment;
energyFragment.stopRequests();
return true;
case R.id.navigation_camera:
energyFragment.stopRequests();
return true;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
Toolbar toolbar = findViewById(R.id.toolbar);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
setSupportActionBar(toolbar);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
container = findViewById(R.id.main_container_coordinator);
fragmentManager = getSupportFragmentManager();
if (savedInstanceState != null) {
energyFragment = (EnergyFragment) fragmentManager.getFragment(savedInstanceState, "energyFragment");
blindsFragment = fragmentManager.getFragment(savedInstanceState, "blindsFragment");
meteoFragment = fragmentManager.getFragment(savedInstanceState, "meteoFragment");
activeFragment = fragmentManager.getFragment(savedInstanceState, "activeFragment");
energyHistoryFragment = (EnergyHistoryFragment) fragmentManager.getFragment(savedInstanceState, "energyHistoryFragment");
}
if(energyHistoryFragment == null){
energyHistoryFragment = new EnergyHistoryFragment();
fragmentManager.beginTransaction().add(R.id.main_container, energyHistoryFragment, "4").hide(energyHistoryFragment).commit();
}
if(meteoFragment == null) {
meteoFragment = new MeteoFragment();
fragmentManager.beginTransaction().add(R.id.main_container, meteoFragment, "3").hide(meteoFragment).commit();
}
if(blindsFragment == null) {
blindsFragment = new BlindsFragment();
fragmentManager.beginTransaction().add(R.id.main_container, blindsFragment, "2").hide(blindsFragment).commit();
}
if(energyFragment == null) {
energyFragment = new EnergyFragment();
fragmentManager.beginTransaction().add(R.id.main_container, energyFragment, "1").commit();
}
if(activeFragment == null) {
activeFragment = energyFragment;
}
energyFragment.setEnergyHistoryFragment(energyHistoryFragment);
APIClient.Initialize(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.main_menu_action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
} else if(id == R.id.main_menu_action_refresh) {
APIClient apiClient = APIClient.getInstance();
apiClient.sendRequest(new GetUserInfoRequest(), new ResponseListener<GetUserInfoRequest.GetUserInfoModel>() {
@Override
public void onSuccess(GetUserInfoRequest.GetUserInfoModel data) {
Snackbar snackbar = Snackbar
.make(container, "Zalogowano jako " + data.getName(), Snackbar.LENGTH_LONG);
snackbar.show();
}
@Override
public void onError(APIError error) {
Snackbar snackbar = Snackbar
.make(container, getString(error.getTranslationId()), Snackbar.LENGTH_LONG);
snackbar.show();
}
});
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
fragmentManager.putFragment(outState, "energyFragment", energyFragment);
fragmentManager.putFragment(outState, "blindsFragment", blindsFragment);
fragmentManager.putFragment(outState, "meteoFragment", meteoFragment);
fragmentManager.putFragment(outState, "activeFragment", activeFragment);
fragmentManager.putFragment(outState, "energyHistoryFragment", energyHistoryFragment);
}
public void setActiveFragment(Fragment fragment){
this.activeFragment = fragment;
}
}
<file_sep>/app/src/main/java/com/thaid/asylum/api/APINoDataOnResponseRequest.java
package com.thaid.asylum.api;
import org.json.JSONException;
import org.json.JSONObject;
public abstract class APINoDataOnResponseRequest extends APIRequest<APINoDataOnResponseRequest.NoDataOnResponseModel>{
public APINoDataOnResponseRequest(String APIEndpoint, JSONObject data) {
super(APIEndpoint, data);
}
public APINoDataOnResponseRequest(String APIEndpoint) {
super(APIEndpoint);
}
@Override
public NoDataOnResponseModel parseResponse(JSONObject json) throws JSONException {
String message = json.getString("msg");
return new NoDataOnResponseModel(message);
}
public class NoDataOnResponseModel {
private final String message;
private NoDataOnResponseModel (String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
}
<file_sep>/app/src/main/java/com/thaid/asylum/api/requests/Energy/GetCurrentPowerDataRequest.java
package com.thaid.asylum.api.requests.Energy;
import com.thaid.asylum.api.APIRequest;
import org.json.JSONException;
import org.json.JSONObject;
public class GetCurrentPowerDataRequest extends APIRequest<GetCurrentPowerDataRequest.GetCurrentPowerDataModel> {
private static final String API_ENDPOINT = "getCurrentPowerData";
public GetCurrentPowerDataRequest(){
super(API_ENDPOINT);
}
@Override
public GetCurrentPowerDataModel parseResponse(JSONObject json) throws JSONException {
int production = json.getInt("production");
int consumption = json.getInt("consumption");
int use = json.getInt("use");
int import_ = json.getInt("import");
int export = json.getInt("export");
int store = json.getInt("store");
return new GetCurrentPowerDataModel(production, consumption, use, import_, export, store);
}
public class GetCurrentPowerDataModel{
private int production;
private int consumption;
private int use;
private int import_;
private int export;
private int store;
public GetCurrentPowerDataModel(int production,
int consumption,
int use,
int import_,
int export,
int store){
this.production = production;
this.consumption = consumption;
this.use = use;
this.import_ = import_;
this.export = export;
this.store = store;
}
public int getProduction(){
return production;
}
public int getConsumption(){
return consumption;
}
public int getUse(){
return use;
}
public int getImport_(){
return import_;
}
public int getExport(){
return export;
}
public int getStore(){
return store;
}
}
}
<file_sep>/app/src/main/java/com/thaid/asylum/Chart/ChartFragment.java
package com.thaid.asylum.Chart;
import com.fatboyindustrial.gsonjodatime.Converters;
import com.google.gson.Gson;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.google.gson.GsonBuilder;
import com.thaid.asylum.MainActivity;
import com.thaid.asylum.R;
import com.thaid.asylum.api.requests.Energy.GetHistoryEnergyDataRequest;
import org.joda.time.Days;
import org.joda.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class ChartFragment extends Fragment {
Fragment previousFragment;
LineChart chart;
ChartData chartData;
public ChartFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_chart, container, false);
chart = rootView.findViewById(R.id.chart);
final Fragment thisFragment = this;
/*rootView.findViewById(R.id.button12).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getFragmentManager().beginTransaction().hide(thisFragment).show(previousFragment).commit();
((MainActivity) getActivity()).setActiveFragment(previousFragment);
}
});
*/
return rootView;
}
public void drawChart(ChartData chartData, Fragment previousFragment){
this.chartData = chartData;
this.previousFragment = previousFragment;
final List<Entry> series = getChartEntryList(chartData);
LineDataSet dataSet = new LineDataSet(series, chartData.getChartName());
dataSet.setColor(chartData.getColor());
dataSet.setDrawCircles(false);
dataSet.setLineWidth(2f);
dataSet.setFillColor(chartData.getColor());
dataSet.setFillAlpha(150);
dataSet.setDrawFilled(true);
LineData lineData = new LineData(dataSet);
chart.setData(lineData);
chart.invalidate();
XAxis xAxis = chart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setLabelRotationAngle(-45);
xAxis.setTextSize(14f);
xAxis.setValueFormatter(new ValueFormatter() {
//Workaround, because "getFormatedValue" do not provide index of element
@Override
public String getFormattedValue(float value) {
LocalDateTime dateTime = new LocalDateTime(2000, 1, 1, 0, 0);
dateTime = dateTime.plusMinutes((int)value);
return dateTime.toString("HH:mm", Locale.US);
}
});
YAxis yAxis = chart.getAxisRight();
yAxis.setEnabled(false);
yAxis = chart.getAxisLeft();
yAxis.setTextSize(13f);
yAxis.setAxisMinimum(0f);
yAxis.setValueFormatter(new ValueFormatter() {
@Override
public String getFormattedValue(float value) {
return Math.round(value) + " W";
}
});
Description desc = new Description();
desc.setText("");
chart.setDescription(desc);
Legend legend = chart.getLegend();
legend.setTextSize(18f);
legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
legend.setDrawInside(true);
legend.setFormSize(18f);
legend.setForm(Legend.LegendForm.LINE);
chart.invalidate();
}
private List<Entry> getChartEntryList(ChartData chartData){
List<Entry> entries = new ArrayList<>();
switch (chartData.getGroupSpan()){
case GetHistoryEnergyDataRequest.GROUP_SPAN_MINUTES:
int dayToMinutesRatio = 24 * 60;
int timeSeparation = 4;
int groupCount = ((Days.daysBetween(chartData.getFromDate(), chartData.getToDate()).getDays() + 1) * dayToMinutesRatio) / timeSeparation;
LocalDateTime dateTime = new LocalDateTime(
2000,
1,
1,
0,
0
);
LocalDateTime now = new LocalDateTime();
for(int i =0; i < groupCount; i++){
entries.add(new Entry((float) (dateTime.getMinuteOfHour() + (dateTime.getHourOfDay() * 60) + ((dateTime.getDayOfMonth() - 1) * 24 * 60)), chartData.getData()[i].floatValue()));
dateTime = dateTime.plusMinutes(timeSeparation);
if (dateTime.compareTo(now) > 0)
break;
}
break;
case GetHistoryEnergyDataRequest.GROUP_SPAN_DAY:
break;
case GetHistoryEnergyDataRequest.GROUP_SPAN_MONTH:
break;
case GetHistoryEnergyDataRequest.GROUP_SPAN_YEAR:
break;
}
return entries;
}
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null) {
FragmentManager fragmentManager = getFragmentManager();
if(fragmentManager != null)
previousFragment = getFragmentManager().getFragment(savedInstanceState,"chartPreviousFragment");
String json= savedInstanceState.getString("chart_data");
if(json != null && !json.isEmpty()) {
Gson gson = Converters.registerLocalDate(new GsonBuilder()).create();
chartData = gson.fromJson(json, ChartData.class);
if(previousFragment !=null && chartData != null)
drawChart(chartData, previousFragment);
}
}
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Gson gson = Converters.registerLocalDate(new GsonBuilder()).create();
String json= gson.toJson(chartData);
outState.putString("chart_data", json);
FragmentManager fragmentManager = getFragmentManager();
if(fragmentManager != null && previousFragment != null)
fragmentManager.putFragment(outState, "chartPreviousFragment", previousFragment);
}
}
<file_sep>/app/src/main/java/com/thaid/asylum/Blinds/BlindsFragment.java
package com.thaid.asylum.Blinds;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.thaid.asylum.R;
import com.thaid.asylum.api.APIClient;
import com.thaid.asylum.api.APIError;
import com.thaid.asylum.api.ResponseListener;
import com.thaid.asylum.api.requests.Blinds.BlindActionRequest;
import com.thaid.asylum.api.requests.Blinds.BlindAllActionRequest;
/**
* A simple {@link Fragment} subclass.
*/
public class BlindsFragment extends Fragment {
public static final Blind[] BLINDS = {
new Blind(-1, R.string.blind_all),
new Blind(0, R.string.blind_name_0),
new Blind(1, R.string.blind_name_1),
new Blind(2, R.string.blind_name_2),
new Blind(3, R.string.blind_name_3),
new Blind(4, R.string.blind_name_4),
new Blind(5, R.string.blind_name_5),
new Blind(6, R.string.blind_name_6),
new Blind(7, R.string.blind_name_7),
new Blind(8, R.string.blind_name_8)
};
public static final Action ACTION0 = new Action(0, R.string.action_name_0);
public static final Action ACTION1 = new Action(1, R.string.action_name_1);
public static final Action ACTION2 = new Action(2, R.string.action_name_2);
View root_view;
public BlindsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_blinds, container, false);
ListView blindsList = root_view.findViewById(R.id.listView);
BlindsAdapter blindsAdapter = new BlindsAdapter(this,root_view.getContext(), BlindsFragment.BLINDS);
blindsList.setAdapter(blindsAdapter);
return root_view;
}
public void setButtonListeners(FloatingActionButton buttonOpen,
FloatingActionButton buttonClose,
FloatingActionButton buttonStop,
final int i,
boolean allBlinds){
if(!allBlinds){
buttonOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
executeAction(new BlindAction(BLINDS[i], ACTION0));
}
});
buttonClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
executeAction(new BlindAction(BLINDS[i], ACTION1));
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
executeAction(new BlindAction(BLINDS[i], ACTION2));
}
});
}else{
buttonOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
executeActionForAllBlinds(ACTION0);
}
});
buttonClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
executeActionForAllBlinds(ACTION1);
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
executeActionForAllBlinds(ACTION2);
}
});
}
}
private void executeAction(final BlindAction blindAction){
APIClient apiClient = APIClient.getInstance();
apiClient.sendRequest(new BlindActionRequest(blindAction),
new ResponseListener<BlindActionRequest.NoDataOnResponseModel>() {
@Override
public void onSuccess(BlindActionRequest.NoDataOnResponseModel data) {
Snackbar snackbar = Snackbar.make(
root_view,
"Wykonano zadanie: " + getString(blindAction.getAction().getNameId()) + " " + getString(blindAction.getBlind().getNameId()),
Snackbar.LENGTH_LONG);
snackbar.show();
}
@Override
public void onError(APIError error) {
Snackbar snackbar = Snackbar
.make(root_view, getString(error.getTranslationId()) + " " + error.getMessage(), Snackbar.LENGTH_LONG);
snackbar.show();
}
});
}
private void executeActionForAllBlinds(final Action action){
APIClient apiClient = APIClient.getInstance();
apiClient.sendRequest(new BlindAllActionRequest(action),
new ResponseListener<BlindActionRequest.NoDataOnResponseModel>() {
@Override
public void onSuccess(BlindActionRequest.NoDataOnResponseModel data) {
Snackbar snackbar = Snackbar.make(
root_view,
"Wykonano zadanie: " + getString(action.getNameId()) + " " + getString(R.string.blind_all),
Snackbar.LENGTH_LONG);
snackbar.show();
}
@Override
public void onError(APIError error) {
Snackbar snackbar = Snackbar
.make(root_view, getString(error.getTranslationId()), Snackbar.LENGTH_LONG);
snackbar.show();
}
});
}
public static class Blind{
private int id;
private int nameId;
public Blind(int id, int nameId){
this.id = id;
this.nameId = nameId;
}
public int getId(){
return id;
}
public int getNameId(){
return nameId;
}
}
public static class Action{
private int id;
private int nameId;
public Action(int id, int nameId){
this.id = id;
this.nameId = nameId;
}
public int getId(){
return id;
}
public int getNameId(){
return nameId;
}
}
public class BlindAction{
private Blind blind;
private Action action;
public BlindAction(Blind blind, Action action){
this.blind = blind;
this.action = action;
}
public Blind getBlind(){
return blind;
}
public Action getAction(){
return action;
}
}
}
|
3d2c0a3497101d8a3887219b5fb9940c4e05ed8b
|
[
"Java"
] | 9 |
Java
|
xThaid/asylum-app
|
9f828eeaac24b62e0da0384778e6b49635305b52
|
2a3c7997abe40a38e597a6d86226b51401e1a9db
|
refs/heads/master
|
<file_sep>'use strict';
const {avatar} = require('../utils');
const validator = require('validator');
const timeago = require('timeago.js');
describe('Utils Tests', () => {
it('should return a valid URL', () => {
const str = avatar('<EMAIL>');
expect(validator.isURL(str)).toBe(true);
});
it('should return a valid Gravatar URL', () => {
const str = avatar('<EMAIL>');
expect(/[a-z0-9]\.jpg$/i.test(str)).toBe(true);
});
it('checks if relative timestamps are displayed correctly', () => {
const now = Date.now();
const oneMinAgo = now - ( 1000 * 60 );
const time = new Date(oneMinAgo);
const str = timeago.format(time);
expect(str.toLowerCase()).toEqual('1 minute ago');
});
});<file_sep>'use strict';
const displayTime = timestamp => {
const time = new Date(parseInt(timestamp, 10));
return timeago.format(time);
};
const displayMessage = ({ target, type, text}) => {
const msg = document.createElement('div');
msg.className = `alert alert-${type} mt-5 mb-5`;
msg.innerText = text;
target.appendChild(msg);
};
const stripTags = input => {
const tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi
const commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi
return input.replace(commentsAndPhpTags, '').replace(tags, '');
};
const postData = async ({url, data}) => {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type' : 'application/json'
}
});
return await response.json();
};
const scrollIntoView = element => {
setTimeout(() => {
element.scrollTop = ( element.scrollHeight - element.clientHeight );
}, 500);
};
const addMobileClass = element => {
if(/mobile/i.test(navigator.userAgent)) {
element.classList.add('mobile');
}
};<file_sep>'use strict';
const WebSocket = require('ws');
class ChatSocket {
constructor({chatServer, port}) {
this.chatServer = chatServer;
this.wss = new WebSocket.Server({ port: port });
this.onConnection();
}
onConnection() {
this.wss.on('connection', ws => {
this.onMessage(ws);
});
}
onMessage(wsInstance) {
const self = this;
wsInstance.on('message', function incoming(data) {
switch(data) {
case 'messages':
self.broadcastData(JSON.stringify({ method: 'getMessages' }));
break;
case 'info':
self.broadcastData(JSON.stringify({ method: 'getInfo' }));
break;
default:
break;
}
});
}
broadcastData(data) {
this.wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
}
}
module.exports = ChatSocket;<file_sep>'use strict';
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const redis = require('redis');
const port = process.env.PORT || 3000;
const ChatServer = require('./classes/ChatServer');
const ChatSocket = require('./classes/ChatSocket');
const chat = new ChatServer(redis);
const chatSocket = new ChatSocket({
chatServer: chat,
port: 8080
});
app.disable('x-powered-by');
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html');
});
app.post('/api/join', (req, res) => { chat.join(req, res); });
app.post('/api/leave', (req, res) => { chat.leave(req, res); });
app.post('/api/send', (req, res) => { chat.send(req, res); });
app.get('/api/messages', (req, res) => { chat.getMessages(req, res); });
app.get('/api/users', (req, res) => { chat.getUsers(req, res); });
app.listen(port);<file_sep># Chat with Redis and ExpressJS
If you experience problems with Redis default authentication and password when you start the Redis server on your local machine,
open your main Redis .conf file and comment the line with `requirepass`.
<file_sep>'use strict';
class ChatClient {
constructor() {
this.socket = new WebSocket('ws://127.0.0.1:8080');
this.info = document.querySelector('#chat-info');
this.joinForm = document.querySelector('#chat-join');
this.userCount = 0;
this.chatWrap = document.querySelector('#chat-wrap');
this.chatMessages = document.querySelector('#chat-messages');
this.sendMessageBtn = document.querySelector('#send-message');
this.leaveChatBtn = document.querySelector('#leave-chat');
this.chatActions = document.querySelector('#chat-actions');
this.chatWrapper = document.querySelector('#chat-wrapper');
this.toggleChatBtn = document.querySelector('#chat-toggle');
this.chatCloseBtn = document.querySelector('#chat-close');
if(sessionStorage.getItem('username') !== null) {
this.socket.onopen = e => {
this.toggleChat();
this.chatWrapper.classList.add('in');
scrollIntoView(this.chatMessages);
};
}
this.openClose();
this.getInfo();
this.joinChat();
this.sendMessage();
this.leaveChat();
this.ws();
addMobileClass(document.body);
}
openClose() {
this.toggleChatBtn.addEventListener('click', e => {
e.preventDefault();
this.chatWrapper.classList.add('in');
}, false);
this.chatCloseBtn.addEventListener('click', e => {
e.preventDefault();
this.chatWrapper.classList.remove('in');
}, false);
}
ws() {
this.socket.onmessage = async message => {
const response = JSON.parse(message.data);
const {method} = response;
await this[method]();
};
}
async getInfo() {
const response = await fetch('/api/users');
const users = await response.json();
if(Array.isArray(users)) {
const total = users.length;
if(sessionStorage.getItem('username') !== null && total > 0) {
const currentUser = sessionStorage.getItem('username');
const onlineUsers = users.filter(user => user !== currentUser);
if(onlineUsers.length > 0) {
const online = onlineUsers.length;
this.info.innerText = `There are ${online} users online`;
}
}
this.userCount = total;
}
}
async getMessages() {
const response = await fetch('/api/messages');
const messages = await response.json();
if(Array.isArray(messages) && messages.length > 0) {
let html = '';
for(const message of messages) {
let avatar = (message.avatarImg.length > 0) ? message.avatarImg : '/public/images/avatar.png';
let time = displayTime(message.time);
let str = `<blockquote>
<img class="avatar" src="${avatar}">
<div>
<cite>${message.username}</cite>
<time>${time}</time>
</div>
<p>${message.message}</p>
</blockquote>`;
html += str;
}
this.chatMessages.innerHTML = html;
}
}
async postMessage() {
const msg = document.querySelector('#message').value;
if(msg.length > 0 && !/^\s+$/.test(msg)) {
const data = {
username: sessionStorage.getItem('username'),
message: stripTags(msg)
};
await postData({url: '/api/send', data});
this.socket.send('messages');
}
}
sendMessage() {
document.querySelector('#message').addEventListener('keydown', async e => {
const keyPressed = e.key;
if(keyPressed === 'Enter') {
e.preventDefault();
await this.postMessage();
scrollIntoView(this.chatMessages);
}
}, false);
}
joinChat() {
let self = this;
this.joinForm.addEventListener('submit', async e => {
e.preventDefault();
const username = stripTags(document.querySelector('#username').value);
const msgs = self.joinForm.querySelectorAll('.alert');
if(msgs.length > 0) {
msgs.forEach(message => {
self.joinForm.removeChild(message);
});
}
if(username.length > 0) {
try {
const response = await postData({ url: '/api/join', data: { username } } );
if(response.error) {
displayMessage({
target: this.joinForm,
type: 'danger',
text: response.error
});
} else {
this.toggleChat(username);
this.socket.send('info');
}
} catch(err) {
displayMessage({
target: this.joinForm,
type: 'danger',
text: JSON.stringify(err)
});
}
} else {
displayMessage({
target: this.joinForm,
type: 'danger',
text: 'Invalid username.'
});
}
}, false);
}
leaveChat() {
this.leaveChatBtn.addEventListener('click', async e => {
e.preventDefault();
const username = sessionStorage.getItem('username');
await postData({url: '/api/leave', username});
sessionStorage.removeItem('username');
this.chatWrap.classList.toggle('d-none');
this.joinForm.classList.remove('d-none');
this.socket.send('info');
}, false);
}
toggleChat(username = '') {
if(username.length > 0) {
sessionStorage.setItem('username', username);
}
if(this.socket.readyState === 1) {
this.socket.send('messages');
}
this.chatWrap.classList.toggle('d-none');
this.joinForm.classList.add('d-none');
}
}
document.addEventListener('DOMContentLoaded', () => {
const client = new ChatClient();
});<file_sep>'use strict';
const {avatar} = require('../utils');
const validator = require('validator');
class ChatServer {
constructor(pubSubLib) {
this.pubSubLib = pubSubLib;
this.client = pubSubLib.createClient();
this.users = [];
this.messages = [];
this.init();
}
init() {
let self = this;
self.client.once('ready', () => {
self.client.flushdb();
self.client.get('users', (err, reply) => {
if (reply) {
self.users = JSON.parse(reply);
}
});
self.client.get('messages', (err, reply) => {
if (reply) {
self.messages = JSON.parse(reply);
}
});
});
}
join(req, res) {
const {username} = req.body;
if (!this.users.includes(username)) {
this.users.push(username);
this.client.set('users', JSON.stringify(this.users));
res.send({
users: this.users
});
} else {
res.send({
error: 'Already joined.'
});
}
}
leave(req, res) {
const {username} = req.body;
this.users.splice(this.users.indexOf(username), 1);
this.client.set('users', JSON.stringify(this.users));
res.send({
done: true
});
}
send(req, res) {
const {username, message} = req.body;
const time = Date.now();
const avatarImg = (validator.isEmail(username)) ? avatar(username) : '';
this.messages.push({
username,
message,
time,
avatarImg
});
this.client.set('messages', JSON.stringify(this.messages));
res.send({
done: true
});
}
getMessages(req, res) {
res.send(this.messages);
}
getUsers(req, res) {
res.send(this.users);
}
}
module.exports = ChatServer;
|
16d2151bfc0be2ab371e6aec3d4422a41f30d1d2
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
deepakverma91123/expressjs-redis-chat
|
6641737fd85484801587c0819dcefd30db1e6f7f
|
e6727886ec7f40b5edfad577e867e8d5cd720fb8
|
refs/heads/master
|
<repo_name>BrianNewsom/api-hackathon<file_sep>/contents/userComments/index.js
var userComments = {
load: function() {
$.get("/api-hackathon/userComments/ui.jade", function(template) {
var html = jade.render(template)
$("#ui").html(html)
})
/*
// default search results
legislators.searchByChamber('senate')
*/
},
searchByName: function(username) {
$.get('https://enigmatic-basin-9438.herokuapp.com/user/' + username, function(data){
console.log(data);
var c = data.data.children[0].data.body;
$.get('https://enigmatic-basin-9438.herokuapp.com/sentiment/' + c.replace(/[&\/\\#,+()$~%.'":*?<>{}"']/g,'_'), function(data){
$.get("/api-hackathon/userComments/list.jade", function(template){
var html = jade.render(template, {comment : c, sentiment: data});
$("#list").html(html);
})
})
});
}
}
<file_sep>/contents/query/index.js
var query = {
load: function() {
$.get("/api-hackathon/query/ui.jade", function(template) {
var html = jade.render(template)
$("#ui").html(html)
})
query.search()
},
search : function(term) {
$.get("https://enigmatic-basin-9438.herokuapp.com/sentiment/" + term, function(data){
console.log('got' + data)
data = data.body
if(data.result){
$.get("/api-hackathon/query/list.jade", function(template){
var html = jade.render(template, {
data: data
})
console.log(html)
$("#list").html(html)
})
}
})
}
}
<file_sep>/contents/top/index.js
var topa = {
load: function() {
$.get("/api-hackathon/top/ui.jade", function(template) {
var html = jade.render(template)
$("#ui").html(html)
})
},
go: function() {
$.get("https://enigmatic-basin-9438.herokuapp.com/list/top", function(data){
var topTitle = data.data.children[0].data.title
$.get("https://enigmatic-basin-9438.herokuapp.com/sentiment/" + topTitle, function(sentiment){
$.get("/api-hackathon/top/list.jade", function(template){
var html = jade.render(template, {title: topTitle, sentiment: sentiment.body})
$("#list").html(html);
})
})
})
}
}
<file_sep>/contents/subReddit/index.js
var subReddit = {
load: function() {
$.get("/api-hackathon/subReddit/ui.jade", function(template) {
var html = jade.render(template)
$("#ui").html(html)
})
/*
// default search results
legislators.searchByChamber('senate')
*/
},
searchByName: function(subreddit){
$.get('https://enigmatic-basin-9438.herokuapp.com/r/' + subreddit, function(data){
var title = data.data.children[0].data.title;
$.get("https://enigmatic-basin-9438.herokuapp.com/sentiment/" + title, function(sentiment){
var sentiment = sentiment.body
$.get('/api-hackathon/subReddit/list.jade', function(template){
var html = jade.render(template, {title : title, sentiment: sentiment});
$("#list").html(html);
})
})
});
}
}
<file_sep>/contents/index.md
---
title: Congress
template: layout.jade
---
|
8ae5799da80c4c9452e516e9beec73348efcd530
|
[
"JavaScript",
"Markdown"
] | 5 |
JavaScript
|
BrianNewsom/api-hackathon
|
88c1a23b8175ec10a6c9f01cb75c0b1fac9307b5
|
e5fc05b6a7ce4c9564302d64be46e85c866d1ca3
|
refs/heads/master
|
<file_sep>package dbhandler
// TODO<file_sep>
package dbhandler
import (
"database/sql"
"errors"
_ "github.com/lib/pq" // postgres
_ "github.com/go-sql-driver/mysql" // mysql
"encoding/json"
"os"
"fmt"
)
var (
// DBTYPE can be mysql or postgres but only mysql implemented for nwo
//DBTYPE = "mysql" // [postgres || mysql]
// DBURL is the connection string used to open sql session
//DBURL string
)
// DBInstance manages the sql session
type DBInstance struct {
SQLSession *sql.DB
MysqlEnv VCAPServicesMySQL
DBTYPE string
DBURL string
}
// NewDBI creates a new DBInstance struct and return it to caller
// caller is expected to close the database instance dbi.Close()
func NewDBI(dbtype string) (*DBInstance, error) {
dbi := new(DBInstance)
dbi.DBTYPE = dbtype
dbi.parseEnv()
err := dbi.ConnectDB()
if err != nil {
return nil, err
}
return dbi, nil
}
// newMockDBI used for testing purposes
func newMockDBI(dbtype, dburl string) (*DBInstance, error) {
dbi := new(DBInstance)
dbi.DBTYPE = dbtype
dbi.DBURL = dburl
err := dbi.ConnectDB()
if err != nil {
return nil, err
}
return dbi, nil
}
// ConnectDB creates a new database session. Caller needs to call Close() when done
func (dbi *DBInstance) ConnectDB() error {
sess, err := sql.Open(dbi.DBTYPE, dbi.DBURL)
if err != nil {
return errors.New("can not connect to database: " + err.Error())
}
dbi.SQLSession = sess
dbi.SQLSession.SetMaxOpenConns(1) // make sure there is only one session open with database at a time
return nil
}
// parseEnv for vcap services
// TODO add postgres support
func (dbi *DBInstance)parseEnv() {
switch {
case dbi.DBTYPE == "mysql":
VCAP := VCAPServicesMySQL{}
setEnv(&VCAP)
if len(VCAP.MySQL) > 0{
dbi.DBURL = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s",
VCAP.MySQL[0].Credentials.Username,
VCAP.MySQL[0].Credentials.Password,
VCAP.MySQL[0].Credentials.Hostname,
VCAP.MySQL[0].Credentials.Port,
VCAP.MySQL[0].Credentials.Name)
}
}
}
// parse VCAP_SERVICES environment into struct pointer
func setEnv(d interface{}) {
VCAP := os.Getenv("VCAP_SERVICES")
if VCAP == "" {
return // no environment found so use whatever DBURL is set to
}
b := []byte(VCAP)
err := json.Unmarshal(b, d)
if err != nil {
fmt.Printf("dbhandler:setEnv:ERROR:%s", err)
}
}
// Close the database session
func (dbi *DBInstance) Close() error {
if dbi.SQLSession != nil {
err := dbi.SQLSession.Close()
if err != nil {
return errors.New("can not close libpq session: " + err.Error())
}
}
return nil
}
/*####################################################################*/
/*
QUERY FUNCTIONS
*/
// GetRowSet returns row set from query and expects caller to handle error like sql.ErrNoRows
func (dbi *DBInstance) GetRowSet(qstring string) (*sql.Rows, error) {
return dbi.SQLSession.Query(qstring)
}
// GetStringList returns string slice from rowset
func (dbi *DBInstance) GetStringList(qstring string) ([]string, error) {
var result []string
result = make([]string, 0)
rows, err := dbi.GetRowSet(qstring)
if err != nil {
return result, err
}
for rows.Next() {
var s string
err := rows.Scan(&s)
if err != nil {
return result, err
}
result = append(result, s)
}
return result, nil
}
// GetIntList returns int slice from rowset
func (dbi *DBInstance) GetIntList(qstring string) ([]int, error) {
var result []int
result = make([]int, 0)
rows, err := dbi.GetRowSet(qstring)
if err != nil {
return result, err
}
for rows.Next() {
var s int
err := rows.Scan(&s)
if err != nil {
return result, err
}
result = append(result, s)
}
return result, nil
}
// GetIntValue Assumed single row/column query result of integer type and returns that value
func (dbi *DBInstance) GetIntValue(qstring string) (int, error) {
var v int
err := dbi.SQLSession.QueryRow(qstring).Scan(&v)
if err != nil {
return v, err
}
return v, nil
}
// GetStringValue Assumed single row/column query result of string type and returns that value
func (dbi *DBInstance) GetStringValue(qstring string) (string, error) {
var v string
err := dbi.SQLSession.QueryRow(qstring).Scan(&v)
if err != nil {
return v, err
}
return v, nil
}
<file_sep>export MOCKDBURLPROTO="root:changeme@tcp(192.168.64.101:3306)/"
export MOCKDB="cf_test_db"
export VCAP_SERVICES=$(cat << EndOfMessage
{
"p-mysql": [
{
"credentials": {
"hostname": "192.168.64.101",
"port": 3306,
"name": "cf_test_db",
"username": "root",
"password": "<PASSWORD>",
"uri": "mysql://root:[email protected]:3306/cf_test_db?reconnect=true",
"jdbcUrl": "jdbc:mysql://proxy.domain.io:3306/cf_xxx_xxx?user=user&password=<PASSWORD>"
},
"syslog_drain_url": null,
"volume_mounts": [],
"label": "mysql",
"provider": null,
"plan": "100mb",
"name": "service-instance-name",
"tags": [
"mysql"
]
}
]
}
EndOfMessage
)<file_sep># Package dbhandler
mysql or postgres drivers that will parse VCAP_SERVICES and connect to database
<file_sep>package dbhandler
import(
"testing"
"os"
"database/sql"
"fmt"
"strings"
)
var (
MockDBURLProto string
MockDB string
MockDBType = "mysql"
)
func init() {
MockDBURLProto = os.Getenv("MOCKDBURLPROTO")
MockDB = os.Getenv("MOCKDB")
MockCreateDatabase()
}
func MockCreateDatabase() {
noDBURL := strings.Replace(MockDBURLProto, MockDB, "", 1)
dbi, err := newMockDBI(MockDBType, noDBURL)
if err != nil {
fmt.Printf("DB create failed: %s\n", err)
os.Exit(1)
}
defer dbi.Close()
// check if db exists
dbname, err := dbi.GetStringValue(fmt.Sprintf("SHOW DATABASES LIKE '%s'", MockDB))
if err != nil && err != sql.ErrNoRows {
fmt.Printf("query for exiting db failed: %s\n", err)
os.Exit(1)
}
if dbname == MockDB {
return // db exists so return
}
_, err = dbi.SQLSession.Exec(fmt.Sprintf("CREATE DATABASE %s", MockDB))
if err != nil {
fmt.Printf("Creating database failed: %s\n", err)
os.Exit(1)
}
}
func TestParseEnv(t *testing.T) {
dbi, err := NewDBI(MockDBType)
if err != nil {
t.Fatal(err)
}
defer dbi.Close()
_, err = dbi.SQLSession.Exec("SHOW DATABASES")
if err != nil {
t.Fatal(err)
}
}<file_sep>package dbhandler
// VCAPServicesMySQL CF mysql service environemnt variables
/*"VCAP_SERVICES": {
"p-mysql": [
{
"credentials": {
"hostname": "proxy.domain.io",
"port": 3306,
"name": "cf_xxx_xxx",
"username": "user",
"password": "<PASSWORD>",
"uri": "mysql://user:[email protected]:3306/cf_xxx_xxx?reconnect=true",
"jdbcUrl": "jdbc:mysql://proxy.domain.io:3306/cf_xxx_xxx?user=user&password=<PASSWORD>"
},
"syslog_drain_url": null,
"volume_mounts": [],
"label": "mysql",
"provider": null,
"plan": "100mb",
"name": "service-instance-name",
"tags": [
"mysql"
]
}
]
}
*/
type VCAPServicesMySQL struct {
MySQL []MySQLInstance `json:"p-mysql"`
}
// MySQLInstance has the vcap service credentials for the given mysql instance
type MySQLInstance struct {
Credentials MySQLCredentials `json:"credentials"`
}
// MySQLCredentials defines the vcap server credentails for mysql
type MySQLCredentials struct {
Hostname string `json:"hostname"`
Port int `json:"port"`
Name string `json:"name"`
Username string `json:"username"`
Password string `json:"<PASSWORD>"`
URI string `json:"uri"`
JDBCUrl string `json:"jdbcUrl"`
}
|
9d72ba04f60941442a06b44ff1b24f54c940f560
|
[
"Markdown",
"Go",
"Shell"
] | 6 |
Go
|
randomtask1155/dbhandler
|
72669c52b122024bcab37847dbda8855008b5ba1
|
5cfdd321c842d9852ca85fa6ffd9e2d270251644
|
refs/heads/master
|
<file_sep># BaseReductor
This is a filter plugin for the [Glyphs font editor](http://glyphsapp.com/). After installation, it will add the menu item *Filter > BaseReductor.* You can set a keyboard shortcut in System Preferences. The filter will reduce diacritics to their base glyphs, e.g. `äáàāą` will appear as `aaaa`. This can be useful for trial fonts.
This image best describes the before/after effect of BaseReductor:

### Installation
1. One-click install *BaseReductor* from *Window > Plugin Manager*
2. Restart Glyphs.
### Usage Instructions
1. Select any number of (compound diacritic) glyphs in Font view or Edit view.
2. Run *Filter > BaseReductor* to rid all your compounds of their accents.
### License
Copyright 2019 <NAME> (@mekkablue), after an idea by <NAME> (@grillitype).
Based on sample code by <NAME> (@schriftgestalt) and <NAME> (@yanone).
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
See the License file included in this repository for further details.
<file_sep># encoding: utf-8
from __future__ import division, print_function, unicode_literals
import objc
from GlyphsApp import *
from GlyphsApp.plugins import *
excludeDict = {
"idotless": "i",
"jdotless": "j",
}
specialDict = {
"AE": ("A", "E",),
"OE": ("O", "E",),
"ae": ("a", "e",),
"oe": ("o", "e",),
"Eng": ("N",),
"eng": ("n",),
"napostrophe": ("n",),
"kgreenlandic": ("k",),
"thorn": ("p",),
"Thorn": ("P",),
"IJ": ("I", "J",),
"ij": ("i", "j",),
"idotless": ("i",),
"jdotless": ("j",),
"dotlessi": ("i",),
"dotlessj": ("j",),
}
class BaseReductor(FilterWithoutDialog):
@objc.python_method
def settings(self):
self.menuName = Glyphs.localize({
'en': 'Base Reductor',
'de': 'Basis-Reduktor',
'fr': 'Réducteur à base',
'es': 'Reductor a la base',
})
self.keyboardShortcut = None # With Cmd+Shift
@objc.python_method
def nameWithoutSuffix(self, glyphName):
if "." in glyphName:
dotOffset = glyphName.find(".")
return glyphName[:dotOffset]
else:
return glyphName
@objc.python_method
def filter(self, Layer, inEditView, customParameters):
glyph = Layer.parent
font = glyph.parent
# check for specials
specialNamesToCheck = [glyph.name,]
if "." in glyph.name:
specialNamesToCheck.append( self.nameWithoutSuffix(glyph.name) )
for specialName in specialNamesToCheck:
if specialName in specialDict:
allSpecialComponentsInFont = True
for specialComponent in specialDict[specialName]:
if not font[specialComponent]:
allSpecialComponentsInFont = False
if not allSpecialComponentsInFont:
print("🔥 Base Reductor: Not all parts available for: %s" % specialName)
else:
Layer.clear()
for basename in specialDict[specialName]:
base = GSComponent(basename)
try:
# GLYPHS 3
Layer.shapes.append(base)
except:
# GLYPHS 2
Layer.components.append(base)
return None
if glyph.category =="Letter" and glyph.subCategory != "Ligature":
glyphInfo = glyph.glyphInfo
if not glyphInfo:
print("🔥 Base Reductor: no glyph info: %s" % glyph.name)
elif glyphInfo.components:
basename = glyphInfo.components[0].name
# i -> idotless, j -> jdotless
if basename in excludeDict:
oldBasename = basename
basename = excludeDict[basename]
# print("🔄 Base Reductor %s: Will use %s instead of %s." % (glyph.name, oldBasename, basename))
# look if glyph exists:
if not font.glyphs[basename] and font.glyphs[self.nameWithoutSuffix(basename)]:
basename = self.nameWithoutSuffix(basename)
if font.glyphs[basename]:
if basename != glyph.name:
Layer.clear()
base = GSComponent(basename)
try:
# GLYPHS 3
Layer.shapes.append(base)
except:
# GLYPHS 2
Layer.components.append(base)
else:
Layer.decomposeComponents() # do not let i/j reference itself
else:
print("❌ Base Reductor: no base glyph (%s) in font for: %s" % (basename, glyph.name))
else:
pass
# print("⚠️ Base Reductor: no components in glyph info: %s" % glyph.name)
else:
pass
# print("💚 Base Reductor: %s left unchanged" % glyph.name)
@objc.python_method
def __file__(self):
"""Please leave this method unchanged"""
return __file__
|
f7ff123f2ec3c7328fa7f5ce0111cf77acac7127
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
mekkablue/BaseReductor
|
ffcafd500ce9a28f14c477699783fd4c1158ac2e
|
8ff4fb197d58f561803cbd62a51ca2a02631230c
|
refs/heads/master
|
<repo_name>purplefeetguy/azure-pfllab<file_sep>/chef-starter/chef-repo/.chef/knife.rb
# See https://docs.getchef.com/config_rb_knife.html for more information on knife configuration options
current_dir = File.dirname(__FILE__)
log_level :info
log_location STDOUT
node_name "purplefeetguy"
client_key "#{current_dir}/purplefeetguy.pem"
validation_client_name "cheflab-validator"
validation_key "#{current_dir}/cheflab-validator.pem"
chef_server_url "https://chef-server.3xhdskl1vufehjrx2ofoa1lieb.gx.internal.cloudapp.net/organizations/cheflab"
cookbook_path ["#{current_dir}/../cookbooks"]
<file_sep>/README.md
# azure-pfllab
Purplefeet Labs Sandbox on Azure
|
4734aa7554991314c84c31d75e2f7b0c29057f8b
|
[
"Markdown",
"Ruby"
] | 2 |
Ruby
|
purplefeetguy/azure-pfllab
|
d1b17bad86c2eccc48451d3b125fc22378f6d8e7
|
c84dd7751b8d5ac1a18efde861f8b5c39307ab63
|
refs/heads/master
|
<repo_name>Simokod/ArchieLab6<file_sep>/Lab6/Task2/makefile
all: mypipeline
mypipeline: mypipeline.o
gcc -g -W -m32 mypipeline.o -o mypipeline
mypipeline.o: mypipeline.c
gcc -g -Wall -m32 -c mypipeline.c -o mypipeline.o
.PHONY: clean
clean:
rm -f *.o mypipeline<file_sep>/Lab6/Task2/mypipeline.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <linux/limits.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
int main(int argc, char **argv) {
char *ls_args[3], *tail_args[4];
int pid1, pid2, i, new_out_fd, new_in_fd, pipefd[2], debug_mode = 0;
FILE *write_file, *read_file;
for(i=1;i<argc;i++) {
if(strcmp(argv[i], "-D") == 0)
debug_mode = 1;
}
pipe(pipefd);
write_file = fdopen(pipefd[1], "w");
read_file = fdopen(pipefd[0], "r");
if(debug_mode){
fprintf(stderr, "(parent_process>forking…)\n");
}
if(!(pid1 = fork())){
if(debug_mode){
fprintf(stderr, "(child1>redirecting stdout to the write end of the pipe…)\n");
}
fclose(stdout);
new_out_fd = dup(pipefd[1]);
fclose(write_file);
if(debug_mode){
fprintf(stderr, "(child1>going to execute cmd: ls)\n");
}
ls_args[0] = "ls";
ls_args[1] = "-l";
ls_args[2] = NULL;
if(execvp(ls_args[0], ls_args) == -1){
perror("cmd ls");
exit(1);
}
}
else{
if(debug_mode){
fprintf(stderr, "(parent_process>created process with id: %d)\n", pid1);
fprintf(stderr, "(parent_process>closing the write end of the pipe…)\n");
}
fclose(write_file);
if(!(pid2 = fork())){
if(debug_mode){
fprintf(stderr, "(child2>redirecting stdin to the read end of the pipe…)\n");
}
fclose(stdin);
new_in_fd = dup(pipefd[0]);
fclose(read_file);
if(debug_mode){
fprintf(stderr, "(child2>going to execute cmd: tail)\n");
}
tail_args[0] = "tail";
tail_args[1] = "-n";
tail_args[2] = "2";
tail_args[3] = NULL;
if(execvp(tail_args[0], tail_args) == -1){
perror("cmd tail");
exit(1);
}
}
else{
if(debug_mode){
fprintf(stderr, "(parent_process>created process with id: %d)\n", pid2);
fprintf(stderr, "(parent_process>closing the read end of the pipe…)\n");
}
fclose(read_file);
if(debug_mode)
fprintf(stderr, "(parent_process>waiting for child 1 processes to terminate)\n");
waitpid(pid1, NULL, 0);
if(debug_mode)
fprintf(stderr, "(parent_process>waiting for child 2 processes to terminate)\n");
waitpid(pid2, NULL, 0);
if(debug_mode)
fprintf(stderr, "(parent_process>exiting)\n");
exit(0);
}
}
}<file_sep>/Lab6/Task4/myshell.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "LineParser.h"
#include <linux/limits.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
typedef struct var{
cmdLine *cmd;
char *name;
char *value;
struct var *next;
} var;
typedef struct process{
cmdLine* cmd; /* the parsed command line*/
pid_t pid; /* the process id that is running the command*/
int status; /* status of the process: RUNNING/SUSPENDED/TERMINATED */
struct process *next; /* next process in chain */
} process;
// receives a parsed line and invokes the program specified in the cmdLine using execv
void execute(cmdLine *pCmdLine){
if(pCmdLine->inputRedirect){
fclose(stdin);
fopen(pCmdLine->inputRedirect, "r");
}
if(pCmdLine->outputRedirect){
fclose(stdout);
fopen(pCmdLine->outputRedirect, "w");
}
if(execvp(pCmdLine->arguments[0], pCmdLine->arguments) == -1){
printf("%s\n", pCmdLine->arguments[0]);
perror("execv error");
exit(1);
}
}
void change_dir(cmdLine *pCmdLine){
char *path_name;
if(pCmdLine->argCount != 2){
fprintf(stderr, "wrong args\n");
return;
}
path_name = pCmdLine->arguments[1];
if(strcmp(path_name, "~") == 0)
path_name = getenv("HOME");
if(chdir(path_name) == -1)
perror("cd error");
}
void set_var(cmdLine *pCmdLine, var **var_list){
var *last_var = NULL;
var *new_var = malloc(sizeof(var));
new_var->name = pCmdLine->arguments[1];
new_var->value = pCmdLine->arguments[2];
new_var->cmd = pCmdLine;
new_var->next = NULL;
if(*var_list == NULL){ // var_list is empty
*var_list = new_var;
return;
}
var *cur_var = *var_list;
while(cur_var != NULL) // searching in var_list if the new var exists
if(strcmp(cur_var->name, pCmdLine->arguments[1]) == 0) {
new_var->next = cur_var->next;
freeCmdLines(cur_var->cmd);
free(cur_var);
if(last_var == NULL)
*var_list = new_var;
else
last_var->next = new_var;
return;
}
else{
last_var = cur_var;
cur_var = cur_var->next;
}
// new_var doesn't exist, adding it to the var_list
last_var->next = new_var;
}
void free_var_list(var *var_list){
if(var_list){
free_var_list(var_list->next);
freeCmdLines(var_list->cmd);
free(var_list);
}
}
void print_vars(var *var_list){
if(var_list){
printf("var: %s, val: %s\n", var_list->name, var_list->value);
print_vars(var_list->next);
}
}
void delete_var(cmdLine *pCmdLine, var **var_list){
var *prev_var = NULL, *cur_var = *var_list;
while(cur_var != NULL){
if(strcmp(pCmdLine->arguments[1], cur_var->name) == 0){
if(prev_var == NULL)
*var_list = cur_var->next;
else
prev_var->next = cur_var->next;
freeCmdLines(cur_var->cmd);
free(cur_var);
return;
}
prev_var = cur_var;
cur_var = cur_var->next;
}
fprintf(stderr, "no such variable\n");
}
int find_var(char *var_name, var **var_list){
var *curr_var = *var_list;
while(curr_var != NULL){
if(strcmp(curr_var->name, var_name) == 0)
return 1;
curr_var = curr_var->next;
}
return 0;
}
char *get_var(char *var_name, var **var_list){
var *curr_var = *var_list;
while(curr_var != NULL){
if(strcmp(curr_var->name, var_name) == 0)
return curr_var->value;
curr_var = curr_var->next;
}
return var_name;
}
void replace_vars(cmdLine *pCmdLine, var **var_list){
int i;
while(pCmdLine != NULL){
for(i=1;i<pCmdLine->argCount;i++){
if(pCmdLine->arguments[i][0] == '$'){
if(find_var(&(pCmdLine->arguments[i][1]), var_list))
replaceCmdArg(pCmdLine, i, get_var(&(pCmdLine->arguments[i][1]), var_list));
else
fprintf(stderr, "var doesn't exist\n");
}
}
pCmdLine = pCmdLine->next;
}
}
// converts input string to number for switch case
int get_command_num(char *input){
if(strcmp(input, "quit") == 0)
return 1;
if(strcmp(input, "cd") == 0)
return 2;
if(strcmp(input, "set") == 0)
return 3;
if(strcmp(input, "vars") == 0)
return 4;
if(strcmp(input, "delete") == 0)
return 5;
return 0;
}
int main(int argc, char **argv) {
char buffer[PATH_MAX], input[2048];
char *prompt_str = buffer;
int pid1, pid2, i, debug_mode = 0, pipefd[2];
cmdLine *pCmdLine;
FILE *write_file, *read_file;
var **var_list;
var_list = malloc (sizeof(int)); // mallocating memory for first pointer
for(i=1;i<argc;i++) {
if(strcmp(argv[i], "-D") == 0)
debug_mode = 1;
}
while(1) {
prompt_str = getcwd(prompt_str, PATH_MAX);
printf("%s> ", prompt_str);
fgets(input, 2048, stdin);
pCmdLine = parseCmdLines(input);
switch (get_command_num(pCmdLine->arguments[0])){
case 1: // quit
freeCmdLines(pCmdLine);
free_var_list(*var_list);
free(var_list);
exit(0);
case 2: // cd
change_dir(pCmdLine);
freeCmdLines(pCmdLine);
break;
case 3: // set
set_var(pCmdLine, var_list);
break;
case 4: // vars
print_vars(*var_list);
freeCmdLines(pCmdLine);
break;
case 5:
delete_var(pCmdLine, var_list);
freeCmdLines(pCmdLine);
break;
default:
replace_vars(pCmdLine, var_list);
if(pCmdLine->next){ // handling pipe
pipe(pipefd);
write_file = fdopen(pipefd[1], "w");
read_file = fdopen(pipefd[0], "r");
if(!(pid1 = fork())){
fclose(stdout);
dup(pipefd[1]);
fclose(write_file);
execute(pCmdLine);
}
fclose(write_file);
if(!(pid2 = fork())){
fclose(stdin);
dup(pipefd[0]);
fclose(read_file);
execute(pCmdLine->next);
}
fclose(read_file);
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
}
else{ // normal command
if(!(pid1=fork())){
if(debug_mode){
fprintf(stderr, "PID: %d\n", pid1);
fprintf(stderr, "Executing command: %s\n", pCmdLine->arguments[0]);
}
execute(pCmdLine);
freeCmdLines(pCmdLine);
exit(1);
}
if(pCmdLine->blocking)
waitpid(pid1, NULL, 0);
}
freeCmdLines(pCmdLine);
break;
}
}
}
|
0bf4e28dfeb59f83a459fd1fb7a6af05f087a313
|
[
"C",
"Makefile"
] | 3 |
Makefile
|
Simokod/ArchieLab6
|
873d35c4c526092917e82fe96f158c8f6914c629
|
3c8fc7c457ea5567448ca945b5897c246f0d8901
|
refs/heads/master
|
<file_sep>using System.IO;
using System.Web.Hosting;
using System.Web.Mvc;
namespace Frapid.Dashboard.Controllers
{
public class DashboardController : BackendController
{
private static readonly string LandingPage = "~/Areas/Frapid.Dashboard/Views/Default/LandingPage.cshtml";
private string GetLayoutFile()
{
string theme = Configuration.GetDefaultTheme(this.Tenant);
return ThemeConfiguration.GetLayout(this.Tenant, theme);
}
private string GetLayoutPath()
{
string layout = Configuration.GetCurrentThemePath(this.Tenant);
string layoutDirectory = HostingEnvironment.MapPath(layout);
if (layoutDirectory != null && Directory.Exists(layoutDirectory))
{
return layout;
}
return null;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
this.ViewBag.LayoutPath = this.GetLayoutPath();
this.ViewBag.LayoutFile = this.GetLayoutFile();
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
this.ViewBag.Layout = this.ViewBag.LayoutPath + this.ViewBag.LayoutFile;
}
}
protected ContentResult FrapidView(string path, object model = null)
{
return this.View(this.HttpContext.Request.IsAjaxRequest() ? path : LandingPage, model);
}
}
}<file_sep>using System.IO;
using Frapid.Configuration;
namespace Frapid.Reports.Models
{
public sealed class ReportLocator
{
public string GetPathToDisk(string tenant, string path)
{
string overridePath = $"Tenant/{tenant}/{path}";
string root = PathMapper.MapPath("/");
overridePath = Path.Combine(root, overridePath);
if (File.Exists(overridePath))
{
return overridePath;
}
string requestedPath = Path.Combine(root, path);
return requestedPath;
}
}
}<file_sep>using System;
using System.Linq;
using System.Reflection;
using Frapid.NPoco;
using NpgsqlTypes;
namespace Frapid.Configuration.Db
{
public class Mapper : DefaultMapper
{
private object GetFromDbConverter(object value, Type destType, Type sourceType)
{
if (value is NpgsqlTimeStampTZ)
{
if (destType == typeof(DateTime))
{
return (DateTime) (NpgsqlTimeStampTZ) value;
}
if (destType == typeof(DateTime?))
{
return (DateTime?) (NpgsqlTimeStampTZ) value;
}
if (destType == typeof(DateTimeOffset))
{
var tstz = (NpgsqlTimeStampTZ) value;
return new DateTimeOffset((DateTime) tstz);
}
if (destType == typeof(DateTimeOffset?))
{
var tstz = (NpgsqlTimeStampTZ) value;
return new DateTimeOffset((DateTime) tstz);
}
}
if (value is NpgsqlTimeStamp)
{
if (destType == typeof(DateTime))
{
return (DateTime) (NpgsqlTimeStamp) value;
}
if (destType == typeof(DateTime?))
{
return (DateTime?) (NpgsqlTimeStamp) value;
}
}
if (value is NpgsqlDate)
{
if (destType == typeof(DateTime))
{
return (DateTime) (NpgsqlDate) value;
}
if (destType == typeof(DateTime?))
{
return (DateTime?) (NpgsqlDate) value;
}
}
if (value is DateTime)
{
if (destType == typeof(DateTimeOffset) ||
destType == typeof(DateTimeOffset?))
{
//value is not null
return new DateTimeOffset((DateTime) value);
}
return value;
}
if (value is DateTimeOffset)
{
if (destType == typeof(DateTime) ||
destType == typeof(DateTime?))
{
//value is not null
return ((DateTimeOffset) value).DateTime;
}
return (DateTimeOffset) value;
}
return value;
}
public override Func<object, object> GetFromDbConverter(Type destType, Type sourceType)
{
if (destType == typeof(DateTimeOffset) ||
destType == typeof(DateTimeOffset?) ||
destType == typeof(DateTime) ||
destType == typeof(DateTime?))
{
return x => this.GetFromDbConverter(x, destType, sourceType);
}
if (destType == typeof(HStore) &&
sourceType == typeof(string))
{
return x => HStore.Create((string) x);
}
return base.GetFromDbConverter(destType, sourceType);
}
public override Func<object, object> GetToDbConverter(Type destType, MemberInfo sourceInfo)
{
if (sourceInfo == null)
{
return x => x;
}
if (sourceInfo == typeof(HStore))
{
return x => ((HStore) x).ToSqlString();
}
if (sourceInfo == typeof(string) &&
destType == typeof(bool))
{
return x => new[]
{
"TRUE",
"YES",
"T"
}.Contains(x.ToString().ToUpperInvariant());
}
return base.GetToDbConverter(destType, sourceInfo);
}
}
}<file_sep>namespace Frapid.Reports.Engine.Model
{
public enum DataSourceParameterType
{
Text,
Number,
Decimal,
Double,
Date,
Bool
}
}<file_sep>using System;
using Frapid.Framework.Extensions;
using Frapid.Reports.Engine.Model;
namespace Frapid.Reports.Helpers
{
public static class DataSourceParameterHelper
{
public static object CastValue(object value, DataSourceParameterType type)
{
switch (type)
{
case DataSourceParameterType.Date:
double milliseconds = value.To<double>();
if (milliseconds > 0)
{
value = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(milliseconds)
.ToLocalTime()
.Date
.ToString("d");
}
else
{
return value.To<DateTime>();
}
break;
case DataSourceParameterType.Number:
return value.To<long>();
case DataSourceParameterType.Bool:
return value.To<bool>();
case DataSourceParameterType.Decimal:
return value.To<decimal>();
case DataSourceParameterType.Double:
return value.To<double>();
}
return value;
}
}
}
|
fdcff5272cdd66a2ba98c60c42ce0be32333a153
|
[
"C#"
] | 5 |
C#
|
limengchang/frapid
|
cb1b3f0f5785ba288362641cc04526a29aa688d0
|
03d7160216150ffc98641e1f60e6b8a4cd64b541
|
refs/heads/main
|
<file_sep>
#
# ~ CARTAS ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -Wall
objects/main.o: main.c objects/cards.o headers/cards.h
gcc -c -o objects/main.o main.c -Wall -I headers
objects/cards.o: lib/cards.c objects/list.o headers/list.h
gcc -c -o objects/cards.o lib/cards.c -Wall -I headers
objects/list.o: lib/list.c headers/list.h
gcc -c -o objects/list.o lib/list.c -Wall -I headers
run: Prog
./Prog
clean:
rm Prog objects/*.o
<file_sep>
#ifndef H_BUSCACAMPOS_
#define H_BUSCACAMPOS_
#include <stdio.h>
#include <register.h>
typedef struct BUSCA_CAMPO_T__ BUSCA_CAMPO_T;
BUSCA_CAMPO_T *BC_new();
int BC_insertUpdate(char *searchField, char *searchValue, char *modifyField, char *modifyValue, BUSCA_CAMPO_T *BC);
int BC_insertSearch(char *searchField, char *searchValue, BUSCA_CAMPO_T *BC);
int BC_search(REGISTRO_T *reg, BUSCA_CAMPO_T *BC);
int BC_searchUpdate(REGISTRO_T *reg, FILE *stream, BUSCA_CAMPO_T *BC);
void BC_destroy(BUSCA_CAMPO_T *BC);
#endif<file_sep>#ifndef QUICKSORT_H_
#define QUICKSORT_H_
void quicksort(void *, int, int (*)(void *,void *), int, int *, int *);
#endif
<file_sep>#include <stdlib.h>
#include <iostream>
#include <set>
using namespace std;
/*
* == Jan-Ken-Puzzle ==
*
* Nomes:
* <NAME> (Nº 10262631)
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
/*
* == Explicação do código ==
*
* Para solucionar este problema, fizemos um algoritmo backtracking "solve".
* Este algoritmo vai percorrer todas as cédulas do tabuleiro verificando
* possíveis movimentos, e chamando a recursão nestes casos.
* Utilizamos um vetor "moves" para estes movimentos, pois dá para usar um
* único "for" ao invés de vários "ifs" para cada um dos quatro movimentos.
*
* Utilizamos da STL (estrutura de dados padrão) "set" do C++:
* O set (ou conjunto) permite inserir elementos sem repetir (ele já verifica
* possíveis repetições) e já mantém os elementos ordenados.
* Usamos o set para manter as resoluções do tabuleiro, pois ele é perfeito
* para tal fim.
*
* O código é compatível com C++ padrão ansi e não possui 'leaks' de memória.
*
* Obs.: Movemos todas as implementações de funções para após a "main" para
* melhor organização.
*/
/* A linha abaixo é usada para facilitar identifição das cédulas no código */
enum { nothing = 0, rock, scissors, paper };
/* Possíveis movimentos no eixo cartesiano (sem contar diagonais) */
int moves[][2] = {
{-1, 0},
{0, -1},
{1, 0},
{0, 1}
};
/* A estrutura abaixo representa uma resolução para o dado tabuleiro */
typedef struct solution_t {
int x, y; /* Coordenadas */
char type; /* Tipo de peça que "venceu" */
bool operator < (const solution_t& cmpObj) const {
/* C++ STL: usado para comparar resoluções (evitar repetição e ordenar) */
if(x == cmpObj.x) {
if(y == cmpObj.y)
return (type < cmpObj.type);
return (y < cmpObj.y);
}
return (x < cmpObj.x);
}
} Solution;
/* A estrutura abaixo representa um tabuleiro */
typedef struct gameBoard_t {
int r, c; /* Número de linhas "R" e de colunas "C" */
char **puzzle; /* Tabuleiro com as cédulas. O tipo 'char' é usado para preservar memória */
set<Solution> solutions; /* Conjunto de resoluções (sem repetição) para dado tabuleiro. Começa vazio */
int solutionCounter; /* Contador de resoluções (com repetição) para dado tabuleiro. Começa com zero */
} GameBoard;
/* Assinatura das funções (implementação após a "main") */
Solution makeSolution(int, int, char);
bool isValidPosition(int, int, GameBoard &);
void solve(int, int, int, GameBoard &);
/* == MAIN == */
int main(int argc, char **argv){
set<Solution>::iterator it; /* C++ STL: para iterar nas soluções do dado tabuleiro */
GameBoard board; /* Tabuleiro que será solucionado */
int i, j, n; /* O "n" é o contador de cédulas não vazias (pedra, tesoura ou papel), necessário no algoritmo */
/* Inicializa parâmetros do tabuleiro */
board.solutions = set<Solution>();
board.solutionCounter = 0;
/* Lê R e C (números de linhas e colunas do tabuleiro) */
cin >> board.r >> board.c;
/* Aloca memória necessária e faz a leitura das cédulas */
board.puzzle = (char **) malloc(sizeof(char *) * board.r);
for(i = n = 0; i < board.r; i++) {
board.puzzle[i] = (char *) malloc(sizeof(char) * board.c);
for(j = 0; j < board.c; j++) {
cin >> board.puzzle[i][j];
board.puzzle[i][j] -= '0'; /* Para obter o valor inteiro, e não o da tabela ASCII */
if(board.puzzle[i][j] != nothing)
n++; /* Se for não vazio (pedra, tesoura ou papel), incrementa o contador */
}
}
/* Chama a função backtracking e resolve o tabuleiro */
solve(0, 0, n, board);
/* Imprimir resultados encontrados na saída padrão */
cout << board.solutionCounter << endl << board.solutions.size() << endl;
for(it = board.solutions.begin(); it != board.solutions.end(); it++) {
cout << ((*it).x + 1) << " " << ((*it).y + 1) << " " << ((int) (*it).type) << endl;
}
/* Desalocar memória alocada anteriormente */
for(i = n = 0; i < board.r; i++) {
free(board.puzzle[i]);
}
free(board.puzzle);
return EXIT_SUCCESS;
}
/* == IMPLEMENTAÇÕES DAS FUNÇÕES == */
/* Função usada para criar uma estrutura que representa uma resolução */
Solution makeSolution(int x, int y, char type) {
Solution auxObj;
auxObj.x = x;
auxObj.y = y;
auxObj.type = type;
return auxObj;
}
/* Função usada para verificar se dados i e j são válidos dentro da matriz que representa o tabuleiro */
bool isValidPosition(int i, int j, GameBoard &board) {
return (i >= 0 && i < board.r && j >= 0 && j < board.c);
}
/* Função backtracking responsável por encontrar todas as soluções para o tabuleiro */
void solve(int x, int y, int n, GameBoard &board) {
int i, j, k;
if(n <= 1) { /* Se tem apenas uma cédula não vazia (pedra, tesoura ou papel), então chegou numa resolução */
/* Condição de parada/fim: tem uma "vencedora" */
board.solutions.insert(makeSolution(x, y, board.puzzle[x][y])); /* Insere a resolução no conjunto de resoluções (repetições são ignoradas) */
board.solutionCounter++; /* Aumenta o contador de resoluções */
return;
}
for(i = 0; i < board.r; i++){
for(j = 0; j < board.c; j++){
/* Para cada cédula do tabuleiro */
switch(board.puzzle[i][j]) {
case rock: /* Se for pedra, só vai mover se tiver tesouras adjacentes */
for(k = 0; k < 4; k++) { /* Para cada movimento possível da cédula... */
if(!isValidPosition(i + moves[k][0], j + moves[k][1], board)) /* Verificar se é válido */
continue;
if(board.puzzle[i + moves[k][0]][j + moves[k][1]] == scissors) { /* E verificar se tem tesoura */
board.puzzle[i + moves[k][0]][j + moves[k][1]] = rock; /* Tem tesoura. Virou pedra agora porque pedra ganha! */
board.puzzle[i][j] = nothing;
solve(i + moves[k][0], j + moves[k][1], n - 1, board); /* Chamar recursão */
board.puzzle[i + moves[k][0]][j + moves[k][1]] = scissors; /* Quando volta da recursão, tem que voltar ao estado original */
board.puzzle[i][j] = rock;
}
}
break;
case scissors: /* Se for tesoura, só vai mover se tiver papeis adjacentes */
for(k = 0; k < 4; k++) { /* Para cada movimento possível da cédula... */
if(!isValidPosition(i + moves[k][0], j + moves[k][1], board)) /* Verificar se é válido */
continue;
if(board.puzzle[i + moves[k][0]][j + moves[k][1]] == paper) { /* E verificar se tem papel */
board.puzzle[i + moves[k][0]][j + moves[k][1]] = scissors; /* Tem papel. Virou tesoura agora porque tesoura ganha! */
board.puzzle[i][j] = nothing;
solve(i + moves[k][0], j + moves[k][1], n - 1, board); /* Chamar recursão */
board.puzzle[i + moves[k][0]][j + moves[k][1]] = paper; /* Quando volta da recursão, tem que voltar ao estado original */
board.puzzle[i][j] = scissors;
}
}
break;
case paper: /* Se for papel, só vai mover se tiver pedras adjacentes */
for(k = 0; k < 4; k++) { /* Para cada movimento possível da cédula... */
if(!isValidPosition(i + moves[k][0], j + moves[k][1], board)) /* Verificar se é válido */
continue;
if(board.puzzle[i + moves[k][0]][j + moves[k][1]] == rock) { /* E verificar se tem pedra */
board.puzzle[i + moves[k][0]][j + moves[k][1]] = paper; /* Tem pedra. Virou papel agora porque papel ganha! */
board.puzzle[i][j] = nothing;
solve(i + moves[k][0], j + moves[k][1], n - 1, board); /* Chamar recursão */
board.puzzle[i + moves[k][0]][j + moves[k][1]] = rock; /* Quando volta da recursão, tem que voltar ao estado original */
board.puzzle[i][j] = paper;
}
}
break;
}
}
}
}
<file_sep># RSA Java
Uma implementação manual da criptografia RSA usando Java.
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <cards.h>
/*
* ~ CARTAS ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv){
int i,N;
LIST *Aux;
scanf("%d",&N);
for(i=0;i<N;i++){ // Para cada possível sequência de cartas...
Aux=ReadCardsFrom(stdin); // Ler a sequência.
ProcessCards(stdout,Aux); // Processar e imprimir.
DestroyCards(Aux); // Remover da memória.
printf("\n");
}
return EXIT_SUCCESS;
}
<file_sep>
#
# ~ Op. Ordenacao ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -Wall
objects/main.o: main.c objects/insertionsort.o headers/insertionsort.h objects/bubblesort.o headers/bubblesort.h objects/mergesort.o headers/mergesort.h objects/heapsort.o headers/heapsort.h objects/quicksort.o headers/quicksort.h
gcc -c -o objects/main.o main.c -Wall -I headers
objects/insertionsort.o: lib/insertionsort.c
gcc -c -o objects/insertionsort.o lib/insertionsort.c -Wall
objects/bubblesort.o: lib/bubblesort.c objects/vectorutils.o headers/vectorutils.h
gcc -c -o objects/bubblesort.o lib/bubblesort.c -Wall -I headers
objects/mergesort.o: lib/mergesort.c objects/vectorutils.o headers/vectorutils.h
gcc -c -o objects/mergesort.o lib/mergesort.c -Wall -I headers
objects/heapsort.o: lib/heapsort.c objects/vectorutils.o headers/vectorutils.h
gcc -c -o objects/heapsort.o lib/heapsort.c -Wall -I headers
objects/quicksort.o: lib/quicksort.c objects/vectorutils.o headers/vectorutils.h
gcc -c -o objects/quicksort.o lib/quicksort.c -Wall -I headers
objects/vectorutils.o: lib/vectorutils.c
gcc -c -o objects/vectorutils.o lib/vectorutils.c -Wall
run: Prog
./Prog
clean:
rm Prog objects/*.o
<file_sep># Objeto
Objeto obtido do website [free3d](https://free3d.com/3d-model/old-house-2-96599.html): licença para uso pessoal.
<file_sep>#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv){
int N, i, Aux, Aux2, Scanned;
char Line[10000];
char O[100], Op;
scanf("%d", &N);
for(i = 0; i < N; i++){
scanf("%s %[^\n]s", O, Line);
Op = O[0];
switch(Op){
case 'S':
Aux = 0;
while((Aux2=sscanf(Line, "%d %[^\n]s", &Scanned, Line)) == 2 || Aux2 == 1){
if(Aux2 == 1) Line[0] = '\0';
Aux += Scanned;
}
printf("T %d\n", Aux);
break;
case 'R':
sscanf(Line, "%d %[^\n]s", &Aux, Line);
while((Aux2=sscanf(Line, "%d %[^\n]s", &Scanned, Line)) == 2 || Aux2 == 1){
if(Aux2 == 1) Line[0] = '\0';
Aux -= Scanned;
}
printf("T %d\n", Aux);
break;
default:
printf("E\n");
}
}
return EXIT_SUCCESS;
}<file_sep># Trabalho Prático
Trabalho Prático de Organização de Arquivos
## ./objects
Aqui se encontram objetos de compilação, usados apenas para compilação e nada mais.
<file_sep># FormRobber (Extensão de navegador)
Aqui está organizado o código (JavaScript) da extensão de navegador.
Esta extensão funciona com o Google Chrome e Opera.
## Como instalar a extensão no navegador de internet
* Altere o arquivo [main.js](main.js) de forma que a variável "formSubmitURL" tenha o endereço do servidor em questão, que receberá os dados capturados (deve ser o endereço completo para a página [capture.php](../Servidor/capture.php)).
* Comprima todos os arquivos desta pasta ([jquery.min.js](jquery.min.js), [main.js](main.js) e [manifest.json](manifest.json)) em um único arquivo *.ZIP.
* Inicie o navegador de internet em que a extensão será instalada.
* Abra a página das extensões do navegador. No Google Chrome esta página é _chrome://extensions/_ e no Opera é _opera://extensions/_.
* Ative o Modo de Desenvolvedor. Essa opção costuma ficar na parte de cima, na barra de ferramentas.
* No explorador de arquivos do seu sistema, localize o *.ZIP com os arquivos da extensão, clique e arraste-o até a página de extensões do navegador (com o Modo de Desenvolvedor ativado).
* Se todos os passos foram seguidos corretamente, a extensão será instalada. Se ela não for automaticamente ativada, faça-o.
* Pronto, a extensão já está funcionando. Talvez seja necessário atualizar as abas abertas para que ela entre em vigor nestas.
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
void testCase() {
ll strLen, patternLen;
char str[1000001], pattern[1000001], *itt;
cin >> str >> pattern;
strLen = strlen(str);
patternLen = strlen(pattern);
vector<ll> found = vector<ll>();
for(itt = str; itt <= str + strLen - patternLen; itt++) {
if(memcmp(itt, pattern, patternLen) == 0) {
found.push_back((ll) (itt - str));
}
}
if(found.size() < 1) {
cout << "Not Found" << endl;
return;
}
cout << found.size() << endl;
for(auto it = found.begin(); it != found.end(); it++) {
cout << (*it + 1) << ' ';
}
cout << endl;
}
int main(int argc, char **argv) {
ll T;
cin >> T;
for(; T > 0; T--) {
testCase();
cout << endl;
}
return EXIT_SUCCESS;
}
<file_sep># USP
Projects developed during Computer Science undergraduation at University of São Paulo (USP). Each folder in this repository contains the projects for the specific course subject.
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int N=0,i,j,*Int;
char R,*Str;
Str=(char *)malloc(0);
do{
R=getchar();
if(R!='\n'){
Str=(char *)realloc(Str,sizeof(char)*(++N));
Str[N-1]=R;
}
}while(R!='x');
for(i=0;i<N;i++){
for(j=i+1;j<N;j++){
if(Str[i]>Str[j]){
R=Str[i];
Str[i]=Str[j];
Str[j]=R;
}
}
if(!((i+1)%4)){
Int=(int *)&Str[i-3];
printf("%d\n",*Int);
}
}
free(Str);
return EXIT_SUCCESS;
}
<file_sep># SCC-0251 Processamento de Imagens - 2018.1
Aqui estão todos os trabalhos que implementei em Processamento de Imagens.
<file_sep># Objeto
Objeto de domínio público. Textura do projeto.
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "consts.h"
#include "register.h"
#include "index.h"
IND_T *I_init(char *path) {
IND_T *aux;
aux = (IND_T *) malloc(sizeof(IND_T));
aux->status = STATUS_CONSISTENTE;
aux->nItems = 0;
aux->data = NULL;
aux->path[0] = '\0';
if(path != NULL) {
if(I_read(aux, path) != 1) {
I_destroy(aux);
return NULL;
}
}
return aux;
}
int I_read(IND_T *index, char *path) {
FILE *stream;
char aux[8];
int i;
stream = fopen(path, "rb");
if(stream == NULL) {
return 0;
}
if(fread(aux, sizeof(char), 8, stream) != 8) {
fclose(stream);
return 0;
}
if(aux[0] != STATUS_CONSISTENTE) {
fclose(stream);
return 0;
}
fseek(stream, 0, SEEK_END);
index->status = STATUS_CONSISTENTE;
index->nItems = (ftell(stream) - 8) / 8;
fseek(stream, 8, SEEK_SET);
if(index->nItems < 0) {
fclose(stream);
return 0;
}
strcpy(index->path, path);
if(index->data != NULL) {
free(index->data);
}
index->data = (IND_DATA *) malloc(sizeof(IND_DATA) * index->nItems);
for(i = 0; i < index->nItems; i++) {
if(fread(aux, sizeof(char), 8, stream) != 8) {
fclose(stream);
return 0;
}
memcpy(&index->data[i].key, aux, sizeof(int));
memcpy(&index->data[i].RRN, &aux[4], sizeof(int));
}
fclose(stream);
return 1;
}
int I_rewrite(IND_T *index) {
FILE *stream;
char aux[8];
int i;
if(index->path[0] == '\0') {
return 0;
}
stream = fopen(index->path, "wb");
if(stream == NULL) {
return 0;
}
index->status = STATUS_INCONSISTENTE;
memset(aux, LIXO, 8);
memcpy(aux, &index->status, sizeof(char));
if(fwrite(aux, sizeof(char), 8, stream) != 8) {
fclose(stream);
return 0;
}
memset(aux, LIXO, 8);
for(i = 0; i < index->nItems; i++) {
memset(aux, LIXO, 8);
memcpy(aux, &index->data[i].key, sizeof(int));
memcpy(&aux[4], &index->data[i].RRN, sizeof(int));
if(fwrite(aux, sizeof(char), 8, stream) != 8) {
fclose(stream);
return 0;
}
}
index->status = STATUS_CONSISTENTE;
memset(aux, LIXO, 8);
memcpy(aux, &index->status, sizeof(char));
fseek(stream, 0, SEEK_SET);
if(fwrite(aux, sizeof(char), 8, stream) != 8) {
fclose(stream);
return 0;
}
fclose(stream);
return 1;
}
int I_write(IND_T *index, char *path) {
strcpy(index->path, path);
return I_rewrite(index);
}
int I_push(REG_DATA *reg, IND_T *index) {
int i, aux;
for(i = 0; i < index->nItems; i++) {
if(reg->idPessoa < index->data[i].key) {
break;
}
}
index->data = (IND_DATA *) realloc(index->data, sizeof(IND_DATA) * (index->nItems + 1));
memmove(&index->data[i + 1], &index->data[i], sizeof(IND_DATA) * (index->nItems - i));
index->data[i].RRN = reg->RRN;
index->data[i].key = reg->idPessoa;
index->nItems++;
return 1;
}
int I_pop(REG_DATA *reg, IND_T *index) {
int i, aux;
for(i = 0; i < index->nItems; i++) {
if(reg->RRN == index->data[i].RRN) {
break;
}
}
if(i >= index->nItems) {
return 0;
}
memmove(&index->data[i], &index->data[i + 1], sizeof(IND_DATA) * (index->nItems - i - 1));
//index->data = (IND_DATA *) realloc(index->data, sizeof(IND_DATA) * (index->header.nItems - 1));
index->nItems--;
return 1;
}
int I_update(REG_DATA *reg, IND_T *index) {
int i, aux;
if(I_pop(reg, index) == 0) {
return 0;
}
return I_push(reg, index);
}
IND_DATA *I_find(int key, IND_T *index) {
int i, j, aux;
for(i = 0; i < index->nItems; i++) {
if(key == index->data[i].key) {
return &index->data[i];
}
}
return NULL;
}
void I_destroy(IND_T *index) {
if(index == NULL) {
return;
}
free(index->data);
free(index);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
<NAME>
<EMAIL>
*/
typedef struct Time_Stamp{
char Dia;
char Mes;
unsigned short Ano;
char Hora;
char Minuto;
char Segundo;
} DATE;
typedef struct Calendar_Activity{
DATE Data_Hora;
char Nome[100];
} EVENTO;
int main(){
int i,N,R;
scanf("%d",&N);
EVENTO Calendario[N];
for(i=0;i<N;i++){
scanf("%d",&R); //Dia
Calendario[i].Data_Hora.Dia=(char)R;
scanf("%d",&R); //Mês
Calendario[i].Data_Hora.Mes=(char)R;
scanf("%d",&R); //Ano
Calendario[i].Data_Hora.Ano=(unsigned short)R;
scanf("%d",&R); //Hora
Calendario[i].Data_Hora.Hora=(char)R;
scanf("%d",&R); //Minuto
Calendario[i].Data_Hora.Minuto=(char)R;
scanf("%d",&R); //Segundo
Calendario[i].Data_Hora.Segundo=(char)R;
getchar();
fgets(Calendario[i].Nome,100,stdin);
Calendario[i].Nome[strlen(Calendario[i].Nome)-1]='\0';
}
for(i=0;i<N;i++){
printf("%02d/%02d/%04d - %02d:%02d:%02d\n%s\n",(int)Calendario[i].Data_Hora.Dia,(int)Calendario[i].Data_Hora.Mes,(int)Calendario[i].Data_Hora.Ano,(int)Calendario[i].Data_Hora.Hora,(int)Calendario[i].Data_Hora.Minuto,(int)Calendario[i].Data_Hora.Segundo,Calendario[i].Nome);
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
Matheus
<EMAIL>
*/
int main(){
int y;
scanf("%d",&y);
printf((y%4)?"NAO":"SIM");
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
/*
* == IMAGENS P&B ==
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
enum __colour_t { empty = 0, full }; // Preto ou Branco
struct __img_t { // Estrutura da imagem
enum __colour_t Colour; // Cor
struct __img_t *Children[4]; // Quadrantes filhos
};
struct __img_t *New_Img(){
/*
* Esta função aloca na memória uma nova imagem e retorna um ponteiro para esta.
*/
struct __img_t *Aux=(struct __img_t *)malloc(sizeof(struct __img_t));
int i;
Aux->Colour=empty;
for(i=0;i<4;i++)
Aux->Children[i]=NULL;
return Aux;
}
char Read_Img(FILE *FStream,struct __img_t *Img){
/*
* Esta função realiza a leitura de 'Fstream' de uma String que represente uma imagem e salva em 'Img'.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
if(Img==NULL) return 0;
char R=getc(FStream);
int i,j;
if(R=='p')
for(i=0;i<4;i++){
Img->Children[i]=(struct __img_t *)malloc(sizeof(struct __img_t));
Img->Children[i]->Colour=empty;
for(j=0;j<4;j++)
Img->Children[i]->Children[j]=NULL;
Read_Img(FStream,Img->Children[i]);
}
else if(R=='f') Img->Colour=full;
else Img->Colour=empty;
return 1;
}
struct __img_t *Join_Img(struct __img_t *A, struct __img_t *B){
/*
* Esta função realiza a soma entre duas imagens 'A' e 'B', retornando a imagem resultante.
*
* Ela retorna um ponteiro para a imagem resultante, ou NULL em caso de erros.
*/
if(A==NULL && B==NULL) return NULL;
struct __img_t *Aux=New_Img();
int i;
if(A==NULL){
if(B->Colour==full) Aux->Colour=full;
}else if(B==NULL){
if(A->Colour==full) Aux->Colour=full;
}else if(A->Colour==full || B->Colour==full){
Aux->Colour=full;
}else{
for(i=0;i<4;i++)
Aux->Children[i]=Join_Img(A->Children[i],B->Children[i]);
}
return Aux;
}
int Count_Img_Filled_Pixels(int Resolution,struct __img_t *Img){
/*
* Esta função conta exatamente o número de pixels pretos em 'Img', considerando uma resolução de imagem de 'Resolution'.
*
* Ela retorna o número de pixels pretos, ou -1 em caso de erros.
*/
if(Img==NULL) return -1;
int i,R,Sum=0;
if(Img->Colour==full) Sum+=Resolution*Resolution;
else
for(i=0;i<4;i++){
R=Count_Img_Filled_Pixels(Resolution/2,Img->Children[i]);
if(R>0) Sum+=R;
}
return Sum;
}
char Destroy_Img(struct __img_t *Img){
/*
* Esta função remove da memória a imagem 'Img' e todos seus filhos.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
if(Img==NULL) return 0;
int i;
for(i=0;i<4;i++)
Destroy_Img(Img->Children[i]);
free(Img);
return 1;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int N,i,j;
scanf("%d",&N);
//getchar();
char Str[N][1000],Rc[1000]; // Str[2][3] == *(Str+2*N+3)
for(i=0;i<N;i++){
scanf("%s",Str[i]);
}
for(i=0;i<N;i++){
for(j=i+1;j<N;j++){
if(strcmp(Str[i],Str[j])>0){
strcpy(Rc,Str[i]);
strcpy(Str[i],Str[j]);
strcpy(Str[j],Rc);
}
}
printf("%s\n",Str[i]);
}
return EXIT_SUCCESS;
}
<file_sep>package resources;
import java.sql.Time;
import java.util.Random;
import java.util.concurrent.Semaphore;
/**
* Essa classe implementa métodos úteis para uso no programa.
*
*/
public class Utils {
private static Random randomGen = null;
/**
* Esse método encerra o programa devido a um erro fatal.
*
*/
public static void fatalError() {
System.err.println("== FATAL ERROR: EXITING ==");
System.exit(-1);
}
/**
* Este método dorme a thread que o chamou.
* @param ms milisegundos
*/
public static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch(Exception exc) {
System.err.printf("Could not sleep thread: %s.",
exc.getMessage());
System.err.println();
fatalError();
}
}
public static void acquireLock(Semaphore lock) {
try {
lock.acquire();
} catch(Exception exc) {
System.err.printf("Could not acquire '%s' semaphore lock: %s.",
lock.toString(), exc.getMessage());
System.err.println();
fatalError();
}
}
public static void joinThread(Thread thread) {
try {
thread.join();
} catch(Exception exc) {
System.err.printf("Could not join threads '%s' and %s.",
Thread.currentThread().toString(), thread.toString());
System.err.println();
fatalError();
}
}
public static Random getRandom() {
if(randomGen == null) {
randomGen = new Random();
randomGen.setSeed(System.currentTimeMillis());
}
return randomGen;
}
}
<file_sep>#include <stdlib.h>
#include <limits.h>
#include <iostream>
#include <vector>
#include <bitset>
#include <cmath>
#include <map>
using namespace std;
bitset<5000> crivo;
map<long, long> extra_crivo;
void CalcularCrivo(){
unsigned long i, j, N;
N = crivo.size();
crivo.set();
crivo[1] = crivo[0] = 0;
for(i = 2; i < N; i++){
for(j = i + 1; j < N; j++){
if(j % i == 0){
crivo[j] = 0;
}
}
}
}
bool IsPrime(unsigned long N){
if(N < crivo.size()) return crivo[N];
if(extra_crivo[N] == 2) return true;
if(N % 2 == 0) return false;
unsigned long i, Max;
Max = floor(sqrt(N));
for(i = 3; i <= Max; i += 2){
if(N % i == 0) return false;
}
extra_crivo[N] = 2;
return true;
}
void ImprimirCrivo(){
int i, N;
N = crivo.size();
for(i = 0; i < N; i++){
cout << i << ": " << crivo[i] << "\n";
}
}
void DecomporPrimos_Para(unsigned int N, map <long, long>&vector){
if(IsPrime(N)){
vector[N]++;
return;
}
int i, Max;
Max = N;
for(i = 2; i <= Max && N >= 2; i++){
if(!IsPrime(i)) continue;
while(N % i == 0){
vector[i]++;
N /= i;
}
}
}
long lcm(long A, long B){
long Min;
Min = (A > B) ? B : A;
for(; Min > 0; Min--){
if(A % Min == 0 && B % Min == 0) break;
}
return (A*B) / Min;
}
long LCM_cardinality(long N){
long i, j, counter = 0;
if(N % 2 == 0){
for(i = 1; i <= N; i++){
if(lcm(i, N) == N){
for(j = i; j <= N; j++){
if(lcm(j, N) == N){
counter++;
}
}
}
}
}else{
for(i = 1; i <= N; i += 2){
if(lcm(i, N) == N){
for(j = i; j <= N; j += 2){
if(lcm(j, N) == N){
counter++;
}
}
}
}
}
return counter;
}
int main(int argc, char **argv){
long Aux, N;
CalcularCrivo();
cin >> Aux;
while(Aux != 0){
map <long, long>vector;
map <long, long>::iterator it;
cout << Aux << " ";
N = 0;
DecomporPrimos_Para(Aux, vector);
for(it = vector.begin(); it != vector.end(); it++){
N += LCM_cardinality(it->first) * it->second;
}
cout << N-1 << '\n';
cin >> Aux;
}
}
<file_sep># Monitoria
Aqui estão alguns dos códigos que implementei para monitorias durante meu período na USP.
<file_sep>
/* Este é o arquivo *.h */
#ifndef FORNECIDO_H_
#define FORNECIDO_H_
void binarioNaTela1(char *nomeArquivoBinario, char *nomeArquivoIndice); /* Correção do arquivo binário. */
void binarioNaTela2(char *nomeArquivoBinario); /* Correção do arquivo binário. */
void scan_quote_string(char *str); /* Use para ler strings entre aspas. */
void trim(char *str); /* Pode ser útil pra você (extra). */
#endif
<file_sep>package game;
import drawable.Drawable;
import resources.Utils;
import javax.swing.*;
import java.awt.*;
/**
* Essa classe representa o painel em que o jogo sera desenhado.
*
*/
@SuppressWarnings("serial")
public class GamePanel extends JPanel {
/**
* Razao do painel de jogo (2:1). Preferivel = 1000x500
*/
private static final double ratio = 2 / 1.0;
/**
* O metodo eh sobrescrito para poder desenhas os elementos do jogo no painel.
* A priori, este método não deve ser modificado.
*
* @param g objeto grafico de desenho no painel
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Utils.acquireLock(GameScreen.game.mutex);
for(Drawable dw : GameScreen.game.getEnemies()){
dw.draw(g);
}
for(Drawable dw : GameScreen.game.getWeapons()) {
dw.draw(g);
}
GameScreen.game.getTower().draw(g);
GameScreen.game.mutex.release();
}
/**
* Usado para manter a razao de tela adequada.
*
* @return o tamanho ideal para o painel
*/
@Override
public Dimension getPreferredSize() {
int xPrefSize, yPrefSize;
Dimension parentSize;
parentSize = this.getParent().getSize();
xPrefSize = (int) Math.min(parentSize.height*ratio, parentSize.width);
yPrefSize = (int) Math.min(parentSize.width/ratio, parentSize.height);
return new Dimension(xPrefSize, yPrefSize);
}
}
<file_sep>
TA_THREAD_SLEEP_TIMEOUT = 10 # Seconds a working thread sleeps before checking for work.
TA_THREAD_SLEEP_RATELIMIT = 15*60 # Seconds to sleep after a API rate limit.
TA_MAX_SEARCH_COUNT = 100 # Max number of tweets to query per iteration (2021-July: API maximum is 100 tweets).
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/*
* ~ Sliding Puzzle ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
struct __slidingpuzzle_t {
char **Matrix;
unsigned long D;
long BlankI, BlankJ;
};
struct __slidingpuzzle_t *New_Puzzle(FILE *FStream, unsigned long D){
if(D < 1) return NULL;
struct __slidingpuzzle_t *Aux = (struct __slidingpuzzle_t *)malloc(sizeof(struct __slidingpuzzle_t));
unsigned long i, j;
char R;
Aux->Matrix = (char **)malloc(sizeof(char *) * D);
Aux->BlankI = Aux->BlankJ = -1;
Aux->D = D;
for(i=0; i<D; i++){
Aux->Matrix[i] = (char *)malloc(sizeof(char)*D);
for(j=0; j<D; j++){
Aux->Matrix[i][j]=getc(FStream);
if(Aux->Matrix[i][j]==' '){
Aux->BlankI=i;
Aux->BlankJ=j;
}
}
while( (R=getc(FStream)) != EOF && R != '\n') { }
}
return Aux;
}
void Move_Puzzle_Swap(char *A, char *B){
if(A==NULL || B==NULL) return;
char R=*B;
*B=*A;
*A=R;
}
int Move_Puzze_Up(struct __slidingpuzzle_t *P){
if(P==NULL) return -1;
if(P->BlankI <= 0) return 0;
Move_Puzzle_Swap(&P->Matrix[P->BlankI][P->BlankJ], &P->Matrix[P->BlankI-1][P->BlankJ]);
P->BlankI--;
return 1;
}
int Move_Puzze_Left(struct __slidingpuzzle_t *P){
if(P==NULL) return -1;
if(P->BlankJ <= 0) return 0;
Move_Puzzle_Swap(&P->Matrix[P->BlankI][P->BlankJ], &P->Matrix[P->BlankI][P->BlankJ-1]);
P->BlankJ--;
return 1;
}
int Move_Puzze_Down(struct __slidingpuzzle_t *P){
if(P==NULL) return -1;
if(P->BlankI >= P->D-1) return 0;
Move_Puzzle_Swap(&P->Matrix[P->BlankI][P->BlankJ], &P->Matrix[P->BlankI+1][P->BlankJ]);
P->BlankI++;
return 1;
}
int Move_Puzze_Right(struct __slidingpuzzle_t *P){
if(P==NULL) return -1;
if(P->BlankJ >= P->D-1) return 0;
Move_Puzzle_Swap(&P->Matrix[P->BlankI][P->BlankJ], &P->Matrix[P->BlankI][P->BlankJ+1]);
P->BlankJ++;
return 1;
}
int Print_Puzzle(FILE *FStream, struct __slidingpuzzle_t *P){
if(P==NULL) return 0;
unsigned long i, j;
for(i=0;i<P->D;i++){
for(j=0;j<P->D;j++)
fprintf(FStream, "%c", P->Matrix[i][j]);
fprintf(FStream, "\n");
}
return 1;
}
void Destroy_Puzzle(struct __slidingpuzzle_t *P){
if(P==NULL) return;
unsigned long i;
for(i=0;i<P->D;i++)
free(P->Matrix[i]);
free(P->Matrix);
free(P);
}
<file_sep>from threading import Thread, Semaphore
import numpy as np
import imageio
import sys
#
# ~ Projeto Final: Inpainting de Objetos Largos ~
#
# <NAME> (Nº USP 9896250)
# <NAME> (Nº USP 10369014)
#
# Processamento de Imagens: SCC-0251 2018.1
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
# == VARIAVEIS GLOBAIS ==
semaphoreSavePatch = Semaphore() # Semáfaro de sincronização multi-threading.
# == DEFINIÇÃO DE FUNÇÕES ==
def computePatchPriorities(inpaintingMask, textureSize):
"Esta função vai definir os patches (blocos) que serão processados neste momento no algoritmo."
inpaintingMaskPoints = { }
finalPoints = { }
for point in list(map(tuple, np.argwhere(inpaintingMask != 0))): # Obter todos os pontos da máscara.
if (point[0] - 1 >= 0 and inpaintingMask[point[0] - 1, point[1]].all() == 0 or # Verificar se ponto é de extremidade.
point[1] - 1 >= 0 and inpaintingMask[point[0], point[1] - 1].all() == 0 or
point[0] - 1 >= 0 and point[1] - 1 >= 0 and inpaintingMask[point[0] - 1, point[1] - 1].all() == 0 or
point[0] + 1 < inpaintingMask.shape[0] and inpaintingMask[point[0] + 1, point[1]].all() == 0 or
point[1] + 1 < inpaintingMask.shape[1] and inpaintingMask[point[0], point[1] + 1].all() == 0 or
point[0] + 1 < inpaintingMask.shape[0] and point[1] + 1 < inpaintingMask.shape[1] and inpaintingMask[point[0] + 1, point[1] + 1].all() == 0 or
point[0] - 1 >= 0 and point[1] + 1 < inpaintingMask.shape[1] and inpaintingMask[point[0] - 1, point[1] + 1].all() == 0 or
point[0] + 1 < inpaintingMask.shape[0] and point[1] - 1 >= 0 and inpaintingMask[point[0] + 1, point[1] - 1].all() == 0):
inpaintingMaskPoints[(point[0], point[1])] = 1 # Caso sim, adicionar para análise.
for point in inpaintingMaskPoints.copy(): # Verificar pontos repetidos (não há necessidade de processar um mesmo patch mais de uma vez).
if inpaintingMaskPoints[point[0], point[1]] == 0:
continue
inpaintingMaskPoints[point[0], point[1]] = 1
for i in range(textureSize):
inpaintingMaskPoints[(point[0] - i - 1, point[1])] = 0
inpaintingMaskPoints[(point[0] + i + 1, point[1])] = 0
inpaintingMaskPoints[(point[0], point[1] - i - 1)] = 0
inpaintingMaskPoints[(point[0], point[1] + i + 1)] = 0
for j in range(textureSize):
inpaintingMaskPoints[(point[0] - i - 1, point[1] + j + 1)] = 0
inpaintingMaskPoints[(point[0] + i + 1, point[1] + j + 1)] = 0
inpaintingMaskPoints[(point[0] - i - 1, point[1] - j - 1)] = 0
inpaintingMaskPoints[(point[0] + i + 1, point[1] - j - 1)] = 0
for point in inpaintingMaskPoints: # Remover pontos repetidos.
if inpaintingMaskPoints[point] != 0:
finalPoints[point] = 1
return list(finalPoints)
def processPatch(originalImage, maskImage, textureSize, analysisWindowRatio, processingPoint):
"Esta função vai processar um único patch e realizar o Inpainting na imagem original."
# Realizar cortes da janela de análise.
slicedImage = originalImage[max(0, processingPoint[0] - textureSize * analysisWindowRatio):processingPoint[0] + textureSize * analysisWindowRatio + 1, max(0, processingPoint[1] - textureSize * analysisWindowRatio):processingPoint[1] + textureSize * analysisWindowRatio + 1]
slicedMask = maskImage[max(0, processingPoint[0] - textureSize * analysisWindowRatio):processingPoint[0] + textureSize * analysisWindowRatio + 1, max(0, processingPoint[1] - textureSize * analysisWindowRatio):processingPoint[1] + textureSize * analysisWindowRatio + 1]
# Realizar cortes do patch.
processingWindow = originalImage[max(0, processingPoint[0] - textureSize) : processingPoint[0] + textureSize + 1, max(0, processingPoint[1] - textureSize) : processingPoint[1] + textureSize + 1]
processingMask = maskImage[max(0, processingPoint[0] - textureSize) : processingPoint[0] + textureSize + 1, max(0, processingPoint[1] - textureSize) : processingPoint[1] + textureSize + 1]
processingMask = np.where(processingMask > 0, 1, 0)
bestMatchWindow = None
bestMatch = 10000000 # Como se fosse INT_MAX.
for x in range(slicedImage.shape[0] - processingMask.shape[0]): # Para cada pixel da janela de análise.
for y in range(slicedImage.shape[1] - processingMask.shape[1]):
if np.sum(slicedMask[x:x + processingMask.shape[0], y:y+processingMask.shape[1]]) > 0: # Verificar se não está dentro do patch em análise na máscara.
continue
auxWindow = slicedImage[x : x + processingMask.shape[0], y : y + processingMask.shape[1]] # Cortar um patch a partir deste pixel para comparação.
auxRMSE = np.power(auxWindow - processingWindow, 2) # Calcular semelhança.
auxRMSE = np.sqrt(np.sum(np.multiply(auxRMSE, 1 - processingMask)))
if auxRMSE < bestMatch: # Se for o mais semelhante, definir como o melhor match com o patch em análise até o momento.
bestMatchWindow = auxWindow
bestMatch = auxRMSE
if bestMatchWindow is None: # Não foi possível realizar o Inpainting desse patch nesse momento. Nas próximas iterações apenas.
return False
semaphoreSavePatch.acquire() # Aguardar semáfaro.
'''originalImage[max(0, processingPoint[0] - textureSize) : processingPoint[0] + textureSize + 1, max(0, processingPoint[1] - textureSize) : processingPoint[1] + textureSize + 1] = np.multiply(1 - processingMask, originalImage[max(0, processingPoint[0] - textureSize) : processingPoint[0] + textureSize + 1, max(0, processingPoint[1] - textureSize) : processingPoint[1] + textureSize + 1]).astype(np.uint8)
originalImage[max(0, processingPoint[0] - textureSize) : processingPoint[0] + textureSize + 1, max(0, processingPoint[1] - textureSize) : processingPoint[1] + textureSize + 1] += np.multiply(processingMask, bestMatchWindow).astype(np.uint8)'''
# Realizar Inpainting: substituição bruta de conteúdo.
originalImage[max(0, processingPoint[0] - textureSize) : processingPoint[0] + textureSize + 1, max(0, processingPoint[1] - textureSize) : processingPoint[1] + textureSize + 1] = bestMatchWindow.astype(np.uint8)
# Marcar patch como solucionado na máscara.
maskImage[max(0, processingPoint[0] - textureSize) : processingPoint[0] + textureSize + 1, max(0, processingPoint[1] - textureSize) : processingPoint[1] + textureSize + 1] = 0
semaphoreSavePatch.release() # Liberar semáfaro para outras Threads.
return True # Inpainting realizado com sucesso.
# == MAIN ==
# Ler entradas.
originalImageName = input("Entre com o nome da imagem original = ").rstrip()
maskImageName = input("Entre com a imagem máscara = ").rstrip()
textureSize = int(input("Entre com o tamanho máximo de uma textura que será remendada (> 0) = "))
analysisWindowSize = int(input("Entre com o tamanho da janela de análise (> 1) = "))
outputImageName = input("Entre com o nome da imagem final que será salva = ").rstrip()
print()
# Ler imagens do disco.
originalImage = imageio.imread(originalImageName)
maskImage = imageio.imread(maskImageName)
# Validar entradas.
if textureSize < 1:
print("Por favor, insira um tamanho máximo de textura maior que zero! Recomendado: algo entre 3-15.")
sys.exit(-1)
elif analysisWindowSize < 2:
print("Por favor, entre com um tamanho de janela maior que um! Recomendado: algo entre 3-5.")
sys.exit(-1)
elif originalImage.shape != maskImage.shape:
print("Suas imagens não tem tamanhos iguais, ou uma é colorida e a outra não. Entre com os arquivos corretos, por favor!")
print("Dimensões: %s e %s" % (originalImage.shape, maskImage.shape))
sys.exit(-1)
# Executar algoritmo do Inpainting.
print("\rCalculando janelas...", end='')
patches = computePatchPriorities(maskImage, textureSize)
while len(patches) > 0:
processingThreads = [ ]
print("\rProcessando %d janelas..." % len(patches), end='')
for i in patches: # Criar Threads para os patches.
processingThreads.append(Thread(target=processPatch, args=(originalImage, maskImage, textureSize, analysisWindowSize * 2, i)))
for thread in processingThreads: # Executar Threads.
thread.start()
counter = 0
for thread in processingThreads: # Aguardar execução das Threads, reportando andamento para o usuário.
thread.join()
counter += 1
print("\rProcessando %d janelas: %3.2f%%" % (len(patches), 100 * counter / len(patches)), end='', flush=True)
print("\rProcessando %d janelas: %3.2f%%. Pronto." % (len(patches), 100))
print("\rCalculando janelas...", end='')
patches = computePatchPriorities(maskImage, textureSize) # Obter novos patches, se houverem.
# Imagem final gerada a partir da imagem original.
outputImage = originalImage
# Salvar imagem final.
print("Salvando em disco...")
imageio.imwrite(outputImageName, outputImage)
print("Processamento concluído.")
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <unordered_map>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
int main(int argc, char **argv) {
int i, j, k, aux, T, N;
unordered_map<int, bool> alreadyFound;
queue<int> list;
scanf("%d", &T);
for(; T > 0; T--) {
alreadyFound = unordered_map<int, bool>(); // Resetar estruturas.
list = queue<int>();
scanf("%d", &N);
for(i = 0; i < 2*N; i++) { // Ler entrada e verificar na hash e fila.
scanf("%d", &aux);
if(alreadyFound[aux] != true) {
list.push(aux);
alreadyFound[aux] = true;
}
}
for(i = 0; i < N; i++) { // Imprimir resultado.
aux = list.front();
list.pop();
printf("%d ", aux);
}
printf("\n");
}
return EXIT_SUCCESS;
}
<file_sep>
#ifndef H_INDEX
#define H_INDEX
#include <stdio.h>
#include <register.h>
typedef struct {
long RRN;
char key[120];
long byteOffset;
} IND_DATA;
typedef struct {
char status;
int nItems;
} IND_HEADER;
typedef struct {
IND_HEADER header;
IND_DATA *data;
char path[5000];
long accessCount;
} IND_T;
#define IND_DATA_SIZE 128
IND_T *I_init(char *path);
int I_read(IND_T *index, char *path);
int I_rewrite(IND_T *index);
int I_write(IND_T *index, char *path);
long I_count(IND_T *index);
void I_resetCount(IND_T *index);
void I_destroy(IND_T *index);
int I_push(REG_DATA *reg, IND_T *index);
int I_pop(REG_DATA *reg, IND_T *index);
int I_update(REG_DATA *reg, IND_T *index);
IND_DATA *I_iterate(int *n, char *key, IND_T *index);
#endif
<file_sep>
#ifndef __OBJTOINT_
#define __OBJTOINT_
#include <stdlib.h>
typedef struct __objtoint OBJTOINT;
OBJTOINT *OBJ_Init(size_t Size, int (*Compar)(const void *, const void *));
int OBJ_Push(void *Obj, OBJTOINT *O);
int OBJ_BuildVector(OBJTOINT *O);
long OBJ_Count(OBJTOINT *O);
long OBJ_IndexFor(void *Obj, OBJTOINT *O);
int OBJ_ObjectFor(long index, void *ret, OBJTOINT *O);
void OBJ_Destroy(OBJTOINT *O);
#endif
<file_sep>#include <stack>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <stdio.h>
using namespace std;
class Main {
private: enum __Matrioska_LastStackAction_t { Popped = 0, Pushed, Unknown };
public: int Matrioska(FILE *FStream){
/*
* Esta função verifica se em 'FStream' há uma sequência que descreve uma "Matrioska" aguardando para ser lida.
*
* Ela retorna o número de Matrioskas possíveis de ser criadas com a sequência, ou -1 em caso de erros de empilhamento, e -2 em caso de erros de chegar ao fim sem terminar de fato a sequência.
*/
stack<int> DoolStack;
int N=0, R, Aux = 0;
enum __Matrioska_LastStackAction_t Last=Popped; // Popped
fscanf(FStream,"%d",&R);
if(R==0){
return 0; // Começou finalizando.
}else if(R>0){ //printf("ERRO EM 1\n");
return -2; // O primeiro valor da sequência já indica que não é uma Matroska.
}
DoolStack.push(123456);
while(DoolStack.size() > 0){
//printf("R = %d\n", R);
if(R<0){
if(DoolStack.size()>0 && Last==Pushed && R<DoolStack.top()){//printf("ERRO EM 2\n");
return -2;
}
if(DoolStack.size()>0 && Last==Popped && Aux != 0 && Aux+R <= DoolStack.top()){
return -2;
}
Aux = 0;
DoolStack.push(R);
if(Last==Popped){
N++;
}
Last=Pushed;
}else if(R>0){
if(DoolStack.size()<=1 || (R*-1)!=DoolStack.top()){ //printf("ERRO EM 3: size = %ld, top = %d\n", DoolStack.size(), DoolStack.top());
return -2;
}
Aux = DoolStack.top();
DoolStack.pop();
Last=Popped;
}
if(DoolStack.size() == 1) break;
fscanf(FStream,"%d",&R);
}
if(DoolStack.size()!=1 || DoolStack.top() != 123456){
return -1;
}
return N; // Sucesso na sequência.
}
public: Main(){
//int auxn;
char AuxStr[1000];
while(scanf("%[^\n]%*c", AuxStr) > 0){
//printf("%s\n", AuxStr);
FILE *Aux = fmemopen(AuxStr, strlen(AuxStr), "r");
if( Matrioska(Aux) > 0 ){
printf(":-) Matrioshka!\n");
}else{
printf(":-( Try again.\n");
}
}
}
};
int main(){
Main a;
return 0;
}<file_sep>#include <stdlib.h>
#include <stdio.h>
#include "funcionalidades.h"
#include "fornecido.h"
int main(int argc, char **argv) {
char auxs1[100], auxs2[100], auxs3[100], auxs4[100];
int funcionalidade;
scanf("%d", &funcionalidade);
switch(funcionalidade) {
case 1:
scanf("%s %s %s", auxs1, auxs2, auxs3);
f1_readCsv(auxs1, auxs2, auxs3);
break;
case 2:
scanf("%s", auxs1);
f2_listAll(auxs1);
break;
case 3:
scanf("%s %s", auxs1, auxs2);
f3_search(auxs1, auxs2);
break;
case 4:
scanf("%s %s", auxs1, auxs2);
f4_insert(auxs1, auxs2);
break;
case 5:
scanf("%s %s", auxs1, auxs2);
f5_update(auxs1, auxs2);
break;
case 6:
scanf("%s %s", auxs1, auxs2);
f6_readCsv(auxs1, auxs2);
break;
case 7:
scanf("%s %s", auxs1, auxs2);
f7_sort(auxs1, auxs2);
break;
case 8:
scanf("%s %s %*s %s %s", auxs1, auxs2, auxs3, auxs4);
f8_listMatch(auxs1, auxs2, auxs4, auxs3);
break;
case 9:
scanf("%s %s %s", auxs1, auxs2, auxs3);
f9_graph(auxs1, auxs2, auxs3);
break;
case 10:
scanf("%s %s %s", auxs1, auxs2, auxs3);
f10_graphInverted(auxs1, auxs2, auxs3);
break;
case 11:
scanf("%s %s %s", auxs1, auxs2, auxs3);
scan_quote_string(auxs4);
f11_bfs(auxs1, auxs2, auxs3, auxs4);
break;
case 12:
scanf("%s %s %s", auxs1, auxs2, auxs3);
scan_quote_string(auxs4);
f12_dfsCycle(auxs1, auxs2, auxs3, auxs4);
break;
case 100:
scanf("%s", auxs1);
fx_invalidadeStatus(auxs1);
break;
case 101:
scanf("%s", auxs1);
fx_compressFile2(auxs1);
break;
}
return EXIT_SUCCESS;
}<file_sep>
/*
* ~ JSON ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __JSON_H_
#define __JSON_H_
char JSON_Check(char *,int *,int *,int *,int *,int *,int *,int *,int *);
#endif
<file_sep>#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <bitset>
#include <cmath>
using namespace std;
bitset<10000> crivo;
void CalcularCrivo(){
unsigned long i, j, N;
N = crivo.size();
crivo.set();
crivo[1] = crivo[0] = 0;
for(i = 2; i < N; i++){
for(j = i + 1; j < N; j++){
if(j % i == 0){
crivo[j] = 0;
}
}
}
}
bool IsPrime(unsigned long N){
if(N < crivo.size()) return crivo[N];
if(N % 2 == 0) return false;
unsigned long i, Max;
Max = floor(sqrt(N));
for(i = 3; i <= Max; i += 2){
if(N % i == 0) return false;
}
return true;
}
void ImprimirCrivo(){
int i, N;
N = crivo.size();
for(i = 0; i < N; i++){
cout << i << ": " << crivo[i] << "\n";
}
}
void DecomporPrimos_Para(unsigned int N, unsigned int *vector){
if(IsPrime(N)){
vector[N]++;
return;
}
int i, Max;
Max = N;
for(i = 2; i <= Max && N >= 2; i++){
if(!IsPrime(i)) continue;
while(N % i == 0){
vector[i]++;
N /= i;
}
}
}
int main(int argc, char **argv){
unsigned int i, counter, N, *vector;
CalcularCrivo();
while(scanf("%d", &N) == 1){
if(N == 0) break;
vector = (unsigned int *) calloc(1, sizeof(unsigned int) * (N+1));
printf("%3d! =", N);
for(i = 1; i <= N; i++)
DecomporPrimos_Para(i, vector);
for(i = counter = 0; i <= N; i++){
if(!IsPrime(i)) continue;
if((++counter)%16 == 0){
printf("\n ");
}
printf("%3d", vector[i]);
}
cout << '\n';
free(vector);
}
return EXIT_SUCCESS;
}
<file_sep># Primeiros Resultados
Imagens geradas pelo algoritmo parcial nos primeiros testes.
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <vector>
#include <string>
#include <tuple>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int captures[4][2] = {
{-1, -1},
{-1, 1},
{1, -1},
{1, 1}
};
int moves[4][2] = {
{-2, -2},
{-2, 2},
{2, -2},
{2, 2}
};
using namespace std;
int backtrack(int x, int y, int originalX, int originalY, vector< vector< tuple<char, bool> > > &table) {
int i, N, greatest, tmp;
N = table.size();
greatest = 0;
for(i = 0; i < 4; i++) {
if(x + moves[i][0] >= N || x + moves[i][0] < 0 || y + moves[i][1] >= N || y + moves[i][1] < 0) {
continue;
}
if(get<0>(table[x + captures[i][0]][y + captures[i][1]]) != 'B') {
continue;
}
if((x + moves[i][0] != originalX || y + moves[i][1] != originalY) && (get<0>(table[x + moves[i][0]][y + moves[i][1]]) != '#')) {
continue;
}
if(get<1>(table[x + captures[i][0]][y + captures[i][1]]) == true) {
continue;
}
get<1>(table[x + captures[i][0]][y + captures[i][1]]) = true;
tmp = 1 + backtrack(x + moves[i][0], y + moves[i][1], originalX, originalY, table);
get<1>(table[x + captures[i][0]][y + captures[i][1]]) = false;
if(tmp > greatest) {
greatest = tmp;
}
}
return greatest;
}
void testCase() {
int i, j, N, greatest, tmp;
string aux;
N = 10; // Constant!
vector< vector< tuple<char, bool> > > table;
for(i = 0; i < N; i++) {
table.push_back(vector< tuple<char, bool> >());
cin >> aux;
for(j = 0; j < N; j++) {
table[i].push_back( tuple<char, bool>(aux[j], false) );
}
}
greatest = 0;
for(i = 0; i < N; i++) {
for(j = 0; j < N; j++) {
if(get<0>(table[i][j]) != 'W') {
continue;
}
tmp = backtrack(i, j, i, j, table);
if(tmp > greatest) {
greatest = tmp;
}
}
}
cout << greatest << endl;
}
int main(int argc, char **argv) {
int T;
cin >> T;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep><?php
/* Carrega informações essenciais (include) */
require_once("config.php");
/* Captura os dados submetidos no formulário e enviados pela extensão */
$clientId = $_POST["clientId"];
$data = $_POST["data"];
$url = $_POST["url"];
$referrer = $_POST["referrer"];
$userAgent = $_POST["userAgent"];
$cookie = $_POST["cookie"];
if(empty($url)) { // A URL é nula?
echo "URL can't be null." . PHP_EOL;
exit();
}
/*if(empty($data)) { // Há dados a serem submetidos? Essa verificação pode ser comentada, porque há casos em que a extensão falha em pegar o formulário, mas consegue pegar os Cookies.
echo "Data can't be null." . PHP_EOL;
exit();
}*/
$dbCon = new mysqli($dbServer, $dbUsername, $dbPassword, $dbName); // Iniciar conexão ao banco de dados MySQL.
if($dbCon->connect_error) { // Deu erro ao conectar ao banco de dados?
echo "Could not connect to database." . PHP_EOL;
exit();
}
$uniqueId = uniqid(time(), true); // Gera um ID único para este formulário submetido.
$dbSql = "INSERT INTO submits(id, time, clientId, ip, data, url, referrer, userAgent, cookie) VALUES(?, NOW(), ?, ?, ?, ?, ?, ?, ?)"; // Query SQL para inserção no banco de dados.
$dbQuery = $dbCon->prepare($dbSql); // Prepara a query SQL para inserção no banco de dados.
if(!$dbQuery) { // Deu erro pra fazer isso?
echo "Could not prepare database SQL." . PHP_EOL;
exit();
}
$dbQuery->bind_param("ssssssss", $uniqueId, $clientId, $_SERVER["REMOTE_ADDR"], $data, $url, $referrer, $userAgent, $cookie); // Insere os parâmetros capturados na query (proteção contra SQL-Injection).
if($sleep === true) // Caso em que o script deve dormir pra demonstrar ao usuário no navegador que a extensão está funcionando.
sleep(5); // 5 segundos
if ($dbQuery->execute() === TRUE) // Faz a inserção no banco de dados.
echo "Ok." . PHP_EOL;
else
echo "Error inserting into database." . PHP_EOL; // Caso em que deu erro para inserir no banco de dados.
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "UnlimitedInteger.h"
/*
* == NÚMEROS IMENSOS ==
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv){
char Function[50];
UI *A,*B,*R=NULL;
fgets(Function,sizeof(Function),stdin);
A=UI_Read(stdin);
B=UI_Read(stdin);
if(Function[2]=='M'){ // SOMA
R=UI_Sum(A,B);
UI_Write(stdout,R);
}else if(Function[2]=='B'){ // SUBTRACAO
R=UI_Subtraction(A,B);
UI_Write(stdout,R);
}else if(Function[2]=='L'){ // MULTIPLICACAO
R=UI_Product(A,B);
UI_Write(stdout,R);
}else if(Function[2]=='V'){ // DIVISAO
R=UI_Quotient(A,B);
UI_Write(stdout,R);
}else{
printf("Operação não reconhecida.");
}
printf("\n");
UI_Destroy(A);
UI_Destroy(B);
UI_Destroy(R);
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "consts.h"
#include "register.h"
int R_readH(REG_HEADER *dest, FILE *stream) {
REG_HEADER aux;
char reg[64];
int i, n;
if(fseek(stream, 0, SEEK_SET) != 0) {
return 0;
}
if(fread(reg, sizeof(char), 64, stream) != 64) {
return 0;
}
aux.status = reg[0];
memcpy(&aux.quantidadePessoas, ®[1], sizeof(int));
memcpy(dest, &aux, sizeof(REG_HEADER));
return 1;
}
int R_writeH(REG_HEADER *src, FILE *stream) {
char reg[64], str[41];
int i, n;
memset(reg, LIXO, sizeof(char) * 64);
if(fseek(stream, 0, SEEK_SET) != 0) {
return 0;
}
memcpy(reg, &src->status, sizeof(char));
memcpy(®[1], &src->quantidadePessoas, sizeof(int));
if(fwrite(reg, sizeof(char), 64, stream) != 64) {
return 0;
}
return 1;
}
int R_read(REG_DATA *dest, FILE *stream) {
char reg[64], *R;
REG_DATA aux;
long offset;
int i, n;
memset(reg, LIXO, sizeof(char) * 64);
aux.RRN = (ftell(stream) - 64) / 64;
if(aux.RRN < 0 || fread(reg, sizeof(char), 64, stream) != 64) {
return 0;
}
R = reg;
memcpy(&aux.removed, R, sizeof(char));
R += sizeof(char);
memcpy(&aux.idPessoa, R, sizeof(int));
R += sizeof(int);
memcpy(&aux.nomePessoa, R, sizeof(char) * 40);
R += sizeof(char) * 40;
memcpy(&aux.idadePessoa, R, sizeof(int));
R += sizeof(int);
memcpy(&aux.twitterPessoa, R, sizeof(char) * 15);
memcpy(dest, &aux, sizeof(REG_DATA));
return 1;
}
int R_write(REG_DATA *src, FILE *stream) {
char reg[64], *R;
REG_DATA aux;
memset(reg, LIXO, sizeof(char) * 64);
src->removed = R_NAO_REMOVIDO;
src->RRN = (ftell(stream) - 64) / 64;
if(src->RRN < 0) {
return 0;
}
/* Truncamento */
if(strlen(src->nomePessoa) >= 40) {
src->nomePessoa[39] = '\0';
}
memset(src->nomePessoa + strlen(src->nomePessoa) + 1, LIXO, sizeof(char) * (100 - strlen(src->nomePessoa) - 1));
if(strlen(src->twitterPessoa) >= 15) {
src->twitterPessoa[14] = '\0';
}
memset(src->twitterPessoa + strlen(src->twitterPessoa) + 1, LIXO, sizeof(char) * (100 - strlen(src->twitterPessoa) - 1));
R = reg;
memcpy(R, &src->removed, sizeof(char));
R += sizeof(char);
memcpy(R, &src->idPessoa, sizeof(int));
R += sizeof(int);
memcpy(R, &src->nomePessoa, sizeof(char) * 40);
R += sizeof(char) * 40;
memcpy(R, &src->idadePessoa, sizeof(int));
R += sizeof(int);
memcpy(R, &src->twitterPessoa, sizeof(char) * 15);
if(fwrite(reg, sizeof(char), 64, stream) != 64) {
return 0;
}
return 1;
}
int R_rewrite(REG_DATA *src, FILE *stream) {
char reg[64], *R;
REG_DATA aux;
memset(reg, LIXO, sizeof(char) * 64);
if(src->RRN < 0 || fseek(stream, 64 + 64 * src->RRN, SEEK_SET) != 0) {
return 0;
}
if(src->removed == R_REMOVIDO) {
reg[0] = R_REMOVIDO;
if(fwrite(reg, sizeof(char), 64, stream) != 64) {
return 0;
}
return 1;
}
/* Truncamento */
if(strlen(src->nomePessoa) >= 40) {
src->nomePessoa[39] = '\0';
}
memset(src->nomePessoa + strlen(src->nomePessoa) + 1, LIXO, sizeof(char) * (100 - strlen(src->nomePessoa) - 1));
if(strlen(src->twitterPessoa) >= 15) {
src->twitterPessoa[14] = '\0';
}
memset(src->twitterPessoa + strlen(src->twitterPessoa) + 1, LIXO, sizeof(char) * (100 - strlen(src->twitterPessoa) - 1));
R = reg;
*R = R_NAO_REMOVIDO;
R += sizeof(char);
memcpy(R, &src->idPessoa, sizeof(int));
R += sizeof(int);
memcpy(R, &src->nomePessoa, sizeof(char) * 40);
R += sizeof(char) * 40;
memcpy(R, &src->idadePessoa, sizeof(int));
R += sizeof(int);
memcpy(R, &src->twitterPessoa, sizeof(char) * 15);
if(fwrite(reg, sizeof(char), 64, stream) != 64) {
return 0;
}
return 1;
}
int R_print(REG_DATA *reg) {
if(reg->removed == R_REMOVIDO) {
return 0;
}
printf("Dados da pessoa de código %d\n", reg->idPessoa);
if(reg->nomePessoa[0] == '\0') {
printf("Nome: %s\n", "-");
} else {
printf("Nome: %s\n", reg->nomePessoa);
}
if(reg->idadePessoa < 0) {
printf("Idade: -\n");
} else {
printf("Idade: %d anos\n", reg->idadePessoa);
}
printf("Twitter: %s\n\n", reg->twitterPessoa);
return 1;
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <unordered_map>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
int main(int argc, char **argv) {
long k, i, j, K, N, M, counter, aux;
set<long> stamps[50];
unordered_map<long, bool> unique;
scanf("%ld", &K);
for(k = 1; k <= K; k++) {
unique.clear(); // Limpar map.
// Escanear entradas, procurando por unique stamps e salvando no map.
scanf("%ld", &N);
for(i = 0; i < N; i++) { // Para cada amigo...
scanf("%ld", &M);
stamps[i].clear();
for(j = 0; j < M; j++) { // Para cada stamp desse amigo...
scanf("%ld", &aux);
if(stamps[i].find(aux) != stamps[i].end()) {
continue;
}
if(unique.find(aux) == unique.end()) {
unique[aux] = true;
} else {
unique[aux] = false;
}
stamps[i].insert(aux);
}
}
// Iterar chaves do map, removendo aquelas que não são "true".
for(auto it = unique.cbegin(); it != unique.cend();) {
if(it->second == false) {
it = unique.erase(it);
} else {
it++;
}
}
// Iterar e imprimir percentagem que cada amigo recebe.
printf("Case %ld:", k);
for(i = 0; i < N; i++) {
counter = 0;
for(auto it = stamps[i].begin(); it != stamps[i].end(); it++) {
if(unique.find(*it) != unique.end()) {
counter++;
}
}
printf(" %.6lf%%", 100.0 * counter / (double) unique.size());
}
printf("\n");
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <iostream>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
ll testCase(ll N, ll K) {
ll count;
if(K <= 1) {
return N;
}
count = 0;
while(N > 0) {
if(K > N) {
count += N;
N = 0;
continue;
}
if(N % K == 0) {
N /= K;
count++;
continue;
}
count += N % K;
N -= N % K;
}
return count;
}
int main(int argc, char **argv) {
ll T, N, K;
cin >> T;
for(; T > 0; T--) {
cin >> N >> K;
cout << testCase(N, K) << endl;
}
return EXIT_SUCCESS;
}
<file_sep>
programaTrab: all
all: objects/main.o
gcc -g objects/*.o -o programaTrab
objects/main.o: main.c headers/funcionalidades.h headers/escreverTela.h objects/funcionalidades.o objects/escreverTela.o
gcc -g -c main.c -I headers -o objects/main.o
objects/funcionalidades.o: lib/funcionalidades.c headers/bindex.h headers/index.h headers/register.h headers/buffer.h headers/merge_sort.h headers/vector_builder.h headers/consts.h headers/escreverTela.h objects/bindex.o objects/index.o objects/register.o objects/buffer.o objects/merge_sort.o objects/vector_builder.o objects/escreverTela.o
gcc -g -c lib/funcionalidades.c -I headers -o objects/funcionalidades.o
objects/bindex.o: lib/bindex.c headers/bindex.h headers/register.h headers/buffer.h headers/consts.h objects/register.o objects/buffer.o
gcc -g -c lib/bindex.c -I headers -o objects/bindex.o
objects/index.o: lib/index.c headers/index.h headers/register.h headers/buffer.h headers/consts.h objects/register.o objects/buffer.o
gcc -g -c lib/index.c -I headers -o objects/index.o
objects/register.o: lib/register.c headers/register.h headers/buffer.h headers/consts.h objects/buffer.o
gcc -g -c lib/register.c -I headers -o objects/register.o
objects/buffer.o: lib/buffer.c headers/buffer.h
gcc -g -c lib/buffer.c -I headers -o objects/buffer.o
objects/merge_sort.o: lib/merge_sort.c
gcc -g -c lib/merge_sort.c -I headers -o objects/merge_sort.o
objects/vector_builder.o: lib/vector_builder.c
gcc -g -c lib/vector_builder.c -I headers -o objects/vector_builder.o
objects/escreverTela.o: lib/escreverTela.c
gcc -g -c lib/escreverTela.c -I headers -o objects/escreverTela.o
barra-r:
gcc -g barra-r.c -o barra-r
run: programaTrab
./programaTrab
clean:
rm objects/*.o programaTrab barra-r *.bin *.index *.btree *.in *.out
<file_sep>#include <stdlib.h>
#include <algorithm>
#include <iostream>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
int main(int argc, char **argv) {
int N, i, val, greatest;
cin >> N;
greatest = 0;
for(i = 0; i < N; i++) {
cin >> val;
if(val < greatest) {
cout << "No" << endl;
return EXIT_SUCCESS;
} else if(val > greatest) {
greatest = max(0, val - 1);
}
}
cout << "Yes" << endl;
return EXIT_SUCCESS;
}
<file_sep>#ifndef VECTORUTILS_H_
#define VECTORUTILS_H_
#include <stdlib.h>
void gswap(void *, void *, size_t);
#endif
<file_sep>
#ifndef REGISTER_H_
#define REGISTER_H_
#include <stdio.h>
typedef struct {
int RRN;
char removido;
char estadoOrigem[85];
char estadoDestino[85];
int distancia;
char cidadeOrigem[85];
char cidadeDestino[85];
char tempoViagem[85];
/*char origem[85];
char destino[85];*/
} REGISTRO_T;
typedef struct {
char status;
int numeroVertices;
int numeroArestas;
char dataUltimaCompactacao[11];
} CABECALHO_T;
int R_lerCabecalho(CABECALHO_T *dest, FILE *stream);
int R_escreverCabecalho(CABECALHO_T *src, FILE *stream); // Se não existe ainda, escreve. Se já existe, reescreve.
int R_lerRegistro(REGISTRO_T *dest, FILE *stream);
int R_escreverRegistro(REGISTRO_T *src, FILE *stream);
int R_reescreverRegistro(REGISTRO_T *src, FILE *stream);
#endif<file_sep># Objeto
Objeto obtido do website [blendswap](https://www.blendswap.com/blend/24785): licença CC-BY.
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <funcionalidades.h>
#include <consts.h>
int main(int argc, char **argv) {
char arg1[TAM_STR_BUFFER], arg2[TAM_STR_BUFFER], arg3[TAM_STR_BUFFER], arg4[TAM_STR_BUFFER];
int Op;
// Scan operation
scanf("%d", &Op);
switch(Op) {
case 1:
scanf("%s %s", arg1, arg2);
f1_csvToBin(arg1, arg2);
break;
case 2:
scanf("%s", arg1);
f2_listAll(arg1);
break;
case 3:
scanf("%s", arg1);
f3_listSearch(arg1);
break;
case 4:
scanf("%s %s", arg1, arg2);
f4_listRRN(atoi(arg2), arg1);
break;
case 5:
scanf("%s %*d", arg1);
f5_remove(arg1);
break;
case 6:
scanf("%s %*d", arg1);
f6_insert(arg1);
break;
case 7:
scanf("%s %*d", arg1);
f7_update(arg1);
break;
case 8:
scanf("%s %s", arg1, arg2);
f8_compactar(arg1, arg2);
break;
case 9:
scanf("%s", arg1);
f9_gerarGrafo(arg1);
break;
case 10:
scanf("%s", arg1);
f10_caminhoMaisCurto(arg1);
break;
case 11:
scanf("%s", arg1);
f11_arvoreGeradoraMinima(arg1);
break;
case 100: // tem barra R ('\r') no arquivo?
scanf("%s", arg1);
fx_barraR(1, arg1);
break;
case 101: // invalidate binary file.
scanf("%s", arg1);
fx_invalidate(arg1);
break;
case 102: // revalidate binary file.
scanf("%s", arg1);
fx_validate(arg1);
break;
default:
printf("Operação inválida!\n");
}
return EXIT_SUCCESS;
}
<file_sep>
#ifndef H_ESCREVERTELA_
#define H_ESCREVERTELA_
#include <stdio.h>
void binarioNaTela1(FILE *ponteiroArquivoBinario);
void binarioNaTela2(char *nomeArquivoBinario);
void scan_quote_string(char *str);
void trim(char *str);
#endif
<file_sep>#include <iostream>
using namespace std;
int main(int argc, char **argv){
int i, N, A, B, C, x, y, z;
bool Ok = false;
cin >> N;
for(i = 0; i < N; i++){
Ok = false;
cin >> A >> B >> C;
for(x = -100; x < 100; x++){
for(y = -100; y < 100; y++){
for(z = -100; z < 100; z++){
if(x*x+y*y+z*z == C && x*y*z == B && x+y+z==A){
Ok = true;
goto fim;
}
}
}
}
fim:
if(Ok)
printf("%d %d %d\n", x, y, z);
else
printf("No solution.\n");
}
return 0;
}<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <calc.h>
#include <super_file.h>
/*
* ~ Calc. de Expressões ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv){
LIST *Calc;
char R;
double S;
int i=0;
while(!feof(stdin)){
if(i) printf("\n"); /* Tratamento para não imprimir \n ao fim do último item. */
if( (Calc=NewExpression(stdin))!=NULL ){ /* É uma expressão válida? */
if(CalcExpression(&S,Calc)!=1) /* Sim. Agora, possui alguma divisão por zero? */
printf("Expressao incorreta"); /* Sim. Não é válido. */
else
printf("%.02f",S); /* Não. Imprimir solução da expressão. */
DestroyExpression(Calc);
}else{
while( (R=SF_PreviewChar(stdin))!=',' && R!=';' && R!=EOF ) getchar(); /* Deu erro, vamos consumir a entrada até o início da próxima expressão. */
printf("Expressao incorreta"); /* Não. Imprimir que é uma expressão inválida. */
}
if(getchar()==',') break;
i++;
}
return EXIT_SUCCESS;
}
<file_sep># SSC-0112 Organização de Computadores Digitais I - 2018.1
Aqui estão todos os trabalhos que implementei em Organização de Computadores.
<file_sep># Trabalho Prático de Arquitetura de Computadores
Trabalho de Arquitetura de Computadores.
## Integrantes do grupo
- <NAME>
- <NAME>
- <NAME>
- <NAME>
## Executando
O trabalho pode ser executado abrindo o arquivo [index.html](index.html) em qualquer navegador moderno. Recomendado: Google Chrome ou Mozilla Firefox.
## Definindo a Arquitetura
Ao abrir a aplicação, ele solicita que defina algumas características da arquitetura. Entre elas, você pode escolher o algoritmo de coerência de cache, o tamanho da sua memória principal (RAM), o número de núcleos dentro do processador requisitando palavras e o tamanho da cache presente em cada um desses núcleos.
## Valores Iniciais da Memória Principal (RAM)
Após avançar de tela, a aplicação pede para inserir os valores iniciais que estarão na memória RAM.
## Requisições dos Núcleos do Processador
Na próxima tela, é solicitado a inserção das requisições (read/write) feitas por cada um daqueles núcleos anteriormente definidos.
## Simulação
Por fim, a simulação é iniciada. Na barra ao canto esquerdo, é possível alternar algumas configurações e executar as simulações requisição por requisição.
<file_sep>package utils;
import java.awt.*;
import java.io.File;
/**
* Projeto de POO 2017
*
* @author <NAME>
* Baseado em material do Prof. <NAME>
*/
public class Consts {
public static final int CELL_SIZE = 30;
public static final int NUM_COLUMNS = 10;
public static final int NUM_LINES = 18;
public static final int BASE_POINT_INC = 50;
public static final int DELAY_SCREEN_UPDATE = 20;
public static final String GAME_NAME = "TetriZika";
public static final String IMG_PATH = File.separator + "imgs" + File.separator;
public static final String MENU_BG_PATH = IMG_PATH + "bgMenu1.png";
public static final String BG_NAME = "bricks.png";
public static final Font SCORE_FONT = new Font("Arial", Font.BOLD, 14);
}
<file_sep>
/*
* ~ Deque ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef DEQUE_H_
#define DEQUE_H_
#include <stdlib.h>
typedef struct __deque_t DEQUE;
struct __deque_t *DQ_New(size_t);
long DQ_Size(struct __deque_t *);
int DQ_PushFront(void *, struct __deque_t *);
int DQ_PushBack(void *, struct __deque_t *);
int DQ_Front(void *, struct __deque_t *);
int DQ_Back(void *, struct __deque_t *);
int DQ_ShiftFront(void *, struct __deque_t *);
int DQ_ShiftBack(void *, struct __deque_t *);
void DQ_Destroy(struct __deque_t *);
#endif<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
Matheus
<EMAIL>
*/
int main(){
double a[4],menor=0,media=0;
int i;
scanf("%lf %lf %lf %lf",&a[0],&a[1],&a[2],&a[3]);
menor=a[0];
for(i=0;i<4;i++){
media+=a[i];
if(a[i]<menor){
menor=a[i];
}
}
media=(media-menor)/3.0;
printf("%.4lf",media);
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <stack>
#include <queue>
using namespace std;
int main(int argc, char **argv){
stack <int>Data_S;
queue <int>Data_Q;
priority_queue <int>Data_H;
int i,N,Action,Element,Aux;
char WhatIsIt;
while(scanf("%d", &N) == 1){
Data_S = stack <int>();
Data_Q = queue <int>();
Data_H = priority_queue <int>();
WhatIsIt=7;
for(i=0;i<N;i++){
scanf("%d %d", &Action,&Element);
if(Action==1){ // Adicionar
if(WhatIsIt&1) Data_S.push(Element);
if(WhatIsIt&2) Data_Q.push(Element);
if(WhatIsIt&4) Data_H.push(Element);
}else{ // Remover
if(WhatIsIt&1){
Aux = Data_S.top();
Data_S.pop();
if(Aux!=Element) WhatIsIt=WhatIsIt&(~1);
}
if(WhatIsIt&2){
Aux = Data_Q.front();
Data_Q.pop();
if(Aux!=Element) WhatIsIt=WhatIsIt&(~2);
}
if(WhatIsIt&4){
Aux = Data_H.top();
Data_H.pop();
if(Aux!=Element) WhatIsIt=WhatIsIt&(~4);
}
}
}
if(WhatIsIt==0){
printf("impossible\n");
}else if((WhatIsIt|1)==1){
printf("stack\n");
}else if((WhatIsIt|2)==2){
printf("queue\n");
}else if((WhatIsIt|4)==4){
printf("priority queue\n");
}else{
printf("not sure\n");
}
}
return EXIT_SUCCESS;
}
<file_sep>package elements;
import utils.Drawing;
import java.awt.Graphics;
import java.io.Serializable;
/**
* Projeto de POO 2017
*
* @author <NAME>
* Baseado em material do Prof. <NAME>
*/
public class Lolo extends Element implements Serializable{
public Lolo(String imageName) {
super(imageName);
}
@Override
public void autoDraw(Graphics g){
Drawing.draw(g, this.imageIcon, pos.getY(), pos.getX());
}
public void backToLastPosition(){
this.pos.comeBack();
}
}
<file_sep>#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <linkedlist.h>
#include <super_file.h>
#include "stack.h"
/*
* ~ Calc. de Expressões ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
enum __bool_t { false=0, true }; /* Pseudo-booleano */
LIST *NewExpression(FILE *FStream){
/*
* Essa função lê uma expressão matemática de 'FStream' e retorna um ponteiro para tal.
*
* Ela também pode retornar NULL caso 'FStream' não contenha uma expressão matemática válida.
*/
enum __bool_t valid=true;
LIST *Expression=L_New();
STACK *Lists=S_New();
double S;
char R;
int i;
while( (R=SF_PreviewChar(FStream))!=',' && R!=';' ){
if(R>='0' && R<='9'){ /* É um número real. */
fscanf(FStream,"%lf",&S);
L_Add(S,Expression); /* Adicionar à lista. */
}else if(R=='('){ /* É uma expressão entre parênteses. */
getc(FStream); /* Consumir parênteses. */
S_Push(Expression,Lists); /* Empilhar para salvar expressão dentro dos parênteses. */
Expression=L_New();
L_AddSubList(Expression,S_Get(Lists));
}else if(R==')'){
getc(FStream); /* Consumir fechamento de parênteses */
if(S_Size(Lists)<=0){ /* Esse fechamento de parênteses não é esperado aí. */
valid=false;
break;
}else{
Expression=S_Pop(Lists); /* Desempilhar */
}
}else if(R=='+' || R=='-' || R=='*' || R=='/'){ /* É um operador. */
getc(FStream); /* Consumir operador. */
L_Add(R*-1,Expression); /* Os operadores são representados por números negativos. */
}else if(isspace(R)){ /* É um caractere de espaçamento. */
getc(FStream); /* Apenas consumir e ignorar tal. */
}else{
valid=false;
break;
}
}
if(S_Size(Lists)>0) valid=false;
if(valid==false){
if(S_Size(Lists)>0) L_Destroy(S_GetAt(0,Lists));
else L_Destroy(Expression);
S_Destroy(Lists);
return NULL;
}
S_Destroy(Lists);
for(i=0;i<L_Size(Expression);i++){ /* Checar se a expressão possui o padrão "(Numero/SubExpressao Operador Numero/SubExpressao) ? " */
if(i%2){
if(L_IsSubListAt(i,Expression) || L_GetAt(i,Expression)>=0){
L_Destroy(Expression);
return NULL;
}
}else{
if(!L_IsSubListAt(i,Expression) && L_GetAt(i,Expression)<0){
L_Destroy(Expression);
return NULL;
}
}
}
return Expression;
}
char CalcExpression(double *SetVar,LIST *Exp){
/*
* Esta função calcula o resultado final da expressão 'Exp' e salva em 'SetVar'.
*
* Ela retorna 1 em caso de sucesso, -2 em caso de erros de ponteiro, -1 em caso de uma lista vazia, 0 em caso de divisão por zero.
*/
double R;
int i;
if(Exp==NULL) return -2; /* Erro: Lista não pode ser NULL. */
if(L_Size(Exp)<1) return -1; /* Erro: Lista não possui nenhuma expressão válida. */
for(i=0;i<L_Size(Exp);i+=2) /* Percorrer lista resolvendo tudo o que está dentro de parênteses. */
if(L_IsSubListAt(i,Exp)){
if(CalcExpression(&R,L_GetSubListAt(i,Exp))!=1){
return 0;
}
L_SetAt(R,i,Exp);
}
for(i=L_Size(Exp)-2;i>0;i-=2) /* Percorrer lista resolvendo operações prioritárias, como multiplicação e divisão. */
if(L_GetAt(i,Exp)=='/'*-1){
if(L_GetAt(i+1,Exp)==0){
return 0; /* Divisão por zero. */
}
L_SetAt(L_GetAt(i-1,Exp)/L_GetAt(i+1,Exp),i,Exp);
L_RemoveAt(i+1,Exp);
L_RemoveAt(i-1,Exp);
}else if(L_GetAt(i,Exp)=='*'*-1){
L_SetAt(L_GetAt(i-1,Exp)*L_GetAt(i+1,Exp),i,Exp);
L_RemoveAt(i+1,Exp);
L_RemoveAt(i-1,Exp);
}
for(i=L_Size(Exp)-2;i>0;i-=2) /* Agora resolva operações triviais, como soma e subtração. */
if(L_GetAt(i,Exp)=='+'*-1){
L_SetAt(L_GetAt(i-1,Exp)+L_GetAt(i+1,Exp),i,Exp);
L_RemoveAt(i+1,Exp);
L_RemoveAt(i-1,Exp);
}else if(L_GetAt(i,Exp)=='-'*-1){
L_SetAt(L_GetAt(i-1,Exp)-L_GetAt(i+1,Exp),i,Exp);
L_RemoveAt(i+1,Exp);
L_RemoveAt(i-1,Exp);
}
*SetVar=L_GetAt(0,Exp); /* O resultado está no primeiro e único elemento agora. */
return 1;
}
char DestroyExpression(LIST *Exp){
/*
* Essa função remove da memória a lista 'Exp'.
* No fundo, ela apenas chama a própria função do TAD responsável por remover listas.
*
* Ela retorna 1 em caso de sucesso, outros valores caso contrário.
*/
return L_Destroy(Exp);
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
/*
* ~ Tabela Hash ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
struct __tree_node_t {
int element;
struct __tree_node_t *l, *r;
};
struct __hash_node_t{
struct __tree_node_t *Root;
unsigned long N;
};
struct __hashtree_t{
struct __hash_node_t *Table;
unsigned long M, N;
};
struct __hashtree_t *HTree_New(unsigned long M){
if(M < 1) return NULL;
struct __hashtree_t *Aux=(struct __hashtree_t *)malloc(sizeof(struct __hashtree_t));
Aux->Table=(struct __hash_node_t *)calloc(M, sizeof(struct __hash_node_t));
Aux->M=M;
Aux->N=0;
return Aux;
}
unsigned long HTree_HashFunction(int element, struct __hashtree_t *T){
unsigned long Key;
Key= element%T->M;
return Key;
}
int HTree_Insert(int element, struct __hashtree_t *T){
if(T==NULL) return 0;
unsigned long Pos=HTree_HashFunction(element, T);
struct __tree_node_t **Aux=&T->Table[Pos].Root;
while((*Aux)!=NULL){
if(element < (*Aux)->element) Aux=&(*Aux)->l;
else Aux=&(*Aux)->r;
}
*Aux = (struct __tree_node_t *)calloc(1, sizeof(struct __tree_node_t));
(*Aux)->element=element;
T->Table[Pos].N++;
T->N++;
return 1;
}
int HTree_Remove(int element, struct __hashtree_t *T){
if(T==NULL) return -1;
unsigned long Pos=HTree_HashFunction(element, T);
struct __tree_node_t **Aux=&T->Table[Pos].Root, **Aux1, *Aux2;
while((*Aux)!=NULL){
if(element < (*Aux)->element) Aux=&(*Aux)->l;
else if(element > (*Aux)->element) Aux=&(*Aux)->r;
else break;
}
if((*Aux)==NULL) return 0;
if((*Aux)->l==NULL){
Aux2=*Aux;
*Aux=(*Aux)->r;
free(Aux2);
}else if((*Aux)->r==NULL){
Aux2=*Aux;
*Aux=(*Aux)->l;
free(Aux2);
}else{
Aux1=&(*Aux)->r;
while((*Aux1)->l!=NULL) Aux1=&(*Aux1)->l;
Aux2=*Aux1;
(*Aux)->element=Aux2->element;
free(Aux2);
*Aux1=NULL;
}
T->Table[Pos].N--;
T->N--;
return 1;
}
int HTree_Count(int element, struct __hashtree_t *T){
if(T==NULL) return 0;
unsigned long Pos=HTree_HashFunction(element, T);
return T->Table[Pos].N;
}
void HTree_Traverse_(FILE *FStream, struct __tree_node_t *Root, unsigned long *N){
if(Root==NULL) return;
HTree_Traverse_(FStream, Root->l, N);
fprintf(FStream, "%d", Root->element);
if(*N>1) fprintf(FStream, ", ");
(*N)--;
HTree_Traverse_(FStream, Root->r, N);
}
int HTree_Traverse(FILE *FStream, struct __hashtree_t *T){
if(T==NULL) return 0;
if(T->N < 1) return 1;
unsigned long i, Aux=T->Table[0].N;
char PrintComma=0;
for(i=1;i<T->M;i++){
Aux=T->Table[i].N;
if(T->Table[i].N > 1){
if(PrintComma) printf(", ");
PrintComma=1;
fprintf(FStream, "(");
HTree_Traverse_(FStream, T->Table[i].Root, &Aux);
fprintf(FStream, ")");
}else if(T->Table[i].N == 1){
if(PrintComma) printf(", ");
PrintComma=1;
HTree_Traverse_(FStream, T->Table[i].Root, &Aux);
}
}
return 2;
}
void HTree_Destroy_(struct __tree_node_t *Root){
if(Root==NULL) return;
HTree_Destroy_(Root->l);
HTree_Destroy_(Root->r);
free(Root);
}
void HTree_Destroy(struct __hashtree_t *T){
if(T==NULL) return;
unsigned long i;
for(i=0;i<T->M;i++)
HTree_Destroy_(T->Table[i].Root);
free(T->Table);
free(T);
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <utility>
#include <vector>
using namespace std;
void DFS(long V, long *visited, vector< vector< pair<long, long> > > &G){
long i, N;
visited[V] = 2;
N = G[V].size();
for(i = 0; i < N; i++){
if(visited[G[V][i].first] < 0){
DFS(G[V][i].first, visited, G);
}
}
}
int main(int argc, char **argv){
long i, j, N, K, counter, *visited;
char aux[200];
cin >> N;
for(i = 0; i < N; i++){
cin >> aux;
K = aux[0] - 'A' + 1;
vector< vector< pair<long, long> > > G(K);
visited = (long *) malloc(sizeof(long) * K);
memset(visited, -1, sizeof(long) * K);
fgets(aux, sizeof(aux)/sizeof(char), stdin);
fgets(aux, sizeof(aux)/sizeof(char), stdin);
while(aux[0] >= 'A' && aux[0] <= 'Z'){
G[aux[0] - 'A'].push_back(make_pair(aux[1] - 'A', 0));
G[aux[1] - 'A'].push_back(make_pair(aux[0] - 'A', 0));
aux[0] = '\0';
fgets(aux, sizeof(aux)/sizeof(char), stdin);
}
for(j = counter = 0; j < K; j++){
if(visited[j] >= 0)
continue;
DFS(j, visited, G);
counter++;
}
if(i)
cout << '\n';
cout << counter << '\n';
}
return EXIT_SUCCESS;
}<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
typedef struct __plane_travel {
int startTime, finishTime, cost;
bool operator()(const struct __plane_travel &a, int b){
return a.finishTime > b;
}
bool operator()(int b, const struct __plane_travel &a){
return a.finishTime > b;
}
bool operator()(const struct __plane_travel &a, const struct __plane_travel &b){
return a.finishTime < b.finishTime;
}
} plane_travel;
int cmp(const plane_travel *A, const plane_travel *B) {
return A->finishTime - B->finishTime;
}
void testCase() {
int i, j, N;
bool found;
cin >> N;
vector<plane_travel> travels = vector<plane_travel>(N);
vector<int> dp = vector<int>(N);
for(i = 0; i < N; i++) {
cin >> travels[i].startTime >> travels[i].finishTime >> travels[i].cost;
travels[i].finishTime += travels[i].startTime;
}
sort(travels.begin(), travels.end(), plane_travel());
dp[0] = travels[0].cost;
for(i = 1; i < N; i++) {
found = false;
j = upper_bound(travels.begin(), travels.begin() + i, travels[i].startTime, plane_travel()) - travels.begin();
j--;
if(i - 1 == j && travels[i - 1].finishTime > travels[i].startTime) {
dp[i] = max(dp[i - 1], travels[i].cost);
} else {
dp[i] = max(dp[i - 1], dp[j] + travels[i].cost);
}
}
cout << dp[N - 1] << endl;
}
int main(int argc, char **argv) {
int T;
cin >> T;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>
#ifndef FUNCIONALIDADES_H_
#define FUNCIONALIDADES_H_
int f1_csvToBin(char *csvPath, char *binPath);
int f2_listAll(char *binPath);
int f3_listSearch(char *binPath);
int f4_listRRN(int RRN, char *binPath);
int f5_remove(char *binPath);
int f6_insert(char *binPath);
int f7_update(char *binPath);
int f8_compactar(char *oldBinPath, char *newBinPath);
int f9_gerarGrafo(char *binPath);
int f10_caminhoMaisCurto(char *binPath);
int f11_arvoreGeradoraMinima(char *binPath);
int fx_barraR(char binary, char *filePath);
int fx_invalidate(char *filePath);
int fx_validate(char *filePath);
#endif<file_sep>
/*
* ~ Calc. de Expressões ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __CALC_H_
#define __CALC_H_
#include "linkedlist.h"
LIST *NewExpression(FILE *);
char CalcExpression(double *,LIST *);
char DestroyExpression(LIST *);
#endif
<file_sep>#include <stdlib.h>
#include <unordered_map>
#include <iostream>
#include <string>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
int main(int argc, char **argv) {
string name, current_name;
int N;
unordered_map<string, int> found_count;
found_count = unordered_map<string, int>(); // Criar.
scanf("%d", &N);
for(; N > 0; N--) {
cin >> name;
if(found_count[name] == 0) {
cout << "OK" << endl;
} else {
cout << name << found_count[name] << endl;
}
found_count[name]++;
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ | |
* | | \ | |___|
* |_______ _______|___|
*
*/
// Definições e macros
#define IS_POINT_INSIDE_BOX(Point, Box) \
( (Point.x>=Box.Min.x && Point.x<=Box.Max.x) \
&& (Point.y>=Box.Min.y && Point.y<=Box.Max.y) \
&& (Point.z>=Box.Min.z && Point.z<=Box.Max.z) )
// Enumerações e estruturas
typedef enum { false = 0, true } bool; // Pseudo-booleano
typedef struct {
float x,y,z; // Um ponto é definido por suas coordenadas em x, y e z.
} POINT;
typedef struct {
POINT Max; // Uma caixa é definida por seus pontos mínimo (Xmin, Ymin, Zmin) e máximo (Xmax, Ymax, Zmax).
POINT Min;
} BOX;
typedef struct {
POINT Coord[3]; // Um triângulo é definido por 3 pontos.
} TRIANGLE;
typedef struct __node {
BOX BoundingBox; // Dimensões da caixa delimitadora do octante.
bool PointHere; // Indica se o objeto p está nesse octante ou não.
struct __node *Boxes; // Este é o vetor das oito caixas do interior (octantes) dos próximos níveis, se o objeto p estiver aqui.
} node;
typedef struct {
POINT Point; // Ponto p.
TRIANGLE *Triangles; // Vetor com todos os triângulos da malha (objeto O).
int TrianglesC; // Número de triângulos na malha.
int Level; // Número de níveis máximo de divisões (nível da Octree).
node Root; // Primeiro nível da octree.
} octree;
// Declaração de funções
void ReadInput(octree *,bool);
void DeployOctree(node *,int,octree);
bool FindCollisions(node,octree);
void DestroyOctree(node *);
// ~~ Início do código ~~
int main(int argc, char **argv){
/*
* Meu programa vai ler as entradas, montar a octree e tentar encontrar colisões nesta respectivamente.
*
* Após, será feita a liberação dos nós da octree da memória.
* Com exceção da leitura das entradas, todas as outras funções são implantadas de forma recursiva.
*/
octree MainOctree;
bool CreateBoundingBox = (getchar()=='0') ? false : true; // É necessário implantar a caixa delimitadora?
ReadInput(&MainOctree,CreateBoundingBox); // Ler entradas, alocar memória na HEAP (dinamicamente) e armazenar os dados na Octree.
DeployOctree(&MainOctree.Root,MainOctree.Level,MainOctree); // Chamar recursiva para montar toda a estrutura da Octree.
if(FindCollisions(MainOctree.Root,MainOctree)==true){ // Chamar recursiva para encontrar uma colisão nessa Octree, se houver.
printf("1\n"); // Houve colisão.
}else{
printf("0\n"); // Não houve colisão.
}
DestroyOctree(&MainOctree.Root); // Chamar recursiva para limpar os octantes da memória.
free(MainOctree.Triangles); // Limpar vetor de triângulos que compõem a malha total.
return EXIT_SUCCESS;
}
void ReadInput(octree *Octree, bool CreateBoundingBox){
/*
* Esta função vai ler todas as entradas de 'stdin' e salvar em seus locais apropriados na Octree (dinamicamente).
*/
int i,j;
POINT R;
scanf("%d %d %f %f %f",&Octree->Level,&Octree->TrianglesC,&Octree->Point.x,&Octree->Point.y,&Octree->Point.z); // Ler o nível da octree, o número de triângulos e ler as coordenadas do objeto p.
Octree->Triangles=(TRIANGLE *)malloc(Octree->TrianglesC*sizeof(TRIANGLE)); // Alocar a memória para os triângulos.
if(CreateBoundingBox==false){
for(i=0;i<Octree->TrianglesC;i++){ // Para cada triângulo...
for(j=0;j<3;j++){ // e para cada ponto deste...
scanf("%f %f %f",&Octree->Triangles[i].Coord[j].x,&Octree->Triangles[i].Coord[j].y,&Octree->Triangles[i].Coord[j].z); // Ler os pontos do triângulo.
}
}
scanf("%f %f %f",&Octree->Root.BoundingBox.Min.x,&Octree->Root.BoundingBox.Min.y,&Octree->Root.BoundingBox.Min.z); // Ler o primeiro ponto da caixa delimitadora.
Octree->Root.BoundingBox.Max=Octree->Root.BoundingBox.Min;
for(i=1;i<8;i++){ // Ler os outros pontos.
scanf("%f %f %f",&R.x,&R.y,&R.z);
if(R.x>Octree->Root.BoundingBox.Max.x){
Octree->Root.BoundingBox.Max.x=R.x;
}else if(R.x<Octree->Root.BoundingBox.Min.x){
Octree->Root.BoundingBox.Min.x=R.x;
}
if(R.y>Octree->Root.BoundingBox.Max.y){
Octree->Root.BoundingBox.Max.y=R.y;
}else if(R.y<Octree->Root.BoundingBox.Min.y){
Octree->Root.BoundingBox.Min.y=R.y;
}
if(R.z>Octree->Root.BoundingBox.Max.z){
Octree->Root.BoundingBox.Max.z=R.z;
}else if(R.z<Octree->Root.BoundingBox.Min.z){
Octree->Root.BoundingBox.Min.z=R.z;
}
}
}else{
// É necessário implantar a caixa delimitadora.
// Nesse caso vamos ler o primeiro triângulo individualmente e o resto dos triângulos em um 'loop for'.
scanf("%f %f %f",&Octree->Triangles[0].Coord[0].x,&Octree->Triangles[0].Coord[0].y,&Octree->Triangles[0].Coord[0].z); // Ler o primeiro ponto do primeiro triângulo.
Octree->Root.BoundingBox.Min=Octree->Root.BoundingBox.Max=Octree->Triangles[0].Coord[0];
for(j=1;j<3;j++){ // Ler os outros dois pontos do primeiro triângulo.
scanf("%f %f %f",&Octree->Triangles[0].Coord[j].x,&Octree->Triangles[0].Coord[j].y,&Octree->Triangles[0].Coord[j].z);
if(Octree->Triangles[0].Coord[j].x>Octree->Root.BoundingBox.Max.x){ // Verificar se o ponto ultrapassa a caixa delimitadora, e se sim, atualizá-la.
Octree->Root.BoundingBox.Max.x=Octree->Triangles[0].Coord[j].x;
}else if(Octree->Triangles[0].Coord[j].x<Octree->Root.BoundingBox.Min.x){
Octree->Root.BoundingBox.Min.x=Octree->Triangles[0].Coord[j].x;
}
if(Octree->Triangles[0].Coord[j].y>Octree->Root.BoundingBox.Max.y){
Octree->Root.BoundingBox.Max.y=Octree->Triangles[0].Coord[j].y;
}else if(Octree->Triangles[0].Coord[j].y<Octree->Root.BoundingBox.Min.y){
Octree->Root.BoundingBox.Min.y=Octree->Triangles[0].Coord[j].y;
}
if(Octree->Triangles[0].Coord[j].z>Octree->Root.BoundingBox.Max.z){
Octree->Root.BoundingBox.Max.z=Octree->Triangles[0].Coord[j].z;
}else if(Octree->Triangles[0].Coord[j].z<Octree->Root.BoundingBox.Min.z){
Octree->Root.BoundingBox.Min.z=Octree->Triangles[0].Coord[j].z;
}
}
for(i=1;i<Octree->TrianglesC;i++){ // Para os outros triângulos da entrada...
for(j=0;j<3;j++){ // e para cada ponto de cada um desses triângulo...
scanf("%f %f %f",&Octree->Triangles[i].Coord[j].x,&Octree->Triangles[i].Coord[j].y,&Octree->Triangles[i].Coord[j].z); // Ler ponto e atribuir ele ao triângulo.
if(Octree->Triangles[i].Coord[j].x>Octree->Root.BoundingBox.Max.x){ // Verificar se o ponto ultrapassa a caixa delimitadora, e se sim, atualizá-la.
Octree->Root.BoundingBox.Max.x=Octree->Triangles[i].Coord[j].x;
}else if(Octree->Triangles[i].Coord[j].x<Octree->Root.BoundingBox.Min.x){
Octree->Root.BoundingBox.Min.x=Octree->Triangles[i].Coord[j].x;
}
if(Octree->Triangles[i].Coord[j].y>Octree->Root.BoundingBox.Max.y){
Octree->Root.BoundingBox.Max.y=Octree->Triangles[i].Coord[j].y;
}else if(Octree->Triangles[i].Coord[j].y<Octree->Root.BoundingBox.Min.y){
Octree->Root.BoundingBox.Min.y=Octree->Triangles[i].Coord[j].y;
}
if(Octree->Triangles[i].Coord[j].z>Octree->Root.BoundingBox.Max.z){
Octree->Root.BoundingBox.Max.z=Octree->Triangles[i].Coord[j].z;
}else if(Octree->Triangles[i].Coord[j].z<Octree->Root.BoundingBox.Min.z){
Octree->Root.BoundingBox.Min.z=Octree->Triangles[i].Coord[j].z;
}
}
}
}
}
void DeployOctree(node *OctNode,int OctLevel,octree Octree){
/*
* Esta função implanta toda a Octree até "OctLevel".
*
* Ela é recursiva, e só implanta os octantes aos quais o objeto p está presente.
* Com isso, a função evita uso desnecessário de CPU e memória, visto que os outros octantes não nos interessam.
*/
if(OctLevel<=0){ // Fim da Octree. Encerrar recursão.
OctNode->Boxes=NULL;
return;
}
int i;
OctNode->Boxes=(node *)malloc(8*sizeof(node)); // Alocar memória para os oito octantes do interior desse nó (node).
{
POINT MiddlePoint; // Ponto do meio de todo o octante.
MiddlePoint.x=(OctNode->BoundingBox.Max.x+OctNode->BoundingBox.Min.x)/(float)2;
MiddlePoint.y=(OctNode->BoundingBox.Max.y+OctNode->BoundingBox.Min.y)/(float)2;
MiddlePoint.z=(OctNode->BoundingBox.Max.z+OctNode->BoundingBox.Min.z)/(float)2;
OctNode->Boxes[0].BoundingBox.Min=OctNode->BoundingBox.Min; // Formar a caixa delimitadora do octante 1.
OctNode->Boxes[0].BoundingBox.Max=MiddlePoint;
OctNode->Boxes[1].BoundingBox.Min.x=MiddlePoint.x; // Formar a caixa delimitadora do octante 2.
OctNode->Boxes[1].BoundingBox.Min.y=OctNode->BoundingBox.Min.y;
OctNode->Boxes[1].BoundingBox.Min.z=OctNode->BoundingBox.Min.z;
OctNode->Boxes[1].BoundingBox.Max.x=OctNode->BoundingBox.Max.x;
OctNode->Boxes[1].BoundingBox.Max.y=MiddlePoint.y;
OctNode->Boxes[1].BoundingBox.Max.z=MiddlePoint.z;
OctNode->Boxes[2].BoundingBox.Min.x=OctNode->BoundingBox.Min.x; // ...
OctNode->Boxes[2].BoundingBox.Min.y=MiddlePoint.y;
OctNode->Boxes[2].BoundingBox.Min.z=OctNode->BoundingBox.Min.z;
OctNode->Boxes[2].BoundingBox.Max.x=MiddlePoint.x;
OctNode->Boxes[2].BoundingBox.Max.y=OctNode->BoundingBox.Max.y;
OctNode->Boxes[2].BoundingBox.Max.z=MiddlePoint.z;
OctNode->Boxes[3].BoundingBox.Min.x=OctNode->BoundingBox.Min.x; // ...
OctNode->Boxes[3].BoundingBox.Min.y=OctNode->BoundingBox.Min.y;
OctNode->Boxes[3].BoundingBox.Min.z=MiddlePoint.z;
OctNode->Boxes[3].BoundingBox.Max.x=MiddlePoint.x;
OctNode->Boxes[3].BoundingBox.Max.y=MiddlePoint.y;
OctNode->Boxes[3].BoundingBox.Max.z=OctNode->BoundingBox.Max.z;
OctNode->Boxes[4].BoundingBox.Min.x=OctNode->BoundingBox.Min.x; // ...
OctNode->Boxes[4].BoundingBox.Min.y=MiddlePoint.y;
OctNode->Boxes[4].BoundingBox.Min.z=MiddlePoint.z;
OctNode->Boxes[4].BoundingBox.Max.x=MiddlePoint.x;
OctNode->Boxes[4].BoundingBox.Max.y=OctNode->BoundingBox.Max.y;
OctNode->Boxes[4].BoundingBox.Max.z=OctNode->BoundingBox.Max.z;
OctNode->Boxes[5].BoundingBox.Min.x=MiddlePoint.x; // ...
OctNode->Boxes[5].BoundingBox.Min.y=OctNode->BoundingBox.Min.y;
OctNode->Boxes[5].BoundingBox.Min.z=MiddlePoint.z;
OctNode->Boxes[5].BoundingBox.Max.x=OctNode->BoundingBox.Max.x;
OctNode->Boxes[5].BoundingBox.Max.y=MiddlePoint.y;
OctNode->Boxes[5].BoundingBox.Max.z=OctNode->BoundingBox.Max.z;
OctNode->Boxes[6].BoundingBox.Min.x=MiddlePoint.x; // ...
OctNode->Boxes[6].BoundingBox.Min.y=MiddlePoint.y;
OctNode->Boxes[6].BoundingBox.Min.z=OctNode->BoundingBox.Min.z;
OctNode->Boxes[6].BoundingBox.Max.x=OctNode->BoundingBox.Max.x;
OctNode->Boxes[6].BoundingBox.Max.y=OctNode->BoundingBox.Max.y;
OctNode->Boxes[6].BoundingBox.Max.z=MiddlePoint.z;
OctNode->Boxes[7].BoundingBox.Min=MiddlePoint; // Formar a caixa delimitadora do octante 8.
OctNode->Boxes[7].BoundingBox.Max=OctNode->BoundingBox.Max;
}
for(i=0;i<8;i++){ // Para cada um destes 8 octantes criados...
if( IS_POINT_INSIDE_BOX(Octree.Point,OctNode->Boxes[i].BoundingBox) ) { // Verificar se o objeto p está dentro do octante...
OctNode->Boxes[i].PointHere=true; // Se sim, marcar este octante e chamar mais um nível de recursão.
DeployOctree(&OctNode->Boxes[i],OctLevel-1,Octree);
}else{
OctNode->Boxes[i].PointHere=false; // Se não, ignorar este octante.
OctNode->Boxes[i].Boxes=NULL;
}
}
}
bool FindCollisions(node OctNode,octree Octree){
/*
* Está função percorre todos os octantes ao qual o objeto p faz parte e verifica se há algum triângulo interseccionando p.
*
* Ela é recursiva e só vai parar até encontrar uma intersecção no nível final da octree ou
* até percorrer todos os octantes e nada for encontrado.
*/
if(OctNode.PointHere==false) return false; // O objeto p não está nesse octante.
int i;
if(OctNode.Boxes==NULL){ // Chegou no fim da octree. Verificar se há algum triângulo aí que intersecciona junto com o objeto p.
for(i=0;i<Octree.TrianglesC;i++){ // Para cada triângulo de toda a malha...
POINT TriangleVertices[3]; // Criar os pontos no centro de sua aresta.
TriangleVertices[0].x=(Octree.Triangles[i].Coord[0].x+Octree.Triangles[i].Coord[1].x)/(float)2;
TriangleVertices[0].y=(Octree.Triangles[i].Coord[0].y+Octree.Triangles[i].Coord[1].y)/(float)2;
TriangleVertices[0].z=(Octree.Triangles[i].Coord[0].z+Octree.Triangles[i].Coord[1].z)/(float)2;
TriangleVertices[1].x=(Octree.Triangles[i].Coord[1].x+Octree.Triangles[i].Coord[2].x)/(float)2;
TriangleVertices[1].y=(Octree.Triangles[i].Coord[1].y+Octree.Triangles[i].Coord[2].y)/(float)2;
TriangleVertices[1].z=(Octree.Triangles[i].Coord[1].z+Octree.Triangles[i].Coord[2].z)/(float)2;
TriangleVertices[2].x=(Octree.Triangles[i].Coord[2].x+Octree.Triangles[i].Coord[0].x)/(float)2;
TriangleVertices[2].y=(Octree.Triangles[i].Coord[2].y+Octree.Triangles[i].Coord[0].y)/(float)2;
TriangleVertices[2].z=(Octree.Triangles[i].Coord[2].z+Octree.Triangles[i].Coord[0].z)/(float)2;
if(IS_POINT_INSIDE_BOX(TriangleVertices[0],OctNode.BoundingBox) || IS_POINT_INSIDE_BOX(TriangleVertices[1],OctNode.BoundingBox) ||
IS_POINT_INSIDE_BOX(TriangleVertices[2],OctNode.BoundingBox) || IS_POINT_INSIDE_BOX(Octree.Triangles[i].Coord[0],OctNode.BoundingBox) || IS_POINT_INSIDE_BOX(Octree.Triangles[i].Coord[1],OctNode.BoundingBox) ||
IS_POINT_INSIDE_BOX(Octree.Triangles[i].Coord[2],OctNode.BoundingBox) ){ // Verificar se os vértices do triângulo ou se algum dos pontos no centro de suas arestas está dentro do octante.
return true; // Se sim, encerrar recursão porque já sabemos que há colisão. Se não, verificar próximo triângulo da malha.
}
}
return false; // Nenhum triângulo aqui dentro interseccionando com o objeto p. Encerrar porque não há colisão.
}
for(i=0;i<8;i++) // Para cada um dos oito octantes do interior...
if(FindCollisions(OctNode.Boxes[i],Octree)==true) // Verificar se há colisão.
return true; // Se sim, encerrar recursão porque já sabemos que há colisão. Se não, verificar o próximo octante.
return false; // Nenhum octante aqui dentro colide com o objeto p. Encerrar porque não há colisão.
}
void DestroyOctree(node *OctNode){
/*
* Está função vai limpar da memória os octantes do interior de "OctNode" e o próprio "OctNode".
*
* Ela é recursiva e só para quando tiver tudo limpo da memória no interior de "OctNode",
* limpando, por fim, o próprio vetor de octantes de "OctNode" da memória.
*/
if(OctNode==NULL || OctNode->Boxes==NULL) return; // Este octante já está limpo.
int i;
for(i=0;i<8;i++) // Para cada octante do interior...
DestroyOctree(&OctNode->Boxes[i]); // destruir tal octante.
free(OctNode->Boxes); // Destruir o vetor principal de octantes.
}
<file_sep># Objeto
Objeto obtido do website [free3d](https://free3d.com/3d-model/light-pole-32057.html): licença para uso pessoal.
<file_sep># Casos de Teste
Aqui se encontram alguns casos de teste que podem ser utilizados no trabalho de forma automática. No Unix, podem ser executados da seguinte maneira __no diretório acima__:
python3 InpaintingLargeObjects.py < TestCases/[...].in
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
int find_NA(int start, int end, int N, int A, int B, int K) {
int NB, current_K, middle, aux;
if(start > end) {
return -1;
}
middle = (start + end) / 2;
current_K = K - middle * A;
NB = current_K / B;
NB = max(NB - 1, 0);
current_K -= NB * B;
if(current_K > B) {
current_K -= B;
NB++;
}
if(K <= 0 || middle + NB < N) {
return find_NA(start, middle - 1, N, A, B, K);
}
aux = find_NA(middle + 1, end, N, A, B, K);
if(aux >= 0) {
return aux;
}
return middle;
}
void testCase() {
int K, N, A, B;
int NA_max;
cin >> K >> N >> A >> B;
NA_max = K / A;
NA_max = max(NA_max - 1, 0);
if(K - NA_max * A > A) {
NA_max++;
}
cout << min(find_NA(0, NA_max, N, A, B, K), N) << endl;
}
int main(int argc, char **argv) {
int T;
cin >> T;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv) {
double cust_table[256], total; /* assim eh mais rapido que hashtable/map */
char line[10001 + 2], aux[10], *it;
int i, j, k, N, K, M;
scanf("%d", &N);
for(i = 0; i < N; i++) {
memset(cust_table, 0, sizeof(double) * 256); /* resetar valor dos char lá */
total = 0.0; /* total */
scanf("%d", &K);
for(j = 0; j < K; j++) { /* ler tabelinha */
scanf("%s", aux);
scanf("%lf", &cust_table[*aux]);
}
scanf("%d", &M); fgets(line, 10001, stdin); /* fgets pra ignorar a linha do proprio numero */
for(j = 0; j < M; j++) { /* fazer a soma aqui */
fgets(line, 10001, stdin);
for(it = line; *it != '\0'; it++) {
total += cust_table[*it];
}
}
/* imprime */
printf("%0.2lf$\n", total/100.0);
}
return EXIT_SUCCESS;
}
<file_sep># SCC-0202 Algoritmos e Estruturas de Dados 1 - 2017.2
Aqui estão todos os trabalhos que implementei em Alg 1.
<file_sep>
/*
* ~ SUPER STRING ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __SUPER_STRING_H_
#define __SUPER_STRING_H_
char *SS_ReadUntil(char *,char,FILE *);
int SS_ReadAllWhites(FILE *);
char SS_InsensitiveCmp(char *A,char *B);
#endif
<file_sep>#!python3
import numpy as np
from math import ceil
import random
import heapq
import sys
#
# ~ Trabalho Prático 1: Gerador de Labirintos ~
#
# Grupo:
# <NAME> (Nº USP 8596351)
# <NAME> (Nº USP 10369014)
# <NAME> (Nº USP 10783243)
#
# Inteligência Artificial: SCC-0230 2020.2
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
EMPTY = '*'
WALL = '-'
AGENT = '#'
GOAL = '$'
LINE_BREAK = '\n'
FOR_PRINT_BUF = 1000000000
movements = [[+1, 0], [0, +1]] # [[+1, 0], [-1, 0], [0, -1], [0, +1]]
def valid_point(width, height, point):
return point[0] >= 0 and point[0] < width \
and point[1] >= 0 and point[1] < height
def find_set(parent, v):
if v == parent[v[0], v[1]]:
return v
parent[v[0], v[1]] = find_set(parent, parent[v[0], v[1]])
return parent[v[0], v[1]]
def union_sets(parent, rank, a, b):
a = find_set(parent, a)
b = find_set(parent, b)
if a != b:
if rank[a[0], a[1]] < rank[b[0], b[1]]:
tmp = a
a = b
b = tmp
parent[b[0], b[1]] = a
if rank[a[0], a[1]] == rank[b[0], b[1]]:
rank[a[0], a[1]] += 1
def generate(width, height, verbose=True):
''' Generate maze using Kruskal Minimum Spanning Tree Algorithm. '''
# Alocate array.
edges_dtype = np.dtype([('w', np.float), ('u', np.int, (2, )), ('v', np.int, (2, )), ('p', np.int, (2, ))])
edges = np.empty([width*height*len(movements)], dtype=edges_dtype)
parent = np.empty([width, height], dtype=tuple)
array = np.full([width * 2 - 1, height * 2 - 1], WALL, dtype=np.str)
rank = np.full([width, height], 0, dtype=np.int)
print('Preenchendo... %.2f%% concluído' % (0.0), end="", file=sys.stderr)
count = 0
iterator = 0
max = width * height
for i in range(width):
for j in range(height):
if count % FOR_PRINT_BUF:
print('\rPreenchendo... %.2f%% concluído' % (100.0*count/max), end="", file=sys.stderr)
count += 1
parent[i, j] = (i, j)
array[i * 2, j * 2] = EMPTY
for move in movements:
adjacent = (i + move[0], j + move[1])
edge = ((i, j), adjacent)
if not valid_point(width, height, adjacent):
continue
weight = random.random()
edges[iterator] = (weight, edge[0], edge[1], (2 * i + move[0], 2 * j + move[1]))
iterator += 1
print('\rPreenchendo... %.2f%% concluído.' % (100.0), file=sys.stderr)
print('Ordenando...', end="", file=sys.stderr)
edges = np.sort(edges[:iterator], order=['w'])
print('\rOrdenando... %.2f%% concluído.' % (100.0), file=sys.stderr)
cost = 0.0
count = 0
max = edges.shape[0]
print('Processando... %.2f%% concluído' % (0.0), end="", file=sys.stderr)
for edge in edges:
if count % FOR_PRINT_BUF:
print('\rProcessando... %.2f%% concluído' % (100.0*count/max), end="", file=sys.stderr)
count += 1
w = edge['w']
u = tuple(edge['u'])
v = tuple(edge['v'])
p = tuple(edge['p'])
if find_set(parent, u) != find_set(parent, v):
cost += w
array[p[0], p[1]] = EMPTY
union_sets(parent, rank, u, v)
print('\rProcessando... %.2f%% concluído.' % (100.0), file=sys.stderr)
return array
if len(sys.argv) != 4:
print("Como usar:", file=sys.stderr)
print("\t> python3 %s WIDTH HEIGHT FILE" % (sys.argv[0]), file=sys.stderr)
print("\tOnde WIDTH é o número de linhas e HEIGHT o número de colunas do labirinto que se deseja gerar, e FILE é o nome do arquivo para salvar os resultados.", file=sys.stderr)
print(file=sys.stderr)
sys.exit(0)
width = int(sys.argv[1])
height = int(sys.argv[2])
file_name = str(sys.argv[3]).strip()
if width < 5 or height < 5:
print("Atenção:", file=sys.stderr)
print("Tanto WIDTH como HEIGHT devem ser números inteiros maiores ou iguais a 5.", file=sys.stderr)
print(file=sys.stderr)
sys.exit(0)
if width % 2 == 0 or height % 2 == 0:
print("Atenção:", file=sys.stderr)
print("Devido a maneira como o código foi implementado, não é possível que WIDTH ou HEIGHT sejam pares. Mas não se preocupe, vamos ajustar tudo para você (consideraremos o ímpar imediatamente menor).", file=sys.stderr)
print(file=sys.stderr)
width = int((width + 1) / 2)
height = int((height + 1) / 2)
print('Gerando labirinto %sx%s...' % (width * 2 - 1, height * 2 - 1), file=sys.stderr)
maze = generate(width, height)
maze[0, 0] = AGENT
maze[maze.shape[0] - 1, maze.shape[1] - 1] = GOAL
print('Salvando em arquivo...', end="", file=sys.stderr)
np.savetxt(file_name, maze, fmt="%s", delimiter="", newline=LINE_BREAK, header="%d %d"%(maze.shape[0], maze.shape[1]), comments="")
print('\rSalvando em arquivo... %.2f%% concluído' % (100.0), file=sys.stderr)
print('Pronto.', file=sys.stderr)
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/*
* ~ SUPER FILE ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
/*
* Esta biblioteca adiciona algumas funções a leitura de Streams.
* Ainda está em fase de desenvolvimento.
*/
char SF_PreviewChar(FILE *FStream){ // Release
/*
* Essa função lê o próximo caractere de 'FStream' e retorna uma posição em 'FStream', retornando o próprio caractere lido.
* Em suma, ela lê um caractere de 'FStream' sem consumir ele.
*
* Ela retorna o próximo caractere de 'FStream', ou EOF em caso de erros.
*/
char R=getc(FStream);
fseek(FStream,-1,SEEK_CUR);
return R;
}
int SF_ReadWhites(FILE *FStream){ // Release
/*
* Esta função vai ler caracteres de 'FStream' até chegar em algo que não é considerado "white-space". Após isso, ela retorna uma posição em 'FStream'.
* Em suma, ela ignora todos os caracteres "white-space" de 'Fstream'.
*
* Ela retorna o número de caracteres lidos, ou -1 em caso de erros.
*/
char R;
int n=0;
while( (R=getc(FStream))!=EOF && isspace(R)!=0 ) n++;
if(R!=EOF) fseek(FStream,-1,SEEK_CUR);
return n;
}
int SF_ReadUntil(char Key,FILE *FStream){
/*
* Esta função vai ler caracteres de 'FStream' até chegar em 'Key'. Após isso, ela retorna uma posição em 'FStream'.
* Em suma, ela ignora todos os caracteres diferentes de 'Key' de 'Fstream'.
*
* Ela retorna o número de caracteres lidos, ou -1 em caso de erros.
*/
char R;
int n=0;
while( (R=getc(FStream))!=EOF && R!=Key ) n++;
if(R!=EOF) fseek(FStream,-1,SEEK_CUR);
return n;
}
char *SF_ReadString(FILE *FStream){
/*
* Esta função vai tentar obter uma string de 'FStream'.
* Caracteres "white-space" que aparecerem antes de uma string serão ignorados.
* Ela vai parar de ler após o primeiro caractere "white-space" aparecer, ou fim do arquivo.
* Em suma, ela lê uma palavra de 'Fstream'.
*
* Ela retorna um ponteiro para uma string na memória, ou NULL em caso de erros.
*/
int n=0;
char R,*ReadString=NULL;
while( (R=getc(FStream))!=EOF && isspace(R)!=0 ) { }
if(R==EOF) return NULL; // Chegou no fim do arquivo e nenhuma string foi encontrada.
ReadString=(char *)malloc(sizeof(char)*2);
ReadString[n++]=R;
while( (R=getc(FStream))!=EOF && isspace(R)==0 ) {
ReadString=(char *)realloc(ReadString,sizeof(char)*(n+2));
ReadString[n++]=R;
}
ReadString[n]='\0';
if(R!=EOF) fseek(FStream,-1,SEEK_CUR);
return ReadString;
}
char *SF_ReadFormattedString(FILE *FStream){
/*
* Esta função vai tentar obter uma string de 'FStream'.
* Caracteres que aparecerem antes de uma aspas duplas de abertura *"* serão ignorados.
* Ela vai ler a string até encontrar uma aspas duplas *"* que completa as aspas de abertura.
* A diferença dessa função com "ReadString" é que esta lê uma string pré-formatada, ou seja, pode inclusive ter caracteres como aspas duplas *\"* e espaços dentro da string.
* Em suma, ela lê uma string de 'Fstream' dentro de aspas duplas *"*.
*
* Ela retorna um ponteiro para uma string na memória, ou NULL em caso de erros.
*/
int n=0;
char R,*ReadString=NULL;
while( (R=getc(FStream))!=EOF && R!='"' ) { }
if(R==EOF) return NULL; // Chegou no fim do arquivo e nenhuma string foi encontrada.
ReadString=(char *)malloc(sizeof(char)*1);
while( (R=getc(FStream))!=EOF && R!='"' ) {
if(R=='\\'){
R=getc(FStream);
if(R==EOF) break;
else if(R=='n') R='\n';
else if(R=='t') R='\t';
else continue;
}
ReadString=(char *)realloc(ReadString,sizeof(char)*(n+2));
ReadString[n++]=R;
}
ReadString[n]='\0';
if(R==EOF) return NULL; // As aspas duplas *"* de fechamento não foram encontradas.
else fseek(FStream,-1,SEEK_CUR);
return ReadString;
}
<file_sep>#include <iostream>
#include <stdlib.h>
#include <cmath>
#include <vector>
#include <queue>
#include <string.h>
using namespace std;
typedef struct __node {
int blki, blkj;
int Org[4][4];
int Diff;
vector<char> Path;
bool operator<(const __node &a) const{
return Path.size()+Diff > a.Path.size()+a.Diff;
}
} V_NODE;
int difference(int A[][4]){
int i, j, sum;
int Aux[4][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 0}
};
for(i = sum = 0; i < 4; i++)
for(j = 0; j < 4; j++)
sum += abs(A[i][j] - Aux[i][j]); // * pow(10, i);
return sum;
}
void swap(int *A, int *B){
int Aux = *A;
*A = *B;
*B = Aux;
}
vector<char> cpy_vec(vector<char> A){
vector<char> Aux = vector<char>();
int i, n;
for(n = A.size(), i = 0; i < n; i++){
Aux.push_back(A[i]);
}
return Aux;
}
void prn_vec(vector<char> A){
int i, n;
for(n = A.size(), i = 0; i < n; i++){
cout << A[i];
}
cout << "\n";
}
int main(int argc, char **argv){
int i, j, k, N;
V_NODE AuxNode;
V_NODE ProcessingNode;
cin >> N;
for(k = 0; k < N; k++){
priority_queue<V_NODE> Nodes = priority_queue<V_NODE>();
AuxNode.Path = vector<char>();
for(i = 0; i < 4; i++){
for(j = 0; j < 4; j++){
cin >> AuxNode.Org[i][j];
if(AuxNode.Org[i][j] == 0){
AuxNode.blki = i;
AuxNode.blkj = j;
}
}
}
AuxNode.Diff = difference(AuxNode.Org);
Nodes.push(AuxNode);
while(Nodes.size() > 0){
ProcessingNode = Nodes.top();
if(difference(ProcessingNode.Org) == 0){
prn_vec(ProcessingNode.Path);
goto end_loop;
}
if(ProcessingNode.Path.size() > 20){
break;
}
Nodes.pop();
memcpy(AuxNode.Org, ProcessingNode.Org, sizeof(int) * 4 * 4);
AuxNode.blki = ProcessingNode.blki;
AuxNode.blkj = ProcessingNode.blkj;
if(AuxNode.blki + 1 < 4){
AuxNode.blki++;
AuxNode.Path = cpy_vec(ProcessingNode.Path);
AuxNode.Path.push_back('D');
swap(&AuxNode.Org[AuxNode.blki][AuxNode.blkj], &AuxNode.Org[AuxNode.blki - 1][AuxNode.blkj]);
AuxNode.Diff = difference(AuxNode.Org);
Nodes.push(AuxNode);
AuxNode.blki--;
swap(&AuxNode.Org[AuxNode.blki][AuxNode.blkj], &AuxNode.Org[AuxNode.blki + 1][AuxNode.blkj]);
}
if(AuxNode.blki - 1 >= 0){
AuxNode.blki--;
AuxNode.Path = cpy_vec(ProcessingNode.Path);
AuxNode.Path.push_back('U');
swap(&AuxNode.Org[AuxNode.blki][AuxNode.blkj], &AuxNode.Org[AuxNode.blki + 1][AuxNode.blkj]);
AuxNode.Diff = difference(AuxNode.Org);
Nodes.push(AuxNode);
AuxNode.blki++;
swap(&AuxNode.Org[AuxNode.blki][AuxNode.blkj], &AuxNode.Org[AuxNode.blki - 1][AuxNode.blkj]);
}
if(AuxNode.blkj + 1 < 4){
AuxNode.blkj++;
AuxNode.Path = cpy_vec(ProcessingNode.Path);
AuxNode.Path.push_back('R');
swap(&AuxNode.Org[AuxNode.blki][AuxNode.blkj], &AuxNode.Org[AuxNode.blki][AuxNode.blkj - 1]);
AuxNode.Diff = difference(AuxNode.Org);
Nodes.push(AuxNode);
AuxNode.blkj--;
swap(&AuxNode.Org[AuxNode.blki][AuxNode.blkj], &AuxNode.Org[AuxNode.blki][AuxNode.blkj + 1]);
}
if(AuxNode.blkj - 1 >= 0){
AuxNode.blkj--;
AuxNode.Path = cpy_vec(ProcessingNode.Path);
AuxNode.Path.push_back('L');
swap(&AuxNode.Org[AuxNode.blki][AuxNode.blkj], &AuxNode.Org[AuxNode.blki][AuxNode.blkj + 1]);
AuxNode.Diff = difference(AuxNode.Org);
Nodes.push(AuxNode);
AuxNode.blkj++;
swap(&AuxNode.Org[AuxNode.blki][AuxNode.blkj], &AuxNode.Org[AuxNode.blki][AuxNode.blkj - 1]);
}
}
cout << "This puzzle is not solvable.\n";
end_loop: ;
}
return EXIT_SUCCESS;
}<file_sep>
#ifndef H_QUEUE_
#define H_QUEUE_
#include <stdio.h>
typedef struct _QUEUE_T QUEUE_T;
QUEUE_T *Q_new(size_t);
int Q_push(void *, QUEUE_T *);
int Q_shift(void *, QUEUE_T *);
unsigned long Q_size(QUEUE_T *);
int Q_clear(QUEUE_T *);
void Q_destroy(QUEUE_T *);
#endif<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <string>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
int count_moves(string S, char c) {
int i, middle, count_1, count_2;
if(S.size() < 1) {
return 0;
}
if(S.size() == 1) {
return S[0] != c;
}
middle = S.size() /2;
count_1 = count_2 = 0;
// First try the first-half as "== c".
for(i = 0; i < middle; i++) {
if(S[i] != c) {
count_1++;
}
}
count_1 += count_moves(S.substr(middle, S.size() - middle), c + 1);
// Now try the second-half as "== c".
for(i = middle; i < S.size(); i++) {
if(S[i] != c) {
count_2++;
}
}
count_2 += count_moves(S.substr(0, middle), c + 1);
//if(count_1 < count_2) {
// return count_1 + count_moves(S, c + 1, middle, end);
//} else if(count_1 > count_2) {
// return count_2 + count_moves(S, c + 1, start, middle - 1);
//}
//return min(count_1 + count_moves(S, c + 1, middle, end), count_2 + count_moves(S, c + 1, start, middle - 1));
return min(count_1, count_2);
}
void testCase() {
int N, i;
string S;
cin >> N;
cin >> S;
//cout << "string: " << S << " - " << S[0];
cout << count_moves(S, 'a') << endl;
}
int main(int argc, char **argv) {
int T;
cin >> T;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep># SCC-0210 Algoritmos Avançados - 2018.1
Aqui estão alguns dos exercícios que implementei em Algoritmos Avançados.
<file_sep>#include <stdlib.h>
#include <string.h>
struct __heap_t {
void *values;
size_t memsize;
unsigned long nitems;
int (*fcmp)(void *, void *);
};
struct __heap_t *H_New(size_t memsize, int (*fcmp)(void *, void *)){
if(memsize<1 || fcmp==NULL) return NULL;
struct __heap_t *Aux=(struct __heap_t *)calloc(1,sizeof(struct __heap_t));
Aux->memsize=memsize;
Aux->fcmp=fcmp;
return Aux;
}
int H_Add(void *Elem, struct __heap_t *H){
if(Elem==NULL || H==NULL) return 0;
int i;
for(i=0;i<H->nitems;i++) if(H->fcmp(Elem,H->values+i*H->memsize)<=0) break;
H->values=(void *)realloc(H->values,(++H->nitems)*H->memsize);
if(i<H->nitems-1) memmove(H->values+(i+1)*H->memsize, H->values+i*H->memsize, H->memsize*(H->nitems-i-1));
memcpy(H->values+i*H->memsize,Elem,H->memsize);
return 1;
}
int H_Get(void *Dest, struct __heap_t *H){
if(Dest==NULL || H==NULL) return 0;
if(H->nitems<1) return 0;
memcpy(Dest,H->values,H->memsize);
return 1;
}
int H_Shift(void *Dest, struct __heap_t *H){
if(Dest==NULL || H==NULL) return 0;
if(H->nitems<1) return 0;
memcpy(Dest,H->values,H->memsize);
if(H->nitems>1) memmove(H->values,H->values+H->memsize,H->memsize*(H->nitems-1));
H->values=(void *)realloc(H->values,(--H->nitems)*H->memsize);
return 1;
}
void H_Destroy(struct __heap_t *H){
if(H==NULL) return;
if(H->values!=NULL) free(H->values);
free(H);
}
<file_sep>/*
* ~ Gerenc. de Processos ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __PROCESSMAN_H_
#define __PROCESSMAN_H_
typedef struct __processlist_t PROC_LIST;
enum __proc_man_t { proc_fifo = 0, proc_round_robin };
struct __processlist_t *NewSession(enum __proc_man_t);
char IncludeProcessesFrom(FILE *,struct __processlist_t *);
char RunProcesses(struct __processlist_t *);
char PrintResults(FILE *,struct __processlist_t *);
char DestroySession(struct __processlist_t *);
#endif
<file_sep>
/*
* ~ SKIPLIST ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef SKIPLIST_H_
#define SKIPLIST_H_
typedef struct __dictionary_t SKIPLIST;
struct __dictionary_t *New_Dictionary(unsigned int);
int Insert_Word(char *, char *, struct __dictionary_t *);
int Set_Word(char *, char *, struct __dictionary_t *);
int Remove_Word(char *, struct __dictionary_t *);
int Print_Word(char *, FILE *, struct __dictionary_t *);
int Print_Words_Starting_With(char, FILE *, struct __dictionary_t *);
void Destroy_Dictionary(struct __dictionary_t *);
#endif<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <vector>
#include <string>
#include <tuple>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
typedef struct __node {
struct __node *left, *right;
int value, index;
} NODE;
using namespace std;
NODE *build_subtree(NODE *root, int *A, int start, int end) {
NODE *aux;
int i;
if(end - start + 1 < 1) {
return NULL;
}
aux = (NODE *) malloc(sizeof(NODE));
aux->left = aux->right = NULL;
aux->value = -1;
aux->index = start;
for(i = start; i <= end; i++) {
if(A[i] > aux->value) {
aux->value = A[i];
aux->index = i;
}
}
aux->left = build_subtree(aux, A, start, aux->index - 1);
aux->right = build_subtree(aux, A, aux->index + 1, end);
return aux;
}
void count_subtree(NODE *root, int *D, int level) {
if(root == NULL) {
return;
}
D[root->index] = level;
count_subtree(root->left, D, level + 1);
count_subtree(root->right, D, level + 1);
}
void free_subtree(NODE *root) {
if(root == NULL) {
return;
}
free_subtree(root->left);
free_subtree(root->right);
free(root);
}
void testCase() {
int N, i, *A, *D;
NODE *root;
cin >> N;
root = (NODE *) malloc(sizeof(NODE));
A = (int *) malloc(sizeof(int) * N);
D = (int *) malloc(sizeof(int) * N);
root->left = root->right = NULL;
root->value = -1;
root->index = 0;
for(i = 0; i < N; i++) {
cin >> A[i];
if(A[i] > root->value) {
root->value = A[i];
root->index = i;
}
}
root->left = build_subtree(root, A, 0, root->index - 1);
root->right = build_subtree(root, A, root->index + 1, N - 1);
count_subtree(root, D, 0);
free_subtree(root);
free(A);
for(i = 0; i < N; i++) {
cout << D[i] << " ";
}
cout << endl;
free(D);
}
int main(int argc, char **argv) {
int T;
cin >> T;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep># Bitwise Trie
Trabalho 1 de Organização de Computadores
## Integrantes
* <NAME>
* <NAME>
* <NAME>
* <NAME>
<file_sep>
#
# ~ Relatório Fluxo ATM ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -Wall
objects/main.o: main.c objects/ATM.o headers/ATM.h objects/hashtable.o headers/hashtable.h
gcc -c -o objects/main.o main.c -Wall -I headers
objects/ATM.o: lib/ATM.c headers/ATM.h objects/hashtable.o headers/hashtable.h
gcc -c -o objects/ATM.o lib/ATM.c -Wall -I headers
objects/hashtable.o: lib/hashtable.c
gcc -c -o objects/hashtable.o lib/hashtable.c -Wall
run: Prog
./Prog
clean:
rm Prog objects/*.o
<file_sep>#include <stdlib.h>
#include <string.h>
/*
* ~ <NAME> ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
enum __nodecolour_t { BLACK = 0, RED };
struct __node_t {
void *value;
enum __nodecolour_t colour;
struct __node_t *p, *l, *r;
};
struct __redblacktree_t {
struct __node_t *root, *nil;
size_t memsize;
int (*fcmp)(void *, void *);
void (*ffree)(void *);
unsigned long nitems;
};
struct __redblacktree_t *RBT_New(size_t memsize, int (*fcmp)(void *, void *), void (*ffree)(void *)){
/*
* Esta função aloca na memória a estrutura que representa uma árvore rubro-negra e retorna um ponteiro para tal.
* É necessário passar para ela o tamanho 'memsize', em bytes, do valor que será armazenado em cada nó.
* Além disso, um ponteiro para função 'fcmp' para comparar esses valores (maior, menor, igual).
* E o usuário pode definir uma função 'ffree' para liberar os dados da memória, caso seja ua estrutura complexa com ponteiros dentro.
*
* Complexidade: O(1)
*
* Ela retorna o ponteiro para a árvore na HEAP, ou NULL em caso de erros.
*/
struct __redblacktree_t *Aux;
if(memsize<1 || fcmp==NULL) return NULL;
Aux=(struct __redblacktree_t *)malloc(sizeof(struct __redblacktree_t));
Aux->root=Aux->nil=(struct __node_t *)calloc(1, sizeof(struct __node_t));
Aux->memsize=memsize;
Aux->fcmp=fcmp;
Aux->ffree=ffree;
Aux->nitems=0;
return Aux;
}
void RBT_Rotate_L(struct __node_t *Root, struct __redblacktree_t *T){
/*
* Esta é uma função auxiliar, ou seja, não está disponível no TAD (.h) e é usada apenas internamente neste arquivo de código (.c).
* Ela rotaciona um nó 'Root' para a esquerda.
*int cmp;
* Complexidade: O(1)
*
* Ela não retorna nada.
*/
struct __node_t *Aux=Root->r;
Root->r=Aux->l;
if(Aux->l!=T->nil){
Aux->l->p=Root;
}
Aux->p=Root->p;
if(Root->p==T->nil) T->root=Aux;
else if(Root==Root->p->l) Root->p->l=Aux;
else Root->p->r=Aux;
Aux->l=Root;
Root->p=Aux;
}
void RBT_Rotate_R(struct __node_t *Root, struct __redblacktree_t *T){
/*
* Esta é uma função auxiliar, ou seja, não está disponível no TAD (.h) e é usada apenas internamente neste arquivo de código (.c).
* Ela rotaciona um nó 'Root' para a direita.
*
* Complexidade: O(1)
*
* Ela não retorna nada.
*/
struct __node_t *Aux=Root->l;
Root->l=Aux->r;
if(Aux->r!=T->nil){
Aux->r->p=Root;
}
Aux->p=Root->p;
if(Root->p==T->nil) T->root=Aux;
else if(Root==Root->p->r) Root->p->r=Aux;
else Root->p->l=Aux;
Aux->r=Root;
Root->p=Aux;
}
void RBT_Insert_Colourise(struct __node_t *Root, struct __redblacktree_t *T){
/*
* Esta é uma função auxiliar, ou seja, não está disponível no TAD (.h) e é usada apenas internamente neste arquivo de código (.c).
* Ela verifica os nós onde será realizada alguma rotação, e atualiza suas cores ("BLACK", "RED").
*
* Complexidade: O(logN)
*
* Ela não retorna nada.
*/
struct __node_t *Aux;
if(Root==NULL || T==NULL) return;
while(Root->p->colour==RED){
if(Root->p==Root->p->p->l){
Aux=Root->p->p->r;
if(Aux->colour==RED){
Root->p->colour=Aux->colour=BLACK;
Root->p->p->colour=RED;
Root=Root->p->p;
}else if(Root==Root->p->r){
Root=Root->p;
RBT_Rotate_L(Root, T);
}else{
Root->p->colour=BLACK;
Root->p->p->colour=RED;
RBT_Rotate_R(Root->p->p, T);
}
}else{
Aux=Root->p->p->l;
if(Aux->colour==RED){
Root->p->colour=Aux->colour=BLACK;
Root->p->p->colour=RED;
Root=Root->p->p;
}else if(Root==Root->p->l){
Root=Root->p;
RBT_Rotate_R(Root, T);
}else{
Root->p->colour=BLACK;
Root->p->p->colour=RED;
RBT_Rotate_L(Root->p->p, T);
}
}
}
T->root->colour=BLACK;
}
int RBT_Insert(void *Elem, struct __redblacktree_t *T){
/*
* Esta função insere 'Elem' na rubro-negra 'T'.
*
* Complexidade: O(logN)
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
struct __node_t **Aux, *Parent;
int cmp;
if(Elem==NULL || T==NULL) return 0;
Aux=&T->root;
Parent=T->nil;
while((*Aux)!=T->nil){
cmp=T->fcmp(Elem, (*Aux)->value);
Parent=*Aux;
if(cmp>0) Aux=&(*Aux)->l;
else Aux=&(*Aux)->r;
}
*Aux=(struct __node_t *)malloc(sizeof(struct __node_t));
(*Aux)->value=(void *)malloc(T->memsize);
(*Aux)->l=(*Aux)->r=T->nil;
(*Aux)->p=Parent;
(*Aux)->colour=RED;
memcpy((*Aux)->value, Elem, T->memsize);
RBT_Insert_Colourise(*Aux, T);
T->nitems++;
return 1;
}
void *RBT_Min_(struct __node_t *Root){
/*
* Esta é uma função auxiliar, ou seja, não está disponível no TAD (.h) e é usada apenas internamente neste arquivo de código (.c).
* Ela acha o menor valor armazenado na sub-árvore 'Root'.
*
* Complexidade: O(logN)
*
* Ela não retorna nada.
*/
struct __node_t *Aux;
if(Root==NULL) return NULL;
Aux=Root;
while(Aux!=NULL && Aux->value!=NULL){
if(Aux->l==NULL || Aux->l->value==NULL) break;
else Aux=Aux->l;
}
return Aux->value;
}
int RBT_Min(void *Dest, struct __redblacktree_t *T){
/*
* Esta função salva o menor elemento da rubro-negra 'T' em 'Dest'.
*
* Complexidade: O(logN)
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros ou árvore vazia.
*/
if(Dest==NULL || T==NULL) return 0;
if(T->nitems<1) return 0;
memcpy(Dest, RBT_Min_(T->root), T->memsize);
return 1;
}
void *RBT_Max_(struct __node_t *Root){
/*
* Esta é uma função auxiliar, ou seja, não está disponível no TAD (.h) e é usada apenas internamente neste arquivo de código (.c).
* Ela acha o maior valor armazenado na sub-árvore 'Root'.
*
* Complexidade: O(logN)
*
* Ela não retorna nada.
*/
struct __node_t *Aux;
if(Root==NULL) return NULL;
Aux=Root;
while(Aux!=NULL && Aux->value!=NULL){
if(Aux->r==NULL || Aux->r->value==NULL) break;
else Aux=Aux->r;
}
return Aux->value;
}
int RBT_Max(void *Dest, struct __redblacktree_t *T){
/*
* Esta função salva o maior elemento da rubro-negra 'T' em 'Dest'.
*
* Complexidade: O(logN)
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros ou árvore vazia.
*/
if(Dest==NULL || T==NULL) return 0;
if(T->nitems<1) return 0;
memcpy(Dest, RBT_Max_(T->root), T->memsize);
return 1;
}
int RBT_Predecessor(void *Dest, void *Elem, struct __redblacktree_t *T){
/*
* Esta função salva em 'Dest' o predecessor de um elemento 'Elem' na rubro-negra 'T'.
*
* Complexidade: O(logN)
*
* Ela retorna 1 em caso de sucesso, 0 caso 'Elem' não tenha predecessor, -1 caso 'Elem' não foi encontrado, ou -2 em caso de erros.
*/
struct __node_t *Aux, *Lefty;
int cmp;
if(Dest==NULL || Elem==NULL || T==NULL) return -2;
Aux=T->root;
Lefty=NULL;
while(Aux!=NULL && Aux!=T->nil){
cmp=T->fcmp(Elem, Aux->value);
if(cmp>0){
Aux=Aux->l;
}else if(cmp<0){
Lefty=Aux;
Aux=Aux->r;
}else break;
}
if(Aux==NULL || Aux==T->nil) return -1; /* 'Elem' não encontrado. */
if(Aux->l!=NULL && Aux->l!=T->nil) memcpy(Dest, RBT_Max_(Aux->l), T->memsize);
else if(Lefty!=NULL) memcpy(Dest, Lefty->value, T->memsize);
else return 0; /* 'Elem' não possui antecessor. */
return 1; /* Ok */
}
int RBT_Successor(void *Dest, void *Elem, struct __redblacktree_t *T){
/*
* Esta função salva em 'Dest' o sucessor de um elemento 'Elem' na rubro-negra 'T'.
*
* Complexidade: O(logN)
*
* Ela retorna 1 em caso de sucesso, 0 caso 'Elem' não tenha sucessor, -1 caso 'Elem' não foi encontrado, ou -2 em caso de erros.
*/
struct __node_t *Aux, *Righty;
int cmp;
if(Dest==NULL || Elem==NULL || T==NULL) return -2;
Aux=T->root;
Righty=NULL;
while(Aux!=NULL && Aux!=T->nil){
cmp=T->fcmp(Elem, Aux->value);
if(cmp>0){
Righty=Aux;
Aux=Aux->l;
}else if(cmp<0){
Aux=Aux->r;
}else break;
}
if(Aux==NULL || Aux==T->nil) return -1; /* 'Elem' não encontrado. */
if(Aux->r!=NULL && Aux->r!=T->nil) memcpy(Dest, RBT_Min_(Aux->r), T->memsize);
else if(Righty!=NULL) memcpy(Dest, Righty->value, T->memsize);
else return 0; /* 'Elem' não possui sucessor. */
return 1; /* Ok. */
}
void RBT_PreOrder_(void (*fact)(void *), struct __node_t *Root){
/*
* Esta é uma função auxiliar, ou seja, não está disponível no TAD (.h) e é usada apenas internamente neste arquivo de código (.c).
* Ela percorre ("traverse") a sub-árvore 'Root' de forma pré-ordem.
*
* Complexidade: O(N)
*
* Ela não retorna nada.
*/
if(fact==NULL || Root==NULL || Root->value==NULL) return;
fact(Root->value);
RBT_PreOrder_(fact, Root->l);
RBT_PreOrder_(fact, Root->r);
}
int RBT_PreOrder(void (*fact)(void *), struct __redblacktree_t *T){
/*
* Esta função percorre todos os elementos da rubro-negra 'T' de forma pré-ordem.
* Ela chama a função 'fact' para cada elemento percorrido, uma função que o usuário pode definir.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros ou árvore vazia.
*/
if(fact==NULL || T==NULL) return 0;
if(T->nitems<1) return 0;
RBT_PreOrder_(fact, T->root);
return 1;
}
void RBT_InOrder_(void (*fact)(void *), struct __node_t *Root){
/*
* Esta é uma função auxiliar, ou seja, não está disponível no TAD (.h) e é usada apenas internamente neste arquivo de código (.c).
* Ela percorre ("traverse") a sub-árvore 'Root' de forma em-ordem.
*
* Complexidade: O(N)
*
* Ela não retorna nada.
*/
if(fact==NULL || Root==NULL || Root->value==NULL) return;
RBT_InOrder_(fact, Root->l);
fact(Root->value);
RBT_InOrder_(fact, Root->r);
}
int RBT_InOrder(void (*fact)(void *), struct __redblacktree_t *T){
/*
* Esta função percorre todos os elementos da rubro-negra 'T' de forma em-ordem.
* Ela chama a função 'fact' para cada elemento percorrido, uma função que o usuário pode definir.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros ou árvore vazia.
*/
if(fact==NULL || T==NULL) return 0;
if(T->nitems<1) return 0;
RBT_InOrder_(fact, T->root);
return 1;
}
void RBT_PostOrder_(void (*fact)(void *), struct __node_t *Root){
/*
* Esta é uma função auxiliar, ou seja, não está disponível no TAD (.h) e é usada apenas internamente neste arquivo de código (.c).
* Ela percorre ("traverse") a sub-árvore 'Root' de forma pós-ordem.
*
* Complexidade: O(N)
*
* Ela não retorna nada.
*/
if(fact==NULL || Root==NULL || Root->value==NULL) return;
RBT_PostOrder_(fact, Root->l);
RBT_PostOrder_(fact, Root->r);
fact(Root->value);
}
int RBT_PostOrder(void (*fact)(void *), struct __redblacktree_t *T){
/*
* Esta função percorre todos os elementos da rubro-negra 'T' de forma pós-ordem.
* Ela chama a função 'fact' para cada elemento percorrido, uma função que o usuário pode definir.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros ou árvore vazia.
*/
if(fact==NULL || T==NULL) return 0;
if(T->nitems<1) return 0;
RBT_PostOrder_(fact, T->root);
return 1;
}
void RBT_Destroy_NULLFFREE_(struct __node_t *Root){
/*
* Esta é uma função auxiliar, ou seja, não está disponível no TAD (.h) e é usada apenas internamente neste arquivo de código (.c).
* Ela limpa da memória o valor e a própria estrutura de cada nó da sub-árvore 'Root'.
*
* Complexidade: O(N)
*
* Ela não retorna nada.
*/
if(Root==NULL || Root->value==NULL) return;
RBT_Destroy_NULLFFREE_(Root->l);
RBT_Destroy_NULLFFREE_(Root->r);
free(Root->value);
free(Root);
}
void RBT_Destroy_FFREE_(void (*ffree)(void *), struct __node_t *Root){
/*
* Esta é uma função auxiliar, ou seja, não está disponível no TAD (.h) e é usada apenas internamente neste arquivo de código (.c).
* Ela limpa da memória o valor e a própria estrutura de cada nó da sub-árvore 'Root'.
* Antes de limpar um valor, ela chama uma função 'ffree' definida pelo usuário, para limpar estruturas complexas (como structs com ponteiros dentro).
*
* Complexidade: O(N)
*
* Ela não retorna nada.
*/
if(Root==NULL || Root->value==NULL) return;
RBT_Destroy_FFREE_(ffree, Root->l);
RBT_Destroy_FFREE_(ffree, Root->r);
ffree(Root->value);
free(Root->value);
free(Root);
}
void RBT_Destroy(struct __redblacktree_t *T){
/*
* Esta função limpa da memória a rubro-negra 'T' e todos seus nós e valores.
* Caso o valor armazenado seja uma estrutura complexa, que tenha outros ponteiros que precisem ser desalocados externamente,
* a função vai chamar outra função definida pelo usuário para liberar cada valor de cada nó.
* Caso o valor armazenado seja uma estrutura simples (como um inteiro, por exemplo), nenhuma outra função é chamada ao liberar os nós.
*
* Ela não retorna nada.
*/
if(T==NULL) return;
if(T->ffree==NULL) RBT_Destroy_NULLFFREE_(T->root);
else RBT_Destroy_FFREE_(T->ffree, T->root);
free(T->nil);
free(T);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int N,i;
scanf(" %d",&N);
double Ni[N],M=0,DP=0;
for(i=0;i<N;i++){
scanf(" %lf",&Ni[i]);
M+=Ni[i];
}
M=M/(double)N;
for(i=0;i<N;i++){
DP+=pow((Ni[i]-M),2);
}
DP=sqrt(DP/(double)N);
printf("%.4lf\n",M);
printf("%.4lf",DP);
return EXIT_SUCCESS;
}
<file_sep>
#
# ~ Trabalho Prático: Parte 2 ~
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados, arquivos binários *.dat e o próprio executável do programa
all: programaTrab2
noobj: programaTrab2
rm objects/*.o
programaTrab2: objects/main.o
gcc -o programaTrab2 objects/*.o -Wall -pedantic -ansi
objects/main.o: main.c objects/funcionalidades.o headers/funcionalidades.h
gcc -c -o objects/main.o main.c -I headers -Wall -pedantic -ansi
objects/funcionalidades.o: lib/funcionalidades.c objects/arvore-b.o headers/arvore-b.h objects/cabecalho.o headers/cabecalho.h
gcc -c -o objects/funcionalidades.o lib/funcionalidades.c -I headers -Wall -pedantic -ansi
objects/arvore-b.o: lib/arvore-b.c objects/cabecalho.o headers/cabecalho.h
gcc -c -o objects/arvore-b.o lib/arvore-b.c -I headers -Wall -pedantic -ansi
objects/cabecalho.o: lib/cabecalho.c headers/cabecalho.h
gcc -c -o objects/cabecalho.o lib/cabecalho.c -I headers -Wall -pedantic -ansi
run: programaTrab2
./programaTrab2
clean:
rm programaTrab2 *.dat buffer-info.text objects/*.o
<file_sep>
/*
* == ABB ==
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __BIN_SEARCH_TREE_H_
#define __BIN_SEARCH_TREE_H_
typedef struct __bin_search_tree BIN_SEARCH_TREE;
struct __bin_search_tree *Create_Tree();
char Find_In(int,struct __bin_search_tree *);
char Insert_Into(int,struct __bin_search_tree *);
char Remove_First_From(int,struct __bin_search_tree *);
char Print_InOrder(FILE *,struct __bin_search_tree *);
char Print_PreOrder(FILE *,struct __bin_search_tree *);
char Print_PostOrder(FILE *,struct __bin_search_tree *);
char Print_LevelOrder(FILE *,struct __bin_search_tree *);
char Destroy_Tree(struct __bin_search_tree *);
#endif<file_sep>#include <stdlib.h>
#include <time.h>
#include <vectorutils.h>
int partition(void *vector, int size, int (*cmp)(void *,void *), int left, int right, int *CmpN, int *MovN) {
int j, i, pivot;
pivot=(left+right)/2;
gswap(vector+left*size, vector+pivot*size, size);
(*MovN)+=3;
for (i = left, j = left+1; j <= right; j++){
(*CmpN)++;
if (cmp(vector+j*size, vector+left*size) >= 0){
(*MovN)+=3;
gswap(vector+j*size, vector+(++i)*size, size);
}
}
gswap(vector+i*size, vector+left*size, size);
(*MovN)+=3;
return i;
}
void quicksort_(void *vector, int size, int (*cmp)(void *,void *), int start, int end, int *CmpN, int *MovN) {
int r;
if (start < end) {
r = partition(vector, size, cmp, start, end, CmpN, MovN);
quicksort_(vector, size, cmp, start, r-1, CmpN, MovN);
quicksort_(vector, size, cmp, r+1, end, CmpN, MovN);
}
}
void quicksort(void *vector, int size, int (*cmp)(void *,void *), int n, int *CmpN, int *MovN) {
int C = 0, M = 0;
srand(time(NULL));
quicksort_(vector,size,cmp,0,n-1, &C, &M);
*CmpN = C;
*MovN = M;
}
/*
Partition que usa pivot aleatório, mas com IF dentro do FOR.
int partition(int *vector, int left, int right) {
int j, i, pivot;
pivot=left+rand()%(right-left+1);
for (i = left, j = left; j <= right; j++) {
if (vector[j] < vector[pivot]) {
if(pivot==i) pivot=j;
swap(vector, j, i);
i++;
}
}
swap(vector, i, pivot);
return i;
}
*/
/*
Partition que usa pivot aleatório, mas sem IF dentro do FOR.
int partition(int *vector, int left, int right) {
int j, i, pivot;
pivot=left+rand()%(right-left+1);
swap(vector,left,pivot);
for (i = left, j = left+1; j <= right; j++) {
if (vector[j] < vector[left]) {
i++;
swap(vector, j, i);
}
}
swap(vector, i, left);
return i;
}
*/
/*
Partition com pivot fixo (left).
int partition(int *vector, int left, int right) {
int j, i;
for (i = left, j = left+1; j <= right; j++) {
if (vector[j] < vector[left]) {
i++;
swap(vector, j, i);
}
}
swap(vector, i, left);
return i;
}
*/
<file_sep>#include <stdlib.h>
#include <limits.h>
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char **argv) {
vector< vector<long> > missiles;
long i, j, k, Aux, n, nmissiles, counter;
missiles = vector< vector<long> >();
missiles.push_back(vector<long>());
cin >> Aux;
n = 0;
do {
if(Aux < 0) {
missiles.push_back(vector<long>());
n++;
continue;
}
missiles[n].push_back(Aux);
} while(cin >> Aux);
n--;
for(i = 0; i < n; i++){
if(i)
cout << '\n';
cout << "Test #" << i + 1 << ":\nmaximum possible interceptions: ";
nmissiles = missiles[i].size();
k = -1;
for(j = counter = 0; j < nmissiles; j++){
if(k < 0){
counter++;
k = 0;
} else if(missiles[i][j] <= missiles[i][k]) {
counter++;
k++;
} else {
k--;
}
}
cout << counter << "\n";
}
return EXIT_SUCCESS;
}
<file_sep>import re
import mysql.connector
import json
import sys
import os
mydb = mysql.connector.connect()
class Config:
# DO NOT MODIFY THESE VARIABLES HERE!
# Their values are updated dynamically from 'config.json' file as soon as the application is up.
LOADED = False
DB_HOSTNAME = None
DB_USERNAME = None
DB_PASSWORD = None
DB_NAME = None
TWITTER_API_KEY = None
TWITTER_API_SECRET = None
TWITTER_ACCESS_TOKEN = None
TWITTER_ACCESS_TOKEN_SECRET = None
KAFKA = None
@staticmethod
def Init(configFile: str = None):
if Config.LOADED:
return
if configFile is None and len(sys.argv) == 2:
configFile = sys.argv[1]
elif configFile is None and 'TA_ConfigFile' in os.environ:
configFile = os.environ['TA_ConfigFile']
elif configFile is None:
configFile = 'config.json'
with open(configFile) as file:
fileContent = file.read()
config = json.loads(fileContent)
if 'database' not in config or 'host' not in config['database'] or 'user' not in config['database'] or 'passwd' not in config['database'] or 'name' not in config['database']:
raise RuntimeError('JSON not in correct format.')
Config.DB_HOSTNAME = config['database']['host']
Config.DB_USERNAME = config['database']['user']
Config.DB_PASSWORD = config['database']['passwd']
Config.DB_NAME = config['database']['name']
if 'twitter' not in config or 'api_key' not in config['twitter'] or 'api_secret' not in config['twitter']:
raise RuntimeError('JSON not in correct format.')
Config.TWITTER_API_KEY = config['twitter']['api_key']
Config.TWITTER_API_SECRET = config['twitter']['api_secret']
if 'access_token' in config['twitter'] and 'access_token_secret' in config['twitter']:
Config.TWITTER_ACCESS_TOKEN = config['twitter']['access_token']
Config.TWITTER_ACCESS_TOKEN_SECRET = config['twitter']['access_token_secret']
if 'kafka' not in config:
raise RuntimeError('JSON not in correct format.')
Config.KAFKA = config['kafka']
Config.LOADED = True
class DBConnection:
def __init__(self):
if Config.LOADED == False:
raise ConnectionError('Config not loaded yet. Please call "Config.Init()". If already called, wait a moment before continuing.')
self.con = mysql.connector.connect(host=Config.DB_HOSTNAME, user=Config.DB_USERNAME, password=Config.DB_PASSWORD, database=Config.DB_NAME)
def fetchAll(self, query: str, args: tuple = None):
cursor = self.con.cursor(buffered=True)
if args is None:
cursor.execute(query)
else:
cursor.execute(query, args)
items = cursor.fetchall()
self.con.commit()
cursor.close()
return items
def fetchOne(self, query: str, args: tuple = None):
cursor = self.con.cursor(buffered=True)
if args is None:
cursor.execute(query)
else:
cursor.execute(query, args)
item = cursor.fetchone()
self.con.commit()
cursor.close()
return item
def insertAll(self, query: str, items: list = None):
if items is None or len(items) < 1:
return 0
for item in items:
if type(item) != tuple:
raise TypeError('In function "insertAll", "items" should be a list of tuple.')
cursor = self.con.cursor(buffered=True)
cursor.executemany(query, items)
self.con.commit()
row_count = cursor.rowcount
cursor.close()
return row_count
def insertOne(self, query: str, item: tuple = None):
if item is None:
return 0
cursor = self.con.cursor(buffered=True)
cursor.execute(query, item)
self.con.commit()
row_count = cursor.rowcount
cursor.close()
return True if row_count > 0 else False
def execute(self, query: str, args: tuple = None):
cursor = self.con.cursor(buffered=True)
if args is None:
cursor.execute(query)
else:
cursor.execute(query, args)
self.con.commit()
row_count = cursor.rowcount
cursor.close()
return row_count
def close(self):
self.con.close()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
class Utils:
@staticmethod
def ValidateField(formData, field, regExp = None, checkEmpty = False, equals = None, minLength = None, maxLength = None):
if field is None:
return False
if field not in formData:
return False
if regExp is not None and not re.match(regExp, formData[field]):
return False
if checkEmpty and formData[field].strip() == '':
return False
if equals is not None and formData[field] != equals:
return False
if minLength is not None and len(formData[field]) < minLength:
return False
if maxLength is not None and len(formData[field]) > maxLength:
return False
return True<file_sep>
/*
* ~ Sliding Puzzle ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef SLIDING_PUZZLE_H_
#define SLIDING_PUZZLE_H_
#include <stdio.h>
typedef struct __slidingpuzzle_t PUZZLE;
struct __slidingpuzzle_t *New_Puzzle(FILE *, unsigned long);
int Move_Puzze_Up(struct __slidingpuzzle_t *);
int Move_Puzze_Left(struct __slidingpuzzle_t *);
int Move_Puzze_Down(struct __slidingpuzzle_t *);
int Move_Puzze_Right(struct __slidingpuzzle_t *);
int Print_Puzzle(FILE *, struct __slidingpuzzle_t *);
void Destroy_Puzzle(struct __slidingpuzzle_t *);
#endif<file_sep>#include <iostream>
#include <stdlib.h>
#include <cmath>
#include <vector>
#include <queue>
#include <string.h>
using namespace std;
typedef struct __node {
int Curr[4];
int Dep;
int Distance;
bool operator<(const __node &a) const{
return Dep+Distance > a.Dep+a.Distance;
}
} V_NODE;
int distance(int *A, int *B){
int i, sum;
for(i = sum = 0; i < 4; i++)
sum += abs(A[i] - B[i]); // * pow(10, i);
return sum;
}
bool is_forb(int *A, vector<int*> &Forb_List){
int i, j, n;
n = Forb_List.size();
for(i = 0; i < n; i++){
for(j = 0; j < 4; j++)
if(Forb_List[i][j] != A[j]) break;
if(j >= 4) return true;
}
return false;
}
int main(int argc, char **argv){
int i, j, k, N, Objective[4], Aux[4], NForb;
int *AuxVet;
V_NODE AuxNode;
V_NODE ProcessingNode;
cin >> N;
for(i = 0; i < N; i++){
vector<int*> Forb_List = vector<int*>();
priority_queue<V_NODE> Nodes = priority_queue<V_NODE>();
cin >> AuxNode.Curr[0] >> AuxNode.Curr[1] >> AuxNode.Curr[2] >> AuxNode.Curr[3];
cin >> Objective[0] >> Objective[1] >> Objective[2] >> Objective[3];
cin >> NForb;
for(j = 0; j < NForb; j++){
cin >> Aux[0] >> Aux[1] >> Aux[2] >> Aux[3];
if(distance(Aux, Objective) == 0 || distance(Aux, AuxNode.Curr) == 0){
for(k = j+1; k < NForb; k++){
cin >> Aux[0] >> Aux[1] >> Aux[2] >> Aux[3];
}
cout << "-1\n"; // Objetivo ou Inicio está na lista de proibidos.
goto continue_loop;
}
AuxVet = (int *)malloc(sizeof(int) * 4);
memcpy(AuxVet, &Aux, sizeof(int) * 4);
Forb_List.push_back(AuxVet);
}
AuxNode.Dep = 0;
AuxNode.Distance = distance(AuxNode.Curr, Objective);
Nodes.push(AuxNode);
while(Nodes.size() > 0){
// Retirar node[0] + calcular nodes filhos + inseri-los
ProcessingNode = Nodes.top();
if(distance(ProcessingNode.Curr, Objective) == 0){
cout << ProcessingNode.Dep << "\n";
goto continue_loop;
}
Nodes.pop();
AuxNode.Dep = ProcessingNode.Dep + 1;
memcpy(AuxNode.Curr, ProcessingNode.Curr, sizeof(int) * 4);
for(j = 0; j < 4; j++){
if(++AuxNode.Curr[j] < 10 && !is_forb(AuxNode.Curr, Forb_List)){
AuxNode.Distance = distance(AuxNode.Curr, Objective);
Nodes.push(AuxNode);
}
AuxNode.Curr[j] = ProcessingNode.Curr[j];
if(--AuxNode.Curr[j] >= 0 && !is_forb(AuxNode.Curr, Forb_List)){
AuxNode.Distance = distance(AuxNode.Curr, Objective);
Nodes.push(AuxNode);
}
AuxNode.Curr[j] = ProcessingNode.Curr[j];
}
}
cout << "-1\n"; // Não possível.
continue_loop: ;
}
return EXIT_SUCCESS;
}<file_sep>#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <ctype.h>
#include <unordered_map>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef struct {
long time;
} BOOK;
int fcmp(const BOOK *a, const BOOK *b) {
return a->time - b->time;
}
int main(int argc, char **argv) {
long i, N, K, NA, NB, NBoth, aux1, aux2, aux3;
BOOK *booksAlice, *booksBob, *booksBoth;
scanf("%ld %ld", &N, &K); // Ler N e K.
booksAlice = (BOOK *) malloc(sizeof(BOOK) * N); // Alocar
booksBob = (BOOK *) malloc(sizeof(BOOK) * N);
booksBoth = (BOOK *) malloc(sizeof(BOOK) * N);
NA = NB = NBoth = 0;
for(i = 0; i < N; i++) { // Ler livros de entrada.
scanf("%ld %ld %ld", &aux1, &aux2, &aux3);
if(aux2 && aux3) {
booksBoth[NBoth++].time = aux1;
} else if(aux2) {
booksAlice[NA++].time = aux1;
} else if(aux3) {
booksBob[NB++].time = aux1;
}
}
if(NA + NBoth < K || NB + NBoth < K) { // Verificar validade.
printf("-1\n");
return EXIT_SUCCESS;
}
qsort(booksAlice, NA, sizeof(BOOK), (int (*)(const void *, const void *)) fcmp); // Ordenar por tempo de leitura crescente.
qsort(booksBob, NB, sizeof(BOOK), (int (*)(const void *, const void *)) fcmp);
qsort(booksBoth, NBoth, sizeof(BOOK), (int (*)(const void *, const void *)) fcmp);
for(i = 1; i < NA; i++) {
booksAlice[i].time += booksAlice[i - 1].time;
}
for(i = 1; i < NB; i++) {
booksBob[i].time += booksBob[i - 1].time;
}
for(i = 1; i < NBoth; i++) {
booksBoth[i].time += booksBoth[i - 1].time;
}
i = 0;
aux3 = INT_MAX;
while(i <= NBoth && i <= K) {
aux1 = (i > 0) ? booksBoth[i - 1].time : 0;
aux2 = K - i;
if(NA >= aux2 && NB >= aux2){
aux1 += (aux2 > 0) ? (booksAlice[aux2 - 1].time + booksBob[aux2 - 1].time) : 0;
aux3 = (aux3 < aux1) ? aux3 : aux1;
}
i++;
}
printf("%ld\n", aux3);
free(booksAlice);
free(booksBob);
free(booksBoth);
return EXIT_SUCCESS;
}
<file_sep># Trabalho Prático
Trabalho Prático de Organização de Arquivos
## ./headers
Aqui se encontram os arquivos de cabeçalho (_\#include_) utilizados no código.
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <SlidingPuzzle.h>
/*
* ~ Sliding Puzzle ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#define MAX_D 5
int main(int argc, char **argv){
PUZZLE *SlidPuz=New_Puzzle(stdin, MAX_D);
char R;
while( (R=getchar()) != EOF && R!='X' ){
if(R=='A'){
if(Move_Puzze_Up(SlidPuz)==1) continue;
}else if(R=='L'){
if(Move_Puzze_Left(SlidPuz)==1) continue;
}else if(R=='B'){
if(Move_Puzze_Down(SlidPuz)==1) continue;
}else if(R=='R'){
if(Move_Puzze_Right(SlidPuz)==1) continue;
}
printf("This puzzle has no final configuration.\n");
return EXIT_SUCCESS;
}
Print_Puzzle(stdout, SlidPuz);
Destroy_Puzzle(SlidPuz);
return EXIT_SUCCESS;
}
<file_sep># Objeto
Objeto obtido do website [free3d](https://free3d.com/3d-model/cinema4d-table-66762.html): licença para uso pessoal.
<file_sep>
#
# ~ Gerenc. de Processos ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -Wall
objects/main.o: main.c objects/processman.o headers/processman.h
gcc -c -o objects/main.o main.c -Wall -I headers
objects/processman.o: lib/processman.c
gcc -c -o objects/processman.o lib/processman.c -Wall
run: Prog
./Prog
clean:
rm Prog objects/*.o
<file_sep># Trabalho Prático
Trabalho Prático de Organização de Arquivos
## ./lib
Aqui se encontra toda a implementação do trabalho.
* [./lib/arvore-b.c](arvore-b.c) implementação do índice árvore-B integrado com um Buffer-Pool com política de substituição SCA (Second-Chance Algorithm).
* [./lib/cabecalho.c](cabecalho.c) implementação de leituras e escritas dos cabeçalhos nos arquivos binários.
* [./lib/funcionalidades.c](funcionalidades.c) implementação de todas as funcionalidades do trabalho.
<file_sep>import numpy as np
import imageio
import sys
#
# ~ Trabalho 4: Filtragem 2D ~
#
# <NAME>
# <EMAIL>
# Nº USP 10369014
# Processamento de Imagens: SCC-0251 2018.1
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
# == DEFINIÇÃO DE FUNÇÕES ==
def Apply_Filter_Space(Arr, Mask):
"Aplica um filtro Mask sob uma imagem Arr no domínio do espaço."
Res = np.zeros(Arr.shape, dtype=np.float)
mask_start = [
int(((Mask.shape[0] - 1) / 2) * -1),
int(((Mask.shape[1] - 1) / 2) * -1) ]
for i in range(Arr.shape[0]):
for j in range(Arr.shape[1]): # Para cada pixel da array resultante...
for x in range(Mask.shape[0]):
for y in range(Mask.shape[1]): # Para cada peso da máscara...
ui = i - (x + mask_start[0])
uj = j - (y + mask_start[1])
if ui < 0 or ui >= Arr.shape[0] or uj < 0 or uj >= Arr.shape[1]: # Se for sob uma posição válida...
continue
Res[i, j] += Arr[ui, uj] * Mask[x, y] # Somar peso
Res = np.floor(Res)
return Res
def Apply_Filter_Frequency(Arr, Mask):
"Aplica um filtro Mask sob uma imagem Arr no domínio das frequências."
Res = np.zeros(Arr.shape, dtype=np.float)
Res[: Mask.shape[0], : Mask.shape[1]] += Mask # Filtro do tamanho da imagem
Arr = np.fft.fft2(Arr) # Transformada de Fourier
Res = np.fft.fft2(Res) # Filtro estendido
Res = np.multiply(Arr, Res) # Multiplicar ponto a ponto
return Res
def New_Laplace_Filter(N, Sigma):
"Cria um filtro Laplaciana da Gaussiana de tamanho N e desvio padrão Sigma."
Res = np.empty([N, N], dtype=np.float)
xyinc = 10 / (N - 1)
Ratio1 = np.pi * (Sigma ** 4)
Ratio2 = 2 * (Sigma * Sigma)
x = -5
for i in range(N): # Para cada linha do filtro...
y = -5
for j in range(N): # Para cada coluna do filtro..
Res[i, j] = (1 - ((x * x + y * y) / Ratio2)) * np.exp(-1 * ((x * x + y * y) / Ratio2)) # Aplicar equação LoG
y += xyinc
x += xyinc
Res = -Res / Ratio1
Ratio3 = -1 * np.sum(np.where(Res > 0, Res, 0)) / np.sum(np.where(Res < 0, Res, 0)) # Criar razão para normalizar
Res = (np.where(Res < 0, Res, 0) * Ratio3) + np.where(Res > 0, Res, 0) # Normalizar
return Res
# == MAIN ==
# Leitura dos dados da entrada padrão
file_name = str(input()).rstrip()
filter_option = int(input())
loaded_image = imageio.imread(file_name) # Carregar imagem
if filter_option == 1: # Filtro Arbitrário
filter_size = np.array(input().split(' '), dtype=np.int) # Ler dimensões do filtro
filter_mask = np.empty(filter_size, dtype=np.float) # Alocar filtro arbitrário
for i in range(filter_size[0]):
filter_mask[i] = np.array(input().split(' '), dtype=np.float) # Ler pesos
generated_image = Apply_Filter_Frequency(loaded_image, filter_mask) # Aplicar filtro
elif filter_option == 2: # Filtro Laplaciana da Gaussiana
filter_size = int(input())
filter_sigma = float(input())
filter_mask = New_Laplace_Filter(filter_size, filter_sigma) # Criar filtro
generated_image = Apply_Filter_Frequency(loaded_image, filter_mask) # Aplicar filtro
else:
filter_mask_x = np.array([ # Filtro Ix
[1, 0, -1],
[2, 0, -2],
[1, 0, -1]
], dtype=np.float)
filter_mask_y = np.array([ # Filtro Iy
[1, 2, 1],
[0, 0, 0],
[-1, -2, -1]
], dtype=np.float)
generated_image_x = Apply_Filter_Space(loaded_image, filter_mask_x) # Aplicar filtro em Ix
generated_image_y = Apply_Filter_Space(loaded_image, filter_mask_y) # Aplicar filtro em Iy
generated_image = np.hypot(generated_image_x, generated_image_y) # Gerar Iout a partir da equação
generated_image = np.fft.fft2(generated_image) # Transformada de Fourier
del generated_image_x # Permitir que Garbage Collector libere da memória
del generated_image_y
positions = np.array(input().split(' '), dtype=np.float) # Posições de corte
generated_image_1 = generated_image[0 : generated_image.shape[0] // 2, 0 : generated_image.shape[1] // 2]
positions[0:2] *= generated_image_1.shape[0]
positions[2:4] *= generated_image_1.shape[1]
positions = np.array(positions, dtype=np.int)
generated_image_2 = generated_image_1[positions[0] : positions[1], positions[2] : positions[3]]
del generated_image # Permitir limpeza do GC nestas matrizes
del generated_image_1
dataset = np.load(input().rstrip()) # Carregar vetores para comparação
dataset_labels = np.load(input().rstrip()) # Carregar labels
# == Algorítmo K-NN de Machine Learning ==
generated_image_2 = generated_image_2.flatten() # Transformar para vetor 1D
nearest_distance = sys.maxsize # INT_MAX
nearest_index = -1
for i in range(dataset.shape[0]): # Para cada vetor...
distance = np.sqrt(np.sum(np.power(np.abs(generated_image_2 - dataset[i]), 2))) # Calcular distância euclidiana
if distance < nearest_distance: # e verificar se é a menor distância
nearest_distance = distance
nearest_index = i
print(dataset_labels[nearest_index]) # Imprimir label
print(nearest_index) # Impimir índice
# == DEBUGGING ==
# Nesse trabalho não tem como fazer um "debugging".
<file_sep>#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
long gcd(long A, long B){
long Max;
Max = (A < B) ? A : B;
while(A % Max != 0 || B % Max != 0) Max--;
return Max;
}
int main(int argc, char **argv){
long N, i, j, k, Aux1, Aux2, GCD;
char Line[10000];
vector<long> V;
cin >> N;
for(i = 0; i < N; i++){
V = vector<long>();
GCD = INT_MIN;
cin >> Aux1;
V.push_back(Aux1);
fgets(Line, sizeof(Line) / sizeof(char), stdin);
while(sscanf(Line, "%ld %[^\n]", &Aux1, Line) > 1){
V.push_back(Aux1);
}
V.push_back(Aux1);
Aux1 = V.size();
for(j = 0; j < Aux1; j++){
for(k = 0; k < Aux1; k++){
if(j == k) continue;
Aux2 = gcd(V[j], V[k]);
if(Aux2 > GCD) GCD = Aux2;
}
}
cout << GCD << '\n';
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
Matheus
<EMAIL>
*/
int main(){
float a,b;
char o;
scanf("%f %s %f",&a,&o,&b);
switch(o){
case '+':
printf("%.2f",a+b);
break;
case '-':
printf("%.2f",a-b);
break;
case '*':
printf("%.2f",a*b);
break;
case '/':
printf("%.2f",a/b);
break;
}
return EXIT_SUCCESS;
}
<file_sep>
#
# == IMAGENS P&B ==
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clear -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: all
rm *.o
Prog: Main.o
gcc -o Prog *.o -Wall
Main.o: Main.c Image.o Image.h
gcc -c -o Main.o Main.c -Wall -I.
Image.o: Image.c Image.h
gcc -c -o Image.o Image.c -Wall
run: Prog
./Prog
clean:
rm Prog *.o
<file_sep>#include <stdlib.h>
#include <string.h>
struct __queue_t {
void *values;
size_t memsize;
unsigned long nitems;
};
struct __queue_t *Q_New(size_t memsize){
if(memsize<1) return NULL;
struct __queue_t *Aux=(struct __queue_t *)calloc(1,sizeof(struct __queue_t));
Aux->memsize=memsize;
return Aux;
}
int Q_Size(struct __queue_t *Q){
if(Q==NULL) return -1;
return Q->nitems;
}
char Q_Add(void *Elem, struct __queue_t *Q){
if(Elem==NULL || Q==NULL) return 0;
Q->values=(void *)realloc(Q->values,(++Q->nitems)*Q->memsize);
memcpy(Q->values+(Q->nitems-1)*Q->memsize,Elem,Q->memsize);
return 1;
}
int Q_Get(void *Dest, struct __queue_t *Q){
if(Dest==NULL || Q==NULL) return 0;
if(Q->nitems<1) return 0;
memcpy(Dest,Q->values,Q->memsize);
return 1;
}
int Q_Shift(void *Dest, struct __queue_t *Q){
if(Dest==NULL || Q==NULL) return 0;
if(Q->nitems<1) return 0;
memcpy(Dest,Q->values,Q->memsize);
if(Q->nitems>1) memmove(Q->values,Q->values+Q->memsize,Q->memsize*(Q->nitems-1));
Q->values=(void *)realloc(Q->values,(--Q->nitems)*Q->memsize);
return 1;
}
void Q_Destroy(struct __queue_t *Q){
if(Q==NULL) return;
if(Q->values!=NULL) free(Q->values);
free(Q);
}
<file_sep><?php
/* Carrega informações essenciais (include) */
require_once("config.php");
/*
* Atenção: essa página não apresenta mecanismos de segurança regulares. Ela está sujeita a brute-force, CSRF, ...
* O objetivo principal foi apenas montar essa interface gráfica para que os dados submetidos pela extensão possam ser visualizados.
* É possível melhorar muito a segurança dessa página (que atualmente é apenas uma senha), mas esse não é o intuito do projeto.
*/
/* Obter parâmetros da página */
$action = $_POST["action"];
$passwd = $_POST["passwd"];
$param = $_POST["param"];
function generateItems($assoc) {
/* Essa função pega itens do banco de dados e gera o HTML deles pra aparecer na página */
$returnValue = "";
while($row = $assoc->fetch_assoc()) {
parse_str($row["data"], $dataObj);
$dataDiv = "";
foreach($dataObj as $key => $value) {
$dataDiv .= "<tr><td><input type='text' readonly='readonly' value='".htmlspecialchars($key)."'></td><td><input type='text' readonly='readonly' value='".htmlspecialchars($value)."'></td></tr>";
}
$returnValue .= "<tr data-id='".$row["id"]."' id='".$row["id"]."-trtag'><td>".htmlentities($row["time"])." <a href='javascript:void(0);' data-id='".$row["id"]."' onclick='removeEntry(this);'>(X)</a></td><td>".htmlentities($row["clientId"])."</td><td>".htmlentities($row["ip"])."</td><td>".htmlentities($row["url"])."</td><td>".htmlentities($row["referrer"])."</td><td>".htmlentities($row["userAgent"])."</td><td><a href='javascript:void(0);' data-id='".$row["id"]."-data' onclick='showMore(this);'>Mostrar</a><table id='".$row["id"]."-data' style='display:none;' class='data-table'>".$dataDiv."</table></td><td><a href='javascript:void(0);' data-id='".$row["id"]."-cookies' onclick='showMore(this);'>Mostrar</a><textarea id='".$row["id"]."-cookies' readonly='readonly' style='display:none;'>".htmlspecialchars($row["cookie"])."</textarea></td></tr>";
}
return $returnValue;
}
sleep(1); // Dormir script por 1 segundo: ajuda a evitar brute-force no campo de senha.
if($action == "list") {
/* O administrador acabou de logar e quer carregar a lista de itens pela primeira vez */
if($passwd != $accessPassword) {
http_response_code(401);
echo "Password incorrect.";
exit();
}
$dbCon = new mysqli($dbServer, $dbUsername, $dbPassword, $dbName); // Conecta ao banco de dados.
if($dbCon->connect_error) {
http_response_code(500); // Deu erro ao conectar ao banco de dados!
echo "Could not connect to database." . PHP_EOL;
exit();
}
$dbSql = "SELECT * FROM submits ORDER BY time DESC LIMIT 30"; // Prepara a query SQL para execução: retornar os formulários mais recentemente capturados (no máximo 30 itens).
$dbQuery = $dbCon->query($dbSql); // Executa a query SQL.
if ($dbQuery) {
echo generateItems($dbQuery); // Sucesso. Agora gera o HTML dos itens no banco de dados e retorna ele.
} else {
http_response_code(500); // Deu erro ao executar a query SQL!
echo "Error reading from database." . PHP_EOL;
}
exit();
} else if($action == "swapSleep") {
/* O administrador já está logado e quer trocar o estado da variável $sleep */
if($passwd != $accessPassword) {
http_response_code(401);
echo "Password incorrect.";
exit();
}
if($sleep) { // Caso o script já esteja dormindo 5 segundos ao inserir novos dados...
file_put_contents("sleep.txt", "false"); // Faz ele parar de dormir.
echo "Not sleeping anymore.";
} else { // Caso não esteja dormindo...
file_put_contents("sleep.txt", "true"); // Faz ele dormir.
echo "Now sleeping.";
}
exit();
} else if($action == "loadMore") {
/* O administrador já está logado e quer carregar mais itens (itens mais antigos) do banco de dados */
if($passwd != $accessPassword) {
http_response_code(401);
echo "Password incorrect.";
exit();
}
$dbCon = new mysqli($dbServer, $dbUsername, $dbPassword, $dbName); // Conecta ao banco de dados.
if($dbCon->connect_error) {
http_response_code(500); // Deu erro ao conectar ao banco de dados!
echo "Could not connect to database." . PHP_EOL;
exit();
}
$dbSql = "SELECT * FROM submits WHERE id<? ORDER BY time DESC LIMIT 30"; // Prepara a query SQL para execução: retornar os formulários mais recentemente capturados que sejam mais antigos que $param (no máximo, mais 30 itens).
$dbQuery = $dbCon->prepare($dbSql);
if(!$dbQuery) { // Erro ao preparar a query SQL.
http_response_code(500);
echo "Error preparing query." . PHP_EOL;
exit();
}
$dbQuery->bind_param("s", $param); // $param => o ID do item mais antigo presente na lista atual na tela do administrador.
if ($dbQuery->execute() === TRUE) { // Executa a query SQL.
echo generateItems($dbQuery->get_result()); // Sucesso. Agora gera o HTML dos itens no banco de dados e retorna ele.
} else {
http_response_code(500); // Deu erro ao executar a query SQL!
echo "Error reading from database." . PHP_EOL;
}
exit();
} else if($action == "update") {
/* O administrador já está logado e quer carregar mais itens (itens mais recentes) do banco de dados */
if($passwd != $accessPassword) {
http_response_code(401);
echo "Password incorrect.";
exit();
}
$dbCon = new mysqli($dbServer, $dbUsername, $dbPassword, $dbName); // Conecta ao banco de dados.
if($dbCon->connect_error) {
http_response_code(500); // Deu erro ao conectar ao banco de dados!
echo "Could not connect to database." . PHP_EOL;
exit();
}
$dbSql = "SELECT * FROM submits WHERE id>? ORDER BY time DESC"; // Prepara a query SQL para execução: retornar os formulários mais recentemente capturados que sejam mais recentes que $param.
$dbQuery = $dbCon->prepare($dbSql);
if(!$dbQuery) { // Erro ao preparar a query SQL.
http_response_code(500);
echo "Error preparing query." . PHP_EOL;
exit();
}
$dbQuery->bind_param("s", $param); // $param => o ID do item mais recente presente na lista atual na tela do administrador.
if ($dbQuery->execute() === TRUE) { // Executa a query SQL.
echo generateItems($dbQuery->get_result()); // Sucesso. Agora gera o HTML dos itens no banco de dados e retorna ele.
} else {
http_response_code(500); // Deu erro ao executar a query SQL!
echo "Error reading from database." . PHP_EOL;
}
exit();
} else if($action == "remove") {
/* O administrador já está logado e quer remover um item do banco de dados */
if($passwd != $accessPassword) {
http_response_code(401);
echo "Password incorrect.";
exit();
}
$dbCon = new mysqli($dbServer, $dbUsername, $dbPassword, $dbName); // Conecta ao banco de dados.
if($dbCon->connect_error) {
http_response_code(500); // Deu erro ao conectar ao banco de dados!
echo "Could not connect to database." . PHP_EOL;
exit();
}
$dbSql = "DELETE FROM submits WHERE id=?"; // Prepara a query SQL para execução: remove do banco de dados o item identificado por $param.
$dbQuery = $dbCon->prepare($dbSql);
if(!$dbQuery) { // Erro ao preparar a query SQL.
http_response_code(500);
echo "Error preparing query." . PHP_EOL;
exit();
}
$dbQuery->bind_param("s", $param); // $param => o ID do item que o administrador clicou para remover.
if ($dbQuery->execute() === TRUE) { // Executa a query SQL.
echo "Item removed." . PHP_EOL; // Sucesso. O item foi removido do banco de dados.
} else {
http_response_code(500); // Deu erro ao executar a query SQL!
echo "Error reading from database." . PHP_EOL;
}
exit();
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1,user-scalable=no">
<meta name="robots" content="noindex,nofollow,noarchive,noodp,noydir">
<title>Ataque XSS</title>
<style type="text/css">
@media not all and (min-width: 915px) and (min-height: 350px){
#main-noscreen {
display: block;
}
#main {
display:none;
}
}
@media all and (min-width: 915px) and (min-height: 350px){
#main-noscreen {
display:none;
}
#main {
display:block;
}
}
body {
display: block;
margin: 0 auto;
background-color: rgb(210, 210, 210);
color: rgb(0, 0, 0);
}
#main {
font-size: 16px;
width: 90%;
min-width: 500px;
margin: 50px auto;
background-color: rgb(255, 255, 255);
border: 1px solid rgb(100, 100, 100);
}
#shadow {
position: fixed;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px;
width: 100%;
height: 100%;
overflow: hidden;
background-color: rgba(0, 0, 0, 0.5);
}
#header {
display: block;
text-align: center;
font-weight: bold;
}
#login, #table {
width: 100%;
text-align: center;
}
#login input {
display: block;
margin: 2px auto;
}
#table a {
display: inline-block;
color: rgb(50, 119, 255);
background-color: transparent;
padding: 5px;
border-radius: 5px;
text-decoration: none;
}
#table a:hover {
color: rgb(0, 0, 0);
background-color: rgb(50, 119, 255);
}
#table > table {
display: block;
margin-top: 10px;
margin-bottom: 10px;
table-layout: fixed;
width: 100%;
max-width: 100%;
}
#table > table thead {
color: rgb(255, 255, 255);
background-color: rgb(0, 0, 0);
font-weight: bold;
width: 100%;
font-size: 1em!important;
}
#table > table > tbody > tr {
margin-top: 4px;
}
#table > table > tbody > tr:nth-child(even) {
background-color: rgb(230, 230, 230);
}
#table > table > tbody > tr:nth-child(odd) {
background-color: rgb(255, 255, 255);
}
#table > table td {
display: inline-block;
vertical-align: middle;
text-align: center;
word-break: break-all;
}
#table > table td:nth-child(1) {
width: 10%;
}
#table > table td:nth-child(2) {
width: 5%;
}
#table > table td:nth-child(3) {
width: 10%;
}
#table > table td:nth-child(4) {
width: 10%;
}
#table > table td:nth-child(5) {
width: 10%;
}
#table > table td:nth-child(6) {
width: 10%;
font-size: 0.75em;
}
#table > table td:nth-child(7) {
width: 33%;
}
#table > table td:nth-child(8) {
width: 10%;
}
#table table td table td {
width: 49%!important;
}
#table table td input {
width: 100%;
}
#table table td textarea {
width: 100%;
height: 100px;
}
#main-noscreen {
margin: 3px;
color: rgb(255,0,0);
text-align: justify;
}
</style>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function list() {
$("#shadow").stop().fadeIn(1000);
document.getElementById("submit-action").value = "list";
document.getElementById("submit-param").value = "";
$.ajax({
url: "?",
cache: false,
method: "POST",
data: $("#submit-form").serializeArray(),
dataType: "text",
timeout: 30000,
success: function(returnedHTML) {
document.getElementById("entries").innerHTML = returnedHTML;
document.getElementById("login").style.display = "none";
document.getElementById("table").style.display = "block";
},
error: function() {
alert("Não deu certo. Tenta de novo.");
document.getElementById("login").style.display = "block";
document.getElementById("table").style.display = "none";
},
complete: function() {
$("#shadow").stop().fadeOut(500);
}
});
}
function update() {
$("#shadow").stop().fadeIn(1000);
var first = document.getElementById("entries").getElementsByTagName("tr");
if(first.length < 1) {
return list();
}
first = first[0].dataset.id;
document.getElementById("submit-action").value = "update";
document.getElementById("submit-param").value = first;
$.ajax({
url: "?",
cache: false,
method: "POST",
data: $("#submit-form").serializeArray(),
dataType: "text",
timeout: 30000,
success: function(returnedHTML) {
document.getElementById("entries").innerHTML = returnedHTML + document.getElementById("entries").innerHTML ;
document.getElementById("login").style.display = "none";
document.getElementById("table").style.display = "block";
},
error: function() {
alert("Não deu certo. Tenta de novo.");
document.getElementById("login").style.display = "block";
document.getElementById("table").style.display = "none";
},
complete: function() {
$("#shadow").stop().fadeOut(500);
}
});
}
function loadMore() {
$("#shadow").stop().fadeIn(1000);
var last = document.getElementById("entries").childNodes;
if(last.length < 1) {
return list();
}
last = last[last.length - 1].dataset.id;
document.getElementById("submit-action").value = "loadMore";
document.getElementById("submit-param").value = last;
$.ajax({
url: "?",
cache: false,
method: "POST",
data: $("#submit-form").serializeArray(),
dataType: "text",
timeout: 30000,
success: function(returnedHTML) {
document.getElementById("entries").innerHTML += returnedHTML;
document.getElementById("login").style.display = "none";
document.getElementById("table").style.display = "block";
},
error: function() {
alert("Não deu certo. Tenta de novo.");
document.getElementById("login").style.display = "block";
document.getElementById("table").style.display = "none";
},
complete: function() {
$("#shadow").stop().fadeOut(500);
}
});
}
function swapSleep() {
$("#shadow").stop().fadeIn(1000);
document.getElementById("submit-action").value = "swapSleep";
document.getElementById("submit-param").value = "";
$.ajax({
url: "?",
cache: false,
method: "POST",
data: $("#submit-form").serializeArray(),
dataType: "text",
timeout: 30000,
success: function(returnedText) {
if(returnedText == "Now sleeping.") {
document.getElementById("sleepCheck").checked = true;
} else {
document.getElementById("sleepCheck").checked = false;
}
document.getElementById("login").style.display = "none";
document.getElementById("table").style.display = "block";
},
error: function() {
alert("Não deu certo. Tenta de novo.");
document.getElementById("login").style.display = "block";
document.getElementById("table").style.display = "none";
},
complete: function() {
$("#shadow").stop().fadeOut(500);
}
});
}
function removeEntry(me) {
$("#shadow").stop().fadeIn(1000);
myID = me.dataset.id;
if(confirm("Tem certeza que deseja remover este item?") != true) {
$("#shadow").stop().fadeOut(500);
return;
}
document.getElementById("submit-action").value = "remove";
document.getElementById("submit-param").value = myID;
$.ajax({
url: "?",
cache: false,
method: "POST",
data: $("#submit-form").serializeArray(),
dataType: "text",
timeout: 30000,
success: function(returnedHTML) {
document.getElementById(myID + "-trtag").remove();
document.getElementById("login").style.display = "none";
document.getElementById("table").style.display = "block";
},
error: function() {
alert("Não deu certo. Tenta de novo.");
document.getElementById("login").style.display = "block";
document.getElementById("table").style.display = "none";
},
complete: function() {
$("#shadow").stop().fadeOut(500);
}
});
}
function showMore(me) {
document.getElementById(me.dataset.id).style.display = "block";
me.outerHTML = "";
}
function submitMe(form) {
var action = document.getElementById("submit-action").value;
if(action == "list")
list();
else if(action == "update")
update();
else if(action == "loadMore")
loadMore();
else
swapSleep();
}
</script>
</head>
<body style="overflow: auto;">
<div id="main">
<div id="shadow" style="display:none;">
</div>
<div id="header">
<h1>Ataques XSS</h1>
</div>
<div id="login">
<form action="javascript:void(0);" id="submit-form" onsubmit="submitMe(this); return false;" method="post">
<p>Esta página permite que você veja todos os dados capturados pela extensão de navegador.<br>PS.: se a extensão estiver em execução no momento, ela também vai capturar este próprio formulário.<br>Para evitar isso, clique no botão "Entrar" com o mouse ao invés de apertar [ENTER] para submeter a senha.<br></p>
<input type="password" name="passwd" placeholder="<PASSWORD>" required="required" autofocus="autofocus">
<input type="hidden" id="submit-action" name="action" value="list">
<input type="hidden" id="submit-param" name="param" value="">
<input type="submit" onclick="submitMe(document.getElementById('submit-form')); return false;" value="Entrar">
</form>
</div>
<div id="table" style="display:none;">
<a href="javascript:void(0);" onclick="update();">Atualizar/Carregar mais novos</a>
<table>
<thead>
<tr>
<td>Data</td>
<td>ID</td>
<td>IP Origem</td>
<td>URL</td>
<td>Referenciador</td>
<td>Navegador</td>
<td>Dados</td>
<td>Cookies</td>
</tr>
</thead>
<tbody id="entries">
</tbody>
</table>
<a href="javascript:void(0);" onclick="loadMore();">Carregar mais antigos</a><br><a href="javascript:void(0)" onclick="swapSleep();" title="Toda vez que um dado for ser capturado, o script vai dormir por 5 segundos para demonstrar que a extensão está em funcionamento."><input type="checkbox" id="sleepCheck" disabled="disabled"<?php if($sleep === true) echo ' checked="checked"'; ?>> Dormir</a>
</div>
</div>
<div id="main-noscreen">
<span>Sua tela é muito pequena para visualizar esta página da web.</span>
</div>
</body>
</html>
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
int readInt(){
int R;
scanf("%d",&R);
return R;
}
double readDouble(){
double R;
scanf("%lf",&R);
return R;
}
void printDouble(double val){
printf("%.2lf\n",val);
}
int main(){
int i,N=readInt();
double MHA=0;
for(i=0;i<N;i++){
MHA+=1/(double)(readDouble()+1);
}
MHA=N/(double)MHA;
printDouble(--MHA);
return EXIT_SUCCESS;
}
<file_sep>
#
# ~ FUTEBOL ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clear -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: all
rm *.o
Prog: main.o
gcc -o Prog *.o -Wall -lm
main.o: main.c soccer.o soccer.h
gcc -c -o main.o main.c -Wall
soccer.o: soccer.c super_string.o super_string.h
gcc -c -o soccer.o soccer.c -Wall -I.
super_string.o: super_string.c
gcc -c -o super_string.o super_string.c -Wall
run: Prog
./Prog
clear:
rm Prog *.o
<file_sep>package elements;
import utils.Consts;
import utils.Drawing;
import javax.swing.*;
import java.awt.*;
import java.io.Serializable;
/**
* Classe que representa um quadrado individual da tela do game
*/
public class Square extends Element implements Serializable {
public static final int TIMER_FIRE = 40;
private int contIntervals;
private boolean isActive = true;
public boolean isObstacle = false;
public static final String LIGHT_BLUE = "lightBlueSquare.png"; // I
public static final String DARK_BLUE = "darkBlueSquare.png"; // J
public static final String ORANGE = "orangeSquare.png"; // L
public static final String YELLOW = "yellowSquare.png"; // O
public static final String GREEN = "greenSquare.png"; // S
public static final String RED = "redSquare.png"; // Z
public static final String PURPLE = "purpleSquare.png"; // T
public static final String OBSTACLE = "caveira.png"; // Obstáculo
/**
* Inicializa um objeto Square a partir de uma constante que indica a sua cor.
*/
public Square(String constColor) {
super(constColor);
this.isTransposable = false;
this.contIntervals = 0;
this.setPosition(0,0);
}
/**
* Inicializa um objeto Square que representa um obstáculo.
*/
public Square() {
super(OBSTACLE);
this.isActive = false;
this.isObstacle = true;
this.isTransposable = false;
this.setPosition(0, 0);
}
public int getContIntervals() {
return this.contIntervals;
}
public void desactivate() {
this.isActive = false;
}
@Override
public void autoDraw(Graphics g) {
if(imageIcon != null)
Drawing.draw(g, this.imageIcon, pos.getY(), pos.getX());
else
Drawing.draw(g, new ImageIcon(Consts.MENU_BG_PATH), pos.getY(), pos.getX());
if (isActive) {
this.contIntervals++;
if(this.contIntervals == TIMER_FIRE){
this.contIntervals = 0;
this.setPosition(pos.getX()+1,pos.getY());
//Drawing.getGameScreen().addElement(f);
}
}
}
/**
* Método da classe Square que "apaga" o quadrado, tirando seu "imageIcon" e
* desativando-o.
*/
public void erase() {
imageIcon = null;
setTransposable(true);
desactivate();
}
}
<file_sep># SCC-0201 Introdução à Ciência da Computação 2 - 2017.2
Aqui estão todos os trabalhos que implementei em ICC 2.
<file_sep>
#ifndef H_BINDEX
#define H_BINDEX
#include <stdio.h>
#include <register.h>
#define BTR_M 7
#define BTR_TRASH -1
#define BTR_IS_LEAVE '1'
#define BTR_IS_NOT_LEAVE '0'
typedef struct {
char status;
int root;
} BTR_HEADER;
typedef struct {
int nodeRRN;
char leave;
int nItems;
int key[BTR_M - 1];
long byteOffset[BTR_M - 1];
int pointers[BTR_M];
} BTR_NODE;
typedef struct {
BTR_HEADER header;
long levelCount;
FILE *stream;
} BTR_T;
#define IND_DATA_SIZE 128
BTR_T *BT_init(char *path);
BTR_T *BT_new(char *path);
long BT_count(BTR_T *index);
void BT_resetCount(BTR_T *index);
int BT_flush(BTR_T *index);
int BT_close(BTR_T *index);
int BT_push(REG_DATA *reg, BTR_T *index);
/*int BT_pop(REG_DATA *reg, BTR_T *index);
int BT_update(REG_DATA *reg, BTR_T *index);*/
long BT_search(int key, BTR_T *index);
#endif
<file_sep>#include <stdlib.h>
#include <math.h>
#include <assert.h>
/*
* ~ SortedHeap ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
enum __bool_t { false = 0, true };
struct __no_t {
int Value;
enum __bool_t Active;
};
struct __sortedheap_t {
int N;
struct __no_t *Root;
};
struct __sortedheap_t *New_SortedHeap(int level){
if(level < 1) return NULL;
struct __sortedheap_t *Aux;
int i,n;
n=pow(2,level)-1;
Aux=malloc(sizeof(struct __sortedheap_t));
Aux->Root=calloc(n,sizeof(struct __no_t));
Aux->N=n;
for(i=0;i<n;i++) Aux->Root[i].Value=i+1;
return Aux;
}
int Traverse_ByStatus(struct __sortedheap_t *SH){
assert(SH != NULL);
int aux=SH->Root[0].Value, pos=0;
while(pos < SH->N){
aux=SH->Root[pos].Value;
if(SH->Root[pos].Active==true){
SH->Root[pos].Active=false;
pos=pos*2+2;
}else{
SH->Root[pos].Active=true;
pos=pos*2+1;
}
}
return aux;
}
void Destroy_SortedHeap(struct __sortedheap_t *SH){
if(SH==NULL) return;
free(SH->Root);
free(SH);
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
typedef struct _QUEUE_NODE_T {
void *item;
struct _LIST_NODE_T *next;
} QUEUE_NODE_T;
typedef struct _QUEUE_T {
QUEUE_NODE_T *first, *last;
unsigned long n;
size_t memsize;
} QUEUE_T;
QUEUE_T *Q_new(size_t memsize) {
QUEUE_T *aux;
if(memsize < 1) {
return NULL;
}
aux = (QUEUE_T *) malloc(sizeof(QUEUE_T));
aux->first = aux->last = NULL;
aux->memsize = memsize;
aux->n = 0;
return aux;
}
int Q_push(void *item, QUEUE_T *list) {
if(list == NULL || item == NULL) {
return -1;
}
if(list->last == NULL) {
list->first = list->last = (QUEUE_NODE_T *) malloc(sizeof(QUEUE_NODE_T));
} else {
list->last->next = (QUEUE_NODE_T *) malloc(sizeof(QUEUE_NODE_T));
list->last = list->last->next;
}
list->last->item = (void *) malloc(list->memsize);
list->last->next = NULL;
memcpy(list->last->item, item, list->memsize);
list->n++;
return 1;
}
int Q_shift(void *item, QUEUE_T *list) {
QUEUE_NODE_T *aux;
if(list == NULL) {
return -1;
}
if(list->first == NULL) {
return 0;
}
if(item != NULL) {
memcpy(item, list->first->item, list->memsize);
}
aux = list->first;
list->first = list->first->next;
free(aux->item);
free(aux);
if(list->first == NULL) {
list->last = NULL;
}
list->n--;
return 1;
}
unsigned long Q_size(QUEUE_T *list) {
if(list == NULL) {
return 0;
}
return list->n;
}
int Q_clear(QUEUE_T *list) {
QUEUE_NODE_T *n, *aux;
if(list == NULL) {
return -1;
}
n = list->first;
while(n != NULL) {
aux = n;
n = n->next;
free(aux->item);
free(aux);
}
list->first = list->last = NULL;
list->n = 0;
return 1;
}
void Q_destroy(QUEUE_T *list) {
QUEUE_NODE_T *n, *aux;
if(list == NULL) {
return;
}
n = list->first;
while(n != NULL) {
aux = n;
n = n->next;
free(aux->item);
free(aux);
}
free(list);
}
<file_sep>#ifndef MERGESORT_H_
#define MERGESORT_H_
void mergesort(void *, int, int (*)(void *,void *), int, int *, int *);
#endif
<file_sep>package elements;
public enum TetrisObjectType {
I, O, T, S, Z, J, L
}
<file_sep>Some audio files in this folder were removed and replaced with a completely silent track.
<file_sep>
/*
* ~ Tabela Hash ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef HASHTREE_H_
#define HASHTREE_H_
#include <stdio.h>
typedef struct __hashtree_t HASHTREE;
struct __hashtree_t *HTree_New(unsigned long);
int HTree_Insert(int, struct __hashtree_t *);
int HTree_Remove(int, struct __hashtree_t *);
int HTree_Count(int, struct __hashtree_t *);
int HTree_Traverse(FILE *, struct __hashtree_t *);
void HTree_Destroy(struct __hashtree_t *T);
#endif<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
Matheus
<EMAIL>
*/
int main(){
int a,b;
scanf("%d %d",&a,&b);
printf("%d\n",a&b);
printf("%d\n",a|b);
printf("%d\n",a^b);
printf("%d\n",~a);
printf("%d\n",~b);
printf("%d\n",a>>2);
printf("%d",b<<2);
return EXIT_SUCCESS;
}
<file_sep># Coordenadoria
Aqui estão _scripts_ usados para controle e melhor organização do grupo de extensão. São _scripts_ que fiz quando Secretário do Ganesh.
## Contador de Membros ([Membros-Calculador.py](Membros-Calculador.py))
O Ganesh possui uma tabela (Excel) com todos os membros ativos e inativos, com seus respectivos curso e ano.
Este programa lê esta tabela (no formato *.CSV, e com as colunas separadas por COMMA) e faz um cálculo de percentagem de membros com relação ao curso e ano.
## Calculador de Feedback ([Feedback-Calculador.py](Feedback-Calculador.py))
O Ganesh possui uma tabela (Excel) preenchida automaticamente com base em submissões no formulário de Feedback das reuniões e atividades realizadas.
Este programa lê esta tabela (no formato *.CSV, e com as colunas separadas por COMMA) e faz um cálculo de percentagem de membros que gostaram de determinada atividade ou reunião.
## Calculador de Presenças ([Presenca-Calculador.py](Presenca-Calculador.py))
O Ganesh possui uma tabela (Excel) preenchida com as presenças na reunião geral obrigatória. Caso haja necessidade de se obter todos os nomes dos presentes em alguma reunião específica, este _script_ pode ser utilizado.
Este programa lê esta tabela (no formato *.CSV, e com as colunas separadas por COMMA) e com base no filtro escolhido pelo usuário, retorna o nome de todos aqueles presentes nas reuniões.
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <TreeBinSearch.h>
/*
* == ABB ==
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv){
BIN_SEARCH_TREE *Main_Tree;
char R;
int S;
Main_Tree=Create_Tree(); // Criar árvore.
while( (R=getchar())!='X' ) {
switch(R){
case 'I': // Inserir um valor.
scanf("%d",&S);
if(Find_In(S,Main_Tree)==1) printf("Chave existente\n"); // Impedir multiplas inserções de um mesmo elemento.
else Insert_Into(S,Main_Tree);
break;
case 'D': // Remover um valor.
scanf("%d",&S);
if(Remove_First_From(S,Main_Tree)==1) printf("%d\n",S);
else printf("Nao encontrado\n");
break;
case 'B': // Buscar um valor.
scanf("%d",&S);
if(Find_In(S,Main_Tree)==1) printf("Encontrado\n");
else printf("Nao encontrado\n");
break;
case 'Y': // Imprimir de todas as formas (cascata).
case 'N': // Imprimir em ordem.
Print_InOrder(stdout,Main_Tree);
if(R=='N') break;
case 'E': // Imprimir pré-ordem.
Print_PreOrder(stdout,Main_Tree);
if(R=='E') break;
case 'O': // Imprimir pós-ordem.
Print_PostOrder(stdout,Main_Tree);
if(R=='O') break;
default: // Imprimir por largura.
Print_LevelOrder(stdout,Main_Tree);
}
getchar(); // Eliminar pulo de linha.
}
Destroy_Tree(Main_Tree);
return EXIT_SUCCESS;
}
<file_sep>
/*
* ~ SortedHeap ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef SORTEDHEAP_H_
#define SORTEDHEAP_H_
typedef struct __sortedheap_t SORTEDHEAP;
struct __sortedheap_t *New_SortedHeap(int);
int Traverse_ByStatus(struct __sortedheap_t *);
void Destroy_SortedHeap(struct __sortedheap_t *);
#endif<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014) - based on https://www.geeksforgeeks.org/bridge-in-a-graph/
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
void dfs(ll u, bool *visited, ll *disc, ll *low, ll *parent, ll *time, ll *sum, vector< vector<ll> > &G) {
ll v;
visited[u] = true;
disc[u] = low[u] = ++(*time);
for(auto it = G[u].begin(); it != G[u].end(); it++) {
v = *it;
if(visited[v]) {
if(v != parent[u]) {
low[u] = min(low[u], disc[v]);
}
continue;
}
parent[v] = u;
dfs(v, visited, disc, low, parent, time, sum, G);
low[u] = min(low[u], low[v]);
if(low[v] > disc[u]) {
(*sum)++;
}
}
}
void testCase() {
ll N, M, i, aux1, aux2, time, sum;
ll *disc, *low, *parent;
bool *visited;
cin >> N >> M;
vector< vector<ll> > G = vector< vector<ll> >();
visited = (bool *) malloc(sizeof(bool) * N);
parent = (ll *) malloc(sizeof(ll) * N);
disc = (ll *) malloc(sizeof(ll) * N);
low = (ll *) malloc(sizeof(ll) * N);
for(i = 0; i < N; i++) {
G.push_back( vector<ll>() );
visited[i] = false;
parent[i] = -1;
disc[i] = 0;
low[i] = 0;
}
for(i = 0; i < M; i++) {
cin >> aux1 >> aux2;
aux1--;
aux2--;
G[aux1].push_back(aux2);
G[aux2].push_back(aux1);
}
time = sum = 0;
for(i = 0; i < N; i++) {
if(!visited[i]) {
dfs(i, visited, disc, low, parent, &time, &sum, G);
}
}
cout << sum << endl;
}
int main(int argc, char **argv) {
ll T;
T = 1;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <tuple>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
bool tuple_cmp(tuple<int, int> a, tuple<int, int> b) {
/*
if (get<0>(a) < get<0>(b)) {
return true;
}
if(get<0>(a) == get<0>(b) && get<1>(a) < get<1>(b)) {
return true;
}
*/
if (get<1>(a) < get<1>(b)) {
return true;
}
return false;
}
int main(int argc, char **argv) {
int T, N, i, start, end, current, count;
vector<tuple<int, int>> data;
cin >> T;
for(; T > 0; T--) {
cin >> N;
data.clear();
for(i = 0; i < N; i++) {
cin >> start >> end;
data.push_back(make_tuple(start, end));
}
count = 0;
current = 0;
sort(data.begin(), data.end(), tuple_cmp);
for(i = 0; i < N; i++) {
if(get<0>(data[i]) < current) {
continue;
}
current = get<1>(data[i]);
count++;
}
cout << count << endl;
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <matrioska.h>
/*
* ~ MATRIOSKA ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv){
int i,N,MatrioskaN,R;
scanf("%d",&N);
for(i=0;i<N;i++){ // Para cada possível sequência Matrioska...
if(i) printf("\n"); // Imprimir o pulo de linha de forma adequada.
if( (MatrioskaN=Matrioska_Check(stdin))>=0 ){ // A sequência Matrioska é válida?
printf("=) Matrioska %d",MatrioskaN); // Sim, imprimir o número de Matrioska/s possível/is.
}else{
printf("=( Tente novamente"); // Não.
if(MatrioskaN==-2)
do { scanf("%d",&R); } while(R!=0); // Se não tiver chegado no fim da sequência, chegar.
}
}
return EXIT_SUCCESS;
}
<file_sep>
#
# == ABB ==
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clear -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: all
rm *.o
Prog: Main.o
gcc -o Prog *.o -Wall
Main.o: Main.c TreeBinSearch.o TreeBinSearch.h
gcc -c -o Main.o Main.c -Wall -I.
TreeBinSearch.o: TreeBinSearch.c TreeBinSearch.h
gcc -c -o TreeBinSearch.o TreeBinSearch.c -Wall
run: Prog
./Prog
clean:
rm Prog *.o
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(int argc, char **argv){
int i,N;
float Space[2][2];
float ScapeSpace[2];
float Distancia[2];
scanf("%d %f %f %f %f",&N,&Space[0][0],&Space[0][1],&Space[1][0],&Space[1][1]);
for(i=0;i<N;i++){
scanf("%f %f",&ScapeSpace[0],&ScapeSpace[1]);
Distancia[0]=sqrt(pow(Space[0][1]-ScapeSpace[1],2)+pow(Space[0][0]-ScapeSpace[0],2));
Distancia[1]=sqrt(pow(Space[1][1]-ScapeSpace[1],2)+pow(Space[1][0]-ScapeSpace[0],2));
if(Distancia[0]<=(Distancia[1]/(float)2)){
printf("O coelho pode escapar pelo buraco (%.3f,%.3f).\n",ScapeSpace[0],ScapeSpace[1]);
return EXIT_SUCCESS;
}
}
printf("O coelho nao pode escapar.\n");
return EXIT_SUCCESS;
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cabecalho.h>
#include <arvore-b.h>
/*
* ~ Trabalho Prático: Parte 2 ~
*
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
/* == Definições de pré-compilação == */
#define VERDADEIRO 1
#define FALSO 0
#define DATA_NULA "\0\0\0\0\0\0\0\0\0\0"
#define UF_NULO "\0\0"
#define REGISTRO_NULO '\0'
#define TAMANHO_REGISTRO 87
#define MASCARA_REMOCAO -1
#define FIM_TOPO_PILHA -1
/* == Declaração da estrutura do registro == */
typedef struct {
/* Campos de tamanho fixo */
int codINEP; /* No caso de registro removido, este campo é igual a MASCARA_REMOCAO */
char dataAtiv[10];
char uf[2];
/* Indicadores de tamanho + campos de tamanho variável */
int indTamEscola; /* No caso de registro removido, este campo assume o topo da pilha */
char *nomeEscola;
int indTamMunicipio;
char *municipio;
int indTamPrestadora;
char *prestadora;
} REGISTRO;
/* Funções úteis, usadas por todas ou grande parte das funcionalidades do trabalho
Estas se encontram ao fim deste arquivo *.c, logo após a implementação das funcionalidades do trabalho */
int lerRegistro(REGISTRO *reg, FILE *arquivoDAT);
int lerRegistroCSV(FILE *arquivoCSV, REGISTRO *reg);
void escreverRegistro(REGISTRO *reg, FILE *arquivoDAT);
void imprimirRegistro(REGISTRO *reg);
void destruirRegistro(REGISTRO *reg);
/* == Implementação das funcionalidades do trabalho == */
/* FUNCIONALIDADE 1 */
void transferirCSV(char *nomeArquivoCSV, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador) {
/*
* Esta função transfere todos os registros contidos no arquivo *.CSV 'nomeArquivoCSV'
* para um novo arquivo binário 'nomeArquivoDAT'.
*
* Se o arquivo binário 'nomeArquivoDAT' já existe, ele é sobrescrito do zero.
*/
FILE *arquivoEntrada, *arquivoBinario, *arquivoIndices;
REGISTRO reg;
int aux, i;
/* Abre o arquivo de entrada *.CSV para organizar os registros em um arquivo binário */
arquivoEntrada = fopen(nomeArquivoCSV, "r");
if (arquivoEntrada == NULL) {
printf("Falha no carregamento do arquivo.\n");
return;
}
/* Cria o arquivo binário */
arquivoBinario = fopen(nomeArquivoDAT, "w+b");
if (arquivoBinario == NULL) {
printf("Falha no carregamento do arquivo.\n");
fclose(arquivoEntrada);
return;
}
/* Cria o arquivo de índices árvore-B */
arquivoIndices = fopen(nomeArquivoIndices, "w+b");
if (arquivoIndices == NULL) {
printf("Falha no carregamento do arquivo.\n");
fclose(arquivoEntrada);
fclose(arquivoBinario);
return;
}
cab.status = FALSO;
cab.topoPilha = FIM_TOPO_PILHA;
escreverCabecalho(arquivoBinario);
cabIndice.status = FALSO;
cabIndice.altura = 0;
cabIndice.noRaiz = cabIndice.ultimoRRN = -1;
escreverCabecalhoIndice(arquivoIndices);
iniciarBufferPool();
i = 0;
/* Enquanto houverem registros no *.CSV... */
while ((aux = lerRegistroCSV(arquivoEntrada, ®)) != 0) {
if (aux == -1) /* Código INEP nulo? Não pode! Pular este registro */
continue;
/* Registro ok. Copiar ele para o arquivo binário e adicionar chave na árvore-B. */
escreverRegistro(®, arquivoBinario);
inserirChave(reg.codINEP, i++, arquivoIndices);
destruirRegistro(®);
}
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinario);
finalizarBufferPool(nomeArquivoContador, arquivoIndices);
cabIndice.status = VERDADEIRO;
escreverCabecalhoIndice(arquivoIndices);
printf("Arquivo carregado.\n");
fclose(arquivoEntrada);
fclose(arquivoBinario);
fclose(arquivoIndices);
}
/* FUNCIONALIDADE 2 */
void recuperarTudo(char *nomeArquivoDAT) {
/*
* Esta função lê e imprime em stdout todos os registros contidos no arquivo 'nomeArquivoDat'.
*/
FILE *arquivoBinario;
int aux, contador;
REGISTRO reg;
arquivoBinario = fopen(nomeArquivoDAT, "rb");
if (arquivoBinario == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
lerCabecalho(arquivoBinario);
if (cab.status != VERDADEIRO) {
/* O status indica que o arquivo está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
contador = 0;
/* Enquanto houverem registros para serem lidos no arquivo binário... */
while((aux = lerRegistro(®, arquivoBinario)) != 0) {
if(aux == -1) /* Registro removido, ignorar */
continue;
/* Imprime o registro */
imprimirRegistro(®);
destruirRegistro(®);
contador++;
}
if(contador < 1){
/* Caso em que nenhum registro foi encontrado */
printf("Registro inexistente.\n");
}
fclose(arquivoBinario);
}
/* FUNCIONALIDADE 3 */
void recuperarPorCampo(char *nomeCampo, char* valorCampo, char *nomeArquivoDAT){
/*
* Esta função busca no arquivo binário 'nomeArquivoDAT' por registros em que o
* campo 'nomeCampo' tenha valor igual a 'valorCampo'.
* Ela imprime em stdout os registros que satisfazem essa condição.
*/
int aux, contador, campo;
FILE *arquivoBinario;
REGISTRO reg;
if(strcmp(nomeCampo, "codINEP") == 0) {
campo = 1;
} else if(strcmp(nomeCampo, "dataAtiv") == 0) {
campo = 2;
} else if(strcmp(nomeCampo, "uf") == 0) {
campo = 3;
} else if(strcmp(nomeCampo, "nomeEscola") == 0) {
campo = 4;
} else if(strcmp(nomeCampo, "municipio") == 0) {
campo = 5;
} else if(strcmp(nomeCampo, "prestadora") == 0) {
campo = 6;
} else {
/* Nome do campo inválido. */
printf("Falha no processamento do arquivo.\n");
return;
}
arquivoBinario = fopen(nomeArquivoDAT, "rb");
if (arquivoBinario == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
lerCabecalho(arquivoBinario);
if (cab.status != VERDADEIRO) {
/* O status indica que o arquivo está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
contador = 0;
/* Enquanto houverem registros para serem lidos no arquivo binário... */
while((aux = lerRegistro(®, arquivoBinario)) != 0) {
if(aux == -1) /* Registro removido. */
continue;
switch(campo){
case 1:
if(reg.codINEP == atoi(valorCampo)){
imprimirRegistro(®);
contador++;
}
break;
case 2:
if(strncmp(reg.dataAtiv, valorCampo, 10) == 0){
imprimirRegistro(®);
contador++;
}
break;
case 3:
if(strncmp(reg.uf, valorCampo, 2) == 0){
imprimirRegistro(®);
contador++;
}
break;
case 4:
if(strcmp(reg.nomeEscola, valorCampo) == 0){
imprimirRegistro(®);
contador++;
}
break;
case 5:
if(strcmp(reg.municipio, valorCampo) == 0){
imprimirRegistro(®);
contador++;
}
break;
case 6:
if(strcmp(reg.prestadora, valorCampo) == 0){
imprimirRegistro(®);
contador++;
}
break;
}
destruirRegistro(®);
}
if(contador < 1){
/* Caso em que nenhum registro que satisfaz a condição foi impresso */
printf("Registro inexistente.\n");
}
fclose(arquivoBinario);
}
/* FUNCIONALIDADE 4 */
void recuperarPorRRN(int RRN, char *nomeArquivoDAT) {
/*
* Esta função imprime em stdout apenas o registro de RRN 'RRN' do arquivo binário 'nomeArquivoDAT'.
*/
FILE *arquivoBinario;
REGISTRO reg;
arquivoBinario = fopen(nomeArquivoDAT, "rb");
if (arquivoBinario == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
lerCabecalho(arquivoBinario);
if(cab.status != VERDADEIRO){
/* O status indica que o arquivo está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
if (fseek(arquivoBinario, TAMANHO_CABECALHO + TAMANHO_REGISTRO * RRN, SEEK_SET) != 0) {
/* Se a operação 'fseek' falhar, então o registro não existe */
printf("Registro inexistente.\n");
fclose(arquivoBinario);
return;
}
/* Leitura do registro */
if (lerRegistro(®, arquivoBinario) != 1) {
printf("Registro inexistente.\n");
fclose(arquivoBinario);
return;
}
/* Impressão do registro */
imprimirRegistro(®);
destruirRegistro(®);
fclose(arquivoBinario);
}
/* FUNCIONALIDADE 5 */
void removerRegistro(int RRN, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador) {
/*
* Esta função remove do arquivo binário 'nomeArquivoDAT' o registro de RRN 'RRN'.
*/
FILE *arquivoBinario, *arquivoIndices;
REGISTRO reg;
arquivoBinario = fopen(nomeArquivoDAT, "r+b");
if (arquivoBinario == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
lerCabecalho(arquivoBinario);
if(cab.status != VERDADEIRO){
/* O status indica que o arquivo está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
arquivoIndices = fopen(nomeArquivoIndices, "r+b");
if (arquivoIndices == NULL) {
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
lerCabecalhoIndice(arquivoIndices);
if(cabIndice.status != VERDADEIRO){
/* O status indica que o arquivo da árvore-B está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
cab.status = FALSO;
escreverCabecalho(arquivoBinario);
if (fseek(arquivoBinario, TAMANHO_CABECALHO + TAMANHO_REGISTRO * RRN, SEEK_SET) != 0) {
/* Se a operação 'fseek' falhar, então o registro não existe */
printf("Registro inexistente.\n");
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinario);
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
/* Leitura do registro */
if (lerRegistro(®, arquivoBinario) != 1) {
printf("Registro inexistente.\n");
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinario);
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
cabIndice.status = FALSO;
escreverCabecalhoIndice(arquivoIndices);
iniciarBufferPool();
/* Remover chave do registro da árvore-B */
removerChave(reg.codINEP, arquivoIndices);
destruirRegistro(®);
/* Voltar para poder reescrever como removido */
fseek(arquivoBinario, -1 * TAMANHO_REGISTRO, SEEK_CUR);
/* Atribuir a MASCARA_REMOCAO e o topo da pilha */
reg.codINEP = MASCARA_REMOCAO;
reg.indTamEscola = cab.topoPilha;
/* Reescrever como removido */
escreverRegistro(®, arquivoBinario);
/* Atualiza o topo da pilha com o RRN do registro que foi removido */
cab.status = VERDADEIRO;
cab.topoPilha = RRN;
escreverCabecalho(arquivoBinario);
finalizarBufferPool(nomeArquivoContador, arquivoIndices);
cabIndice.status = VERDADEIRO;
escreverCabecalhoIndice(arquivoIndices);
printf("Registro removido com sucesso.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
}
/* FUNCIONALIDADE 6 */
void inserirRegistro(char **campos, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador) {
/*
* Esta função insere no arquivo binário 'nomeArquivoDAT' um novo registro.
* Os campos para este novo registro são passados de forma ordenada (0-5) em 'campos'.
*/
FILE *arquivoBinario, *arquivoIndices;
REGISTRO reg;
int i;
/* Validação dos campos */
if(strlen(campos[1]) != 10 && (campos[1][0] != '0' || campos[1][1] != '\0')){
printf("Falha no processamento do arquivo.\n");
return;
}
if(strlen(campos[2]) != 2 && (campos[2][0] != '0' || campos[2][1] != '\0')){
printf("Falha no processamento do arquivo.\n");
return;
}
if(strlen(campos[3]) + strlen(campos[4]) + strlen(campos[5]) > TAMANHO_REGISTRO - sizeof(int) * 4 - sizeof(char) * 12){
printf("Falha no processamento do arquivo.\n");
return;
}
arquivoBinario = fopen(nomeArquivoDAT, "r+b");
if (arquivoBinario == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
lerCabecalho(arquivoBinario);
if(cab.status != VERDADEIRO){
/* O status indica que o arquivo está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
arquivoIndices = fopen(nomeArquivoIndices, "r+b");
if (arquivoIndices == NULL) {
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
lerCabecalhoIndice(arquivoIndices);
if(cabIndice.status != VERDADEIRO){
/* O status indica que o arquivo da árvore-B está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
cab.status = FALSO;
escreverCabecalho(arquivoBinario);
cabIndice.status = FALSO;
escreverCabecalhoIndice(arquivoIndices);
iniciarBufferPool();
if (cab.topoPilha == FIM_TOPO_PILHA) {
/* Não há registros removidos na pilha, inserir no final do arquivo */
fseek(arquivoBinario, 0, SEEK_END);
i = (ftell(arquivoBinario) - TAMANHO_CABECALHO) / TAMANHO_REGISTRO;
} else {
/* Existe pelo menos um registro removido na pilha, inserir em sua posição */
i = cab.topoPilha;
fseek(arquivoBinario, TAMANHO_CABECALHO + TAMANHO_REGISTRO * cab.topoPilha, SEEK_SET);
lerRegistro(®, arquivoBinario);
cab.topoPilha = reg.indTamEscola;
fseek(arquivoBinario, -1 * TAMANHO_REGISTRO, SEEK_CUR); /* Voltar para poder sobrescrever */
}
/* Colocar campos no registro */
reg.codINEP = atoi(campos[0]);
if (strlen(campos[1]) == 10)
strncpy(reg.dataAtiv, campos[1], 10);
else
strncpy(reg.dataAtiv, DATA_NULA, 10);
if(strlen(campos[2]) == 2)
strncpy(reg.uf, campos[2], 2);
else
strncpy(reg.uf, UF_NULO, 2);
reg.indTamEscola = strlen(campos[3]);
reg.nomeEscola = (char *) malloc(sizeof(char) * (reg.indTamEscola + 1));
strcpy(reg.nomeEscola, campos[3]);
reg.indTamMunicipio = strlen(campos[4]);
reg.municipio = (char *) malloc(sizeof(char) * (reg.indTamMunicipio + 1));
strcpy(reg.municipio, campos[4]);
reg.indTamPrestadora = strlen(campos[5]);
reg.prestadora = (char *) malloc(sizeof(char) * (reg.indTamPrestadora + 1));
strcpy(reg.prestadora, campos[5]);
/* Escrever registro e adicionar chave na árvore-B */
escreverRegistro(®, arquivoBinario);
inserirChave(reg.codINEP, i, arquivoIndices);
destruirRegistro(®);
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinario);
finalizarBufferPool(nomeArquivoContador, arquivoIndices);
cabIndice.status = VERDADEIRO;
escreverCabecalhoIndice(arquivoIndices);
printf("Registro inserido com sucesso.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
}
/* FUNCIONALIDADE 7 */
void atualizarRegistro(int RRN, char **campos, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador) {
/*
* Esta função atualiza no arquivo binário 'nomeArquivoDAT' o registro de RRN 'RRN'.
* Os campos para este registro são passados de forma ordenada (0-5) em 'campos'.
*/
FILE *arquivoBinario, *arquivoIndices;
REGISTRO reg;
/* Validação dos campos */
if(strlen(campos[1]) != 10 && (campos[1][0] != '0' || campos[1][1] != '\0')){
printf("Falha no processamento do arquivo.\n");
return;
}
if(strlen(campos[2]) != 2 && (campos[2][0] != '0' || campos[2][1] != '\0')){
printf("Falha no processamento do arquivo.\n");
return;
}
if(strlen(campos[3]) + strlen(campos[4]) + strlen(campos[5]) > TAMANHO_REGISTRO - sizeof(int) * 4 - sizeof(char) * 12){
printf("Falha no processamento do arquivo.\n");
return;
}
arquivoBinario = fopen(nomeArquivoDAT, "r+b");
if (arquivoBinario == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
lerCabecalho(arquivoBinario);
if(cab.status != VERDADEIRO){
/* O status indica que o arquivo está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
arquivoIndices = fopen(nomeArquivoIndices, "r+b");
if (arquivoIndices == NULL) {
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
lerCabecalhoIndice(arquivoIndices);
if(cabIndice.status != VERDADEIRO){
/* O status indica que o arquivo da árvore-B está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
cab.status = FALSO;
escreverCabecalho(arquivoBinario);
if (fseek(arquivoBinario, TAMANHO_CABECALHO + TAMANHO_REGISTRO * RRN, SEEK_SET) != 0) {
/* Se a operação 'fseek' falhar, então o registro não existe */
printf("Registro inexistente.\n");
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinario);
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
/* Leitura do registro */
if (lerRegistro(®, arquivoBinario) != 1) {
printf("Registro inexistente.\n");
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinario);
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
cabIndice.status = FALSO;
escreverCabecalhoIndice(arquivoIndices);
iniciarBufferPool();
/* Remover chave antiga da árvore-B */
removerChave(reg.codINEP, arquivoIndices);
destruirRegistro(®);
/* Voltar para poder reescrever */
fseek(arquivoBinario, -1 * TAMANHO_REGISTRO, SEEK_CUR);
/* Colocar campos no registro */
reg.codINEP = atoi(campos[0]);
if (strlen(campos[1]) == 10)
strncpy(reg.dataAtiv, campos[1], 10);
else
strncpy(reg.dataAtiv, DATA_NULA, 10);
if(strlen(campos[2]) == 2)
strncpy(reg.uf, campos[2], 2);
else
strncpy(reg.uf, UF_NULO, 2);
reg.indTamEscola = strlen(campos[3]);
reg.nomeEscola = (char *) malloc(sizeof(char) * (reg.indTamEscola + 1));
strcpy(reg.nomeEscola, campos[3]);
reg.indTamMunicipio = strlen(campos[4]);
reg.municipio = (char *) malloc(sizeof(char) * (reg.indTamMunicipio + 1));
strcpy(reg.municipio, campos[4]);
reg.indTamPrestadora = strlen(campos[5]);
reg.prestadora = (char *) malloc(sizeof(char) * (reg.indTamPrestadora + 1));
strcpy(reg.prestadora, campos[5]);
/* Reescrever registro e adicionar nova chave na árvore-B */
escreverRegistro(®, arquivoBinario);
inserirChave(reg.codINEP, RRN, arquivoIndices);
destruirRegistro(®);
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinario);
finalizarBufferPool(nomeArquivoContador, arquivoIndices);
cabIndice.status = VERDADEIRO;
escreverCabecalhoIndice(arquivoIndices);
printf("Registro alterado com sucesso.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
}
/* FUNCIONALIDADE 8 */
void desfragmentarBinario(char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador) {
/*
* Esta função realiza a compactação eficiente (desfragmentação) do arquivo binário 'nomeArquivoDAT'.
*
* Note que ela vai criar um arquivo temporário com o nome ".'nomearquivoDAT'.tmp",
* ou seja, se 'nomeArquivoDAT' for igual a "bin.dat", ele vai criar um arquivo
* ".bin.dat.tmp" que será usado como auxiliar para desfragmentação.
*/
FILE *arquivoBinario, *arquivoBinarioTemporario, *arquivoIndices;
char *nomeArquivoTemporarioDAT, *nomeArquivoTemporarioIndices;
REGISTRO reg;
int aux, i;
arquivoBinario = fopen(nomeArquivoDAT, "rb");
if (arquivoBinario == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
lerCabecalho(arquivoBinario);
if(cab.status != VERDADEIRO){
/* O status indica que o arquivo está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
nomeArquivoTemporarioDAT = (char *) malloc(sizeof(char) * (strlen(nomeArquivoDAT) + 6));
nomeArquivoTemporarioIndices = (char *) malloc(sizeof(char) * (strlen(nomeArquivoIndices) + 6));
/* Designar nomes dos arquivos temporários adicionando "." no começo e ".tmp" ao final dos nomes originais */
nomeArquivoTemporarioDAT[0] = '.';
strcpy(nomeArquivoTemporarioDAT + sizeof(char), nomeArquivoDAT);
strcat(nomeArquivoTemporarioDAT, ".tmp");
nomeArquivoTemporarioIndices[0] = '.';
strcpy(nomeArquivoTemporarioIndices + sizeof(char), nomeArquivoIndices);
strcat(nomeArquivoTemporarioIndices, ".tmp");
/* Cria arquivo de dados temporário */
arquivoBinarioTemporario = fopen(nomeArquivoTemporarioDAT, "wb");
if(arquivoBinarioTemporario == NULL){
printf("Falha no processamento do arquivo.\n");
free(nomeArquivoTemporarioDAT);
free(nomeArquivoTemporarioIndices);
fclose(arquivoBinario);
return;
}
/* Cria arquivo de árvore-B temporário */
arquivoIndices = fopen(nomeArquivoTemporarioIndices, "w+b");
if(arquivoIndices == NULL){
printf("Falha no processamento do arquivo.\n");
free(nomeArquivoTemporarioDAT);
free(nomeArquivoTemporarioIndices);
fclose(arquivoBinario);
fclose(arquivoBinarioTemporario);
return;
}
cab.status = FALSO;
cab.topoPilha = FIM_TOPO_PILHA;
escreverCabecalho(arquivoBinarioTemporario);
cabIndice.status = FALSO;
cabIndice.altura = 0;
cabIndice.noRaiz = cabIndice.ultimoRRN = -1;
escreverCabecalhoIndice(arquivoIndices);
iniciarBufferPool();
i = 0;
/* Enquanto houverem registros no arquivo binário original... */
while((aux = lerRegistro(®, arquivoBinario)) != 0) {
if(aux == -1) /* Registro removido, ignorar */
continue;
/* Escrever registro no arquivo temporário e adicionar chave na árvore-B temporária */
escreverRegistro(®, arquivoBinarioTemporario);
inserirChave(reg.codINEP, i++, arquivoIndices);
destruirRegistro(®);
}
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinarioTemporario);
finalizarBufferPool(nomeArquivoContador, arquivoIndices);
cabIndice.status = VERDADEIRO;
escreverCabecalhoIndice(arquivoIndices);
fclose(arquivoBinario);
fclose(arquivoBinarioTemporario);
fclose(arquivoIndices);
/* Remove os arquivos originais e renomeia os arquivos temporários de forma que estes adquiram os lugares dos originais. */
if (remove(nomeArquivoDAT) == 0 && remove(nomeArquivoIndices) == 0 && rename(nomeArquivoTemporarioDAT, nomeArquivoDAT) == 0 && rename(nomeArquivoTemporarioIndices, nomeArquivoIndices) == 0) {
printf("Arquivo de dados compactado com sucesso.\n");
} else {
printf("Falha no processamento do arquivo.\n");
}
free(nomeArquivoTemporarioDAT);
free(nomeArquivoTemporarioIndices);
}
/* FUNCIONALIDADE 9 */
void imprimirPilha(char *nomeArquivoDAT) {
/*
* Esta função imprime a pilha de registros removidos do arquivo binário 'nomeArquivoDAT'.
*/
FILE *arquivoBinario;
int aux, contador;
REGISTRO reg;
arquivoBinario = fopen(nomeArquivoDAT, "rb");
if (arquivoBinario == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
lerCabecalho(arquivoBinario);
if(cab.status != VERDADEIRO){
/* O status indica que o arquivo está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
aux = cab.topoPilha;
contador = 0;
/* Enquanto não chegar ao fim da pilha... */
while (aux != FIM_TOPO_PILHA) {
/* Imprimir valor atual do RRN na pilha */
printf("%d ", aux);
/* Buscar próximo RRN */
fseek(arquivoBinario, TAMANHO_CABECALHO + TAMANHO_REGISTRO * aux, SEEK_SET);
lerRegistro(®, arquivoBinario);
aux = reg.indTamEscola;
contador++;
}
if(contador < 1)
printf("Pilha vazia.");
printf("\n");
fclose(arquivoBinario);
}
/* Funcionalidades 10 e 11 são equivalentes a 1 e 6 respectivamente */
/* FUNCIONALIDADE 12 */
void recuperarPorChave(int Chave, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador) {
/*
* Esta função imprime em stdout apenas o registro de chave 'Chave' do arquivo binário 'nomeArquivoDAT'.
*/
FILE *arquivoBinario, *arquivoIndices;
REGISTRO reg;
int RRN;
arquivoBinario = fopen(nomeArquivoDAT, "rb");
if (arquivoBinario == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
lerCabecalho(arquivoBinario);
if(cab.status != VERDADEIRO){
/* O status indica que o arquivo está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
arquivoIndices = fopen(nomeArquivoIndices, "rb");
if (arquivoIndices == NULL) {
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
lerCabecalhoIndice(arquivoIndices);
if(cabIndice.status != VERDADEIRO){
/* O status indica que o arquivo da árvore-B está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
iniciarBufferPool();
/* Busca o RRN na árvore-B */
RRN = buscaRRN(Chave, arquivoIndices);
finalizarBufferPool(nomeArquivoContador, arquivoIndices);
if (RRN < 0 || fseek(arquivoBinario, TAMANHO_CABECALHO + TAMANHO_REGISTRO * RRN, SEEK_SET) != 0) {
/* Se a operação 'fseek' falhar, então o registro não existe */
printf("Registro inexistente.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
/* Leitura do registro */
if (lerRegistro(®, arquivoBinario) != 1) {
printf("Registro inexistente.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
/* Impressão do registro */
imprimirRegistro(®);
destruirRegistro(®);
fclose(arquivoBinario);
fclose(arquivoIndices);
}
/* FUNCIONALIDADE 13 */
void removerRegistroChave(int Chave, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador) {
/*
* Esta função remove do arquivo binário 'nomeArquivoDAT' o registro de chave 'Chave'.
*/
FILE *arquivoBinario, *arquivoIndices;
REGISTRO reg;
int RRN;
arquivoBinario = fopen(nomeArquivoDAT, "r+b");
if (arquivoBinario == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
lerCabecalho(arquivoBinario);
if(cab.status != VERDADEIRO){
/* O status indica que o arquivo está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
arquivoIndices = fopen(nomeArquivoIndices, "r+b");
if (arquivoIndices == NULL) {
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
lerCabecalhoIndice(arquivoIndices);
if(cabIndice.status != VERDADEIRO){
/* O status indica que o arquivo da árvore-B está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
cab.status = FALSO;
escreverCabecalho(arquivoBinario);
cabIndice.status = FALSO;
escreverCabecalhoIndice(arquivoIndices);
iniciarBufferPool();
/* Busca o RRN na árvore-B, já removendo tal chave */
RRN = removerChave(Chave, arquivoIndices);
if (RRN < 0 || fseek(arquivoBinario, TAMANHO_CABECALHO + TAMANHO_REGISTRO * RRN, SEEK_SET) != 0) {
/* Se a operação 'fseek' falhar, então o registro não existe */
printf("Registro inexistente.\n");
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinario);
finalizarBufferPool(nomeArquivoContador, arquivoIndices);
cabIndice.status = VERDADEIRO;
escreverCabecalhoIndice(arquivoIndices);
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
/* Leitura do registro */
if (lerRegistro(®, arquivoBinario) != 1) {
printf("Registro inexistente.\n");
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinario);
finalizarBufferPool(nomeArquivoContador, arquivoIndices);
cabIndice.status = VERDADEIRO;
escreverCabecalhoIndice(arquivoIndices);
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
destruirRegistro(®);
/* Voltar para poder reescrever */
fseek(arquivoBinario, -1 * TAMANHO_REGISTRO, SEEK_CUR);
/* Atribuir a MASCARA_REMOCAO e o topo da pilha */
reg.codINEP = MASCARA_REMOCAO;
reg.indTamEscola = cab.topoPilha;
/* Reescrever como removido */
escreverRegistro(®, arquivoBinario);
/* Atualiza o topo da pilha com o RRN do registro que foi removido */
cab.status = VERDADEIRO;
cab.topoPilha = RRN;
escreverCabecalho(arquivoBinario);
finalizarBufferPool(nomeArquivoContador, arquivoIndices);
cabIndice.status = VERDADEIRO;
escreverCabecalhoIndice(arquivoIndices);
printf("Registro removido com sucesso.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
}
/* FUNCIONALIDADE 14 */
void atualizarRegistroChave(int Chave, char **campos, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador) {
/*
* Esta função atualiza no arquivo binário 'nomeArquivoDAT' o registro de chave 'Chave'.
* Os campos para este registro são passados de forma ordenada (0-5) em 'campos'.
*/
FILE *arquivoBinario, *arquivoIndices;
REGISTRO reg;
int RRN;
/* Validação dos campos */
if(strlen(campos[1]) != 10 && (campos[1][0] != '0' || campos[1][1] != '\0')){
printf("Falha no processamento do arquivo.\n");
return;
}
if(strlen(campos[2]) != 2 && (campos[2][0] != '0' || campos[2][1] != '\0')){
printf("Falha no processamento do arquivo.\n");
return;
}
if(strlen(campos[3]) + strlen(campos[4]) + strlen(campos[5]) > TAMANHO_REGISTRO - sizeof(int) * 4 - sizeof(char) * 12){
printf("Falha no processamento do arquivo.\n");
return;
}
arquivoBinario = fopen(nomeArquivoDAT, "r+b");
if (arquivoBinario == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
lerCabecalho(arquivoBinario);
if(cab.status != VERDADEIRO){
/* O status indica que o arquivo está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
arquivoIndices = fopen(nomeArquivoIndices, "r+b");
if (arquivoIndices == NULL) {
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
return;
}
lerCabecalhoIndice(arquivoIndices);
if(cabIndice.status != VERDADEIRO){
/* O status indica que o arquivo da árvore-B está inconsistente */
printf("Falha no processamento do arquivo.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
cabIndice.status = FALSO;
escreverCabecalhoIndice(arquivoIndices);
iniciarBufferPool();
/* Busca o RRN na árvore-B, já removendo tal chave (antiga) */
RRN = removerChave(Chave, arquivoIndices);
if (RRN < 0 || fseek(arquivoBinario, TAMANHO_CABECALHO + TAMANHO_REGISTRO * RRN, SEEK_SET) != 0) {
/* Se a operação 'fseek' falhar, então o registro não existe */
printf("Registro inexistente.\n");
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinario);
finalizarBufferPool(nomeArquivoContador, arquivoIndices);
cabIndice.status = VERDADEIRO;
escreverCabecalhoIndice(arquivoIndices);
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
/* Leitura do registro */
if (lerRegistro(®, arquivoBinario) != 1) {
printf("Registro inexistente.\n");
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinario);
finalizarBufferPool(nomeArquivoContador, arquivoIndices);
cabIndice.status = VERDADEIRO;
escreverCabecalhoIndice(arquivoIndices);
fclose(arquivoBinario);
fclose(arquivoIndices);
return;
}
destruirRegistro(®);
/* Voltar para poder reescrever */
fseek(arquivoBinario, -1 * TAMANHO_REGISTRO, SEEK_CUR);
/* Colocar campos no registro */
reg.codINEP = atoi(campos[0]);
if (strlen(campos[1]) == 10)
strncpy(reg.dataAtiv, campos[1], 10);
else
strncpy(reg.dataAtiv, DATA_NULA, 10);
if(strlen(campos[2]) == 2)
strncpy(reg.uf, campos[2], 2);
else
strncpy(reg.uf, UF_NULO, 2);
reg.indTamEscola = strlen(campos[3]);
reg.nomeEscola = (char *) malloc(sizeof(char) * (reg.indTamEscola + 1));
strcpy(reg.nomeEscola, campos[3]);
reg.indTamMunicipio = strlen(campos[4]);
reg.municipio = (char *) malloc(sizeof(char) * (reg.indTamMunicipio + 1));
strcpy(reg.municipio, campos[4]);
reg.indTamPrestadora = strlen(campos[5]);
reg.prestadora = (char *) malloc(sizeof(char) * (reg.indTamPrestadora + 1));
strcpy(reg.prestadora, campos[5]);
/* Reescrever registro e adicionar nova chave na árvore-B */
escreverRegistro(®, arquivoBinario);
inserirChave(reg.codINEP, RRN, arquivoIndices);
destruirRegistro(®);
cab.status = VERDADEIRO;
escreverCabecalho(arquivoBinario);
finalizarBufferPool(nomeArquivoContador, arquivoIndices);
cabIndice.status = VERDADEIRO;
escreverCabecalhoIndice(arquivoIndices);
printf("Registro alterado com sucesso.\n");
fclose(arquivoBinario);
fclose(arquivoIndices);
}
/* == Funções úteis == */
int lerRegistro(REGISTRO *reg, FILE *arquivoDAT) {
/*
* Esta função lê um registro de 'arquivoDAT' e atribui em 'reg'.
*
* Ela retorna 1 se o registro foi lido com sucesso e é válido,
* -1 se foi lido com sucesso mas é um registro removido,
* ou 0 em caso de erros/EOF.
*/
char auxRegistro[TAMANHO_REGISTRO], *auxPonteiro;
auxPonteiro = auxRegistro;
/* Ler registro do disco, verificando caso de erros/EOF */
if(fread(auxRegistro, TAMANHO_REGISTRO, 1, arquivoDAT) != 1) {
return 0;
}
/* Copiar todos os campos do espaço de memória do registro para 'reg' */
memcpy(®->codINEP, auxPonteiro, sizeof(int));
auxPonteiro += sizeof(int);
memcpy(reg->dataAtiv, auxPonteiro, sizeof(char) * 10);
auxPonteiro += sizeof(char) * 10;
memcpy(reg->uf, auxPonteiro, sizeof(char) * 2);
auxPonteiro += sizeof(char) * 2;
if(reg->codINEP == MASCARA_REMOCAO) {
/* Caso em que o registro foi removido */
memcpy(®->indTamEscola, reg->dataAtiv, sizeof(int));
return -1;
}
memcpy(®->indTamEscola, auxPonteiro, sizeof(int));
auxPonteiro += sizeof(int);
reg->nomeEscola = (char *) malloc(sizeof(char) * (reg->indTamEscola + 1));
memcpy(reg->nomeEscola, auxPonteiro, sizeof(char) * reg->indTamEscola);
reg->nomeEscola[reg->indTamEscola] = '\0';
auxPonteiro += sizeof(char) * reg->indTamEscola;
memcpy(®->indTamMunicipio, auxPonteiro, sizeof(int));
auxPonteiro += sizeof(int);
reg->municipio = (char *) malloc(sizeof(char) * (reg->indTamMunicipio + 1));
memcpy(reg->municipio, auxPonteiro, sizeof(char) * reg->indTamMunicipio);
reg->municipio[reg->indTamMunicipio] = '\0';
auxPonteiro += sizeof(char) * reg->indTamMunicipio;
memcpy(®->indTamPrestadora, auxPonteiro, sizeof(int));
auxPonteiro += sizeof(int);
reg->prestadora = (char *) malloc(sizeof(char) * (reg->indTamPrestadora + 1));
memcpy(reg->prestadora, auxPonteiro, sizeof(char) * reg->indTamPrestadora);
reg->prestadora[reg->indTamPrestadora] = '\0';
return 1;
}
int lerRegistroCSV(FILE *arquivoCSV, REGISTRO *reg) {
/*
* Esta função lê do arquivo *.CSV 'arquivoCSV' um registro e atribui seus campos em 'reg'.
*
* Ela retorna 1 se o registro foi lido com sucesso e é válido,
* -1 se foi lido com sucesso mas é inválido,
* ou 0 em caso de erros/EOF.
*/
char auxLinha[1024], auxCampos[6][1024]; /* Todos os campos do *.CSV são do tipo string. */
int i, j, k;
memset(auxCampos, 0, sizeof(auxCampos));
/* Ler uma linha de um registro */
if (fscanf(arquivoCSV, "%1024[^\n]%*c", auxLinha) < 1)
return 0;
/* Dessa linha lida, obter campos */
for(i = j = k = 0; auxLinha[i] != '\0' && j < 6; i++){
if(auxLinha[i] == ';'){
k = 0;
j++;
continue;
}
auxCampos[j][k++] = auxLinha[i];
}
if (strlen(auxCampos[2]) < 1) /* Código INEP não pode ser nulo */
return -1;
if(strlen(auxCampos[0]) + strlen(auxCampos[3]) + strlen(auxCampos[4]) > TAMANHO_REGISTRO - sizeof(int) * 4 + sizeof(char) * 12) /* Campos inválidos */
return -1;
/* Atribuir prestadora */
reg->indTamPrestadora = strlen(auxCampos[0]);
reg->prestadora = (char *) malloc(sizeof(char) * (reg->indTamPrestadora + 1));
strcpy(reg->prestadora, auxCampos[0]);
/* Atribuir data */
if (strlen(auxCampos[1]) == 10)
strncpy(reg->dataAtiv, auxCampos[1], 10);
else
strncpy(reg->dataAtiv, DATA_NULA, 10);
/* Atribuir código INEP */
reg->codINEP = atoi(auxCampos[2]);
/* Atribuir escola */
reg->indTamEscola = strlen(auxCampos[3]);
reg->nomeEscola = (char *) malloc(sizeof(char) * (reg->indTamEscola + 1));
strcpy(reg->nomeEscola, auxCampos[3]);
/* Atribuir município */
reg->indTamMunicipio = strlen(auxCampos[4]);
reg->municipio = (char *) malloc(sizeof(char) * (reg->indTamMunicipio + 1));
strcpy(reg->municipio, auxCampos[4]);
/* Atribuir UF */
if (strlen(auxCampos[5]) < 2)
strncpy(reg->uf, UF_NULO, 2);
else
strncpy(reg->uf, auxCampos[5], 2);
return 1;
}
void escreverRegistro(REGISTRO *reg, FILE *arquivoDAT) {
/*
* Esta função escreve em 'arquivoDAT' o registro 'reg'.
*/
char auxRegistro[TAMANHO_REGISTRO], *auxPonteiro;
auxPonteiro = auxRegistro;
memset(auxRegistro, REGISTRO_NULO, TAMANHO_REGISTRO);
/* Escrever todos os campos nesse espaço reservado para o registro */
memcpy(auxPonteiro, ®->codINEP, sizeof(int));
auxPonteiro += sizeof(int);
if(reg->codINEP == MASCARA_REMOCAO){
/* Caso em que o registro está marcado como removido */
memcpy(auxPonteiro, ®->indTamEscola, sizeof(int));
fwrite(auxRegistro, TAMANHO_REGISTRO, 1, arquivoDAT);
return;
}
memcpy(auxPonteiro, reg->dataAtiv, sizeof(char) * 10);
auxPonteiro += sizeof(char) * 10;
memcpy(auxPonteiro, reg->uf, sizeof(char) * 2);
auxPonteiro += sizeof(char) * 2;
memcpy(auxPonteiro, ®->indTamEscola, sizeof(int));
auxPonteiro += sizeof(int);
memcpy(auxPonteiro, reg->nomeEscola, sizeof(char) * reg->indTamEscola);
auxPonteiro += sizeof(char) * reg->indTamEscola;
memcpy(auxPonteiro, ®->indTamMunicipio, sizeof(int));
auxPonteiro += sizeof(int);
memcpy(auxPonteiro, reg->municipio, sizeof(char) * reg->indTamMunicipio);
auxPonteiro += sizeof(char) * reg->indTamMunicipio;
memcpy(auxPonteiro, ®->indTamPrestadora, sizeof(int));
auxPonteiro += sizeof(int);
memcpy(auxPonteiro, reg->prestadora, sizeof(char) * reg->indTamPrestadora);
/* Escrever em disco */
fwrite(auxRegistro, TAMANHO_REGISTRO, 1, arquivoDAT);
}
void imprimirRegistro(REGISTRO *reg) {
/*
* Esta função imprime em stdout todos os campos do registro 'reg'.
*/
printf("%d ", reg->codINEP);
if(reg->dataAtiv[0] != '\0')
printf("%.10s ", reg->dataAtiv);
else
printf("%s ", "0000000000");
if(reg->uf[0] != '\0')
printf("%.2s ", reg->uf);
else
printf("%s ", "00");
printf("%d ", reg->indTamEscola);
printf("%s ", reg->nomeEscola);
printf("%d ", reg->indTamMunicipio);
printf("%s ", reg->municipio);
printf("%d ", reg->indTamPrestadora);
printf("%s\n", reg->prestadora);
}
void destruirRegistro(REGISTRO *reg) {
/*
* Esta função limpa da memória dinâmica (HEAP) os campos de tamanho
* variável que foram alocados em 'reg'.
*/
free(reg->municipio);
free(reg->nomeEscola);
free(reg->prestadora);
}
<file_sep>package drawable;
import game.GameScreen;
import resources.Resources;
import resources.Utils;
import java.awt.*;
import java.io.Serializable;
import java.util.concurrent.Semaphore;
/**
* Essa classe representa um objeto que pode ser desenhado no painel do jogo
* (Torre, Inimigo, Arma, ...).
*
*/
@SuppressWarnings("serial")
public class Drawable implements Serializable, Runnable {
/**
* Posicao (x, y).
*/
protected Point position;
/**
* Tamanho (width, height);
*/
protected Dimension size;
protected int x, y, width, height;
/**
* ID da imagem que sera desenhada na posicao "position" e de tamanho
* "size".
*/
protected int resource;
/**
* Vida, protecao e dano de ataque do objeto.
*
*/
public double life, speed, damage;
/**
* Semaforo que controla o acesso unico (Mutex) aos recursos do objeto.
*
*/
public transient Semaphore mutex;
/**
* Thread que controla o funcionamento deste objeto (enemy, weapon, tower,
* ...)
*
*/
public transient Thread runningThread;
/**
* Tamanho da tela em que trabalharemos. Eh usado para calculo de escala.
*/
private static final Dimension progSize = new Dimension(100, 50);
public void init() {
runningThread = new Thread(this);
mutex = new Semaphore(1);
runningThread.start();
}
/**
* Desenha este elemento no painel
*
* @param g
* Objeto grafico de desenho do painel.
*/
public void draw(Graphics g) {
Dimension currentSize;
currentSize = g.getClipBounds().getSize();
g.drawImage(Resources.Image.get(this.resource),
(position.x * currentSize.width) / progSize.width,
(position.y * currentSize.height) / progSize.height,
(size.width * currentSize.width) / progSize.width,
(size.height * currentSize.height) / progSize.height, null);
}
@Override
public void run() {
Utils.acquireLock(GameScreen.game.pause);
GameScreen.game.pause.release();
if(GameScreen.game.state != 0)
return;
}
public Point getPosition() {
return position;
}
public void setPosition(Point position) {
this.position = position;
}
public int getResource() {
return resource;
}
public void setResource(int resource) {
this.resource = resource;
}
public Dimension getSize() {
return size;
}
public void setSize(Dimension size) {
this.size = size;
}
public void setDamage(double damage) {
this.damage = damage;
}
public double getDamage() {
return this.damage;
}
public void setLife(double life) {
this.life = life;
}
public double getLife() {
return this.life;
}
public void setSpeed(double armor) {
this.speed = armor;
}
public double getSpeed() {
return this.speed;
}
}
<file_sep>#include <stdlib.h>
#include <string.h>
struct __stack_t {
void *values;
size_t memsize;
unsigned long nitems;
};
struct __stack_t *S_New(size_t memsize){
if(memsize<1) return NULL;
struct __stack_t *Aux=(struct __stack_t *)calloc(1,sizeof(struct __stack_t));
Aux->memsize=memsize;
return Aux;
}
int S_Push(void *Elem, struct __stack_t *S){
if(Elem==NULL || S==NULL) return 0;
S->values=(void *)realloc(S->values,(++S->nitems)*S->memsize);
memcpy(S->values+(S->nitems-1)*S->memsize,Elem,S->memsize);
return 1;
}
int S_Get(void *Dest, struct __stack_t *S){
if(Dest==NULL || S==NULL) return 0;
if(S->nitems<1) return 0;
memcpy(Dest,S->values+S->memsize*(S->nitems-1),S->memsize);
return 1;
}
int S_Pop(void *Dest, struct __stack_t *S){
if(S==NULL) return 0;
if(S->nitems<1) return 0;
memcpy(Dest,S->values+S->memsize*(--S->nitems),S->memsize);
S->values=(void *)realloc(S->values,(S->nitems)*S->memsize);
return 1;
}
void S_Destroy(struct __stack_t *S){
if(S==NULL) return;
if(S->values!=NULL) free(S->values);
free(S);
}
<file_sep># Vending Machine
## Membros do grupo
- <NAME> (Nº 10368980)
- <NAME> (Nº 10369014)
## Diretório
- Toda a documentação e explicação do projeto do trabalho está disponível em "Documentação" (PDF).
- As imagens (*.png) são versões com maiores definição do que está na documentação.
- Ambos os códigos VHDL (*.vhd) compilaram no Quartus Lite com sucesso.
- O "Vending Machine" é o código simplificado e de mais fácil entendimento; enquanto o "Vending Machine Detailed" é o código em que todas as áreas do circuito foram implementadas manualmente (desde as combinações de 'reset', a até mesmo os Flip-Flops).
<file_sep>
#
# == NÚMEROS IMENSOS ==
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clear -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: all
rm *.o
Prog: Main.o
gcc -o Prog *.o -Wall
Main.o: Main.c UnlimitedInteger.o UnlimitedInteger.h
gcc -c -o Main.o Main.c -Wall
UnlimitedInteger.o: UnlimitedInteger.c UnlimitedInteger.h List.o List.h
gcc -c -o UnlimitedInteger.o UnlimitedInteger.c -Wall
List.o: List.c List.h
gcc -c -o List.o List.c -Wall
run: Prog
./Prog
clear:
rm Prog *.o
<file_sep># Ganesh
Aqui estão alguns dos códigos que implementei para o grupo de extensão Ganesh da USP.
<file_sep>all:
gcc -o programaTrab main.c lib/*.c -lm -g -I headers
run:
./programaTrab<file_sep>
/*
* ~ Pilha ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef STACK_H_
#define STACK_H_
#include <stdlib.h>
typedef struct __stack_t STACK;
struct __stack_t *S_New(size_t);
long S_Size(struct __stack_t *);
int S_Push(void *, struct __stack_t *);
int S_Top(void *, struct __stack_t *);
int S_Bottom(void *, struct __stack_t *);
int S_Pop(void *, struct __stack_t *);
void S_Destroy(struct __stack_t *);
#endif
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
Por <NAME>.
<EMAIL>
*/
int main(){
int a,b,c,maior;
scanf("%d",&a);
maior=a;
scanf("%d",&b);
if(b>maior){
maior=b;
}
scanf("%d",&c);
if(c>maior){
maior=c;
}
printf("%d",maior);
return EXIT_SUCCESS;
}
<file_sep>
#ifndef CONSTS_H_
#define CONSTS_H_
#define TAM_REGISTRO_DADOS 85
#define TAM_REGISTRO_DADOS_VARIAVEIS TAM_REGISTRO_DADOS - 2 - 2 - 4 - 3
#define TAM_REGISTRO_CABECALHO 19
#define TAM_LINE_BUFFER 1024*10
#define TAM_STR_BUFFER 100
#define R_TRUE '1'
#define R_FALSE '0'
#define R_REMOVIDO '*'
#define R_DELIMITADOR '|'
#define R_LIXO '#'
#define R_NIL '\0'
#define R_DATA_COMPACTACAO "01/11/2019"
#define INDEX_HASHTABLE_LEN 1024*8
#define INDEX_KEY_MAX_LEN 100
#endif<file_sep>package score;
import java.io.Serializable;
/**
* Essa classe representa um score de jogador.
*
*/
@SuppressWarnings("serial")
public class Score implements Serializable {
private long score, duration;
private String player;
public Score(String player) {
score = duration = 0;
this.player = player;
}
public long getScore() {
return score;
}
public void setScore(long score) {
this.score = score;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public String getPlayer() {
return player;
}
public void setPlayer(String player) {
this.player = player;
}
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <SortedHeap.h>
/*
* ~ <NAME> ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv){
SORTEDHEAP *ItemsHeap;
int Level, N, Aux=-1;
scanf("%d %d",&Level,&N);
ItemsHeap=New_SortedHeap(Level);
for(;N>0;N--) Aux=Traverse_ByStatus(ItemsHeap);
Destroy_SortedHeap(ItemsHeap);
printf("%d",Aux);
return EXIT_SUCCESS;
}
<file_sep>from threading import Thread, Semaphore
from bs4 import BeautifulSoup as Soup
import urllib
import requests
import time
import queue
import csv
import sys
import random
import unicodedata
import re
# URL:
# http://www.distanciasentrecidades.com/pesquisa?from={from}&to={to}
# Todas as cidades que serão combinadas.
cities = ["São Carlos - SP", "São Paulo - SP", "Limeira - SP", "Araraquara - SP", "Barretos - SP", "Ribeirão Preto - SP", "Uberaba - MG", "Rio de Janeiro - RJ",
"Cuiabá - MT", "Belo Horizonte - MG", "Florianópolis - SC", "Salvador - BA", "Manaus - AM", "Rio Branco - AC", "Maceió - AL", "Belém - PA",
"Macapá - AP", "Brasília - DF", "Fortaleza - CE", "Vitória - ES", "Goiânia - GO", "Caldas Novas - GO", "São Luís - MA", "Campo Grande - MS",
"Uberlândia - MG", "Mariana - MG", "Ouro Preto - MG", "João Pessoa - PB", "Curitiba - PR", "Recife - PE", "Teresina - PI", "Natal - RN",
"Porto Alegre - RS", "Porto Velho - RO", "Boa Vista - RR", "Aracaju - SE", "Palmas - TO", "Gramado - RS", "Petrópolis - RJ", "Campos do Jordão - SP",
"Foz do Iguaçu - PR", "Paraty - RJ", "Blumenau - SC", "Bento Gonçalves - RS", "Porto Seguro - BA", "Olinda - PE", "Bonito - MS", "Holambra - SP",
"Niterói - RJ", "Rio Grande - RS", "Santos - SP"]
csvDel = ',' # Delimitador do CSV de saída
maxCount = 5000 #maximo de itens
Null6 = 200 # Qtd de campos TEMPO VIAGEM nulos
tamVariaveis = 2000 # Tamanho maximo total dos três campos variaveis
maxThreads = 5 # Máximo de threads filhas executando simultaneamente
sleepThread = 2 # Tempo em segundos que a thread dorme após requisição (evitar bloqueio de IP)
grafoDirecionado = False # Direcionado ou não-direcionado
timeRegExp = r'^\s*(?:([0-9]+)\s*d[a-zA-Z]*)?\s*(?:([0-9]+)\s*h[a-zA-Z]*)?\s*(?:([0-9]+)\s*m[a-zA-Z]*)?\s*(?:([0-9]+)\s*s[a-zA-Z]*)?\s*$'
def processCities(city1, city2, vector, mutexSem, syncSem):
cidadeOrigem = city1[1].split('-', 2)[0].strip()
estadoOrigem = city1[1].split('-', 2)[1].strip()
cidadeDestino = city2[1].split('-', 2)[0].strip()
estadoDestino = city2[1].split('-', 2)[1].strip()
try:
fetch = requests.get(sys.argv[1].replace('{from}', urllib.parse.quote(city1[0])).replace('{to}', urllib.parse.quote(city2[0])), timeout=10)
if not fetch or fetch.status_code != 200:
print("\rCombinação '%s' -> '%s' deu erro ao carregar. Ignorando tal..." % (city1[0], city2[0]))
syncSem.release()
return
fetch = fetch.text
soupObj = Soup(fetch, features="lxml")
distancia = soupObj.select_one("#kmsruta") # Km
tempoViagem = soupObj.select_one("#web #results+p strong") # horas, minutos, ...
if distancia is None or tempoViagem is None:
print("\rCombinação '%s' -> '%s' deu erro ao processar. Ignorando tal..." % (city1[0], city2[0]))
syncSem.release()
return
distancia = distancia.text
tempoViagemMatches = re.search(timeRegExp, tempoViagem.text)
tempoViagem = 0
if tempoViagemMatches is None:
print("\rCombinação '%s' -> '%s' deu erro ao processar o tempo de viagem. Ignorando tal..." % (city1[0], city2[0]))
syncSem.release()
return
if tempoViagemMatches.group(1) is not None:
tempoViagem += 24 * 60 * 60 * int(tempoViagemMatches.group(1))
if tempoViagemMatches.group(2) is not None:
tempoViagem += 60 * 60 * int(tempoViagemMatches.group(2))
if tempoViagemMatches.group(3) is not None:
tempoViagem += 60 * int(tempoViagemMatches.group(3))
if tempoViagemMatches.group(4) is not None:
tempoViagem += int(tempoViagemMatches.group(4))
if tempoViagem < 1:
print("\rCombinação '%s' -> '%s' deu erro ao calcular o tempo de viagem. Ignorando tal..." % (city1[0], city2[0]))
syncSem.release()
return
except Exception as ex:
print("\rCombinação '%s' -> '%s' deu erro (%s). Ignorando tal..." % (city1[0], city2[0], str(ex)))
syncSem.release()
return
tempoViagem /= 60 # minutos
tempoViagemStr = str(int(tempoViagem % 60)) + "min"
tempoViagemStr = str(int(tempoViagem/60)) + "h " + tempoViagemStr
item = [estadoOrigem, estadoDestino, int(float(distancia.replace(".", ""))), cidadeOrigem, cidadeDestino, tempoViagemStr]
mutexSem.acquire()
vector.append(item)
mutexSem.release()
time.sleep(sleepThread)
syncSem.release()
if len(sys.argv) != 2 and len(sys.argv) != 3:
print("Passe a URL do site que vai fornecer os dados para gerar o CSV e o nome do arquivo final:")
print("> python3 codigo.py SITE [ARQUIVO]")
print("\tonde:")
print("\tSITE -> é a URL http ou https, com os modificadores {from} e {to} que serão substituidos pelas cidades.")
print("\t[ARQUIVO] -> é o nome do arquivo CSV que será salvo. Se não for passado, será impresso na tela.")
sys.exit()
def removerAcentos(campos):
# remove acentuação de campos
for i in range(len(campos)):
campos[i] = ''.join(c for c in unicodedata.normalize('NFD', campos[i])
if unicodedata.category(c) != 'Mn')
campos[i] = campos[i].replace('ç', 'c').replace('Ç', 'C').replace(csvDel, '').strip()
def paraMaiusculo(campos):
# torna campos maiusculos
for i in range(len(campos)):
campos[i] = campos[i].upper()
# Função nunca usada
'''
def truncarTamanho(campos):
# trunca tamanho máximo de campos
catcampos = ''.join(campos)
lcatcampos = len(catcampos) + len(campos)
olcatcampos = -1
while lcatcampos > tamVariaveis:
if(lcatcampos == olcatcampos):
print("parece que um campo (i = %d) não foi devidamente trucado" % lcatcampos)
print("encerrando script")
sys.exit()
splitingField = random.randint(0, len(campos))
tmpFieldValues = re.split(r'\s+', campos[splitingField])
tmpRnd = random.randint(1, len(tmpFieldValues) - 1)
tmpFieldValues[tmpRnd] = tmpFieldValues[tmpRnd][0]
campos[splitingField] = ' '.join(tmpFieldValues)
catcampos = ''.join(campos)
olcatcampos = lcatcampos
lcatcampos = len(catcampos) + len(campos)
return campos
'''
# Remover cidades repetidas
citiesLen = len(cities)
citiesUnique = list(dict.fromkeys(cities))
if len(citiesUnique) != citiesLen:
citiesDict = { }
citiesRepeated = [ ]
for city in cities:
if city in citiesDict:
citiesRepeated.append(city)
citiesDict[city] = 1
print("Atenção, os seguintes items estão repetidos:")
print(citiesRepeated)
print()
cities = citiesUnique.copy()
citiesUpper = cities.copy()
removerAcentos(citiesUpper)
paraMaiusculo(citiesUpper)
semMutex = Semaphore()
semSync = Semaphore(maxThreads)
threadsQueue = queue.Queue()
items = [ ]
if grafoDirecionado:
print("Com %d cidades na lista, aproximadamente %d itens serão gerados..." % (len(cities), len(cities) * len(cities) - len(cities)))
else:
print("Com %d cidades na lista, aproximadamente %d itens serão gerados..." % (len(cities), (len(cities) * len(cities) - len(cities))/2))
print("Processando... 0%", end = '')
# Combinar todas as cidades
for i in range(0, len(cities)):
for j in range(0, len(cities)):
if i == j:
continue
if not grafoDirecionado and citiesUpper[i] > citiesUpper[j]: # Direcionado ou não direcionado?
continue
if len(citiesUpper[i] + citiesUpper[j]) + 6 > tamVariaveis:
print("\rCombinação '%s' -> '%s' ignorada." % (citiesUpper[i], citiesUpper[j]))
continue
semMutex.acquire()
print("\rProcessando... %d%%" % (100 * len(items) / (len(cities) * len(cities) - len(cities))), end = '')
#print("\rCombinação '%s' -> '%s'..." % (citiesUpper[i], citiesUpper[j]))
semMutex.release()
semSync.acquire()
currentThread = Thread(target=processCities, args=([cities[i], citiesUpper[i]], [cities[j], citiesUpper[j]], items, semMutex, semSync))
threadsQueue.put(currentThread)
currentThread.start()
while not threadsQueue.empty():
threadsQueue.get().join()
print("\rProcessando... 100%")
print()
print("Foram gerados %d itens. Processando..." % (len(items)))
random.shuffle(items)
items = items[:maxCount]
i = 0
for item in items:
if len(item[3] + item[4] + item[5]) + 6 > tamVariaveis:
item[5] = ""
i += 1
for item in items:
if i >= Null6:
break
i += 1
item[5] = ""
random.shuffle(items)
items.insert(0, ['estadoOrigem', 'estadoDestino', 'distancia', 'cidadeOrigem', 'cidadeDestino', 'tempoViagem'])
if len(sys.argv) != 3:
print(items)
sys.exit()
with open(sys.argv[2], 'w') as csvfile: # salvar
spamwriter = csv.writer(csvfile, delimiter=csvDel, quotechar='', escapechar='\\', quoting=csv.QUOTE_NONE)
spamwriter.writerows(items)
<file_sep>#include <stdlib.h>
#include <stdio.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int i,j,N_questoes,N_alunos;
scanf("%d %d",&N_questoes,&N_alunos);
char Gabarito[N_questoes], Leitura;
int Alunos[N_alunos];
for(i=0;i<N_questoes;i++){
scanf(" %c",&Gabarito[i]);
}
for(i=0;i<N_alunos;i++){
Alunos[i]=0;
for(j=0;j<N_questoes;j++){
scanf(" %c",&Leitura);
if(Leitura==Gabarito[j]){
Alunos[i]++;
}
}
}
for(i=0;i<N_alunos;i++){
printf("%.2f\n",(Alunos[i]/(float)sizeof(Gabarito))*10);
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <math.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int i,N;
float O[2],R[2],distancia=0;
scanf("%d",&N);
for(i=0;i<N;i++){
if(i){
O[0]=R[0];
O[1]=R[1];
}
scanf("%f %f",&R[0],&R[1]);
if(i){
distancia+=sqrt(pow(R[0]-O[0],2)+pow(R[1]-O[1],2));
}
}
printf("%.4f",distancia);
return EXIT_SUCCESS;
}<file_sep>from utils import Config, DBConnection
from threading import Thread, Lock
from consts import TA_THREAD_SLEEP_TIMEOUT, TA_MAX_SEARCH_COUNT, TA_THREAD_SLEEP_RATELIMIT
from time import sleep
import datetime
import tweepy
class APICommunicator:
_THREAD = None
_MUTEX = None
_STOP = None
@staticmethod
def Init():
if APICommunicator._STOP != None:
return
APICommunicator._THREAD = Thread(target=APICommunicator._Run)
APICommunicator._MUTEX = Lock()
APICommunicator._THREAD.start()
APICommunicator._STOP = False
@staticmethod
def _Run_InsertAll(con, found_tweets, oldest_tweet, most_recent_tweet, database):
insert_tweets = [ ]
for t in found_tweets:
if oldest_tweet is not None and t.id_str == oldest_tweet[0]:
continue
if most_recent_tweet is not None and t.id_str == most_recent_tweet[0]:
continue
if database['tweeted_after_date'] is not None and datetime.datetime.timestamp(datetime.datetime.strptime(t._json['created_at'], '%a %b %d %H:%M:%S %z %Y')) < database['tweeted_after_date']:
continue
insert_tweets.append( (
database['id'],
t.id_str,
int(datetime.datetime.timestamp(datetime.datetime.strptime(t._json['created_at'], '%a %b %d %H:%M:%S %z %Y'))),
t.favorite_count,
t.retweet_count,
t.in_reply_to_status_id_str,
t.lang,
t.user.id_str,
t.user.screen_name,
int(datetime.datetime.timestamp(datetime.datetime.strptime(t._json['user']['created_at'], '%a %b %d %H:%M:%S %z %Y'))),
1 if t.user.protected else 0,
1 if t.user.verified else 0,
t.user.followers_count,
t.user.friends_count,
t.user.listed_count,
t.user.favourites_count,
t.user.statuses_count,
1 if t.user.default_profile else 0,
1 if t.user.default_profile_image else 0,
) )
if len(insert_tweets) >= 1:
return con.insertAll('INSERT IGNORE INTO `tweets` (`db_id`, `twitterid`, `createdat`, `favoritecount`, `retweetcount`, `replytostatusid`, `lang`, `user_id`, `user_screenname`, `user_createdat`, `user_protected`, `user_verified`, `user_followers`, `user_following`, `user_listedcount`, `user_favoritescount`, `user_statuscount`, `user_defaultprofile`, `user_defaultpicture`) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', insert_tweets)
return 0
@staticmethod
def _Run():
api_auth = tweepy.OAuthHandler(Config.TWITTER_API_KEY, Config.TWITTER_API_SECRET)
if Config.TWITTER_ACCESS_TOKEN is not None and Config.TWITTER_ACCESS_TOKEN_SECRET is not None:
api_auth.set_access_token(Config.TWITTER_ACCESS_TOKEN, Config.TWITTER_ACCESS_TOKEN_SECRET)
api = tweepy.API(api_auth)
while True:
APICommunicator._MUTEX.acquire(timeout = TA_THREAD_SLEEP_TIMEOUT)
if APICommunicator._STOP == True: # Stop thread?
return
con = DBConnection()
database = con.fetchOne('SELECT `id`,`query`,`tweeted_before_date`,`tweeted_after_date`,`lang` FROM `dbs` WHERE `ready`=false')
if database is None: # Any database waiting for data to be retrieved?
con.close()
continue
database = { 'id': database[0], 'query': database[1], 'tweeted_before_date': database[2], 'tweeted_after_date': database[3], 'lang': database[4] }
if database['tweeted_before_date'] is not None:
database['tweeted_before_date'] = datetime.datetime.fromtimestamp(database['tweeted_before_date'], tz=datetime.timezone.utc).strftime('%Y-%m-%d')
# Find oldest tweet to keep pagination from there.
oldest_tweet = con.fetchOne('SELECT `twitterid` FROM `tweets` WHERE `db_id` = %s ORDER BY `createdat` ASC LIMIT 1', (database['id'], ))
found_tweets = [ ]
if oldest_tweet is None:
# Found no tweets in database. In this case, try to gather a few tweets first.
try:
found_tweets = api.search(database['query'], count = TA_MAX_SEARCH_COUNT, lang = database['lang'], until = database['tweeted_before_date'])
except tweepy.RateLimitError:
APICommunicator._MUTEX.release()
con.close()
sleep(TA_THREAD_SLEEP_RATELIMIT)
continue
if APICommunicator._Run_InsertAll(con, found_tweets, None, None, database) > 0:
APICommunicator._MUTEX.release()
con.close()
continue
else:
# Found a oldest tweet. This means we can try to continue pagination from there.
try:
found_tweets = api.search(database['query'], count = TA_MAX_SEARCH_COUNT, lang = database['lang'], until = database['tweeted_before_date'], max_id = oldest_tweet[0])
except tweepy.RateLimitError:
APICommunicator._MUTEX.release()
con.close()
sleep(TA_THREAD_SLEEP_RATELIMIT)
continue
if APICommunicator._Run_InsertAll(con, found_tweets, oldest_tweet, None, database) > 0:
# Pagination worked for the past tweets.
APICommunicator._MUTEX.release()
con.close()
continue
# There's no oldest tweet anymore (finished pagination for past tweets). Now find most recent tweet.
most_recent_tweet = con.fetchOne('SELECT `twitterid` FROM `tweets` WHERE `db_id` = %s ORDER BY `createdat` DESC LIMIT 1', (database['id'], ))
try:
found_tweets = api.search(database['query'], count = TA_MAX_SEARCH_COUNT, lang = database['lang'], until = database['tweeted_before_date'], since_id = most_recent_tweet[0])
except tweepy.RateLimitError:
APICommunicator._MUTEX.release()
con.close()
sleep(TA_THREAD_SLEEP_RATELIMIT)
continue
if APICommunicator._Run_InsertAll(con, found_tweets, oldest_tweet, None, database) > 0:
# Pagination worked for the recent tweets.
APICommunicator._MUTEX.release()
con.close()
continue
# Now finished pagination in this database. In this case, mark it as complete.
con.execute('UPDATE `dbs` SET `ready` = true WHERE `id` = %s', (database['id'], ))
APICommunicator._MUTEX.release()
con.close()
@staticmethod
def WakeUp():
if APICommunicator._STOP != False:
return
APICommunicator._MUTEX.release()
@staticmethod
def Stop():
if APICommunicator._STOP != False:
return
APICommunicator._STOP = True
APICommunicator._THREAD.join()
APICommunicator._THREAD = None
APICommunicator._MUTEX = None
APICommunicator._STOP = None
@staticmethod
def WaitStop():
if APICommunicator._STOP != False:
return
APICommunicator._THREAD.join()
if __name__ == '__main__':
print('Running api_comm.py as main...')
Config.Init()
APICommunicator.Init()
APICommunicator.WaitStop()
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/*
* ~ FUTEBOL ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
char *SS_ReadUntil(char *String,char Ch,FILE *FStream){
/*
* Esta função lê de 'FStream' uma string até chegar em um caractere 'Ch'. Ela não inclui 'Ch' na string gerada, mas inclui o caracter NULL "\0".
* - Se 'String' for igual a NULL, a função vai alocar na memória uma string e retornar o endereço para tal.
* - Se 'String' for diferente de NULL, a função vai modificar a própria 'String'.
* CUIDADO: Nesse caso, a função pode e vai sobrescrever indefinidamente 'String', podendo inclusive ultrapassar os limites de tal, ocasionando um erro de segmentação (Out of Bounds).
*
* Ela retorna um ponteiro para a string alocada ou modificada.
*/
int n=0;
char R,*Aux=String;
if(Aux==NULL){
Aux=(char*)malloc(sizeof(char)*1);
while( (R=getc(FStream))!=EOF && R!=Ch){
Aux=(char *)realloc(Aux,sizeof(char)*n+2);
Aux[n++]=R;
}
}else
while( (R=getc(FStream))!=EOF && R!=Ch) Aux[n++]=R;
Aux[n]='\0';
if(R!=EOF) fseek(FStream,-1,SEEK_CUR);
return Aux;
}
int SS_ReadAllWhites(FILE *FStream){
/*
* Esta função avança o ponteiro de 'FStream' até um ponto em que não existam mais caracteres considerados "white-space".
*
* Ela retorna o número de caracteres pulados para chegar até tal, ou -1 em caso de erros.
*/
char R;
int n=0;
while( (R=getc(FStream))!=EOF && isspace(R) ) n++;
if(R==EOF) return -1;
fseek(FStream,-1,SEEK_CUR);
return n;
}
char SS_InsensitiveCmp(char *A,char *B){
/*
* Esta função compara 'A' com 'B' em formato "case-insensitive", ou seja, sem levar em consideração a diferença entre maiúsculos e minúsculos.
*
* Ela retorna -1 para 'A' maior que 'B', 0 se forem iguais, e 1 para 'B' maior que 'A'.
*/
int i,NA=strlen(A),NB=strlen(B);
char *StrA=(char *)malloc(sizeof(char)*NA),*StrB=(char *)malloc(sizeof(char)*NB);
for(i=0;i<NA;i++) StrA[i]=tolower(A[i]);
for(i=0;i<NB;i++) StrB[i]=tolower(B[i]);
i=strcmp(StrA,StrB);
free(StrA);
free(StrB);
if(i>0) return 1;
else if(i<0) return -1;
else return 0;
}
struct __soccer_game_t { // Estrutura de cada jogo.
int TeamA,TeamB;
int PointsA,PointsB;
};
struct __soccer_team_t { // Estrutura de cada equipe.
char Name[50];
int Points,VictoryCount,DrawCount,DefeatCount,GoalCount,ReceivedGoalCount;
};
struct __soccer_tour_t { // Estrutura de um torneio.
char Name[150];
int TeamCount,GameCount;
struct __soccer_team_t *Teams;
struct __soccer_game_t *Games;
};
struct __soccer_tour_t *S_NewFrom(FILE *FStream){
/*
* Esta função cria um novo torneio a partir de 'FStream'.
*/
struct __soccer_tour_t *Aux=(struct __soccer_tour_t *)malloc(sizeof(struct __soccer_tour_t));
char Str[200];
int i,j;
SS_ReadAllWhites(FStream);
SS_ReadUntil(Aux->Name,'\n',FStream);
scanf("%d",&Aux->TeamCount);
Aux->Teams=(struct __soccer_team_t *)malloc(sizeof(struct __soccer_team_t)*Aux->TeamCount);
for(i=0;i<Aux->TeamCount;i++){
SS_ReadAllWhites(FStream);
SS_ReadUntil(Aux->Teams[i].Name,'\n',FStream);
Aux->Teams[i].Points=Aux->Teams[i].VictoryCount=Aux->Teams[i].DrawCount=Aux->Teams[i].DefeatCount=Aux->Teams[i].GoalCount=Aux->Teams[i].ReceivedGoalCount=0;
}
scanf("%d",&Aux->GameCount);
Aux->Games=(struct __soccer_game_t *)malloc(sizeof(struct __soccer_game_t)*Aux->GameCount);
for(i=0;i<Aux->GameCount;i++){
SS_ReadAllWhites(FStream);
SS_ReadUntil(Str,'#',FStream);
for(j=0;j<Aux->TeamCount;j++)
if(strcmp(Aux->Teams[j].Name,Str)==0){
Aux->Games[i].TeamA=j;
break;
}
scanf("%*c%d%*c%d%*c",&Aux->Games[i].PointsA,&Aux->Games[i].PointsB);
SS_ReadUntil(Str,'\n',FStream);
for(j=0;j<Aux->TeamCount;j++)
if(strcmp(Aux->Teams[j].Name,Str)==0){
Aux->Games[i].TeamB=j;
break;
}
}
return Aux;
}
char S_Calc(struct __soccer_tour_t *Soc){
/*
* Esta função calcula todos os gols de 'Soc' e salva o resultado de cada equipe.
*
* Ela retorna 1 em caso de sucesso, e 0 em caso de erros.
*/
if(Soc==NULL) return 0;
int i;
for(i=0;i<Soc->GameCount;i++){ // Para cada jogo...
Soc->Teams[Soc->Games[i].TeamA].GoalCount+=Soc->Games[i].PointsA; // Calcular pontuação das equipes participantes.
Soc->Teams[Soc->Games[i].TeamB].GoalCount+=Soc->Games[i].PointsB;
Soc->Teams[Soc->Games[i].TeamA].ReceivedGoalCount+=Soc->Games[i].PointsB;
Soc->Teams[Soc->Games[i].TeamB].ReceivedGoalCount+=Soc->Games[i].PointsA;
if(Soc->Games[i].PointsA>Soc->Games[i].PointsB){ // A venceu B...
Soc->Teams[Soc->Games[i].TeamA].Points+=3; // Mais 3 pontos para A.
Soc->Teams[Soc->Games[i].TeamA].VictoryCount++;
Soc->Teams[Soc->Games[i].TeamB].DefeatCount++;
}else if(Soc->Games[i].PointsA<Soc->Games[i].PointsB){ // B venceu A...
Soc->Teams[Soc->Games[i].TeamB].Points+=3; // Mais 3 pontos para B.
Soc->Teams[Soc->Games[i].TeamB].VictoryCount++;
Soc->Teams[Soc->Games[i].TeamA].DefeatCount++;
}else{ // Empate...
Soc->Teams[Soc->Games[i].TeamA].Points+=1; // Mais 1 ponto para A.
Soc->Teams[Soc->Games[i].TeamB].Points+=1; // Mais 1 ponto para B.
Soc->Teams[Soc->Games[i].TeamA].DrawCount++;
Soc->Teams[Soc->Games[i].TeamB].DrawCount++;
}
}
return 1;
}
char S_Sort(struct __soccer_tour_t *Soc){
/*
* Esta função ordena as equipes de 'Soc' com base nos requisitos.
*
* Ela retorna 1 em caso de sucesso, e 0 em caso de erros.
*/
if(Soc==NULL) return 0;
struct __soccer_team_t R;
int i,j,k;
k=Soc->TeamCount/2;
// Shell Sort
while(k>0){
for(j=k;j<Soc->TeamCount;j++){
R=Soc->Teams[j];
i=j;
while( i>=k && ( Soc->Teams[i-k].Points<R.Points
|| (Soc->Teams[i-k].Points==R.Points && Soc->Teams[i-k].VictoryCount<R.VictoryCount)
|| (Soc->Teams[i-k].Points==R.Points && Soc->Teams[i-k].VictoryCount==R.VictoryCount && Soc->Teams[i-k].GoalCount-Soc->Teams[i-k].ReceivedGoalCount<R.GoalCount-R.ReceivedGoalCount)
|| (Soc->Teams[i-k].Points==R.Points && Soc->Teams[i-k].VictoryCount==R.VictoryCount && Soc->Teams[i-k].GoalCount-Soc->Teams[i-k].ReceivedGoalCount==R.GoalCount-R.ReceivedGoalCount && Soc->Teams[i-k].GoalCount<R.GoalCount)
|| (Soc->Teams[i-k].Points==R.Points && Soc->Teams[i-k].VictoryCount==R.VictoryCount && Soc->Teams[i-k].GoalCount-Soc->Teams[i-k].ReceivedGoalCount==R.GoalCount-R.ReceivedGoalCount && Soc->Teams[i-k].GoalCount==R.GoalCount && Soc->Teams[i-k].VictoryCount+Soc->Teams[i-k].DrawCount+Soc->Teams[i-k].DefeatCount>R.VictoryCount+R.DrawCount+R.DefeatCount)
|| (Soc->Teams[i-k].Points==R.Points && Soc->Teams[i-k].VictoryCount==R.VictoryCount && Soc->Teams[i-k].GoalCount-Soc->Teams[i-k].ReceivedGoalCount==R.GoalCount-R.ReceivedGoalCount && Soc->Teams[i-k].GoalCount==R.GoalCount && Soc->Teams[i-k].VictoryCount+Soc->Teams[i-k].DrawCount+Soc->Teams[i-k].DefeatCount==R.VictoryCount+R.DrawCount+R.DefeatCount && SS_InsensitiveCmp(Soc->Teams[i-k].Name,R.Name)>0) ) ){
Soc->Teams[i]=Soc->Teams[i-k];
i-=k;
}
Soc->Teams[i]=R;
}
k/=2;
}
return 1;
}
char S_Print(struct __soccer_tour_t *Soc,FILE *FStream){
/*
* Esta função imprime as equipes de 'Soc' e seus resultados em 'FStream'.
*
* Ela retorna 1 em caso de sucesso, e 0 em caso de erros.
*/
if(Soc==NULL) return 0;
int i;
fprintf(FStream,"%s\n",Soc->Name);
for(i=0;i<Soc->TeamCount;i++){
fprintf(FStream,"%d) %s %dp, %dg (%d-%d-%d), %dgd (%d-%d)\n",i+1,Soc->Teams[i].Name,Soc->Teams[i].Points,Soc->Teams[i].VictoryCount+Soc->Teams[i].DrawCount+Soc->Teams[i].DefeatCount,Soc->Teams[i].VictoryCount,Soc->Teams[i].DrawCount,Soc->Teams[i].DefeatCount,Soc->Teams[i].GoalCount-Soc->Teams[i].ReceivedGoalCount,Soc->Teams[i].GoalCount,Soc->Teams[i].ReceivedGoalCount);
}
return 1;
}
char S_Destroy(struct __soccer_tour_t *Soc){
/*
* Esta função limpa 'Soc' da memória.
*
* Ela retorna 1 em caso de sucesso, e 0 em caso de erros.
*/
if(Soc==NULL) return 0;
free(Soc->Teams);
free(Soc->Games);
free(Soc);
return 1;
}
typedef struct __soccer_tour_t SOCCER_TOUR;
int main(int argc, char **argv){
int i,N;
SOCCER_TOUR *Aux;
scanf("%d",&N); // Quantos torneios serão?
for(i=0;i<N;i++){ // Para cada torneio...
if(i>0) printf("\n");
Aux=S_NewFrom(stdin); // Ler torneio da entrada padrão.
S_Calc(Aux); // Calcular pontuação de cada equipe.
S_Sort(Aux); // Ordenar da forma correta.
S_Print(Aux,stdout); // Imprimir na saída padrão.
S_Destroy(Aux); // Limpar da memória.
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
<NAME>
<EMAIL>
*/
#define ADDITION_NUMBER 10
int main(){
int i,N=0,S=1;
char c,*Str=(char *)malloc(sizeof(char)*S);
do{
c=getchar();
Str[N++]=c;
if(N>=S){
S+=ADDITION_NUMBER;
Str=(char *)realloc(Str,sizeof(char)*S);
}
} while(c!='\n');
Str[N-1]='\0';
for(i=0;i<strlen(Str);i++){
if(i){
printf("\n%c",Str[i]);
}else{
printf("%c",Str[i]);
}
}
free(Str);
return EXIT_SUCCESS;
}
<file_sep>import sys
import csv
#
# ~ Contador de Membros Ganesh ~
# Este programa vai fazer a contagem dos membros do Ganesh e calcular
# a percentagem por curso e ano.
# Ele recebe como entrada o arquivo *.CSV da tabela dos membros separado
# por COMMA.
# Abaixo estão algumas definições de pré-compilação que podem ajudar.
#
# <NAME> (017)
# Secretário (2018.2)
# <EMAIL>
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
COMMA = ',' # Delimitador de coluna do *.CSV
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Este programa faz a contagem dos membros do Ganesh e calcula a percentagem por curso e ano.")
print("É necessário baixar a tabela dos membros do Ganesh, disponível no Google Drive, e utilizar a COMMA como separador.")
print("Uso do programa:")
print("\tpython3 " + sys.argv[0] + " CAMINHO_CSV [HEADER]")
print("Onde:")
print("\tCAMINHO_CSV -> caminho para o arquivo *.CSV da tabela com colunas separadas por COMMA")
print("\t[HEADER] -> opcional: se for igual a 1, a primeira linha da tabela será ignorada")
sys.exit(0);
with open(sys.argv[1], mode='r') as fStream:
lines = csv.reader(fStream, delimiter=COMMA)
lines = list(lines)
courses = { }
nMembers = 0
if len(sys.argv) == 3:
if sys.argv[2] == '1':
del lines[0]
for member in lines:
if member[8] == 'Inativo':
continue
nMembers += 1
if not member[3] in courses:
courses[member[3]] = [0, {}]
courses[member[3]][0] += 1
if member[4] in courses[member[3]][1]:
courses[member[3]][1][member[4]] += 1
else:
courses[member[3]][1][member[4]] = 1
print("== Membros do Ganesh: " + str(nMembers) + " ==")
print()
for course in sorted(courses):
print("~ " + course + ": " + str(courses[course][0]) + " (" + str(round(courses[course][0]*100/nMembers, 2)) + "%) ~")
for year in sorted(courses[course][1]):
print("\t" + year + " -> " + str(courses[course][1][year]) + " (" + str(round(courses[course][1][year]*100/nMembers, 2)) + "%)")
print()
<file_sep>package gerenciador;
public class Uspiano implements Comparable<Uspiano> {
private int numeroUSP;
private String nome;
public Uspiano(int nUsp, String nome) {
if(nome == null) {
throw new NullPointerException();
}
this.numeroUSP = nUsp;
this.nome = nome;
}
public Uspiano(String nUsp, String nome) {
this(Integer.parseInt(nUsp), nome);
}
public int getNumeroUSP() {
return this.numeroUSP;
}
public String getName() {
return this.nome;
}
@Override
public String toString() {
return this.nome + " (NUSP " + this.numeroUSP + ")";
}
@Override
public int compareTo(Uspiano a) {
return this.getName().compareTo(a.getName());
}
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
Por <NAME>.
<EMAIL>
*/
int main(){
float a,b,mh;
scanf("%f",&a);
scanf("%f",&b);
mh=(2/( (1/(a+1))+(1/(b+1)) ))-1;
printf("%.2f",mh);
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
/*
* ~ Gerenc. de Processos ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
/*
* Para gerenciar os processos, utilizei o conceito da Heap.
*
* Muitos sistemas baseados em Linux utilizam da Heap para gerenciar processos,
* mas eles utilizam uma Min-Heap, pois quanto menor o valor, maior a prioridade.
* Como nesse trabalho é o contrário, quanto maior o valor, maior a prioridade,
* vou utilizar uma Max-Heap.
*
* Funcionará de acordo com o método Round Robin, onde há 4 prioridades, e os processos
* são executados com base na prioridade, ou no PID quando no mesmo nível.
*
* Além disso, implantei a prioridade de tempo real, e o método FIFO.
*/
enum __proc_man_t { proc_fifo = 0, proc_round_robin }; // Tipo de gerenciamento dos processos.
struct __process_t { // Estrutura que representa um único processo.
int PID,Priority,TickStart,TickCount;
int RunningPoint; // Flag que ajuda no gerenciamento da Heap.
};
struct __processlist_t { // Estrutura que representa todos os processos.
int QueueN, RunningN, FinishedN;
enum __proc_man_t ProcManType; // Tipo (FIFO ou Round Robin).
struct __process_t *Queued; // Lista de processos aguardando para serem executados.
struct __process_t *Running; // Lista de processos em execução.
struct __process_t *Finished; // Lista de processos encerrados.
};
struct __processlist_t *NewSession(enum __proc_man_t org_type){
/*
* Esta função inicia uma nova sessão de processos. "org_type" indica se será FIFO ou Round Robin.
*
* Ela retorna um ponteiro para a estrutura responsável por armazenar os dados dos processos na memória.
*/
struct __processlist_t *Aux=(struct __processlist_t *)malloc(sizeof(struct __processlist_t));
Aux->Queued=Aux->Running=Aux->Finished=NULL;
Aux->QueueN=Aux->RunningN=Aux->FinishedN=0;
Aux->ProcManType=org_type;
return Aux;
}
char AddProcess(int PID, int TickStart, int TickCount, int Priority, struct __processlist_t *PL){
/*
* Esta função adiciona à fila de espera de 'PL' o processo de PID 'PID', prioridade 'Priority',
* que se inicia no tempo 'TickStart' e dura 'TickCount' ciclos.
*
* Ela retorna 0 em caso de erros, e 1 em caso de sucesso.
*/
if(PL==NULL) return 0;
PL->Queued=(struct __process_t *)realloc(PL->Queued,sizeof(struct __process_t)*(PL->QueueN+1));
PL->Queued[PL->QueueN].PID=PID;
PL->Queued[PL->QueueN].TickStart=TickStart;
PL->Queued[PL->QueueN].TickCount=TickCount;
PL->Queued[PL->QueueN].Priority=PL->Queued[PL->QueueN].RunningPoint=Priority;
PL->QueueN++;
return 1;
}
char ProcessExist(int PID, struct __processlist_t *PL){
/*
* Essa função verifica se já existe na fila de espera de 'PL' um processo de PID 'PID'.
*
* Ela retorna -1 em caso de erros, 0 se não existir e 1 se existir.
*/
if(PL==NULL) return -1;
int i;
for(i=0;i<PL->QueueN;i++)
if(PL->Queued[i].PID==PID)
return 1;
return 0;
}
char IncludeProcessesFrom(FILE *FStream, struct __processlist_t *PL){
/*
* Esta função lê de 'FStream' uma lista de processos e adiciona todos à lista de espera de 'PL', para aguardarem sua hora de serem executados.
*
* Ela retorna -1 em caso de erros, e o número de processos adicionados em caso de sucesso.
*/
if(PL==NULL) return -1;
int ScanCount,PID,TickStart,TickCount,Priority,N=0;
if(PL->ProcManType==proc_round_robin){ // A leitura será de uma lista do tipo Round Robin ou FIFO?
while( (ScanCount=fscanf(FStream,"%d %d %d %d",&PID,&TickStart,&TickCount,&Priority))!=EOF && ScanCount==4 ){ // Para cada processo lido da entrada (Round Robin)...
while(ProcessExist(PID,PL)==1){ // Enquanto o PID for repetido...
PID++; // Incrementar PID.
}
if(Priority==0) Priority=6; // Caso em que a prioridade é de tempo real.
AddProcess(PID,TickStart,TickCount,Priority,PL); // Adicionar processo à LP.
N++;
}
}else{
while( (ScanCount=fscanf(FStream,"%d %d %d",&PID,&TickStart,&TickCount))!=EOF && ScanCount==3 ){ // Para cada processo lido da entrada (FIFO)...
while(ProcessExist(PID,PL)==1){ // Enquanto o PID for repetido...
PID++; // Incrementar PID.
}
AddProcess(PID,TickStart,TickCount,1,PL); // Adicionar processo, porém com prioridade fixa sempre (qualquer uma, no caso).
N++;
}
}
return N;
}
char HeapifyProcessNode(int i, struct __processlist_t *PL){
/*
* Esta função é responsável por manter a Max-Heap da forma "PAI MAIOR QUE FILHOS".
* Dessa maneira, esta função ajuda a organizar a Heap para selecionarmos quais processos serão executados.
*
* Na literatura, é conhecida como Max-Heapify ou Min-Heapify.
* Nesse caso, ela age como Max-Heap quando leva a prioridade em consideração (porque prioridade 4 > prioridade 3, por exemplo),
* mas age como Min-Heap quando as prioridades são iguais e analisamos o PID (porque PID 7 < PID 9, por exemplo).
*
* Ela retorna 0 em caso de erros, e 1 em caso de sucesso.
*/
if(PL==NULL) return 0;
int MaxKey = i, LeftKey = 2*i+1, RightKey = 2*i+2;
struct __process_t Aux;
if(LeftKey<PL->RunningN && (PL->Running[LeftKey].RunningPoint>PL->Running[MaxKey].RunningPoint
|| (PL->Running[LeftKey].RunningPoint==PL->Running[MaxKey].RunningPoint && PL->Running[LeftKey].PID<PL->Running[MaxKey].PID)))
MaxKey=LeftKey;
if(RightKey<PL->RunningN && (PL->Running[RightKey].RunningPoint>PL->Running[MaxKey].RunningPoint
|| (PL->Running[RightKey].RunningPoint==PL->Running[MaxKey].RunningPoint && PL->Running[RightKey].PID<PL->Running[MaxKey].PID)))
MaxKey=RightKey;
if(MaxKey!=i){
Aux=PL->Running[i];
PL->Running[i]=PL->Running[MaxKey];
PL->Running[MaxKey]=Aux;
HeapifyProcessNode(MaxKey,PL);
}
return 1;
}
char BuildProcessHeap(struct __processlist_t *PL){
/*
* Esta função constrói a nossa Heap.
* Ela deve ser chamada toda vez que um novo processo se inicia, toda vez que um processo acaba,
* e toda vez que alteramos as chaves que identificam a ordem de execução dos processos.
*
* Ela retorna 0 em caso de erros, e 1 em caso de sucesso.
*/
if(PL==NULL) return 0;
int i;
for(i=PL->RunningN/2-1;i>=0;i--)
HeapifyProcessNode(i,PL);
return 1;
}
char StartProcess(int i,struct __processlist_t *PL){
/*
* Essa função inicia o processo 'i'.
* Ela retira o processo 'i' da lista de processos em espera, e adiciona à lista de processos em execução.
*
* Ela retorna 0 em caso de erros, e 1 em caso de sucesso.
*/
if(PL==NULL) return 0;
if(i<0 || i>=PL->QueueN) return 0;
int j;
PL->Running=(struct __process_t *)realloc(PL->Running,sizeof(struct __process_t)*(PL->RunningN+1));
PL->Running[PL->RunningN++]=PL->Queued[i];
for(j=i+1;j<PL->QueueN;j++)
PL->Queued[j-1]=PL->Queued[j];
PL->Queued=(struct __process_t *)realloc(PL->Queued,sizeof(struct __process_t)*(--PL->QueueN));
return 1;
}
char KillProcess(int i,struct __processlist_t *PL){
/*
* Essa função mata o processo 'i'.
* Ela retira o processo 'i' da lista de processos em execução, e adiciona à lista de processos finalizados.
* Ela deve ser chamada toda vez que um processo termina.
*
* Ela retorna 0 em caso de erros, e 1 em caso de sucesso.
*/
if(PL==NULL) return 0;
if(i<0 || i>=PL->RunningN) return 0;
int j;
PL->Finished=(struct __process_t *)realloc(PL->Finished,sizeof(struct __process_t)*(PL->FinishedN+1));
PL->Finished[PL->FinishedN++]=PL->Running[i];
for(j=i+1;j<PL->RunningN;j++)
PL->Running[j-1]=PL->Running[j];
PL->Running=(struct __process_t *)realloc(PL->Running,sizeof(struct __process_t)*(--PL->RunningN));
return 1;
}
int StartProcesses(int Tick,struct __processlist_t *PL){
/*
* Essa função verifica se existem novos processos que vão se iniciar no tempo 'Tick'.
* Se existirem, ela inicia tais.
*
* Ela retorna -1 em caso de erros, e a maior prioridade de um processo adicionado em caso de sucesso.
*/
if(PL==NULL) return -1;
int i,R=0;
for(i=PL->QueueN-1;i>=0;i--){
if(PL->Queued[i].TickStart<=Tick){
if(PL->Queued[i].Priority>R) R=PL->Queued[i].Priority;
StartProcess(i,PL);
}
}
return R;
}
char RunProcesses(struct __processlist_t *PL){
/*
* Essa função executa todos os processos de 'PL' até que não sobre nenhum.
* Além disso, ela já organiza a lista de processos finalizados.
*
* Ela retorna 0 em caso de erros, e 1 em caso de sucesso.
*/
if(PL==NULL) return 0;
int i,R=0, ExecutionTick=0; // O tempo começa em zero.
if(PL->ProcManType == proc_round_robin){ // Vai ser Round Robin ou FIFO?
while (PL->RunningN>0 || PL->QueueN>0) { // Round Robin.
BuildProcessHeap(PL); // Construir ou reconstruir Heap.
if(PL->RunningN>0 && (PL->Running[0].RunningPoint==-1 || PL->Running[0].RunningPoint==5) ){ // Já executou todo um ciclo?
for(i=0;i<PL->RunningN;i++){ // Sim, retornar processos ao seu padrão.
PL->Running[i].RunningPoint=PL->Running[i].Priority;
}
continue;
}
R=StartProcesses(ExecutionTick,PL); // Iniciar possíveis processos nesse tempo.
if(R>0){ // Teve algum processo que iniciou?
if(R-1>PL->Running[0].Priority){ // Sim. Ele forçará retornar um nível de prioridade?
for(i=0;i<PL->RunningN;i++) // Sim. Retornar um nível de prioridade.
if(PL->Running[i].Priority <= R)
PL->Running[i].RunningPoint=PL->Running[i].Priority;
continue;
}else if(ExecutionTick>1 && R>PL->Running[0].Priority){ // Sim. Ele forçará executar os processos novamente?
for(i=1;i<PL->RunningN;i++) // Sim. Executar os processos novamente.
PL->Running[i].RunningPoint=-1;
}
}
if(PL->RunningN>0){ // Há algum processo executando?
PL->Running[0].TickCount--; // Sim. Executar então.
if(PL->Running[0].TickCount<1) { // O processo terminou todas suas operações?
PL->Running[0].TickCount=ExecutionTick; // Sim. Armazenar quando ele terminou e matar ele.
KillProcess(0,PL);
}else{
if(PL->Running[0].Priority==6) PL->Running[0].RunningPoint=5; // Não. Apenas não executar mais nesse ciclo.
else PL->Running[0].RunningPoint=-1;
}
}
ExecutionTick++; // Incrementar tempo atual.
}
}else{
while (PL->RunningN>0 || PL->QueueN>0) { // FIFO.
if(PL->RunningN<1){ // Vamos adicionar um processo agora?
StartProcesses(R++, PL); // Sim. Adicionar processo.
if(R<=ExecutionTick) continue;
}
BuildProcessHeap(PL); // Construir ou reconstruir Heap.
if(PL->RunningN>0){ // Há algum processo executando?
PL->Running[0].TickCount--; // Sim. Executar então.
if(PL->Running[0].TickCount<1) { // O processo terminou todas suas operações?
PL->Running[0].TickCount=ExecutionTick; // Sim. Armazenar quando ele terminou e matar ele.
KillProcess(0,PL);
}
}
ExecutionTick++; // Incrementar tempo atual.
}
}
return 1;
}
char PrintResults(FILE *FStream,struct __processlist_t *PL){
/*
* Essa função imprime em 'FStream' a lista de processos finalizados.
*
* Ela retorna 0 em caso de erros, e 1 em caso de sucesso.
*/
if(PL==NULL) return 0;
if(PL->Finished==NULL) return 0;
int i;
for(i=0;i<PL->FinishedN;i++){
fprintf(FStream,"%d %d\n",PL->Finished[i].PID,PL->Finished[i].TickCount);
}
return 1;
}
char DestroySession(struct __processlist_t *PL){
/*
* Essa função remove da memória a estrutura responsável por armazenar informações dos processos 'PL'.
*
* Ela retorna 0 em caso de erros, e 1 em caso de sucesso.
*/
if(PL==NULL) return 0;
if(PL->Queued!=NULL) free(PL->Queued);
if(PL->Running!=NULL) free(PL->Running);
if(PL->Finished!=NULL) free(PL->Finished);
free(PL);
return 1;
}
<file_sep># SCC-0250 Computação Gráfica - 2020.1
Aqui estão todos os trabalhos e exercícios que implementei em CG.
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
void testCase() {
ll *prices, *dp;
ll i, N;
cin >> N;
prices = (ll *) calloc(sizeof(ll), N + 10);
dp = (ll *) calloc(sizeof(ll), N + 10);
for(i = 0; i < N; i++) {
cin >> prices[i];
}
for(i = N - 1; i >= 0; i--) {
dp[i] = prices[i] + dp[i + 2];
if(i + 1 < N) {
dp[i] = max(dp[i], prices[i] + prices[i + 1] + dp[i + 4]);
}
if(i + 2 < N) {
dp[i] = max(dp[i], prices[i] + prices[i + 1] + prices[i + 2] + dp[i + 6]);
}
}
cout << dp[0] << endl;
free(prices);
free(dp);
}
int main(int argc, char **argv) {
int T;
cin >> T;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <hashtable.h>
#include "ATM.h"
/*
* ~ ATM ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int ReadOperation(char *Command, int *ATM, int *Limit, int *Bank1, int *Bank2, double *Money) {
/*
* Esta função lê da entrada padrão (stdin) uma operação no formato especificado no trabalho.
* Ela preenche todos os dados relevantes das operações nos ponteiros para variável declarados nos argumentos.
*
* Ela retorna 3 em caso de erros, 2 caso seja a última operação da Stream, 1 caso esteja tudo ok, ou -1 em caso de erros.
*/
if(Command==NULL || ATM==NULL || Limit==NULL || Bank1==NULL || Bank2==NULL || Money==NULL)
return -1;
double Aux1, Aux2;
char Aux3[1000], Aux4;
scanf("%d %c", ATM, Command);
if(*Command=='S' || *Command=='D' || *Command=='C' || *Command=='T'){
scanf("%d", Limit);
*Command*=-1; // "Auditoria".
}else{
fseek(stdin, -1, SEEK_CUR);
scanf("%d %c", Bank1, Command);
switch(*Command){
case 'S': // Saque.
scanf("%lf", Money);
break;
case 'D': // Depósito.
scanf("%lf", Money);
break;
case 'T': // Transferência
fgets(Aux3, sizeof(Aux3)/sizeof(char), stdin);
if(sscanf(Aux3, "%lf %lf", &Aux1, &Aux2)==2){
sscanf(Aux3, "%d %lf", Bank2, Money);
*Command='U'; // Transferência bancos diferentes.
}else{
sscanf(Aux3, "%lf", Money);
}
break;
default: // Por último, consulta.
break;
}
}
*ATM-=1;
while( (Aux4=getchar())!=EOF && isspace(Aux4)) { }
if(Aux4=='E'){ // "ERRO".
fgets(Aux3, sizeof(Aux3)/sizeof(char), stdin);
return 3;
}else if(Aux4==EOF){ // Fim da entrada.
return 2;
}
fseek(stdin, -1, SEEK_CUR);
return 1; // Ok.
}
int Withdraw(double Money, int Bank, HASHTABLE *HT){
/*
* Esta função faz um saque de 'Money' do banco 'Bank' através do terminal 'HT'.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
if(HT==NULL) return 0;
BANK Aux;
BANK *Aux2=&Aux;
if(Search_From_HashTable(Bank, &Aux2, HT)<1){ // Primeira inserção.
memset(&Aux, 0, sizeof(BANK));
Aux.Bank=Bank;
Aux.WithdrawnMoney=Money;
Insert_Into_HashTable(Bank, &Aux, HT);
}else{ // Apenas mudar valor.
Aux2[0].WithdrawnMoney+=Money;
}
return 1;
}
int Deposit(double Money, int Bank, HASHTABLE *HT){
/*
* Esta função faz um depósito de 'Money' do banco 'Bank' através do terminal 'HT'.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
if(HT==NULL) return 0;
BANK Aux;
BANK *Aux2=&Aux;
if(Search_From_HashTable(Bank, &Aux2, HT)<1){ // Primeira inserção.
memset(&Aux, 0, sizeof(BANK));
Aux.Bank=Bank;
Aux.DepositedMoney=Money;
Insert_Into_HashTable(Bank, &Aux, HT);
}else{ // Apenas mudar valor.
Aux2[0].DepositedMoney+=Money;
}
return 1;
}
int TransferFrom(double Money, int Bank, HASHTABLE *HT){
/*
* Esta função faz uma transferência de 'Money' do banco 'Bank' através do terminal 'HT'.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
if(HT==NULL) return 0;
BANK Aux;
BANK *Aux2=&Aux;
if(Search_From_HashTable(Bank, &Aux2, HT)<1){ // Primeira inserção.
memset(&Aux, 0, sizeof(BANK));
Aux.Bank=Bank;
Aux.TransfersFrom=Money;
Insert_Into_HashTable(Bank, &Aux, HT);
}else{ // Apenas mudar valor.
Aux2[0].TransfersFrom+=Money;
}
return 1;
}
int TransferTo(double Money, int Bank, HASHTABLE *HT){
/*
* Esta função faz uma transferência de 'Money' para o banco 'Bank' através do terminal 'HT'.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
if(HT==NULL) return 0;
BANK Aux;
BANK *Aux2=&Aux;
if(Search_From_HashTable(Bank, &Aux2, HT)<1){ // Primeira inserção.
memset(&Aux, 0, sizeof(BANK));
Aux.Bank=Bank;
Aux.TransfersTo=Money;
Insert_Into_HashTable(Bank, &Aux, HT);
}else{ // Apenas mudar valor.
Aux2[0].TransfersTo+=Money;
}
return 1;
}
int AddAudit(int ATM, char Command, int Bank1, int Bank2, double Money, HASHTABLE *HT){
/*
* Esta função adiciona uma operação realizada a HashTable 'HT'.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
if(HT==NULL) return 0;
OPERATION Aux;
Aux.Bank1=Bank1;
Aux.Bank2=Bank2;
Aux.Money=Money;
Insert_Into_HashTable(Command|(ATM<<2), &Aux, HT);
return 1;
}
void PrintATM_Line(void *Bank){
/*
* Esta é uma função auxiliar. Ela é usada para imprimir uma linha de informações de um banco de um determinado terminal.
* Ela é auxiliar de "PrintATM".
*/
BANK *Aux=Bank;
printf("Banco %d: Moeda +%.2lf -%.2lf Transferencia +%.2lf -%.2lf\n", Aux->Bank, Aux->DepositedMoney, Aux->WithdrawnMoney, Aux->TransfersTo, Aux->TransfersFrom);
}
int PrintATM(HASHTABLE *HT){
/*
* Esta função imprime informações processadas no terminal 'HT'.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
if(HT==NULL) return 0;
Traverse_HashTable(PrintATM_Line, HT);
return 1;
}
int PrintAudit(int ATM, char Command, unsigned long Limit, HASHTABLE *HT){
/*
* Esta função imprime informações de uma audição solicitada diretamente da HashTable 'HT'.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
if(HT==NULL) return 0;
OPERATION *Aux;
unsigned long i, n=Search_From_HashTable(Command|(ATM<<2), &Aux, HT);
printf("Mostrando primeiros %ld resultados\n", Limit);
if(n==0){
printf("Sem resultados\n");
}else{
for(i=0;i<n && Limit>0;i++, Limit--){
if(Aux[i].Bank2>0) printf("%ld- Banco origem %d Banco destino %d %.2lf\n", i+1, Aux[i].Bank1, Aux[i].Bank2, Aux[i].Money);
else printf("%ld- Banco %d %.2lf\n", i+1, Aux[i].Bank1, Aux[i].Money);
}
}
return 1;
}
<file_sep>#include <stdio.h>
#include <list.h>
/*
* ~ Cartas ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
LIST *ReadCardsFrom(FILE *FStream){
/*
* Esta função lê de 'FStream' um conjunto de cartas.
*
* Ela retorna um ponteiro para a lista que representa esse conjunto, ou NULL em caso de erros.
*/
LIST *Aux=L_New();
int R=0;
scanf("%d",&R);
while(R!=0){
L_Add(R,Aux);
scanf("%d",&R);
}
if(L_Size(Aux)<=0){
L_Destroy(Aux);
return NULL;
}
return Aux;
}
char ProcessCards(FILE *FStream, LIST *Cards){
/*
* Esta função processa as cartas da lista 'Cards' e imprime o resultado em 'FStream'.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
if(Cards==NULL || L_Size(Cards)<=0) return 0;
fprintf(FStream,"Cartas jogadas:");
while(L_Size(Cards)>1){
fprintf(FStream," %d",L_GetAt(0,Cards));
L_RemoveAt(0,Cards);
L_Add(L_GetAt(0,Cards),Cards);
L_RemoveAt(0,Cards);
}
fprintf(FStream,"\nCarta restante: %d",L_Get(Cards));
return 1;
}
char DestroyCards(LIST *Cards){
return L_Destroy(Cards);
}
<file_sep>package game;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import drawable.Drawable;
import resources.Resources;
import resources.Utils;
import score.Score;
import tower.Tower;
import weapon.Weapon;
import enemy.Enemy;
/**
* Essa classe representa um jogo e todos os seus possiveis estados.
*
*/
@SuppressWarnings("serial")
public class Game implements Serializable, Runnable {
/**
* Semaforos de pause e dos objetos.
*
*/
public transient Semaphore pause;
public transient Semaphore mutex;
public transient Thread runningThread;
private boolean paused;
public transient int state;
public long score;
/**
* Lista dos inimigos, armas e torre do jogo.
*
*/
private ArrayList<Enemy> enemies;
private ArrayList<Weapon> weapons;
private Tower tower;
public int semester, test, killedEnemies, totalEnemies;
public Game() {
enemies = new ArrayList<>();
weapons = new ArrayList<>();
tower = new Tower();
paused = false;
state = semester = test = killedEnemies = 0;
totalEnemies = 5;
}
public void init() {
runningThread = new Thread(this);
pause = new Semaphore((paused) ? 0 : 1);
mutex = new Semaphore(1);
for(Enemy e : enemies) {
e.init();
}
for(Weapon w : weapons) {
w.init();
}
tower.init();
state = 0;
// inicia o jogo
runningThread.start();
}
public void damage(int type) {
Weapon w;
w = new Weapon(type);
Utils.acquireLock(this.mutex);
weapons.add(w);
this.mutex.release();
w.init();
}
/**
* Metodo que roda em thread separada para controle do jogo.
*/
@Override
public void run() {
Drawable ens[], wes[], tow;
Enemy e;
while(true) {
Utils.acquireLock(GameScreen.game.pause);
GameScreen.game.pause.release();
if(GameScreen.game.state != 0) {
Utils.acquireLock(mutex);
ens = (Enemy[]) enemies.toArray(new Enemy[0]);
wes = (Weapon[]) weapons.toArray(new Weapon[0]);
tow = (Tower) tower;
mutex.release();
for(Drawable dw : ens) {
Utils.joinThread(dw.runningThread);
}
for(Drawable dw : wes) {
Utils.joinThread(dw.runningThread);
}
Utils.joinThread(tow.runningThread);
return;
}
if(semester >= 5) {
gameWon();
} else if(test >= 5) {
semester++;
test = 0;
} else if(killedEnemies >= totalEnemies) {
test++;
killedEnemies = 0;
totalEnemies = (test + 1) * (semester + 1) * 2;
} else {
//if (Utils.getRandom().nextInt(100) < 25) {
e = new Enemy(semester, test);
Utils.acquireLock(mutex);
enemies.add(e);
e.init();
mutex.release();
//}
Utils.sleep(2500 - ((semester + 1) * (test + 1) * 100));
continue;
}
Thread.yield();
}
}
public boolean isPaused() {
return paused;
}
public void pause() {
try {
pause.acquire();
} catch (InterruptedException exc) {
System.err.printf("Could not acquire pause lock: %s.",
exc.getMessage());
Utils.fatalError();
}
paused = true;
}
public void pause(JButton playPauseButton) {
pause();
playPauseButton.setIcon(new ImageIcon(Resources.Image
.get(Resources.Image.PLAY_ICON)));
}
public void unpause() {
pause.release();
paused = false;
}
public void unpause(JButton playPauseButton) {
unpause();
playPauseButton.setIcon(new ImageIcon(Resources.Image
.get(Resources.Image.PAUSE_ICON)));
}
public void gameOver() {
state = 1;
}
public void gameWon() {
state = 2;
}
public ArrayList<Enemy> getEnemies() {
return enemies;
}
public ArrayList<Weapon> getWeapons() {
return weapons;
}
public void setWeapons(ArrayList<Weapon> weapons) {
this.weapons = weapons;
}
public Tower getTower() {
return tower;
}
public void setTower(Tower tower) {
this.tower = tower;
}
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <funcionalidades.h>
/*
* ~ Trabalho Prático: Parte 2 ~
*
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
/* == Definição do nome do arquivo binário *.DAT */
#define NOME_ARQUIVO_BINARIO "registros.dat"
#define NOME_ARQUIVO_INDICES "indice-arvoreb.dat"
#define NOME_ARQUIVO_CONTADOR "buffer-info.text"
/* == Enumeração de argumentos do programa == */
enum {
NOME_PROG,
OPERACAO,
ARG1,
ARG2,
ARG3,
ARG4,
ARG5,
ARG6,
ARG7
};
/* == MAIN == */
int main(int argc, char **argv) {
int codigoOperacao;
if(argc < 2) { /* Verificar se o usuário está passando os argumentos necessários */
printf("Uso:\n\t%s (CODIGO_OPERACAO) [...POSSIVEIS_ARGUMENTOS]\n", argv[NOME_PROG]);
return EXIT_FAILURE;
}
codigoOperacao = atoi(argv[OPERACAO]);
switch (codigoOperacao) {
case 10:
case 1: /* Transferir todos os registros do *.CSV para o *.DAT */
if (argc != 3) { /* Verificar se o usuário está passando os argumentos corretamente */
printf("Uso para a operação %d:\n\t%s %d (NOME_ARQUIVO_CSV)\n", codigoOperacao, argv[NOME_PROG], codigoOperacao);
return EXIT_FAILURE;
}
transferirCSV(argv[ARG1], NOME_ARQUIVO_BINARIO, NOME_ARQUIVO_INDICES, NOME_ARQUIVO_CONTADOR);
break;
case 2: /* Recuperar todos os registros do binário */
if (argc != 2) { /* Verificar se o usuário está passando os argumentos corretamente */
printf("Uso para a operação %d:\n\t%s %d\n", codigoOperacao, argv[NOME_PROG], codigoOperacao);
return EXIT_FAILURE;
}
recuperarTudo(NOME_ARQUIVO_BINARIO);
break;
case 3: /* Buscar registros por um campo específico */
if (argc != 4) { /* Verificar se o usuário está passando os argumentos corretamente */
printf("Uso para a operação %d:\n\t%s %d (NOME_CAMPO) (VALOR_BUSCADO)\n", codigoOperacao, argv[NOME_PROG], codigoOperacao);
return EXIT_FAILURE;
}
recuperarPorCampo(argv[ARG1], argv[ARG2], NOME_ARQUIVO_BINARIO);
break;
case 4: /* Recuperar registro por RRN */
if (argc != 3) { /* Verificar se o usuário está passando os argumentos corretamente */
printf("Uso para a operação %d:\n\t%s %d (RRN)\n", codigoOperacao, argv[NOME_PROG], codigoOperacao);
return EXIT_FAILURE;
}
recuperarPorRRN(atoi(argv[ARG1]), NOME_ARQUIVO_BINARIO);
break;
case 5: /* Remover registro por RRN */
if (argc != 3) { /* Verificar se o usuário está passando os argumentos corretamente */
printf("Uso para a operação %d:\n\t%s %d (RRN)\n", codigoOperacao, argv[NOME_PROG], codigoOperacao);
return EXIT_FAILURE;
}
removerRegistro(atoi(argv[ARG1]), NOME_ARQUIVO_BINARIO, NOME_ARQUIVO_INDICES, NOME_ARQUIVO_CONTADOR);
break;
case 11:
case 6: /* Inserir registro */
if (argc != 8) { /* Verificar se o usuário está passando os argumentos corretamente */
printf("Uso para a operação %d:\n\t%s %d (CAMPO1=codINEP) (CAMPO2=dataAtiv) (CAMPO3=uf) (CAMPO4=nomeEscola) (CAMPO5=municipio) (CAMPO6=prestadora)\n", codigoOperacao, argv[NOME_PROG], codigoOperacao);
return EXIT_FAILURE;
}
inserirRegistro(&argv[ARG1], NOME_ARQUIVO_BINARIO, NOME_ARQUIVO_INDICES, NOME_ARQUIVO_CONTADOR);
break;
case 7: /* Atualizar registro */
if (argc != 9) { /* Verificar se o usuário está passando os argumentos corretamente */
printf("Uso para a operação %d:\n\t%s %d (RRN) (CAMPO1=codINEP) (CAMPO2=dataAtiv) (CAMPO3=uf) (CAMPO4=nomeEscola) (CAMPO5=municipio) (CAMPO6=prestadora)\n", codigoOperacao, argv[NOME_PROG], codigoOperacao);
return EXIT_FAILURE;
}
atualizarRegistro(atoi(argv[ARG1]), &argv[ARG2], NOME_ARQUIVO_BINARIO, NOME_ARQUIVO_INDICES, NOME_ARQUIVO_CONTADOR);
break;
case 8: /* Desfragmentar arquivo binário */
if (argc != 2) { /* Verificar se o usuário está passando os argumentos corretamente */
printf("Uso para a operação %d:\n\t%s %d\n", codigoOperacao, argv[NOME_PROG], codigoOperacao);
return EXIT_FAILURE;
}
desfragmentarBinario(NOME_ARQUIVO_BINARIO, NOME_ARQUIVO_INDICES, NOME_ARQUIVO_CONTADOR);
break;
case 9: /* Imprimir pilha de registros removidos */
if (argc != 2) { /* Verificar se o usuário está passando os argumentos corretamente */
printf("Uso para a operação %d:\n\t%s %d\n", codigoOperacao, argv[NOME_PROG], codigoOperacao);
return EXIT_FAILURE;
}
imprimirPilha(NOME_ARQUIVO_BINARIO);
break;
case 12: /* Buscar registro através da árvore-B */
if (argc != 3) { /* Verificar se o usuário está passando os argumentos corretamente */
printf("Uso para a operação %d:\n\t%s %d (CHAVE=codINEP)\n", codigoOperacao, argv[NOME_PROG], codigoOperacao);
return EXIT_FAILURE;
}
recuperarPorChave(atoi(argv[ARG1]), NOME_ARQUIVO_BINARIO, NOME_ARQUIVO_INDICES, NOME_ARQUIVO_CONTADOR);
break;
case 13: /* Remover registro através da árvore-B */
if (argc != 3) { /* Verificar se o usuário está passando os argumentos corretamente */
printf("Uso para a operação %d:\n\t%s %d (CHAVE=codINEP)\n", codigoOperacao, argv[NOME_PROG], codigoOperacao);
return EXIT_FAILURE;
}
removerRegistroChave(atoi(argv[ARG1]), NOME_ARQUIVO_BINARIO, NOME_ARQUIVO_INDICES, NOME_ARQUIVO_CONTADOR);
break;
case 14: /* Atualizar registro através da árvore-B */
if (argc != 9) { /* Verificar se o usuário está passando os argumentos corretamente */
printf("Uso para a operação %d:\n\t%s %d (CHAVE=codINEP) (CAMPO1=codINEP) (CAMPO2=dataAtiv) (CAMPO3=uf) (CAMPO4=nomeEscola) (CAMPO5=municipio) (CAMPO6=prestadora)\n", codigoOperacao, argv[NOME_PROG], codigoOperacao);
return EXIT_FAILURE;
}
atualizarRegistroChave(atoi(argv[ARG1]), &argv[ARG2], NOME_ARQUIVO_BINARIO, NOME_ARQUIVO_INDICES, NOME_ARQUIVO_CONTADOR);
break;
default: /* Código de operação inválido */
printf("Código de operação deve estar entre 1 e 14.\nUso:\n\t%s (CODIGO_OPERACAO) [...POSSIVEIS_ARGUMENTOS]\n", argv[NOME_PROG]);
return EXIT_FAILURE;
break;
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
* ~ SKIPLIST ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
struct __node_t {
char word[51]; /* Palavra */
char meaning[141]; /* Definição */
struct __node_t *left, *right, *topper, *bottom;
};
struct __dictionary_t {
struct __node_t *first; /* Primeiro elemento da SkipList */
};
struct __dictionary_t *New_Dictionary(unsigned int RandomSeed){
/*
* Essa função cria um dicionário, ou seja, a estrutura que representa a SkipList.
*
* Ela retorna um ponteiro para esta estrutura já alocada na memória.
*/
struct __dictionary_t *Aux=(struct __dictionary_t *)calloc(1,sizeof(struct __dictionary_t));
Aux->first=(struct __node_t *)calloc(1,sizeof(struct __node_t));
srand(RandomSeed);
return Aux;
}
int Insert_Word(char *Word, char *Meaning, struct __dictionary_t *Dic){
/*
* Essa função insere na SkipList 'Dic' a palavra 'Word', com definição 'Meaning'.
*
* Ela retorna 1 caso a inserção tenha ocorrido com sucesso, 0 caso a palavra já exista, e -1 em caso de erros.
*/
struct __node_t *Aux, *Last=NULL, *Curr;
int cmp;
if(Word==NULL || Meaning==NULL || Dic==NULL) return -1;
Curr=Dic->first;
while(Curr!=NULL) {
cmp=strcmp(Curr->word,Word);
if(cmp<0) if(Curr->right!=NULL) Curr=Curr->right; else if(Curr->bottom!=NULL) Curr=Curr->bottom; else break;
else if(cmp>0) if(Curr->left->bottom!=NULL) Curr=Curr->left->bottom; else { Curr=Curr->left; break; }
else return 0;
}
do {
Aux=(struct __node_t *)calloc(1,sizeof(struct __node_t));
Aux->left=Curr;
Aux->right=Curr->right;
if(Last!=NULL) {
Aux->bottom=Last;
Last->topper=Aux;
}
if(Curr->right!=NULL) Curr->right->left=Aux;
Curr->right=Aux;
strncpy(Aux->word, Word, 50);
strncpy(Aux->meaning, Meaning, 140);
Last=Aux;
while(Curr->topper==NULL && Curr->left!=NULL) Curr=Curr->left;
if(Curr->topper==NULL) {
Dic->first=Curr->topper=(struct __node_t *)calloc(1,sizeof(struct __node_t));
Curr->topper->bottom=Curr;
Curr=Curr->topper;
} else Curr=Curr->topper;
} while(rand()%2);
return 1;
}
int Set_Word(char *Word, char *Meaning, struct __dictionary_t *Dic){
/*
* Essa função altera a definição da palavra 'Word' na SkipList 'Dic' para 'Meaning'.
*
* Ela retorna 1 caso a alteração tenha ocorrido com sucesso, 0 caso a palavra não exista, e -1 em caso de erros.
*/
struct __node_t *Curr;
int cmp;
if(Word==NULL || Meaning==NULL || Dic==NULL) return -1;
Curr=Dic->first;
while(Curr!=NULL) {
cmp=strcmp(Curr->word,Word);
if(cmp<0) if(Curr->right!=NULL) Curr=Curr->right; else Curr=Curr->bottom;
else if(cmp>0) Curr=Curr->left->bottom;
else break;
}
if(Curr==NULL) return 0;
while(Curr!=NULL) {
strncpy(Curr->meaning, Meaning, 140);
Curr=Curr->bottom;
}
return 1;
}
int Remove_Word(char *Word, struct __dictionary_t *Dic){
/*
* Essa função remove a palavra 'Word' e sua definição da SkipList 'Dic'.
*
* Ela retorna 1 caso a remoção tenha ocorrido com sucesso, 0 caso a palavra não exista, e -1 em caso de erros.
*/
struct __node_t *Aux, *Curr;
int cmp;
if(Word==NULL || Dic==NULL) return -1;
Curr=Dic->first;
while(Curr!=NULL) {
cmp=strcmp(Curr->word,Word);
if(cmp<0) if(Curr->right!=NULL) Curr=Curr->right; else Curr=Curr->bottom;
else if(cmp>0) Curr=Curr->left->bottom;
else break;
}
if(Curr==NULL) return 0;
while(Curr!=NULL) {
if(Curr->left!=NULL) Curr->left->right=Curr->right;
if(Curr->right!=NULL) Curr->right->left=Curr->left;
Aux=Curr;
Curr=Curr->bottom;
free(Aux);
}
return 1;
}
int Print_Word(char *Word, FILE *FStream, struct __dictionary_t *Dic){
/*
* Essa função imprime em 'FStream' a palavra 'Word' e sua definição, presentes na SkipList 'Dic'.
*
* Ela retorna 1 caso a impressão tenha ocorrido com sucesso, 0 caso a palavra não exista, e -1 em caso de erros.
*/
struct __node_t *Curr;
int cmp;
if(Word==NULL || Dic==NULL) return -1;
Curr=Dic->first;
while(Curr!=NULL) {
cmp=strcmp(Curr->word,Word);
if(cmp<0) if(Curr->right!=NULL) Curr=Curr->right; else Curr=Curr->bottom;
else if(cmp>0) Curr=Curr->left->bottom;
else {
fprintf(FStream, "%s %s\n", Word, Curr->meaning);
return 1;
}
}
return 0;
}
int Print_Words_Starting_With(char Ch, FILE *FStream, struct __dictionary_t *Dic){
/*
* Essa função imprime em 'FStream' todas as palavras que começam com 'Ch' e suas respectivas definições, presentes na SkipList 'Dic'.
*
* Ela retorna 1 caso a impressão tenha ocorrido com sucesso, 0 caso nenhuma palavra que começa com 'Ch' foi encontrada, e -1 em caso de erros.
*/
struct __node_t *Curr;
int cmp;
if(Dic==NULL) return -1;
Curr=Dic->first;
while(Curr!=NULL) {
cmp=(*Curr->word)-Ch;
if(cmp<0) if(Curr->right!=NULL) Curr=Curr->right; else Curr=Curr->bottom;
else if(cmp>0) Curr=Curr->left->bottom;
else {
while(Curr->bottom!=NULL) {
Curr=Curr->bottom;
while(Curr->left!=NULL && (*Curr->left->word)==Ch) Curr=Curr->left;
}
break;
}
}
if(Curr==NULL) return 0;
while(Curr!=NULL && (*Curr->word)==Ch) {
fprintf(FStream, "%s %s\n", Curr->word, Curr->meaning);
Curr=Curr->right;
}
return 1;
}
void Destroy_Dictionary(struct __dictionary_t *Dic){
/*
* Essa função limpa da memória todas as palavras e suas respectivas definições de 'Dic'.
* Ou seja, ela limpa da memória todos os nós de 'Dic', e a própria estrutura 'Dic'.
*/
struct __node_t *Aux, *Line=NULL, *Column;
if(Dic==NULL) return;
Column=Dic->first;
if(Dic->first!=NULL) Line=Dic->first->bottom;
while(Line!=NULL || Column!=NULL)
if(Column!=NULL) {
Aux=Column;
Column=Column->right;
free(Aux);
} else {
Column=Line;
Line=Line->bottom;
}
free(Dic);
}
<file_sep>import numpy as np
import imageio
#
# ~ Trabalho 6: Restauração de imagens ~
#
# <NAME>
# <EMAIL>
# Nº USP 10369014
# Processamento de Imagens: SCC-0251 2018.1
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
# == DEFINIÇÃO DE FUNÇÕES ==
def Res_AdaptiveFilter(Arr, N, sigmaNoisy):
"Esta função retorna a restauração por filtro adaptativo de redução de ruído local da imagem Arr usando um tamanho N e uma distribuição de ruído sigmaNoisy."
Temp = np.lib.pad(Arr.astype(np.float), N // 2, 'wrap') # Imagem estendida temporária
sigmaN = np.empty(Arr.shape, dtype=np.float) # Variância
mN = np.empty(Arr.shape, dtype=np.float) # Média aritmética
Res = np.copy(Arr).astype(np.float) # Iout
sigmaNoisy = sigmaNoisy ** 2
for x in range(Arr.shape[0]):
for y in range(Arr.shape[1]): # Obter médias e variâncias
mN[x, y] = np.average(Temp[N // 2 + x:N // 2 + x + N, N // 2 + y:N // 2 + y + N])
sigmaN[x, y] = np.var(Temp[N // 2 + x:N // 2 + x + N, N // 2 + y:N // 2 + y + N])
sigmaN = np.where(sigmaN == 0, 1, sigmaN) # Evitar divisão por zero
Res = np.multiply((sigmaNoisy / sigmaN), Arr) + np.multiply(1 - (sigmaNoisy / sigmaN), mN) # Aplicar equação
return Res
def Res_Median(Arr, N, M):
"Esta função retorna a restauração por filtro adaptativo de mediana da imagem Arr usando um tamanho N e um tamanho máximo M."
Temp = np.lib.pad(Arr.astype(np.float), N // 2, 'symmetric') # Imagem estendida temporária
Res = np.empty(Arr.shape, dtype=np.float) # Iout
for x in range(Arr.shape[0]):
for y in range(Arr.shape[1]): # Algoritmo
zMin = np.min(Temp[N // 2 + x:N // 2 + x + N, N // 2 + y:N // 2 + y + N])
zMax = np.max(Temp[N // 2 + x:N // 2 + x + N, N // 2 + y:N // 2 + y + N])
zMed = np.median(Temp[N // 2 + x:N // 2 + x + N, N // 2 + y:N // 2 + y + N])
A1 = zMed - zMin
A2 = zMed - zMax
while A1 <= 0 or A2 >= 0:
N += 1
Temp = np.lib.pad(Arr.astype(np.float), N // 2, 'symmetric')
zMin = np.min(Temp[N // 2 + x:N // 2 + x + N, N // 2 + y:N // 2 + y + N])
zMax = np.max(Temp[N // 2 + x:N // 2 + x + N, N // 2 + y:N // 2 + y + N])
zMed = np.median(Temp[N // 2 + x:N // 2 + x + N, N // 2 + y:N // 2 + y + N])
A1 = zMed - zMin
A2 = zMed - zMax
if N > M:
Res[x, y] = zMed
break
B1 = Arr[x, y] - zMin
B2 = zMed - zMax
if B1 <= 0 or B2 >= 0 or Arr[x, y] == zMax:
Res[x, y] = zMed
return Res
def Res_ContraharmonicMean(Arr, N, Q):
"Esta função retorna a restauração por filtro da média contra-harmônica da imagem Arr usando um tamanho N e um parâmetro Q."
Temp = np.lib.pad(Arr.astype(np.float), N // 2, 'constant', constant_values=0) # Imagem estendida temporária
Res = np.empty(Arr.shape, dtype=np.float) # Iout
Temp1 = np.power(Temp, Q + 1) # Elevar tudo a Q + 1
Temp2 = np.power(np.where(Temp == 0, 1, Temp), Q) # Elevar tudo a Q, eliminando chances de divisão por zero
for x in range(Arr.shape[0]):
for y in range(Arr.shape[1]): # Para cada pixel da imagem resultante...
Res[x, y] = np.sum(Temp1[N // 2 + x:N // 2 + x + N, N // 2 + y:N // 2 + y + N]) # Fazer somatórios e dividir
Res[x, y] /= np.sum(Temp2[N // 2 + x:N // 2 + x + N, N // 2 + y:N // 2 + y + N])
return Res
# == MAIN ==
# Leitura dos dados da entrada padrão
filename_Icomp = str(input()).rstrip()
filename_Inoisy = str(input()).rstrip()
filter_method = int(input())
filter_size = int(input())
filter_param = input()
# Carregamento das imagens
Icomp = imageio.imread(filename_Icomp) # Carregar imagem para comparação
Inoisy = imageio.imread(filename_Inoisy) # Carregar imagem que precisa ser restaurada
# Executar o algorítmo específico
if filter_method == 1:
Inoisy = Res_AdaptiveFilter(Inoisy, filter_size, np.float(filter_param))
elif filter_method == 2:
Inoisy = Res_Median(Inoisy, filter_size, int(filter_param))
else:
Inoisy = Res_ContraharmonicMean(Inoisy, filter_size, np.float(filter_param))
# Converter para o tipo inteiro de 8 bits
Inoisy = np.uint8(Inoisy)
# Calcular RMSE
RMSE = np.sqrt(np.sum(np.power(Icomp - Inoisy, 2)) / Icomp.size)
# Imprimir resultado do RMSE com 4 casas decimais
print("%.4f" % round(RMSE, 4))
# == DEBUGGING ==
#imageio.imwrite("out_expected.png", Icomp)
#imageio.imwrite("out_generated.png", Inoisy)
<file_sep>var FSM={
"inputs":{},
"outputs":{},
"states":{},
"currentstate":null,
"resetstate":null,
"moore":false
};
var MessageBox={
close: function(cancel, box){
if(cancel===true) return;
$(document.getElementById(box)).stop().slideUp(500);
$("#MessageBox").stop().fadeOut(1000);
},
onok: null,
onyes: null,
onno: null
};
var ExitConfirmation=false;
var ExitConfirmationMessage=null;
var IsConditionedState=false;
var ConfigState=null;
var Simulation=false;
var CircleRadius=1;
function AddInput(value){
var Me=document.createElement("span");
if(!value) value="";
Me.innerHTML='<input type="text" placeholder="Nome da entrada" value="'+value+'" pattern="^[a-zA-Z0-9_]+$" title="Apenas caracteres alfanuméricos, sem acentuação." required><a href="javascript:void(0);" onclick="MoveMeUp(this);">↑</a><a href="javascript:void(0);" onclick="MoveMeDown(this);">↓</a><a href="javascript:void(0);" onclick="DeleteMe(this);">x</a>';
document.getElementById("Form_Inputs").appendChild(Me);
Me.firstElementChild.focus();
}
function AddOutput(value){
var Me=document.createElement("span");
if(!value) value="";
Me.innerHTML='<input type="text" placeholder="Nome da saída" value="'+value+'" pattern="^[a-zA-Z0-9_]+$" title="Apenas caracteres alfanuméricos, sem acentuação." required><a href="javascript:void(0);" onclick="MoveMeUp(this);">↑</a><a href="javascript:void(0);" onclick="MoveMeDown(this);">↓</a><a href="javascript:void(0);" onclick="DeleteMe(this);">x</a>';
document.getElementById("Form_Outputs").appendChild(Me);
Me.firstElementChild.focus();
}
function AddState(value){
var Me=document.createElement("span");
if(!value) value="";
Me.innerHTML='<input type="text" placeholder="Nome (ou codificação) do estado" value="'+value+'" pattern="^[a-zA-Z0-9_]+$" title="Apenas caracteres alfanuméricos, sem acentuação." required><a href="javascript:void(0);" onclick="MoveMeUp(this);">↑</a><a href="javascript:void(0);" onclick="MoveMeDown(this);">↓</a><a href="javascript:void(0);" onclick="DeleteMe(this);">x</a>';
document.getElementById("Form_States").appendChild(Me);
Me.firstElementChild.focus();
}
function ResetDescription(){
document.getElementById("Form_Inputs").innerHTML="";
document.getElementById("Form_Outputs").innerHTML="";
document.getElementById("Form_States").innerHTML="";
}
function AddConfig(){
var Me=document.createElement("span");
Me.innerHTML='<input type="text" list="FSM_Datalist_Outputs" placeholder="Saída" pattern="^[a-zA-Z0-9_]+$" title="Apenas caracteres alfanuméricos, sem acentuação." required> será <select><option value="0" selected>0</option><option value="1">1</option></select><a href="javascript:void(0);" onclick="MoveMeUp(this);">↑</a><a href="javascript:void(0);" onclick="MoveMeDown(this);">↓</a><a href="javascript:void(0);" onclick="DeleteMe(this);">x</a>';
document.getElementById("Form_NC_Configs").appendChild(Me);
Me.firstElementChild.focus();
}
function AddConditionedConfig(){
var Me=document.createElement("span");
if(IsConditionedState===true){
Me.innerHTML='Se <input type="text" placeholder="Condição (Verilog)" pattern="^[a-zA-Z0-9_&|~^\\s]+$" title="Uma equação Verilog válida." required>, o próximo estado será <input type="text" list="FSM_Datalist_States" placeholder="Estado" pattern="^[a-zA-Z0-9_]+$" title="Apenas caracteres alfanuméricos, sem acentuação." required><a href="javascript:void(0);" onclick="MoveMeUp(this);">↑</a><a href="javascript:void(0);" onclick="MoveMeDown(this);">↓</a><a href="javascript:void(0);" onclick="DeleteMe(this);">x</a>';
}else{
Me.innerHTML='Se <input type="text" placeholder="Condição (Verilog)" pattern="^[a-zA-Z0-9_&|~^\\s]+$" title="Uma equação Verilog válida." required>, <input type="text" list="FSM_Datalist_Outputs" placeholder="Saída" pattern="^[a-zA-Z0-9_]+$" title="Apenas caracteres alfanuméricos, sem acentuação." required> será <select><option value="0" selected>0</option><option value="1">1</option></select><a href="javascript:void(0);" onclick="MoveMeUp(this);">↑</a><a href="javascript:void(0);" onclick="MoveMeDown(this);">↓</a><a href="javascript:void(0);" onclick="DeleteMe(this);">x</a>';
}
document.getElementById("Form_WC_Configs").appendChild(Me);
Me.firstElementChild.focus();
}
function MoveMeUp(Dom){
var Me=Dom.parentNode;
var Parent=Me.parentNode;
var Previous=Me.previousElementSibling;
if(Previous!=null)
Parent.insertBefore(Me, Previous);
}
function MoveMeDown(Dom){
var Me=Dom.parentNode;
var Parent=Me.parentNode;
var Next=Me.nextElementSibling;
if(Next!=null)
Parent.insertBefore(Next, Me);
}
function DeleteMe(Dom){
Dom.parentNode.outerHTML="";
}
function ParseDraggedFile(e){
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect='copy';
}
function ParseDroppedFile(e){
e.stopPropagation();
e.preventDefault();
ParseFile(e.dataTransfer.files);
}
function ParseFile(evt){
var FR = new FileReader();
if(evt[0].size>52428800){ // 50 MiB
document.getElementById("Form_File").reset();
document.getElementById("DevelopMachine").style.display="block";
AlertBox("Arquivo selecionado não é válido (tamanho maior que 50 MiB)!", BreakEvent);
return;
}
if(!(evt[0].type.match(/^\s*$/g) || evt[0].type.match(/(text)/gi))){
document.getElementById("Form_File").reset();
document.getElementById("DevelopMachine").style.display="block";
AlertBox("Arquivo selecionado não é válido (não é arquivo de texto)!", BreakEvent);
return;
}
FR.onload=function(e){
var i, j, k, Content=e.target.result;
var IsMoore, NStates, NBits, NInputs, NOutputs;
var AuxEq, AuxState, AuxNextState;
var CmbState = { }, CmbInput = { }, CmbOutput = { };
if(!Content.match(/^\s*[01]\s+[0-9]+\s+[0-9]+\s+[0-9]+\s+(\s|[01Xx])+$/g)){
document.getElementById("Form_File").reset();
document.getElementById("DevelopMachine").style.display="block";
AlertBox("Arquivo selecionado não é válido (não está no formato adequado)!", BreakEvent);
return;
}
if(Content.replace(/^\s*([01])(.|\s)*$/g,"$1")=='1'){
document.getElementById("fi_machinetype_moore").checked=true;
IsMoore=true;
}else{
document.getElementById("fi_machinetype_mealy").checked=true;
IsMoore=false;
}
Content=Content.replace(/^\s*[01]\s+((.|\s)+)$/g, "$1");
NStates=parseInt(Content.replace(/^\s*([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+((.|\s)+)$/g,"$1"));
NInputs=parseInt(Content.replace(/^\s*([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+((.|\s)+)$/g,"$2"));
NOutputs=parseInt(Content.replace(/^\s*([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+((.|\s)+)$/g,"$3"));
Content=Content.replace(/^\s*([0-9]+)\s+([0-9]+)\s+([0-9]+)\s+((.|\s)+)$/g,"$4");
Content=Content.replace(/.*[Xx].*/g, "");
Content=Content.replace(/\s/g, "");
NBits=Math.ceil(Math.log(NStates)/Math.log(2));
for(j=0;j<Content.length;j){
if(j+2*NBits+NInputs+NOutputs > Content.length) break;
AuxState="S_";
for(i=0;i<NBits;i++){
AuxState+=(Content.charAt(j++)=='0')?'0':'1';
}
if(!CmbState.hasOwnProperty(AuxState)){
CmbState[AuxState] = { "nextstates": { }, "outputs": { } };
}
AuxEq="";
for(i=0;i<NInputs;i++){
CmbInput["Entrada_"+(i+1)]="0";
if(Content.charAt(j++)=="0"){
AuxEq+="~Entrada_"+(i+1)+"&";
}else{
AuxEq+="Entrada_"+(i+1)+"&";
}
}
AuxEq=AuxEq.substr(0, AuxEq.length-1);
AuxNextState="S_";
for(i=0;i<NBits;i++){
AuxNextState+=(Content.charAt(j++)=='0')?'0':'1';
}
CmbState[AuxState]["nextstates"][AuxNextState]=AuxEq;
if(!CmbState.hasOwnProperty(AuxNextState)){
CmbState[AuxNextState] = { "nextstates": { }, "outputs": { } };
}
for(i=0;i<NOutputs;i++){
CmbOutput["Saida_"+(i+1)]="0";
if(IsMoore==true){
CmbState[AuxState]["outputs"]["Saida_"+(i+1)]=(Content.charAt(j++)=='0')?'0':'1';
}else{
if(!CmbState[AuxState]["outputs"].hasOwnProperty("Saida_"+(i+1))){
CmbState[AuxState]["outputs"]["Saida_"+(i+1)] = { };
}
CmbState[AuxState]["outputs"]["Saida_"+(i+1)][((Content.charAt(j++)=='0')?0:1).toString()]=AuxEq;
}
}
}
ResetDescription();
for(Input in CmbInput){
AddInput(Input);
}
for(Output in CmbOutput){
AddOutput(Output);
}
for(State in CmbState){
AddState(State);
}
GenMachineTable();
FSM["states"]=CmbState;
FSM["moore"]=IsMoore;
Start();
document.getElementById("Form_File").reset();
};
FR.readAsText(evt[0]);
}
function GenMachineTable(){
var NInputs, NOutputs, NStates, i;
FSM["inputs"]={ };
FSM["outputs"]={ };
FSM["states"]={ };
document.getElementById("DevelopMachine").style.display="none";
NInputs=document.getElementById("Form_Inputs").getElementsByTagName("span");
NOutputs=document.getElementById("Form_Outputs").getElementsByTagName("span");
NStates=document.getElementById("Form_States").getElementsByTagName("span");
document.getElementById("Form_Table").innerHTML="";
document.getElementById("ConfigureBox_WC_Inputs").innerHTML="";
document.getElementById("FSM_Datalist_Outputs").innerHTML="";
document.getElementById("FSM_Datalist_States").innerHTML="";
document.getElementById("Inputs_Bar").innerHTML="";
document.getElementById("Outputs_Bar").innerHTML="";
if(NInputs.length<1){
document.getElementById("DevelopMachine").style.display="block";
AlertBox("Insira ao menos uma entrada!", BreakEvent);
return;
}
if(NOutputs.length<1){
document.getElementById("DevelopMachine").style.display="block";
AlertBox("Insira ao menos uma saída!", BreakEvent);
return;
}
if(NStates.length<1){
document.getElementById("DevelopMachine").style.display="block";
AlertBox("Insira ao menos um estado!", BreakEvent);
return;
}
for(i=0;i<NInputs.length;i++){
if(NInputs[i].firstElementChild.value=="" || FSM["inputs"].hasOwnProperty(NInputs[i].firstElementChild.value)){
document.getElementById("DevelopMachine").style.display="block";
AlertBox("Não podem coexistir duas entradas com o mesmo nome!", BreakEvent);
return;
}
FSM["inputs"][NInputs[i].firstElementChild.value]="0";
document.getElementById("ConfigureBox_WC_Inputs").innerHTML+=NInputs[i].firstElementChild.value + " ";
document.getElementById("Inputs_Bar").innerHTML+='<tr><td>'+NInputs[i].firstElementChild.value+'</td><td><a href="javascript:void(0);" onclick="document.getElementById(\'InputValue.'+NInputs[i].firstElementChild.value+'\').checked=false;DefineInputs();Clock();">0</a></td><td><span class="f_switch"><input type="checkbox" onchange="DefineInputs();" id="InputValue.'+NInputs[i].firstElementChild.value+'"><label for="InputValue.'+NInputs[i].firstElementChild.value+'"></label></span></td><td><a href="javascript:void(0);" onclick="document.getElementById(\'InputValue.'+NInputs[i].firstElementChild.value+'\').checked=true;DefineInputs();Clock();">1</a></td></tr>';
}
for(i=0;i<NOutputs.length;i++){
if(NOutputs[i].firstElementChild.value=="" || FSM["outputs"].hasOwnProperty(NOutputs[i].firstElementChild.value)){
document.getElementById("DevelopMachine").style.display="block";
AlertBox("Não podem coexistir duas saídas com o mesmo nome!", BreakEvent);
return;
}
FSM["outputs"][NOutputs[i].firstElementChild.value]="0";
document.getElementById("FSM_Datalist_Outputs").innerHTML+=' <option value="'+NOutputs[i].firstElementChild.value+'">';
document.getElementById("Outputs_Bar").innerHTML+='<tr><td>'+NOutputs[i].firstElementChild.value+'</td><td id="OutputValue.'+NOutputs[i].firstElementChild.value+'">U</td></tr>';
}
for(i=0;i<NStates.length;i++){
if(NStates[i].firstElementChild.value=="" || FSM["states"].hasOwnProperty(NStates[i].firstElementChild.value)){
document.getElementById("DevelopMachine").style.display="block";
AlertBox("Não podem coexistir dois estados com o mesmo nome (ou codificação)!", BreakEvent);
return;
}
FSM["states"][NStates[i].firstElementChild.value] = { "nextstates": null, "outputs": null };
document.getElementById("FSM_Datalist_States").innerHTML+=' <option value="'+NStates[i].firstElementChild.value+'">';
document.getElementById("Form_Table").innerHTML+='<tr><td><input type="radio" name="reset_state" value="'+NStates[i].firstElementChild.value+'" title="Este é o estado inicial e definido após reset?" '+((i==0)?'checked':'')+'></td><td>'+NStates[i].firstElementChild.value+'</td><td><a href="javascript:void(0);" onclick="SetNextStatesFor(\''+NStates[i].firstElementChild.value+'\');">Definir...</a></td><td><a href="javascript:void(0);" onclick="SetOutputsFor(\''+NStates[i].firstElementChild.value+'\');">Definir...</a></td></tr>';
}
if(document.getElementById("fi_machinetype_moore").checked==true){
FSM["moore"]=true;
}else{
FSM["moore"]=false;
}
MouseScroll("#Form_Table tr td:nth-child(2)");
$("#DevelopMachineArchitecture").stop().fadeIn(500);
}
function Start(){
var State, len=0, R=100+50, Xc=0, Yc=0, i, Angle;
document.getElementById("DevelopMachineArchitecture").style.display="none";
for(State in FSM["states"]){
if(FSM["states"].hasOwnProperty(State)) len++;
}
Angle=(2*Math.PI)/len;
R=Math.sqrt((R*R)/(2-2*Math.cos((2*Math.PI)/(len+1))));
CircleRadius=R;
Xc=R;
Yc=R;
i=0;
document.getElementById("States").innerHTML='<div id="States_Animate" style="display:none;"></div>';
for(State in FSM["states"]){
document.getElementById("States").innerHTML+='<div class="state" id="FSM_State.'+State+'" style="top:'+(Yc-Math.sin(Angle*i)*R)+'px;left:'+(Xc+Math.cos(Angle*i)*R)+'px;"><span>'+State+'</span></div>';
i++;
}
for(State in FSM["states"]){
for(NextState in FSM["states"][State]["nextstates"]){
if(NextState==State) continue;
ArrowName=(State >= NextState)?State+"."+NextState:NextState+"."+State;
ArrowName="FSM_Arrow."+ArrowName;
if(document.getElementById(ArrowName)){
document.getElementById(ArrowName).getElementsByClassName("state_arrowleft")[0].style.display="block";
document.getElementById(ArrowName).getElementsByClassName("state_arrowright")[0].style.display="block";
continue;
}
PA={x: parseInt(document.getElementById("FSM_State."+State).style.left)+50, y: parseInt(document.getElementById("FSM_State."+State).style.top)+50};
PB={x: parseInt(document.getElementById("FSM_State."+NextState).style.left)+50, y: parseInt(document.getElementById("FSM_State."+NextState).style.top)+50};
Vector={x: PA.x-PB.x, y: PA.y-PB.y};
Topper={x: (PA.x<=PB.x)?PA.x:PB.x, y: (PA.y<=PB.y)?PA.y:PB.y };
Len={x: Math.abs(Vector.x), y: Math.abs(Vector.y) };
Size=Math.sqrt(Vector.x*Vector.x+Vector.y*Vector.y);
document.getElementById("States").innerHTML+='<div class="state_arrow" id="'+ArrowName+'" style="width:'+Len.x+'px;height:'+Len.y+'px;top:'+Topper.y+'px;left:'+Topper.x+'px;"><div class="state_arrowdiv" style="transform:rotate('+Math.atan2(Vector.y,Vector.x)+'rad);margin-left:-'+Size/2+'px;width:'+Size+'px;"><div class="state_arrowleft" style="display:block;">◀</div><div class="state_arrowright" style="display:none;">▶</div></div></div>';
}
}
FSM["currentstate"]=FSM["resetstate"]=document.querySelector('input[name="reset_state"]:checked').value;
DefineInputs();
MouseScroll("#States .state");
document.getElementById("States").style.width=document.getElementById("States").style.height=(2*R+110)+"px";
Simulation=true;
$("#DeployMachine").stop().fadeIn(500);
UpdateView();
}
function SetNextStatesFor(State){
var i;
document.getElementById("ConfigureBox_NC").style.display="none";
document.getElementById("ConfigureBox_WC").style.display="none";
IsConditionedState=true;
ConfigState=State;
document.getElementById("ConfigureBox_WC_Message").innerHTML="Quais serão os próximos estados?";
document.getElementById("ConfigureBox_WC_Placeholder").placeholder="Próximo estado...";
document.getElementById("Form_WC_Configs").innerHTML="";
for(NextState in FSM["states"][State]["nextstates"]){
document.getElementById("Form_WC_Configs").innerHTML+='<span>Se <input type="text" placeholder="Condição (Verilog)" pattern="^[a-zA-Z0-9_&|~^\\s]+$" value="'+FSM["states"][State]["nextstates"][NextState]+'" title="Uma equação Verilog válida." required>, o próximo estado será <input type="text" list="FSM_Datalist_States" placeholder="Estado" pattern="^[a-zA-Z0-9_]+$" title="Apenas caracteres alfanuméricos, sem acentuação." value="'+NextState+'" required><a href="javascript:void(0);" onclick="MoveMeUp(this);">↑</a><a href="javascript:void(0);" onclick="MoveMeDown(this);">↓</a><a href="javascript:void(0);" onclick="DeleteMe(this);">x</a></span>';
}
$("#ConfigureBox").stop().fadeIn(500);
$("#ConfigureBox_WC").stop().slideDown(1000);
}
function SetOutputsFor(State){
document.getElementById("ConfigureBox_NC").style.display="none";
document.getElementById("ConfigureBox_WC").style.display="none";
ConfigState=State;
if(FSM["moore"]==true){
document.getElementById("Form_NC_Configs").innerHTML="";
for(Output in FSM["states"][State]["outputs"]){
document.getElementById("Form_NC_Configs").innerHTML+='<span><input type="text" list="FSM_Datalist_Outputs" placeholder="Saída" pattern="^[a-zA-Z0-9_]+$" title="Apenas caracteres alfanuméricos, sem acentuação." value="'+Output+'" required> será <select><option value="0" '+((FSM["states"][State]["outputs"][Output]=="0")?"selected":"")+'>0</option><option value="1" '+((FSM["states"][State]["outputs"][Output]=="0")?"":"selected")+'>1</option></select><a href="javascript:void(0);" onclick="MoveMeUp(this);">↑</a><a href="javascript:void(0);" onclick="MoveMeDown(this);">↓</a><a href="javascript:void(0);" onclick="DeleteMe(this);">x</a></span>';
}
$("#ConfigureBox").stop().fadeIn(500);
$("#ConfigureBox_NC").stop().slideDown(1000);
}else{
IsConditionedState=false;
document.getElementById("ConfigureBox_WC_Message").innerHTML="Quais as saídas desse estado?";
document.getElementById("ConfigureBox_WC_Placeholder").placeholder="Saída...";
document.getElementById("Form_WC_Configs").innerHTML="";
for(Output in FSM["states"][State]["outputs"]){
for(OutputValue in FSM["states"][State]["outputs"][Output]){
document.getElementById("Form_WC_Configs").innerHTML+='<span>Se <input type="text" placeholder="Condição (Verilog)" pattern="^[a-zA-Z0-9_&|~^\\s]+$" title="Uma equação Verilog válida." value="'+FSM["states"][State]["outputs"][Output][OutputValue]+'" required>, <input type="text" list="FSM_Datalist_Outputs" placeholder="Saída" pattern="^[a-zA-Z0-9_]+$" title="Apenas caracteres alfanuméricos, sem acentuação." value="'+Output+'" required> será <select><option value="0" '+((OutputValue=="0")?"selected":"")+'>0</option><option value="1" '+((OutputValue=="0")?"":"selected")+'>1</option></select><a href="javascript:void(0);" onclick="MoveMeUp(this);">↑</a><a href="javascript:void(0);" onclick="MoveMeDown(this);">↓</a><a href="javascript:void(0);" onclick="DeleteMe(this);">x</a></span>';
}
}
$("#ConfigureBox").stop().fadeIn(500);
$("#ConfigureBox_WC").stop().slideDown(1000);
}
}
function ValidateConditionEq(Eq){
for(Input in FSM["inputs"]){
Eq=Eq.replace(new RegExp("([^a-zA-Z0-9])("+Input+")([^a-zA-Z0-9])|^("+Input+")([^a-zA-Z0-9])|([^a-zA-Z0-9])("+Input+")$|^("+Input+")$","g"),"$1$6.$3$5");
}
Eq=Eq.replace(/[\^][\~]/g,"*").replace(/[\~][\^]/g,"*").replace(/\s/g,"");
while(Eq.match(/[\(]([~]*[\.])([\&\|\^\*][~]*[\.])*[\)]/g)){
Eq=Eq.replace(/[\(]([~]*[\.])([\&\|\^\*][~]*[\.])*[\)]/g,".");
}
if(Eq.match(/^([~]*[\.])([\&\|\^\*][~]*[\.])*$/g)){
return true;
}
return false;
}
function CalculateConditionEq(Eq){
for(Input in FSM["inputs"]){
Eq=Eq.replace(new RegExp("([^a-zA-Z0-9])("+Input+")([^a-zA-Z0-9])|^("+Input+")([^a-zA-Z0-9])|([^a-zA-Z0-9])("+Input+")$|^("+Input+")$","g"),"$1$6"+FSM["inputs"][Input]+"$3$5");
}
Eq=Eq.replace(/[\^][\~]/g,"*").replace(/[\~][\^]/g,"*").replace(/\s/g,"");
while(!Eq.match(/^[01]$/g)){
if(Eq.match(/~0/g))
Eq=Eq.replace(/~0/g,"1");
else if(Eq.match(/~1/g))
Eq=Eq.replace(/~1/g,"0");
else if(Eq.match(/0&1|1&0|0&0|0\|0|0\^0|1\^1|0\*1|1\*0/g))
Eq=Eq.replace(/0&1|1&0|0&0|0\|0|0\^0|1\^1|0\*1|1\*0/g,"0");
else if(Eq.match(/1&1|1\|0|0\|1|1\|1|1\^0|0\^1|0\*0|1\*1/g))
Eq=Eq.replace(/1&1|1\|0|0\|1|1\|1|1\^0|0\^1|0\*0|1\*1/g,"1");
else /*if(Eq.match(/1&1|1\|0|0\|1|1\|1|1\^0|0\^1|0\*0|1\*1/g))*/
Eq=Eq.replace(/[\(]([01])[\)]/g,"$1");
}
return Eq;
}
function DefineInputs(){
for(Input in FSM["inputs"]){
if(document.getElementById("InputValue."+Input).checked==true){
FSM["inputs"][Input]="1";
}else{
FSM["inputs"][Input]="0";
}
}
CalculateOutputs();
}
function CalculateOutputs(){
document.getElementById("CurrentState_Bar").innerHTML=FSM["currentstate"];
if(FSM["moore"]==true){
for(Output in FSM["states"][FSM["currentstate"]]["outputs"]){
document.getElementById("OutputValue."+Output).innerHTML=FSM["states"][FSM["currentstate"]]["outputs"][Output];
}
}else{
for(Output in FSM["states"][FSM["currentstate"]]["outputs"]){
for(OutputValue in FSM["states"][FSM["currentstate"]]["outputs"][Output]){
if(CalculateConditionEq(FSM["states"][FSM["currentstate"]]["outputs"][Output][OutputValue])=="1"){
document.getElementById("OutputValue."+Output).innerHTML=OutputValue;
break;
}
}
}
}
}
function Clock(){
var CurrentState=FSM["currentstate"];
for(NextState in FSM["states"][CurrentState]["nextstates"]){
if(CalculateConditionEq(FSM["states"][CurrentState]["nextstates"][NextState])=="1"){
FSM["currentstate"]=NextState;
DefineInputs();
$("#States_Panel").stop().animate({
scrollLeft:Math.floor(document.getElementById("FSM_State."+FSM["currentstate"]).offsetLeft/document.getElementById("States_Panel").offsetWidth)*document.getElementById("States_Panel").offsetWidth+(document.getElementById("FSM_State."+FSM["currentstate"]).offsetLeft%document.getElementById("States_Panel").offsetWidth),
scrollTop:Math.floor(document.getElementById("FSM_State."+FSM["currentstate"]).offsetTop/document.getElementById("States_Panel").offsetHeight)*document.getElementById("States_Panel").offsetHeight+(document.getElementById("FSM_State."+FSM["currentstate"]).offsetTop%document.getElementById("States_Panel").offsetHeight)
}, 2500);
$(document.getElementById("FSM_State."+CurrentState)).finish().finish().animate({backgroundColor: "rgb(255,255,150)"},1250, function(){
$(this).animate({backgroundColor: "rgb(255,255,255)"},1250);
});
$(document.getElementById("FSM_State."+NextState)).finish().finish().animate({backgroundColor: "rgb(255,255,150)"},1250, function(){
$(this).animate({backgroundColor: "rgb(255,255,255)"},1250);
});
$("#States_Animate").finish();
document.getElementById("States_Animate").style.top=document.getElementById("FSM_State."+CurrentState).style.top;
document.getElementById("States_Animate").style.left=document.getElementById("FSM_State."+CurrentState).style.left;
document.getElementById("States_Animate").style.display="block";
$("#States_Animate").animate({
top:document.getElementById("FSM_State."+NextState).style.top,
left:document.getElementById("FSM_State."+NextState).style.left
},2500, function(){
document.getElementById("States_Animate").style.display="none";
});
break;
}
}
}
function ResetClock(){
for(Input in FSM["inputs"]){
FSM["inputs"][Input]="0";
document.getElementById("InputValue."+Input).checked=false;
}
FSM["currentstate"]=FSM["resetstate"];
DefineInputs();
UpdateView();
}
function UpdateView(){
var A, B;
if(Simulation===true){
document.getElementById("States").style.marginLeft=document.getElementById("States").style.marginTop=(-1*(CircleRadius+55))+"px";
if(document.getElementById("DefaultSimulationVision").checked==true){
A=(window.innerWidth<=window.innerHeight) ? window.innerWidth : window.innerHeight;
document.getElementById("States_Panel").scrollTop=0;
document.getElementById("States_Panel").scrollLeft=0;
if(A<2*CircleRadius+250){
document.getElementById("States").style.transform="scale("+(A/(2*CircleRadius+250))+")";
}else{
document.getElementById("States").style.transform="scale(1.0)";
}
}else{
if(document.getElementById("States").offsetWidth>=document.getElementById("States_Panel").offsetWidth){
document.getElementById("States").style.marginLeft="0px";
}
if(document.getElementById("States").offsetHeight>=document.getElementById("States_Panel").offsetHeight){
document.getElementById("States").style.marginTop="0px";
}
document.getElementById("States").style.transform="scale(1.0)";
$("#States_Panel").stop().animate({
scrollLeft:Math.floor(document.getElementById("FSM_State."+FSM["currentstate"]).offsetLeft/document.getElementById("States_Panel").offsetWidth)*document.getElementById("States_Panel").offsetWidth+(document.getElementById("FSM_State."+FSM["currentstate"]).offsetLeft%document.getElementById("States_Panel").offsetWidth),
scrollTop:Math.floor(document.getElementById("FSM_State."+FSM["currentstate"]).offsetTop/document.getElementById("States_Panel").offsetHeight)*document.getElementById("States_Panel").offsetHeight+(document.getElementById("FSM_State."+FSM["currentstate"]).offsetTop%document.getElementById("States_Panel").offsetHeight)
}, 250);
}
}
}
function SaveNCConfigs(){
var i, Cmb={ };
document.getElementById("ConfigureBox_NC").style.display="none";
NConfigs=document.getElementById("Form_NC_Configs").getElementsByTagName("span");
for(i=0;i<NConfigs.length;i++){
if(NConfigs[i].firstElementChild.value=="" || !FSM["outputs"].hasOwnProperty(NConfigs[i].firstElementChild.value) || Cmb.hasOwnProperty(NConfigs[i].firstElementChild.value)){
document.getElementById("ConfigureBox_NC").style.display="block";
AlertBox("Você entrou com uma saída inválida (não declarada), ou saídas repetidas!", BreakEvent);
return;
}
Cmb[NConfigs[i].firstElementChild.value]=NConfigs[i].getElementsByTagName("select")[0].value;
}
FSM["states"][ConfigState]["outputs"]=Cmb;
document.getElementById("ConfigureBox_NC").style.display="block";
$("#ConfigureBox_NC").slideUp(500);
$("#ConfigureBox").fadeOut(1000);
}
function SaveWCConfigs(){
var i, Cmb={ }, AuxCmb={ };
document.getElementById("ConfigureBox_WC").style.display="none";
NConfigs=document.getElementById("Form_WC_Configs").getElementsByTagName("span");
if(IsConditionedState){ // Estados
for(i=0;i<NConfigs.length;i++){
if(NConfigs[i].firstElementChild.value=="" || !ValidateConditionEq(NConfigs[i].firstElementChild.value)){
document.getElementById("ConfigureBox_WC").style.display="block";
AlertBox("Equação Verilog não válida!", BreakEvent);
return;
}
if(!FSM["states"].hasOwnProperty(NConfigs[i].getElementsByTagName("input")[1].value)){
document.getElementById("ConfigureBox_WC").style.display="block";
AlertBox("Você entrou com um estado inválido (não declarado)!", BreakEvent);
return;
}
if(Cmb.hasOwnProperty(NConfigs[i].getElementsByTagName("input")[1].value)){
document.getElementById("ConfigureBox_WC").style.display="block";
AlertBox("Você designou mais de uma equação Verilog para o mesmo estado!", BreakEvent);
return;
}
Cmb[NConfigs[i].getElementsByTagName("input")[1].value]=NConfigs[i].firstElementChild.value;
AuxCmb[NConfigs[i].getElementsByTagName("input")[1].value]=NConfigs[i].firstElementChild.value;
}
FSM["states"][ConfigState]["nextstates"]=AuxCmb;
}else{ // Saídas Mealy
for(i=0;i<NConfigs.length;i++){
if(NConfigs[i].firstElementChild.value=="" || !ValidateConditionEq(NConfigs[i].firstElementChild.value)){
document.getElementById("ConfigureBox_WC").style.display="block";
AlertBox("Equação Verilog inválida!", BreakEvent);
return;
}
if(!FSM["outputs"].hasOwnProperty(NConfigs[i].getElementsByTagName("input")[1].value)){
document.getElementById("ConfigureBox_WC").style.display="block";
AlertBox("Você entrou com uma saída inválida (não declarada)!", BreakEvent);
return;
}
if(Cmb.hasOwnProperty(NConfigs[i].getElementsByTagName("input")[1].value+"."+NConfigs[i].getElementsByTagName("select")[0].value)){
document.getElementById("ConfigureBox_WC").style.display="block";
AlertBox("Você designou mais de uma equação Verilog para a mesma saída!", BreakEvent);
return;
}
if(!AuxCmb.hasOwnProperty(NConfigs[i].getElementsByTagName("input")[1].value)){
AuxCmb[NConfigs[i].getElementsByTagName("input")[1].value] = { };
}
Cmb[NConfigs[i].getElementsByTagName("input")[1].value+"."+NConfigs[i].getElementsByTagName("select")[0].value]=NConfigs[i].firstElementChild.value;
AuxCmb[NConfigs[i].getElementsByTagName("input")[1].value][NConfigs[i].getElementsByTagName("select")[0].value]=NConfigs[i].firstElementChild.value;
}
FSM["states"][ConfigState]["outputs"]=AuxCmb;
}
document.getElementById("ConfigureBox_WC").style.display="block";
$("#ConfigureBox_WC").slideUp(500);
$("#ConfigureBox").fadeOut(1000);
}
function CancelNCConfigs(){
$("#ConfigureBox_NC").slideUp(500);
$("#ConfigureBox").fadeOut(1000);
}
function CancelWCConfigs(){
$("#ConfigureBox_WC").slideUp(500);
$("#ConfigureBox").fadeOut(1000);
}
function BackToMachineDescription(){
document.getElementById("DevelopMachineArchitecture").style.display="none";
$("#DevelopMachine").stop().fadeIn(500);
}
function BackToMachineArchitecture(){
document.getElementById("DeployMachine").style.display="none";
Simulation=false;
$("#DevelopMachineArchitecture").stop().fadeIn(500);
}
function MouseScroll(Elem){
$(Elem).mouseenter(function(){
$(this).stop().animate({scrollLeft: this.scrollWidth}, this.scrollWidth*10, "linear");
}).mouseleave(function(){
$(this).stop().animate({scrollLeft: 0}, 250);
});
}
function AlertBox(Message, OnClose){
document.getElementById("MessageAlertBox").innerHTML=Message;
MessageBox.onok=OnClose;
document.getElementById("ConfirmBox").style.display="none";
document.getElementById("AlertBox").style.display="none";
$("#MessageBox").stop().fadeIn(500);
$("#AlertBox").stop().slideDown(1000);
$("#AlertBox .messageBox_buttons a:first-child").focus();
}
function ConfirmBox(Message, OnYes, OnNo){
document.getElementById("MessageConfirmBox").innerHTML=Message;
MessageBox.onyes=OnYes;
MessageBox.onno=OnNo;
document.getElementById("AlertBox").style.display="none";
document.getElementById("ConfirmBox").style.display="none";
$("#MessageBox").stop().fadeIn(500);
$("#ConfirmBox").stop().slideDown(1000);
$("#ConfirmBox .messageBox_buttons a:nth-child(2)").focus();
}
function WindowExit(){
if(ExitConfirmation===true){
return ExitConfirmationMessage;
}
}
function ToggleFixed(El, Fix){
var Me=document.getElementById(El);
if(Fix==true){
Me.classList.add("fixed");
}else{
Me.classList.remove("fixed");
}
}
function MainFSM(){
document.getElementById("DevelopMachine").ondragover=ParseDraggedFile;
document.getElementById("DevelopMachine").ondrop=ParseDroppedFile;
document.getElementById("DevelopMachine").style.display="block";
MouseScroll(CurrentState_Bar);
$("#SplashScreen").stop().fadeOut(500);
}
function BreakEvent(){
return false;
}<file_sep>
/*
* ~ Trabalho Prático: Parte 2 ~
*
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef FUNCIONALIDADES_H_
#define FUNCIONALIDADES_H_
void transferirCSV(char *nomeArquivoCSV, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador);
void recuperarTudo(char *nomeArquivoDAT);
void recuperarPorCampo(char *nomeCampo, char* valorCampo, char *nomeArquivoDAT);
void recuperarPorRRN(int RRN, char *nomeArquivoDAT);
void removerRegistro(int RRN, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador);
void inserirRegistro(char **campos, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador);
void atualizarRegistro(int RRN, char **campos, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador);
void desfragmentarBinario(char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador);
void imprimirPilha(char *nomeArquivoDAT);
void recuperarPorChave(int Chave, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador);
void removerRegistroChave(int Chave, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador);
void atualizarRegistroChave(int Chave, char **campos, char *nomeArquivoDAT, char *nomeArquivoIndices, char *nomeArquivoContador);
#endif
<file_sep>import java.util.Scanner;
import java.util.Arrays;
import java.io.*;
class UsuarioNaoAchadoException extends Exception {
@Override
public String getMessage() {
return "Usuário não existe no banco de dados.";
}
}
class UsuarioExistenteException extends Exception {
@Override
public String getMessage() {
return "Usuário já existe no banco de dados.";
}
}
class SenhaIncorretaException extends Exception {
@Override
public String getMessage() {
return "Senha do usuário está incorreta.";
}
}
/**
* Classe que representa um usuário do sistema.
*
* @author Matheus (github.com/mcarvalhor)
*/
class Usuario implements Serializable {
/**
* Dados do usuário.
*
*/
public String
nomeUsuario,
senha,
nomeCompleto;
/**
* Construtor padrão.
*
* @param nomeCompleto nome completo do usuário
* @param nomeUsuario nome de usuário único (login)
* @param senha senha do usuário
*/
public Usuario(String nomeCompleto, String nomeUsuario, String senha){
this.nomeCompleto = nomeCompleto;
this.nomeUsuario = nomeUsuario;
this.senha = senha;
}
/**
* Construtor que busca o usuário de um arquivo binário (de objetos).
*
* @param nomeUsuario nome de usuário (login)
* @param senha senha para tentar login
* @param arquivoObjetos arquivo onde estão os usuários
*/
public Usuario(String nomeUsuario, String senha, ObjectInputStream arquivoObjetos) throws SenhaIncorretaException, UsuarioNaoAchadoException, IOException, ClassNotFoundException {
Usuario[] usuarioAux;
int i;
usuarioAux = (Usuario[]) arquivoObjetos.readObject();
for(i = 0; i < usuarioAux.length; i++) {
if(usuarioAux[i].nomeUsuario.equals(nomeUsuario)) {
if(!usuarioAux[i].credenciar(senha))
throw new SenhaIncorretaException();
this.nomeCompleto = usuarioAux[i].nomeCompleto;
this.nomeUsuario = usuarioAux[i].nomeUsuario;
this.senha = usuarioAux[i].senha;
return;
}
}
throw new UsuarioNaoAchadoException();
}
/**
* Construtor que busca o usuário de um arquivo de texto.
*
* @param nomeUsuario nome de usuário (login)
* @param senha senha para tentar login
* @param arquivoTexto arquivo onde estão os usuários
*/
public Usuario(String nomeUsuario, String senha, BufferedReader arquivoTexto) throws SenhaIncorretaException, UsuarioNaoAchadoException, IOException {
String usuarioAux, nomeAux;
Usuario aux;
int i;
while((usuarioAux = arquivoTexto.readLine()) != null){
if(usuarioAux.split(" ")[0].equals(nomeUsuario)) {
nomeAux = usuarioAux.split(" ")[2];
for(i = 3; i < usuarioAux.split(" ").length; i++){
nomeAux += " " + usuarioAux.split(" ")[i];
}
aux = new Usuario(nomeAux, usuarioAux.split(" ")[0], usuarioAux.split(" ")[1]);
if(!aux.credenciar(senha))
throw new SenhaIncorretaException();
this.nomeCompleto = aux.nomeCompleto;
this.nomeUsuario = aux.nomeUsuario;
this.senha = aux.senha;
return;
}
}
throw new UsuarioNaoAchadoException();
}
/**
* Tenta credenciar um usuário através de uma senha.
*
* @param senha senha para credenciar usuário
* @return true se a senha estiver correta ou false caso contrário
*/
public boolean credenciar(String senha) {
//senha = senha;
if(this.senha.equals(senha))
return true;
return false;
}
/**
* Salva o usuário (this) em um arquivo binário (de objetos).
*
* @param arquivoEntrada arquivo onde já possuem usuários salvos (leitura)
* @param arquivoSaida arquivo em que os usuários já salvos e o usuário atual serão salvos (escrita)
*/
public void cadastrar(ObjectInputStream arquivoEntrada, ObjectOutputStream arquivoSaida) throws UsuarioExistenteException, IOException, ClassNotFoundException {
Usuario[] usuarioAux;
int i;
if(arquivoEntrada != null){
usuarioAux = (Usuario[]) arquivoEntrada.readObject();
for(i = 0; i < usuarioAux.length; i++)
if(usuarioAux[i].nomeUsuario.equals(this.nomeUsuario))
throw new UsuarioExistenteException();
}else
usuarioAux = new Usuario[0];
usuarioAux = Arrays.copyOf(usuarioAux, usuarioAux.length + 1);
usuarioAux[usuarioAux.length - 1] = this;
arquivoSaida.writeObject(usuarioAux);
}
/**
* Salva o usuário (this) em um arquivo de texto.
*
* @param arquivoEntrada arquivo onde já possuem usuários salvos (leitura)
* @param arquivoSaida arquivo em que os usuários já salvos e o usuário atual serão salvos (escrita)
*/
public void cadastrar(BufferedReader arquivoEntrada, BufferedWriter arquivoSaida) throws UsuarioExistenteException, IOException {
String usuarioAux;
if(arquivoEntrada != null){
while((usuarioAux = arquivoEntrada.readLine()) != null)
if(usuarioAux.split(" ")[0].equals(this.nomeUsuario))
throw new UsuarioExistenteException();
}
usuarioAux = this.nomeUsuario + " " + this.senha + " " + this.nomeCompleto;
arquivoSaida.write(usuarioAux);
}
}
/**
* Classe principal do programa.
*
* @author Matheus (github.com/Matheus)
*/
class Main {
String nomeArquivoObjetos = "usuarios.obj.dat", nomeArquivoTexto = "usuarios.txt.dat";
/**
* Função principal do programa.
*
* @param args argumentos de linha de comando
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
String nomeCompleto, nomeUsuario, senha;
ObjectOutputStream escritorObjetos;
ObjectInputStream leitorObjetos;
Usuario usuarioAux;
Console console;
Scanner reader;
int op;
if(args.length != 2) {
System.out.println("Uso do programa:\n\t" + Main.class.getName() + " (TIPO_DE_ARQUIVO) (NOME_ARQUIVO)\nOnde:\n\t(TIPO_DE_ARQUIVO) -> 0 para arquivo de objetos ou 1 para arquivo de texto\n\t(NOME_ARQUIVO) -> nome do arquivo a ser usado");
System.exit(-1);
}
console = System.console();
if(console == null) {
System.out.println("Erro ao carregar o console!");
System.exit(-1);
}
reader = new Scanner(System.in);
System.out.println("Bem-vind@ ao programa de login.\n");
System.out.println("== Principal ==");
System.out.println(" 1. Cadastrar usuário");
System.out.println(" 2. Logar usuário");
System.out.println(" -1. Sair");
System.out.print(" Entre com a operação > ");
op = reader.nextInt();
while(op != -1){
switch(op){
case 1:
System.out.println("\n\t== Cadastro ==");
System.out.print("\tEntre com um nome de usuário > ");
nomeUsuario = reader.next();
System.out.print("\tEntre com o seu nome completo > ");
nomeCompleto = reader.next();
nomeCompleto += reader.nextLine();
System.out.print("\tEntre com uma senha > ");
senha = new String(console.readPassword());
usuarioAux = new Usuario(nomeCompleto, nomeUsuario, senha);
leitorObjetos = null;
escritorObjetos = null;
try {
try {
leitorObjetos = new ObjectInputStream(new BufferedInputStream(new FileInputStream(nomeArquivoObjetos)));
} catch(Exception e){
leitorObjetos = null;
}
escritorObjetos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(nomeArquivoObjetos)));
usuarioAux.cadastrar(leitorObjetos, escritorObjetos);
} catch(UsuarioExistenteException e){
System.out.println("Usuário já existe!");
} finally {
if(leitorObjetos != null){
leitorObjetos.close();
}
if(escritorObjetos != null){
escritorObjetos.close();
}
}
break;
case 2:
System.out.println("\n\t== Login ==");
System.out.print("\tEntre com seu nome de usuário > ");
nomeUsuario = reader.next();
System.out.print("\tEntre com sua senha > ");
senha = new String(console.readPassword());
leitorObjetos = null;
try {
leitorObjetos = new ObjectInputStream(new BufferedInputStream(new FileInputStream(nomeArquivoObjetos)));
usuarioAux = new Usuario(nomeUsuario, senha, leitorObjetos);
System.out.println("\tBem-vind@ ao sistema, " + usuarioAux.nomeCompleto + "! Fazendo logoff...");
} catch(UsuarioNaoAchadoException|FileNotFoundException e) {
System.out.println("\tUsuário não cadastrado!");
} catch(SenhaIncorretaException e) {
System.out.println("\tSenha incorreta!");
} finally {
if(leitorObjetos != null){
leitorObjetos.close();
}
}
break;
default:
System.out.println("Operação inválida!");
}
System.out.println("\n== Principal ==");
System.out.println(" 1. Cadastrar usuário");
System.out.println(" 2. Logar usuário");
System.out.println(" -1. Sair");
System.out.print(" Entre com a operação > ");
op = reader.nextInt();
}
System.out.println("Até logo!");
reader.close();
}
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv){
int Soma = 0, Aux1, Aux2;
while(scanf("%d %d", &Aux1, &Aux2) == 2){
Soma += Aux1 + Aux2;
}
printf("%d\n", Soma);
return EXIT_SUCCESS;
}
<file_sep>
/*
* ~ <NAME> ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef REDBLACKTREE_H_
#define REDBLACKTREE_H_
#include <stdlib.h>
typedef struct __redblacktree_t RBT;
struct __redblacktree_t *RBT_New(size_t, int (*)(void *, void *), void (*)(void *));
int RBT_Insert(void *, struct __redblacktree_t *);
int RBT_Min(void *, struct __redblacktree_t *);
int RBT_Max(void *, struct __redblacktree_t *);
int RBT_Predecessor(void *, void *, struct __redblacktree_t *);
int RBT_Successor(void *, void *, struct __redblacktree_t *);
int RBT_PreOrder(void (*)(void *), struct __redblacktree_t *);
int RBT_InOrder(void (*)(void *), struct __redblacktree_t *);
int RBT_PostOrder(void (*)(void *), struct __redblacktree_t *);
void RBT_Destroy(struct __redblacktree_t *);
#endif<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <vector>
#include <stack>
#include <queue>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
int main(int argc, char **argv) {
int i, N, aux;
queue<int> expectingCoachesOnB;
stack<int> currentCoachesOnStation;
while(scanf("%d", &N) == 1 && N != 0) { // Enquanto ainda existirem casos de teste...
while(scanf("%d", &aux) == 1 && aux != 0) { // Enquanto ainda existirem casos de teste para este caso de teste...
// Limpar fila e pilha.
expectingCoachesOnB = queue<int>();
currentCoachesOnStation = stack<int>();
// Ler entrada.
expectingCoachesOnB.push(aux);
for(i = 1; i < N; i++) {
scanf("%d", &aux);
expectingCoachesOnB.push(aux);
}
// Processar entrada.
for(i = 1; i <= N; i++) {
currentCoachesOnStation.push(i);
while(!currentCoachesOnStation.empty() && currentCoachesOnStation.top() == expectingCoachesOnB.front()) { // O que está na pilha é esperado no resultado final. Liberar coach então!
expectingCoachesOnB.pop();
currentCoachesOnStation.pop();
}
}
// Processar o que está parado na estação (o resto).
while(!currentCoachesOnStation.empty()) {
if(expectingCoachesOnB.front() != currentCoachesOnStation.top()) { // Se forem diferentes, não dá certo... "break" impede que o código continue para o "pop".
break;
}
expectingCoachesOnB.pop();
currentCoachesOnStation.pop();
}
if(currentCoachesOnStation.empty()) { // Só dá certo se não sobrar nenhum coach na estação.
printf("Yes\n");
} else {
printf("No\n");
}
}
printf("\n");
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
Matheus
<EMAIL>
*/
int main(){
float valor,poupanca,lci,cdb_a,cdb_b,cdb;
int meses;
scanf("%f %d",&valor,&meses);
poupanca=valor*pow(1.0059,meses);
if(meses<6){
lci=valor;
}else{
lci=valor*pow(1.0086,meses);
}
cdb_a=valor*pow(1.01032,meses);
if(meses<7){
cdb_b=0.225;
}else if(meses<13){
cdb_b=0.2;
}else if(meses<25){
cdb_b=0.175;
}else{
cdb_b=0.15;
}
cdb=cdb_a-((cdb_a-valor)*cdb_b);
printf("%.2f\n",poupanca);
printf("%.2f\n",lci);
printf("%.2f\n",cdb);
if(poupanca>lci && poupanca>cdb){
printf("P");
}else if(lci>poupanca && lci>cdb){
printf("L");
}else{
printf("C");
}
return EXIT_SUCCESS;
}
<file_sep>
#ifndef H_FUNCIONALIDADES
#define H_FUNCIONALIDADES
int f1_csvBuild(char *binPath, char *csvPath);
int f2_list(char *binPath);
int f3_search(char *binPath, char *field, char *value);
int f4_removeRegs(char *binPath, int n, FILE *input);
int f5_addRegs(char *binPath, int n, FILE *input);
int f6_updateRegs(char *binPath, int n, FILE *input);
int f7_sort(char *inPath, char *outPath);
int f8_merge(char *in1Path, char *in2Path, char *outPath);
int f9_match(char *in1Path, char *in2Path, char *outPath);
int f10_index(char *binPath, char *indPath);
int f11_searchKey(char *binPath, char *indPath, char *value);
int f12_removeRegsKey(char *binPath, char *indPath, int n, FILE *input);
int f13_addRegsKey(char *binPath, char *indPath, int n, FILE *input);
int f14_searchKeyStats(char *binPath, char *indPath, char *value);
int f15_indexB(char *binPath, char *indPath);
int f16_searchKeyB(char *binPath, char *indPath, char *value);
int fx_invalidate(char *binPath);
int fx_listRemoved(char *binPath);
#endif
<file_sep>
#ifndef H_VECTOR_BUILDER_
#define H_VECTOR_BUILDER_
#include <stdio.h>
typedef struct __VECTOR_T VECTOR_T;
VECTOR_T *V_new(size_t);
int V_pushback(void *, VECTOR_T *);
unsigned long V_size(VECTOR_T *);
unsigned long V_copy(void *, VECTOR_T *);
unsigned long V_build(void *, VECTOR_T *);
int V_clear(VECTOR_T *);
void V_destroy(VECTOR_T *v);
#endif<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <utility>
#include <vector>
using namespace std;
void DFS(long V, long Test, long *visited, vector< vector< pair<long, long> > > &G){
long i, N;
visited[V]++;
N = G[V].size();
for(i = 0; i < N; i++){
if(visited[G[V][i].first] < 0 && G[V][i].first != Test){
DFS(G[V][i].first, Test, visited, G);
}
}
}
int main(int argc, char **argv){
long i, j, k, T, N, Aux, *visited, **results;
cin >> T;
for(i = 0; i < T; i++){
cin >> N;
vector< vector< pair<long, long> > > G(N);
results = (long **) malloc(sizeof(long *) * N);
visited = (long *) malloc(sizeof(long) * N);
for(j = 0; j < N; j++){
results[j] = (long *) malloc(sizeof(long) * N);
for(k = 0; k < N; k++){
cin >> Aux;
if(Aux > 0){
G[j].push_back(make_pair(k, 0));
}
}
}
for(j = 0; j < N; j++){
memset(visited, -1, sizeof(long) * N);
if(j)
DFS(0, j, visited, G);
for(k = 0; k < N; k++)
results[j][k] = visited[k];
}
cout << "Case " << i + 1 << ":\n+";
for(k = N * 2; k > 1; k--)
cout << '-';
cout << "+\n";
for(j = 0; j < N; j++){
cout << '|';
for(k = 0; k < N; k++)
cout << ((results[j][k] < 0) ? 'Y':'N') << '|';
cout << "\n+";
for(k = N * 2; k > 1; k--)
cout << '-';
cout << "+\n";
}
for(j = 0; j < N; j++)
free(results[j]);
free(visited);
free(results);
}
return EXIT_SUCCESS;
}<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <buffer.h>
unsigned long B_count(FILE *stream) {
long n, p;
n = ftell(stream);
if(n < 0) {
return -1;
}
p = n/PAGE_SIZE;
if(n % PAGE_SIZE != 0) {
p++;
}
return p;
}
unsigned long B_offset(FILE *stream) {
long n;
n = ftell(stream);
if(n < 0) {
return -1;
}
n = n % PAGE_SIZE;
return n;
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <vector>
#include <string>
#include <tuple>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int moves[8][2] = {
{-1, 0},
{1, 0},
{0, -1},
{0, 1},
{1, -1},
{-1, 1},
{1, 1},
{-1, -1}
};
using namespace std;
bool sort_cmp(string &a, string &b) {
if(a.size() == b.size()) {
return a < b;
} else if(a.size() < b.size()) {
return true;
} else {
return false;
}
}
vector<string> backtrack(int x, int y, string beginning, char lastChar, vector< vector< tuple<char, bool> > > &table) {
char currentChar, nextChar;
vector<string> found;
vector<string> aux;
int i;
if(x >= table.size() || y >= table.size() || x < 0 || y < 0) {
return found;
}
if( get<1>(table[x][y]) != false ) {
return found;
}
currentChar = get<0>(table[x][y]);
if(currentChar <= lastChar) {
return found;
}
found.push_back(beginning + currentChar);
get<1>(table[x][y]) = true;
for(i = 0; i < 8; i++) {
aux = backtrack(x + moves[i][0], y + moves[i][1], beginning + currentChar, currentChar, table);
found.insert(found.end(), aux.begin(), aux.end());
}
get<1>(table[x][y]) = false;
return found;
}
void testCase() {
int i, j, N;
cin >> N;
vector< vector< tuple<char, bool> > > table;
vector< vector< vector<string> > > foundWords;
string aux;
for(i = 0; i < N; i++) {
cin >> aux;
table.push_back(vector< tuple<char, bool> >());
foundWords.push_back(vector< vector<string> >());
for(j = 0; j < N; j++) {
table[i].push_back(tuple<char, bool>(aux[j], false));
foundWords[i].push_back(vector<string>());
}
}
vector<string> found;
vector<string> auxF;
for(i = 0; i < N; i++) {
for(j = 0; j < N; j++) {
auxF = backtrack(i, j, "", 0, table);
found.insert(found.end(), auxF.begin(), auxF.end());
}
}
unordered_map<string, bool> foundMap;
for(vector<string>::iterator it = found.begin(); it != found.end(); it++) {
if((*it).size() < 3 || (*it).size() > N*N) {
continue;
}
foundMap[*it] = true;
}
found.clear();
for(unordered_map<string, bool>::iterator it = foundMap.begin(); it != foundMap.end(); it++) {
found.push_back(it->first);
}
foundMap.clear();
for(vector<string>::iterator it = found.begin(); it != found.end(); it++) {
if((*it).size() < 3 || (*it).size() > N*N) {
continue;
}
foundMap[*it] = true;
}
sort(found.begin(), found.end(), sort_cmp);
for(vector<string>::iterator it = found.begin(); it != found.end(); it++) {
cout << *it << endl;
}
}
int main(int argc, char **argv) {
int T;
cin >> T;
for(; T > 0; T--) {
testCase();
if(T > 1) {
cout << endl;
}
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
#define ALPHABET_START ('a')
#define ALPHABET_END ('z')
#define ALPHABET_SIZE (ALPHABET_END - ALPHABET_START + 1)
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
typedef struct __node {
struct __node *alphabet[ALPHABET_SIZE];
ll nWords, nTotalWords;
} NODE;
void add_to_index(char *str, NODE *root) {
NODE *aux;
ll i;
if(*str == '\0') {
root->nWords++;
root->nTotalWords++;
return;
}
if(root->alphabet[*str - ALPHABET_START] == NULL) {
aux = (NODE *) malloc(sizeof(NODE));
memset(aux->alphabet, 0, sizeof(NODE *) * ALPHABET_SIZE);
aux->nWords = aux->nTotalWords = 0;
root->alphabet[*str - ALPHABET_START] = aux;
}
add_to_index(str + 1, root->alphabet[*str - ALPHABET_START]);
root->nTotalWords++;
}
/*ll find_all_words(NODE *root) {
ll i, count;
if(root == NULL) {
return 0;
}
count = 0;
for(i = 0; i < ALPHABET_SIZE; i++) {
count += find_all_words(root->alphabet[i]);
}
count += root->nWords;
return count;
}*/
/*ll found(char *q, NODE *root) {
if(root == NULL) {
return 0;
}
if(*q != '\0') {
return found(q + 1, root->alphabet[*q - ALPHABET_START]);
}
return root->nTotalWords;
}*/
void count_chars(ll height, ll *count, NODE *root) {
ll i;
if(root == NULL) {
return;
}
for(i = 0; i < ALPHABET_SIZE; i++) {
if(root->alphabet[i] == NULL) {
continue;
}
count_chars(height + 1, count, root->alphabet[i]);
if(root->nTotalWords != 1 && root->alphabet[i]->nTotalWords == 1) {
*count += height;
}
}
}
void destroy(NODE *root) {
ll i;
if(root == NULL) {
return;
}
for(i = 0; i < ALPHABET_SIZE; i++) {
destroy(root->alphabet[i]);
}
free(root);
}
void testCase() {
char str[1000001];
ll i, N, count;
NODE *root;
root = (NODE *) malloc(sizeof(NODE));
memset(root->alphabet, 0, sizeof(NODE *) * ALPHABET_SIZE);
root->nWords = root->nTotalWords = 0;
cin >> N;
for(i = 0; i < N; i++) {
cin >> str;
add_to_index(str, root);
}
count = 0;
count_chars(1, &count, root);
cout << count << endl;
destroy(root);
}
int main(int argc, char **argv) {
ll T;
cin >> T;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep># SCC-0218 Algoritmos Avançados - 2018.2
Aqui estão todos os projetos que implementei em conjunto em Algoritmos Avançados.
<file_sep># SCC-0222 Laboratório de Introdução à Ciência da Computação 1 - 2017.1
Aqui estão todos os trabalhos que implementei em Laboratório de ICC 1.
<file_sep>
/*
* ~ MATRIOSKA ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __MATRIOSKA_H_
#define __MATRIOSKA_H_
int Matrioska_Check(FILE *);
#endif
<file_sep>#include <stdlib.h>
#include <stdio.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int i,K;
double X0,r;
scanf("%lf %lf %d",&X0,&r,&K);
for(i=1;i<=K;i++){
X0=r*X0*(1-X0);
printf("%d %.6lf\n",i,X0);
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <assert.h>
#include "stack.h"
#ifndef STACK_ELEM
#define STACK_ELEM int
#endif
/*
* ~ STACK ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
struct __stack_t { // Estrutura da pilha.
int Top;
STACK_ELEM *L;
};
struct __stack_t *S_New(){
/*
* Cria uma nova pilha, retornando-a.
*/
struct __stack_t *Aux=(struct __stack_t *)malloc(sizeof(struct __stack_t));
Aux->Top=-1;
Aux->L=NULL;
return Aux;
}
struct __stack_t *S_NewFrom(struct __stack_t *S){
/*
* Cria uma nova pilha como cópia de 'S'.
*
* Retorna o endereço da nova pilha cópia, ou NULL em caso de erros.
*/
if(S==NULL) return NULL;
struct __stack_t *Aux=(struct __stack_t *)malloc(sizeof(struct __stack_t));
int i;
Aux->Top=S->Top;
Aux->L=(STACK_ELEM *)malloc(sizeof(STACK_ELEM)*(S->Top+1));
for(i=0;i<=S->Top;i++) Aux->L[i]=S->L[i];
return Aux;
}
char S_Cmp(struct __stack_t *A,struct __stack_t *B){
/*
* Esta função compara duas pilhas 'A' e 'B' em seus valores (como se fossem uma "string").
*
* Retorna 0 se forem pilhas iguais, -1 se 'A' for maior, 1 se 'B' for maior, e -2 em caso de erros.
*/
if(A==NULL || B==NULL) return -2;
int i,G;
if(A->Top<=B->Top) G=A->Top;
else G=B->Top;
for(i=0;i<=G;i++){
if(A->L[i]>B->L[i]) return -1;
else if(A->L[i]<B->L[i]) return 1;
}
if(A->Top<B->Top) return -1;
else if(A->Top>B->Top) return 1;
return 0;
}
char S_IsEmpty(struct __stack_t *S){
/*
* Retorna 1 se a pilha 'S' estiver vazia, ou 0 em caso contrário.
*
* Retorna também -1 em casos de erros.
*/
if(S==NULL) return -1;
return (S->Top>-1) ? 0 : 1;
}
int S_Size(struct __stack_t *S){
/*
* Retorna o tamanho da pilha 'S', ou -1 em caso de erros.
*/
if(S==NULL) return -1;
return S->Top+1;
}
char S_Push(STACK_ELEM X,struct __stack_t *S){
/*
* Adiciona 'X' ao topo da pilha 'S'.
*
* Retorna 0 em caso de erros ou 1 em caso de sucesso.
*/
if(S==NULL) return 0;
S->L=(STACK_ELEM *)realloc(S->L,sizeof(STACK_ELEM)*(S->Top+2));
S->Top++;
S->L[S->Top]=X;
return 1;
}
STACK_ELEM S_Pop(struct __stack_t *S){
/*
* Retorna o último elemento da pilha 'S', retirando-o dela.
*
* ATENÇÃO: Em caso de erros, essa função PARA a execução.
*/
if(S==NULL) assert(0); // Erro: ponteiro nulo.
if(S->Top<0) assert(0); // Erro: pilha vazia.
STACK_ELEM Aux=S->L[S->Top];
S->L=(STACK_ELEM *)realloc(S->L,sizeof(STACK_ELEM)*S->Top);
S->Top--;
return Aux;
}
STACK_ELEM S_Get(struct __stack_t *S){
/*
* Retorna o último elemento da pilha 'S', sem retirar este dela.
*
* ATENÇÃO: Em caso de erros, essa função PARA a execução.
*/
if(S==NULL) assert(0); // Erro: ponteiro nulo.
if(S->Top<0) assert(0); // Erro: pilha vazia.
return S->L[S->Top];
}
STACK_ELEM S_GetAt(int i,struct __stack_t *S){
/*
* Retorna o elemento 'i' da pilha 'S', sem retirar este dela.
*
* ATENÇÃO: Em caso de erros, essa função PARA a execução.
*/
if(S==NULL) assert(0); // Erro: ponteiro nulo.
if(S->Top<0) assert(0); // Erro: pilha vazia.
if(i<0 || i>S->Top) assert(0); // Erro: posição "i" fora do intervalo da pilha.
return S->L[i];
}
char S_Destroy(struct __stack_t *S){
/*
* Limpa da memória a pilha 'S'.
*/
if(S==NULL) return 0;
if(S->L!=NULL) free(S->L);
free(S);
return 1;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
/*
* == ABB ==
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
struct __bin_search_node { // Nó da árvore.
int Value;
struct __bin_search_node *L,*R;
};
struct __bin_search_tree { // Estrutura da árvore.
struct __bin_search_node *Root;
};
struct __bin_search_tree *Create_Tree(){
/*
* Esta função vai criar uma árvore binária de busca.
*
* Ela retorna um ponteiro para a árvore criada.
*/
struct __bin_search_tree *Aux=(struct __bin_search_tree *)malloc(sizeof(struct __bin_search_tree));
Aux->Root=NULL;
return Aux;
}
char Find_In_Node(int X, struct __bin_search_node *N){
/*
* Esta é uma função auxiliar (não disponível abertamente na biblioteca) para "Find_In".
*/
if(N==NULL) return -1;
if(X==N->Value) return 1;
if(X<N->Value && N->L!=NULL && Find_In_Node(X,N->L)!=0) return 1;
if(X>N->Value && N->R!=NULL && Find_In_Node(X,N->R)!=0) return 1;
return 0;
}
char Find_In(int X, struct __bin_search_tree *T){
/*
* Esta função procura por 'X' na árvore binária de busca 'T'.
*
* Ela retorna 1 se 'X' existe na árvore, 0 se não existe, ou -1 em caso de erros.
*/
if(T==NULL) return -1;
if(T->Root!=NULL && Find_In_Node(X,T->Root)!=0) return 1;
return 0;
}
char Insert_Into_Node(int X, struct __bin_search_node *N){
/*
* Esta é uma função auxiliar (não disponível abertamente na biblioteca) para "Insert_Into".
*/
if(N==NULL) return 0;
if(X<=N->Value){
if(N->L!=NULL) return Insert_Into_Node(X,N->L);
N->L=(struct __bin_search_node *)malloc(sizeof(struct __bin_search_node));
N->L->Value=X;
N->L->L=N->L->R=NULL;
return 1;
}
if(N->R!=NULL) return Insert_Into_Node(X,N->R);
N->R=(struct __bin_search_node *)malloc(sizeof(struct __bin_search_node));
N->R->Value=X;
N->R->L=N->R->R=NULL;
return 1;
};
char Insert_Into(int X, struct __bin_search_tree *T){
/*
* Esta função insere na árvore binária de busca 'T' o valor 'X'.
*
* Ela retorna 1 se inseriu com sucesso, ou 0 em caso de erros.
*/
if(T==NULL) return 0;
if(T->Root!=NULL) return Insert_Into_Node(X,T->Root);
T->Root=(struct __bin_search_node *)malloc(sizeof(struct __bin_search_node));
T->Root->Value=X;
T->Root->L=T->Root->R=NULL;
return 1;
}
char Remove_First_From_Node(int X, struct __bin_search_node **N){
/*
* Esta é uma função auxiliar (não disponível abertamente na biblioteca) para "Remove_First_From".
*/
if(N==NULL || *N==NULL) return -1;
struct __bin_search_node *Aux;
if(X==(*N)->Value){
Aux=*N;
if((*N)->L==NULL) *N=(*N)->R;
else if((*N)->R==NULL) *N=(*N)->L;
else{
struct __bin_search_node **R=&(*N)->R;
while((*R)->L!=NULL){
R=&(*R)->L;
}
Aux=*R;
(*N)->Value=(*R)->Value;
*R=(*R)->R;
}
free(Aux);
return 1;
}
if(X<(*N)->Value && (*N)->L!=NULL && Remove_First_From_Node(X,&(*N)->L)==1) return 1;
if(X>(*N)->Value && (*N)->R!=NULL && Remove_First_From_Node(X,&(*N)->R)==1) return 1;
return 0;
}
char Remove_First_From(int X, struct __bin_search_tree *T){
/*
* Esta função remove a primeira ocorrência encontrada de 'X' da árvore binária de busca 'T'.
*
* Ela retorna 1 se 'X' foi removido, 0 se 'X' não existe na árvore, ou -1 em caso de erros.
*/
if(T==NULL) return -1;
if(T->Root!=NULL && Remove_First_From_Node(X,&T->Root)==1) return 1;
return 0;
}
char Print_Node_InOrder(FILE *FStream,struct __bin_search_node *N){
/*
* Esta é uma função auxiliar (não disponível abertamente na biblioteca) para "Print_InOrder".
*/
if(N==NULL) return 0;
Print_Node_InOrder(FStream,N->L);
fprintf(FStream," %d",N->Value);
Print_Node_InOrder(FStream,N->R);
return 1;
}
char Print_InOrder(FILE *FStream,struct __bin_search_tree *T){
/*
* Esta função imprime em 'FStream' toda a árvore binária de busca 'T'.
* Note que ela vai imprimir da forma "em ordem", ou seja, primeiro os filhos da esquerda, a chave, e finalmente os filhos da direita.
*
* Ela retorna 1 se imprimiu com sucesso, ou 0 em caso de erros.
*/
if(T==NULL) return 0;
fprintf(FStream,"InOrdem:");
Print_Node_InOrder(FStream,T->Root);
printf("\n");
return 1;
}
char Print_Node_PreOrder(FILE *FStream,struct __bin_search_node *N){
/*
* Esta é uma função auxiliar (não disponível abertamente na biblioteca) para "Print_PreOrder".
*/
if(N==NULL) return 0;
fprintf(FStream," %d",N->Value);
Print_Node_PreOrder(FStream,N->L);
Print_Node_PreOrder(FStream,N->R);
return 1;
}
char Print_PreOrder(FILE *FStream,struct __bin_search_tree *T){
/*
* Esta função imprime em 'FStream' toda a árvore binária de busca 'T'.
* Note que ela vai imprimir da forma "pré-ordem", ou seja, primeiro a chave, os filhos da esquerda, e finalmente os filhos da direita.
*
* Ela retorna 1 se imprimiu com sucesso, ou 0 em caso de erros.
*/
if(T==NULL) return 0;
fprintf(FStream,"PreOrdem:");
Print_Node_PreOrder(FStream,T->Root);
printf("\n");
return 1;
}
char Print_Node_PostOrder(FILE *FStream,struct __bin_search_node *N){
/*
* Esta é uma função auxiliar (não disponível abertamente na biblioteca) para "Print_PostOrder".
*/
if(N==NULL) return 0;
Print_Node_PostOrder(FStream,N->L);
Print_Node_PostOrder(FStream,N->R);
fprintf(FStream," %d",N->Value);
return 1;
}
char Print_PostOrder(FILE *FStream,struct __bin_search_tree *T){
/*
* Esta função imprime em 'FStream' toda a árvore binária de busca 'T'.
* Note que ela vai imprimir da forma "pós-ordem", ou seja, primeiro os filhos da esquerda, os filhos da direita, e finalmente a chave.
*
* Ela retorna 1 se imprimiu com sucesso, ou 0 em caso de erros.
*/
if(T==NULL) return 0;
fprintf(FStream,"PosOrdem:");
Print_Node_PostOrder(FStream,T->Root);
printf("\n");
return 1;
}
char Print_Node_LevelOrder(FILE *FStream,int Level,struct __bin_search_node *N){ // Cuidado: complexidade O(n²).
/*
* Esta é uma função auxiliar (não disponível abertamente na biblioteca) para "Print_LevelOrder".
*/
if(N==NULL) return 0;
char R;
if(Level<=1){
fprintf(FStream," %d",N->Value); fflush(FStream);
return 1;
}
Level--;
R=Print_Node_LevelOrder(FStream,Level,N->L);
if(Print_Node_LevelOrder(FStream,Level,N->R)!=1 && R!=1) return 0;
return 1;
}
char Print_LevelOrder(FILE *FStream,struct __bin_search_tree *T){
/*
* Esta função imprime em 'FStream' toda a árvore binária de busca 'T'.
* Note que ela vai imprimir da forma "largura", ou seja, todos os elementos do nível 1, 2, 3, ..., e n, sendo n o último nível da árvore.
*
* Ela retorna 1 se imprimiu com sucesso, ou 0 em caso de erros.
*/
if(T==NULL) return 0;
int i=1;
fprintf(FStream,"Largura:");
while(Print_Node_LevelOrder(FStream,i,T->Root)==1) i++;
printf("\n");
return 1;
}
char Destroy_Node(struct __bin_search_node *N){
/*
* Esta é uma função auxiliar (não disponível abertamente na biblioteca) para "Destroy_Tree".
*/
if(N==NULL) return 0;
Destroy_Node(N->L);
Destroy_Node(N->R);
free(N);
return 1;
}
char Destroy_Tree(struct __bin_search_tree *T){
/*
* Esta função vai remover da memória toda a árvore binária de busca 'T'.
*
* Ela retorna 1 se removeu com sucesso, ou 0 em caso de erros.
*/
if(T==NULL) return 0;
Destroy_Node(T->Root);
free(T);
return 1;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <json.h>
/*
* ~ JSON Parser ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv){
int Line,ObjectN,ArrayN,PairN,StringN,NumberN,TrueN,FalseN,NullN;
char *JSON_Line=NULL;
size_t N;
N=Line=ObjectN=ArrayN=PairN=StringN=NumberN=TrueN=FalseN=NullN=0; // Zerar todas as contagens.
while( getline(&JSON_Line,&N,stdin)!=-1 ){ // Se tiver uma linha pra ser lida...
Line++; // Incrementar o número da linha onde estamos.
if(JSON_Check(JSON_Line,&ObjectN,&ArrayN,&PairN,&StringN,&NumberN,&TrueN,&FalseN,&NullN)==0){ // Essa linha obedece a gramática 'G'?
printf("Error line %d\n",Line); // Não. "Throw exception".
break; // Parar a leitura já.
}
}
printf("Number of Objects: %d\n",ObjectN);
printf("Number of Arrays: %d\n",ArrayN);
printf("Number of Pairs: %d\n",PairN);
printf("Number of Strings: %d\n",StringN);
printf("Number of Numbers: %d\n",NumberN);
printf("Number of Trues: %d\n",TrueN);
printf("Number of Falses: %d\n",FalseN);
printf("Number of Nulls: %d\n",NullN);
free(JSON_Line); // Liberar a nossa string de expressão JSON da memória.
return EXIT_SUCCESS;
}
<file_sep># SSC-0114 Arquitetura de Computadores - 2018.2
Aqui estão todos os trabalhos que implementei em Arquitetura de Computadores.
<file_sep>
/*
* ~ SOCCER ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __SOCCER_H_
#define __SOCCER_H_
typedef struct __soccer_tour_t SOCCER_TOUR;
struct __soccer_tour_t *S_NewFrom(FILE *);
char S_Calc(struct __soccer_tour_t *);
char S_Sort(struct __soccer_tour_t *);
char S_Print(struct __soccer_tour_t *,FILE *);
char S_Destroy(struct __soccer_tour_t *);
#endif
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
void dfs(int current, int s, int *it1, int *it2, char *status, int N, vector< vector<int> > &G) {
int i;
status[current] = s;
if(s == 1) {
(*it1)++;
} else {
(*it2)++;
}
for(i = 0; i < G[current].size(); i++) {
if(status[G[current][i]] < 1) {
dfs(G[current][i], 3 - s, it1, it2, status, N, G);
}
}
}
void testCase() {
int M, N, K, a, b, i, it, it1, it2;
char *status;
cin >> N >> M;
vector< vector<int> > G = vector< vector<int> >();
status = (char *) malloc(sizeof(char) * N);
memset(status, 0, sizeof(char) * N);
for(i = 0; i < N; i++) {
G.push_back( vector<int>() );
}
for(i = 0; i < M; i++) {
cin >> a >> b;
G[a - 1].push_back(b - 1);
G[b - 1].push_back(a - 1);
}
it1 = it2 = 0;
dfs(1, 1, &it1, &it2, status, N, G);
cout << min(it1, it2) << endl;
for(i = 0; i < N; i++) {
if((it1 <= it2 && status[i] == 1) || (it1 > it2 && status[i] == 2)) {
cout << i + 1 << ' ';
}
}
cout << endl;
free(status);
}
int main(int argc, char **argv) {
int T;
cin >> T;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>
#
# ~ JSON Parser ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -Wall
objects/main.o: main.c objects/json.o headers/json.h
gcc -c -o objects/main.o main.c -Wall -I headers
objects/json.o: lib/json.c objects/super_file.o headers/super_file.h objects/stack.o headers/stack.h
gcc -c -o objects/json.o lib/json.c -Wall -I headers
objects/stack.o: lib/stack.c headers/stack.h
gcc -c -o objects/stack.o lib/stack.c -Wall -I headers
objects/super_file.o: lib/super_file.c
gcc -c -o objects/super_file.o lib/super_file.c -Wall
run: Prog
./Prog
clean:
rm Prog objects/*.o
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <cmath>
using namespace std;
int abtoi(char *Str){
int counter, N, i, Aux;
N = strlen(Str);
for(i = N - 1, counter = Aux = 0; i >= 0 && counter < 30; i--, counter++){
if(Str[i] == '1'){
Aux += pow(2, counter);
}else if(Str[i] != '0'){
counter--;
}
}
return Aux;
}
int main(int argc, char **argv){
char Digit[100005], R;
int N = 131071, Aux;
while(scanf("%[^#]%c", Digit, &R) == 2){
Aux = abtoi(Digit);
if(Aux % N == 0){
cout << "YES\n";
}else{
cout << "NO\n";
}
}
return EXIT_SUCCESS;
}<file_sep>#!/usr/bin/env bash
HTTP_EXPOSED_PORT=8080
echo "Este script vai instalar a aplicação em um cluster distribuído."
echo "Antes de começar, por favor note que precisamos do acesso 'root' de todas as máquinas em que os serviços serão instalados!"
echo "Configure o acesso root via SSH. Se você desejar, também pode utilizar uma chave SSH - evitando ter que digitar a senha toda vez que formos nos conectar à máquina."
echo "Instale o Docker e o docker-compose em todas as máquinas e ative seu serviço."
echo "Vamos precisar também das suas chaves de API do Twitter. Se você ainda não tem, crie uma agora."
echo
echo "Vamos começar..."
echo
read -r -p "Onde será instalada a aplicação (entre com o hostname)? " app_host
read -r -p "Onde será instalado o Kafka (entre com o hostname)? " kafka_host
read -r -p "Onde será instalado o banco de dados MySQL (entre com o hostname)? " mysql_host
read -r -p "Qual é sua chave pública da API do Twitter (API Key)? " api_key
read -r -p "Qual é sua chave secreta da API do Twitter (API Secret)? " api_secret
echo
echo "===== Dados da Instalação ====="
echo "A aplicação será instalada em: root@${app_host}"
echo "O Kafka será instalado em: root@${kafka_host}"
echo "O banco de dados MySQL será instalado em: root@${mysql_host}"
echo "A chave pública do Twitter é: ${api_key}"
echo "A chave secreta do Twitter é: ${api_secret}"
echo "==============================="
echo
read -r -p "(se estiver tudo certo, pressione [ENTER] para continuar com a instalação) "
echo
echo "Gerando arquivo de configuração..."
cp config.sample.json config.json
sed -i "s/YOUR_DATABASE_HOSTNAME/${mysql_host}/g" config.json
sed -i "s/YOUR_DATABASE_USERNAME/root/g" config.json
sed -i "s/YOUR_DATABASE_PASSWORD/root/g" config.json
sed -i "s/YOUR_DATABASE_NAME/TwitterAnalyser/g" config.json
sed -i "s/YOUR_TWITTER_API_KEY/${api_key}/g" config.json
sed -i "s/YOUR_TWITTER_API_SECRET/${api_secret}/g" config.json
sed -i "s/YOUR_KAFKA_CONNECTION_STRING/${kafka_host}:29092/g" config.json
echo
echo "Gerando arquivo de implantação do Kafka..."
cp kafka-docker-compose.sample.yaml docker-compose.yaml
sed -i "s/YOUR_KAFKA_CONNECTION_HOST/${kafka_host}/g" docker-compose.yaml
echo
echo "Verificando máquinas..."
ssh root@${kafka_host} "which docker >/dev/null"
if [[ $? -ne 0 ]]
then
echo
echo "Por favor, instale o Docker na máquina ${kafka_host}!"
exit 1
fi
ssh root@${kafka_host} "which docker-compose >/dev/null"
if [[ $? -ne 0 ]]
then
echo
echo "Por favor, instale o 'docker-compose' na máquina ${kafka_host}!"
exit 1
fi
ssh root@${mysql_host} "which docker >/dev/null"
if [[ $? -ne 0 ]]
then
echo
echo "Por favor, instale o Docker na máquina ${mysql_host}!"
exit 1
fi
ssh root@${app_host} "which docker >/dev/null"
if [[ $? -ne 0 ]]
then
echo
echo "Por favor, instale o Docker na máquina ${app_host}!"
exit 1
fi
echo
echo "Implantando Kafka..."
ssh root@${kafka_host} "rm -Rf ~/TwitterAnalyser && mkdir ~/TwitterAnalyser"
scp docker-compose.yaml root@${kafka_host}:~/TwitterAnalyser/.
ssh root@${kafka_host} "cd ~/TwitterAnalyser; docker-compose up -d"
echo
echo "Implantando MySQL..."
ssh root@${mysql_host} "docker run --name TA_mysql -e MYSQL_ROOT_PASSWORD=root -p 3306:3306 -d mysql"
read -r -t 240 -p "Aguardando o MySQL iniciar... (não se preocupe, essa etapa do MySQL realmente vai demorar muito)"
scp database-deploy.sql root@${mysql_host}:/tmp/TA_db-deploy.sql
ssh root@${mysql_host} "docker exec -i TA_mysql mysql -uroot -proot < /tmp/TA_db-deploy.sql"
echo
echo "Implantando aplicação..."
ssh root@${app_host} "rm -Rf ~/TwitterAnalyser && mkdir ~/TwitterAnalyser"
scp -r Code/* root@${app_host}:~/TwitterAnalyser/.
scp config.json root@${app_host}:~/TwitterAnalyser/.
ssh root@${app_host} "cd ~/TwitterAnalyser/ && docker build -t ta_app-image ."
ssh root@${app_host} "docker run --name TA_app -p ${HTTP_EXPOSED_PORT}:8080 -d ta_app-image"
echo
echo "Limpando arquivos temporários..."
rm config.json docker-compose.yaml
echo
echo "Pronto! Sua aplicação está rodando em http://${app_host}:${HTTP_EXPOSED_PORT}/."
<file_sep>#include <stdlib.h>
#include <string.h>
void gswap(void *A, void *B, size_t memsize){
void *Aux;
if(A==NULL || B==NULL || A == B) return;
Aux = (void *) malloc(memsize);
memcpy(Aux, B, memsize);
memcpy(B, A, memsize);
memcpy(A, Aux, memsize);
free(Aux);
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <vector>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
/*
vector< vector<ll> > findSubsets(vector<ll> &set, ll min_size, ll max_size) {
ll N, count, i, j;
vector< vector<ll> > subsets = vector< vector<ll> >();
vector<ll> subset = vector<ll>();
N = set.size();
count = pow(2, N);
// Generate all possible subsets.
for(i = 0; i < count; i++) {
subset.clear();
for(j = 0; j < N; j++) {
if((i & (1 << j)) != 0) {
subset.push_back(set[j]);
}
}
subsets.push_back(subset);
}
// Remove subsets that don't respect minimum and maximum length.
for(auto it = subsets.begin(); it != subsets.end(); it++) {
if((*it).size() >= min_size && (*it).size() <= max_size) {
continue;
}
subsets.erase(it--);
}
return subsets;
}
*/
void recursive_sum(ll position, ll sPosition, ll *totalsum, vector< unordered_map<ll, bool> > &dp, unordered_map<ll, bool> &sums, vector<ll> &set) {
if(sums[sPosition] == false) {
sums[sPosition] = true;
*totalsum += sPosition;
}
if(position < 0 || position >= set.size()) {
return;
}
if(dp[position][sPosition]) {
return;
}
recursive_sum(position + 1, sPosition, totalsum, dp, sums, set);
recursive_sum(position + 1, sPosition + set[position], totalsum, dp, sums, set);
dp[position][sPosition] = true;
}
ll testCase() {
ll N, i, aux, totalsum;
vector<ll> set = vector<ll>();
vector< unordered_map<ll, bool> > dp = vector< unordered_map<ll, bool> >();
unordered_map<ll, bool> sums = unordered_map<ll, bool>();
cin >> N;
for(i = 0; i < N; i++) {
cin >> aux;
set.push_back(aux);
dp.push_back( unordered_map<ll, bool>() );
}
totalsum = 0;
recursive_sum(0, 0, &totalsum, dp, sums, set);
return totalsum;
}
int main(int argc, char **argv) {
ll T;
cin >> T;
for(; T > 0; T--) {
cout << testCase() << endl;
}
return EXIT_SUCCESS;
}
<file_sep># SCC-0215 Organização de Arquivos - 2018.1
Aqui estão todos os trabalhos que implementei em Organização de Arquivos.
<file_sep># Resultados
Imagens geradas pelo algoritmo nos testes.
<file_sep># SCC-0250 Computação Gráfica - 2020.1
Aqui estão todos os exercícios que implementei em CG. É necessário o Jupyter Notebook para abrir.
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int N,i;
double s=0;
scanf(" %d",&N);
for(i=N;i>0;i--){
s+=i/(double)(N-i+1);
}
printf("%.4f",s);
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
typedef struct Country_Score{
char Pais[4];
int N_Ouro;
int N_Prata;
int N_Bronze;
} SCORE;
int main(){
int i,j,N;
SCORE R;
scanf("%d",&N);
SCORE JogosOlimpicos[N];
for(i=0;i<N;i++){
scanf("%s %d %d %d",JogosOlimpicos[i].Pais,&JogosOlimpicos[i].N_Ouro,&JogosOlimpicos[i].N_Prata,&JogosOlimpicos[i].N_Bronze);
getchar();
}
for(i=0;i<N;i++){
for(j=i+1;j<N;j++){
if( (JogosOlimpicos[j].N_Ouro>JogosOlimpicos[i].N_Ouro) || (JogosOlimpicos[j].N_Ouro==JogosOlimpicos[i].N_Ouro && JogosOlimpicos[j].N_Prata>JogosOlimpicos[i].N_Prata) || (JogosOlimpicos[j].N_Ouro==JogosOlimpicos[i].N_Ouro && JogosOlimpicos[j].N_Prata==JogosOlimpicos[i].N_Prata && JogosOlimpicos[j].N_Bronze>JogosOlimpicos[i].N_Bronze)){
R=JogosOlimpicos[j];
JogosOlimpicos[j]=JogosOlimpicos[i];
JogosOlimpicos[i]=R;
}
}
printf("%s %d %d %d\n",JogosOlimpicos[i].Pais,JogosOlimpicos[i].N_Ouro,JogosOlimpicos[i].N_Prata,JogosOlimpicos[i].N_Bronze);
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <insertionsort.h>
#include <bubblesort.h>
#include <mergesort.h>
#include <heapsort.h>
#include <quicksort.h>
/*
* ~ Op. Ordenacao ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
typedef enum { insertion_sort = 0, bubble_sort, merge_sort, heap_sort, quick_sort } SORTING_NAME;
typedef struct {
SORTING_NAME Type;
char Name[101];
int C;
int M;
} SORTING_METHOD;
int compare_integer(void *, void *);
int compare_C(void *, void *);
int compare_M(void *, void *);
int main(int argc, char **argv){
SORTING_METHOD *Algorithms;
int i, O, N, AuxInt;
int *Vector, *AuxVector;
scanf("%d %d", &O, &N);
Algorithms = (SORTING_METHOD *) malloc(sizeof(SORTING_METHOD) * O);
Vector = (int *) malloc(sizeof(int) * N);
AuxVector = (int *) malloc(sizeof(int) * N);
for(i=0; i<O; i++){
scanf("%100s", Algorithms[i].Name);
if(!strcmp(Algorithms[i].Name, "INSERTIONSORT")) Algorithms[i].Type = insertion_sort;
else if(!strcmp(Algorithms[i].Name, "BUBBLESORT")) Algorithms[i].Type = bubble_sort;
else if(!strcmp(Algorithms[i].Name, "MERGESORT")) Algorithms[i].Type = merge_sort;
else if(!strcmp(Algorithms[i].Name, "HEAPSORT")) Algorithms[i].Type = heap_sort;
else Algorithms[i].Type = quick_sort;
}
for(i=0;i<N;i++){
scanf("%d", &AuxInt);
Vector[i] = AuxInt;
}
for(i=0; i<O; i++){
memcpy(AuxVector, Vector, sizeof(int) * N);
switch(Algorithms[i].Type){
case insertion_sort:
insertionsort(AuxVector, sizeof(int), compare_integer, N, &Algorithms[i].C, &Algorithms[i].M);
break;
case bubble_sort:
bubblesort(AuxVector, sizeof(int), compare_integer, N, &Algorithms[i].C, &Algorithms[i].M);
break;
case merge_sort:
mergesort(AuxVector, sizeof(int), compare_integer, N, &Algorithms[i].C, &Algorithms[i].M);
break;
case heap_sort:
heapsort(AuxVector, sizeof(int), compare_integer, N, &Algorithms[i].C, &Algorithms[i].M);
break;
default:
quicksort(AuxVector, sizeof(int), compare_integer, N, &Algorithms[i].C, &Algorithms[i].M);
break;
}
}
mergesort(Algorithms, sizeof(SORTING_METHOD), compare_C, O, &AuxInt, &AuxInt);
printf("Menor C: %s\nMaior C: %s\n", Algorithms[0].Name, Algorithms[O-1].Name);
mergesort(Algorithms, sizeof(SORTING_METHOD), compare_M, O, &AuxInt, &AuxInt);
printf("Menor M: %s\nMaior M: %s\n", Algorithms[0].Name, Algorithms[O-1].Name);
free(Vector);
free(AuxVector);
free(Algorithms);
return EXIT_SUCCESS;
}
int compare_integer(void *PA, void *PB){
int *A=PA, *B=PB;
return (*B)-(*A);
}
int compare_C(void *PA, void *PB){
SORTING_METHOD *A=PA, *B=PB;
return B->C - A->C;
}
int compare_M(void *PA, void *PB){
SORTING_METHOD *A=PA, *B=PB;
return B->M - A->M;
}
<file_sep>#ifndef INSERTION_H_
#define INSERTION_H_
void insertionsort(void *, int, int (*)(void *,void *), int, int *, int *);
#endif
<file_sep>#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <math.h>
using namespace std;
#define ERR 1e-7
double function(long p, long q, long r, long s, long t, long u, double x){
return p*exp(-x) + q*sin(x) + r*cos(x) + s*tan(x) + t*x*x + u;
}
void solve(long p, long q, long r, long s, long t, long u){
double x, max = 1, min = 0;
if(function(p, q, r, s, t, u, max) * function(p, q, r, s, t, u, min) > 0){
printf("No solution\n");
return;
}
while(min + ERR < max){
x = (max + min) / 2.0;
if(function(p, q, r, s, t, u, min) * function(p, q, r, s, t, u, x) <= 0)
max = x;
else
min = x;
}
printf("%.4lf\n", (max + min) / 2.0);
}
int main(int argc, char **argv) {
long p, q, r, s, t, u;
while(scanf("%ld %ld %ld %ld %ld %ld", &p, &q, &r, &s, &t, &u) == 6){
solve(p, q, r, s, t, u);
}
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <iostream>
#include <vector>
#include <queue>
#include <tuple>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
void dijkstra(long long source, long long *distances, vector< vector< pair<long long, long long> > > G) {
long long i, j, N, u, v, w, minV, minI;
N = G.size();
priority_queue< pair<long long, long long> > Q = priority_queue< pair<long long, long long> >();
for(i = 0; i < N; i++) {
distances[i] = LLONG_MAX;
}
distances[source] = 0;
Q.push( make_pair(0, source) );
while(Q.size() > 0) {
u = Q.top().second;
Q.pop();
for(j = 0; j < G[u].size(); j++) {
v = G[u][j].first;
w = G[u][j].second;
if(distances[u] + w < distances[v]) {
distances[v] = distances[u] + w;
Q.push( make_pair(-distances[v], v) );
}
}
}
}
void testCase() {
long long N, M, T, K, P, *distances;
long long i, aux1, aux2, aux3;
bool *is_pine;
cin >> N >> M >> T >> K >> P;
vector< vector< pair<long long, long long> > > G = vector< vector< pair<long long, long long> > >();
is_pine = (bool *) malloc(sizeof(bool) * N);
distances = (long long *) malloc(sizeof(long long) * N);
memset(distances, 0, sizeof(long long) * N);
for(i = 0; i < N; i++) {
is_pine[i] = false;
distances[i] = LLONG_MAX;
G.push_back( vector< pair<long long, long long> >() );
}
for(i = 0; i < P; i++) {
cin >> aux1;
aux1--;
is_pine[aux1] = true;
}
T *= 60;
for(i = 0; i < M; i++) {
cin >> aux1 >> aux2 >> aux3;
aux1--;
aux2--;
aux3 *= 60; // Minutes to Seconds
if(is_pine[aux2]) {
G[aux1].push_back( make_pair(aux2, aux3 + K) );
} else {
G[aux1].push_back( make_pair(aux2, aux3) );
}
/*if(is_pine[aux1]) {
G[aux2].push_back( make_pair(aux1, aux3 + K) );
} else {
G[aux2].push_back( make_pair(aux1, aux3) );
}*/
}
free(is_pine);
dijkstra(0, distances, G);
if(distances[N - 1] <= T && distances[N - 1] != LLONG_MAX) {
cout << distances[N - 1] << endl; // Yeah they don't mention that, but they want this result in seconds...
} else {
cout << -1 << endl;
}
free(distances);
}
int main(int argc, char **argv) {
int T;
T = 1;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
/*
<NAME>
<EMAIL>
*/
typedef enum {false = 0, true, undefinedbool} bool;
typedef struct{
bool **Lab;
char StartPoint;
char EndPoint;
int Width;
int Height;
} lab;
bool CheckLab(lab Obj,int X,int Y){
if(X<0 || Y<0 || X>=Obj.Width || Y>=Obj.Height)
return false;
if(Obj.Lab[Y][X]!=true)
return false;
else if(Obj.Lab[Y][X]==true)
Obj.Lab[Y][X]=undefinedbool;
if(Obj.EndPoint=='N' && Y==0){
return true;
}else if(Obj.EndPoint=='S' && Y==Obj.Height-1){
return true;
}else if(Obj.EndPoint=='L' && X==Obj.Width-1){
return true;
}else if(Obj.EndPoint=='O' && X==0){
return true;
}
if(X+1<Obj.Width && Obj.Lab[Y][X+1]==true && CheckLab(Obj,X+1,Y)==true){
return true;
}else if(Y+1<Obj.Height && Obj.Lab[Y+1][X]==true && CheckLab(Obj,X,Y+1)==true){
return true;
}else if(X-1>=0 && Obj.Lab[Y][X-1]==true && CheckLab(Obj,X-1,Y)==true){
return true;
}else if(Y-1>=0 && Obj.Lab[Y-1][X]==true && CheckLab(Obj,X,Y-1)==true){
return true;
}
if(Obj.Lab[Y][X]==undefinedbool)
Obj.Lab[Y][X]=true;
return false;
}
int main(int argc, char ** argv){
lab Obj;
int i,j,R;
bool Possible=false;
scanf("%c %c %d %d",&Obj.StartPoint,&Obj.EndPoint,&Obj.Height,&Obj.Width);
Obj.Lab=(bool **)malloc(sizeof(bool *)*Obj.Width);
for(i=0;i<Obj.Height;i++){
Obj.Lab[i]=(bool *)malloc(sizeof(bool)*Obj.Width);
for(j=0;j<Obj.Width;j++){
scanf("%d",&R);
Obj.Lab[i][j]=(R==0) ? true : false;
}
}
if(Obj.StartPoint=='N'){
for(i=0;i<Obj.Width;i++)
if(CheckLab(Obj,i,0)==true){
Possible=true;
break;
}
}else if(Obj.StartPoint=='S'){
for(i=0;i<Obj.Width;i++)
if(CheckLab(Obj,i,Obj.Height-1)==true){
Possible=true;
break;
}
}else if(Obj.StartPoint=='L'){
for(i=0;i<Obj.Height;i++)
if(CheckLab(Obj,Obj.Width-1,i)==true){
Possible=true;
break;
}
}else{ // Obj.StartPoint == 'O'
for(i=0;i<Obj.Height;i++)
if(CheckLab(Obj,0,i)==true){
Possible=true;
break;
}
}
if(Possible==true){
printf("Existe saida %c - %c.\n",Obj.StartPoint,Obj.EndPoint);
}else{
printf("Nao existe saida %c - %c.\n",Obj.StartPoint,Obj.EndPoint);
}
for(i=0;i<Obj.Height;i++)
free(Obj.Lab[i]);
free(Obj.Lab);
return EXIT_SUCCESS;
}<file_sep>#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
long recursion(long M, long k, vector< vector<long> > &items, long counter[][256]) {
long i, N, aux;
if(M < 0)
return -1;
else if(!k)
return 0;
counter[M][k] = -1;
N = items[k - 1].size();
for(i = 0; i < N; i++){
if((aux=recursion(M - items[k - 1][i], k - 1, items, counter)) != -1)
if(counter[M][k] < aux + items[k - 1][i])
counter[M][k] = aux + items[k - 1][i];
}
return counter[M][k];
}
int main(int argc, char **argv) {
vector< vector<long> > items;
long i, j, k, N, M, C, K, S;
long counter[256][256];
cin >> N;
for(i = 0; i < N; i++){
cin >> M >> C;
items = vector< vector<long> >(C);
for(j = 0; j < C; j++) {
cin >> K;
items[j] = vector<long>(K);
for(k = 0; k < K; k++){
cin >> items[j][k];
}
}
for(j = 0; j < 256; j++)
for(k = 0; k < 256; k++)
counter[j][k] = -2;
S = recursion(M, C, items, counter);
if(S < 0)
cout << "no solution\n";
else
cout << S << '\n';
}
return EXIT_SUCCESS;
}
<file_sep>package chave;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import console.Console;
public class Chave {
private String serverAddress;
private int serverPort;
/**
* Construtor padrao.
*
* @param serverAddress
* endereco do servidor do gerenciador.
* @param serverPort
* porta do servidor do gerenciador.
*/
public Chave(String serverAddress, int serverPort)
throws IOException, IllegalArgumentException {
String message;
Message m;
this.serverAddress = serverAddress;
this.serverPort = serverPort;
/* Tentar conectar ao gerenciador, mandando minha porta de servidor */
message = new Message("CHAVE", "CONNECT", "").send(
serverAddress, serverPort);
m = new Message(message);
if (!m.getBody().equals("1")) {
throw new IOException("O gerenciador nao permitiu a minha conexao!");
}
}
public void execute() {
Message saida;
Console console = Console.getInstance();
while (true) {
int on = console
.readInt("Deseja alterar o estado da chave?\n\t0 - Desligado\n\t1 - Ligado");
saida = new Message("CHAVE", "", "");
if (on == 1) {
saida.setAction("ON");
} else if (on == 0) {
saida.setAction("OFF");
} else {
System.out.println("Valor incorreto");
continue;
}
try {
saida.send(this.serverAddress, this.serverPort);
} catch (IOException ex) {
System.err
.println("Nao deu certo. :(");
System.err.println(ex);
ex.printStackTrace();
}
}
}
}
<file_sep>import unicodedata
import threading
import random
import string
import time
import sys
import csv
import re
import tweepy
CONSUMER_KEY = 'CONSUMER KEY HERE'
CONSUMER_SECRET = 'CONSUMER SECRET HERE'
ACCESS_KEY = 'ACCESS KEY HERE'
ACCESS_SECRET = 'ACCESS SECRET HERE'
RATE_SLEEP_INTERVAL = 15 * 60 # In seconds (recommended: 15 min = 60*15).
MAX_CONCURRENT_REQUESTS = 20
csvDel = ',' # Delimitador do CSV de saída
Null1 = .0 # % de campos NOME nulos
Null2 = .0 # % de campos IDADE nulos
lista = { }
count = 0
def normalize(text):
text = ''.join(c for c in unicodedata.normalize('NFD', text) if unicodedata.category(c) != 'Mn')
text = text.replace('Ç', 'C').replace('ç', 'c').replace(csvDel, '').strip()
text = re.sub(r'[^a-zA-Z0-9\-\_\s\.]+', ' ', text)
return text
def get_user(account): # Baixar dados e salvar na lista.
global permit, lista
permit.acquire()
tries = 0
while tries < 3:
try:
user = api.get_user(screen_name = account)
user_data = [0, normalize(user.name) if type(user.name) == str else "", str(random.randint(16, 60)), account]
lista.append(user_data)
permit.release()
return
except tweepy.RateLimitError:
time.sleep(RATE_SLEEP_INTERVAL)
except:
tries += 1
permit.release()
if len(sys.argv) != 2:
print("Passe como argumento o nome do arquivo CSV a ser salvo.")
sys.exit(0)
# Autenticar
auth = tweepy.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
api = tweepy.API(auth)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
contas = { }
print("Entre com cada conta de Twitter em uma linha diferente, sem o '@' (use EOF ou CTRL+D para parar):")
while True:
try:
linha = input("> ").strip()
if linha == "":
continue
contas[linha] = True
except EOFError:
break
print()
print("Por favor, aguarde enquanto buscamos os dados na API do Twitter...")
contas = list(contas.keys())
threads = [ ]
lista = [ ]
permit = threading.Semaphore(MAX_CONCURRENT_REQUESTS)
for conta in contas:
threads.append(threading.Thread(target=get_user, args=(conta,)))
for t in threads:
t.start()
for t in threads:
t.join()
for i in range(0, len(lista)):
lista[i][0] = str(i + 1)
Null1 = int(Null1 * len(lista))
Null2 = int(Null2 * len(lista))
random.shuffle(lista)
for i in range(Null1):
lista[i][1] = ""
random.shuffle(lista)
for i in range(Null2):
lista[i][2] = "-1"
random.shuffle(lista)
lista.insert(0, ["idPessoa", "nomePessoa", "idadePessoa", "twitterPessoa"])
with open(sys.argv[1], 'w') as csvfile: # Salvar.
spamwriter = csv.writer(csvfile, delimiter=csvDel, quotechar='', escapechar='\\', quoting=csv.QUOTE_NONE)
spamwriter.writerows(lista)
<file_sep># SSC-0142 Redes de Computadores - 2019.1
Aqui estão todos os trabalhos que implementei em Redes de Computadores.
<file_sep>#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv){
int Soma = 0, Aux1;
scanf("%*d");
while(scanf("%d", &Aux1) == 1){
Soma += Aux1;
}
printf("%d\n", Soma);
return EXIT_SUCCESS;
}<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main(int argc, char **argv){
int i, j, k, T, N, B, K, Sum, InternalSum, Aux;
cin >> T;
for(i = 0; i < T; i++){
cin >> N >> B;
for(j = Sum = 0; j < B; j++) {
cin >> K;
for(k = 0, InternalSum = 1; k < K; k++) {
cin >> Aux;
InternalSum *= Aux;
InternalSum %= N;
}
Sum += InternalSum;
Sum %= N;
}
cout << Sum << '\n';
}
return EXIT_SUCCESS;
}
<file_sep>
/*
* ~ Cartas ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __CARDS_H_
#define __CARDS_H_
#include <list.h>
LIST *ReadCardsFrom(FILE *);
char ProcessCards(FILE *,LIST *);
char DestroyCards(LIST *);
#endif
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <map>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
ll recursive_lcs(char *a, char *b, map< pair<char *, char *>, ll > &dp) {
ll selectCount, passCount;
if(*a == '\0' || *b == '\0') {
return 0;
}
if(dp.count(make_pair(a, b)) > 0) {
return dp[make_pair(a, b)];
}
if(*a == *b) {
dp[make_pair(a, b)] = recursive_lcs(a + 1, b + 1, dp) + 1;
return dp[make_pair(a, b)];
}
passCount = recursive_lcs(a + 1, b, dp);
selectCount = recursive_lcs(a, b + 1, dp);
if(selectCount >= passCount) {
dp[make_pair(a, b)] = selectCount;
} else {
dp[make_pair(a, b)] = passCount;
}
return dp[make_pair(a, b)];
}
ll testCase(char *a, char *b) {
map< pair<char *, char *>, ll > dp = map< pair<char *, char *>, ll >();
return recursive_lcs(a, b, dp);
}
int main(int argc, char **argv) {
char a[1001], b[1001];
while(gets(a)) {
gets(b);
cout << testCase(a, b) << endl;
}
return EXIT_SUCCESS;
}<file_sep>#ifndef HEAPSORT_H_
#define HEAPSORT_H_
void heapsort(void *, int, int (*)(void *,void *), int, int *, int *);
#endif
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <register.h>
#include <consts.h>
typedef struct CAMPO_PAR_T__ {
char fieldName[100];
char fieldValue[100];
char newFieldName[100];
char newFieldValue[100];
struct CAMPO_PAR_T__ *next;
} CAMPO_PAR_T;
typedef struct BUSCA_CAMPO_T__ {
CAMPO_PAR_T *first;
char vector;
int n;
} BUSCA_CAMPO_T;
int BC_searchMarked(CAMPO_PAR_T *campos, int nCampos, int start, REGISTRO_T *reg) {
int i;
for(i = start; i < nCampos; i++) {
if(strcmp(campos[i].fieldName, "RRN") == 0) {
if(atoi(campos[i].fieldValue) == reg->RRN) {
return i;
}
} else if(strcmp(campos[i].fieldName, "estadoOrigem") == 0) {
if(strcmp(campos[i].fieldValue, reg->estadoOrigem) == 0) {
return i;
}
} else if(strcmp(campos[i].fieldName, "estadoDestino") == 0) {
if(strcmp(campos[i].fieldValue, reg->estadoDestino) == 0) {
return i;
}
} else if(strcmp(campos[i].fieldName, "distancia") == 0) {
if(atoi(campos[i].fieldValue) == reg->distancia) {
return i;
}
} else if(strcmp(campos[i].fieldName, "cidadeOrigem") == 0) {
if(strcmp(campos[i].fieldValue, reg->cidadeOrigem) == 0) {
return i;
}
} else if(strcmp(campos[i].fieldName, "cidadeDestino") == 0) {
if(strcmp(campos[i].fieldValue, reg->cidadeDestino) == 0) {
return i;
}
} else if(strcmp(campos[i].fieldName, "tempoViagem") == 0) {
if(strcmp(campos[i].fieldValue, reg->tempoViagem) == 0) {
return i;
}
}
}
return -1;
}
BUSCA_CAMPO_T *BC_new() {
BUSCA_CAMPO_T *aux;
aux = (BUSCA_CAMPO_T *) malloc(sizeof(BUSCA_CAMPO_T));
if(aux == NULL) {
return NULL;
}
aux->n = 0;
aux->vector = 0;
aux->first = NULL;
return aux;
}
int BC_asVector(BUSCA_CAMPO_T *BC) {
CAMPO_PAR_T *newVector, *aux;
int i;
if(BC == NULL) {
return 0;
}
if(BC->vector == 1) {
return 1;
}
if(BC->n < 1) {
BC->first = NULL;
BC->vector = 1;
return 1;
}
newVector = (CAMPO_PAR_T *) malloc(sizeof(CAMPO_PAR_T) * BC->n);
if(newVector == NULL) {
return 0;
}
i = BC->n - 1;
while(BC->first != NULL) {
aux = BC->first;
memcpy(&newVector[i--], aux, sizeof(CAMPO_PAR_T));
BC->first = BC->first->next;
free(aux);
}
BC->first = newVector;
BC->vector = 1;
return 1;
}
int BC_asList(BUSCA_CAMPO_T *BC) {
CAMPO_PAR_T *oldVector, *aux;
char success;
int i;
if(BC == NULL) {
return 0;
}
if(BC->vector != 1) {
return 1;
}
oldVector = BC->first;
BC->first = NULL;
success = 1;
for(i = 0; i < BC->n; i++) {
aux = (CAMPO_PAR_T *) malloc(sizeof(CAMPO_PAR_T));
if(aux == NULL) {
success = 0;
continue;
}
memcpy(aux, &oldVector[i], sizeof(CAMPO_PAR_T));
aux->next = BC->first;
BC->first = aux;
}
free(oldVector);
BC->vector = 0;
return success;
}
int BC_insertUpdate(char *searchField, char *searchValue, char *modifyField, char *modifyValue, BUSCA_CAMPO_T *BC) {
CAMPO_PAR_T *aux;
if(searchField == NULL || searchValue == NULL || BC == NULL) {
return 0;
}
if(BC_asList(BC) != 1) {
return 0;
}
aux = (CAMPO_PAR_T *) malloc(sizeof(CAMPO_PAR_T));
if(aux == NULL) {
return 0;
}
strcpy(aux->fieldName, searchField);
strcpy(aux->fieldValue, searchValue);
if(modifyField != NULL) {
strcpy(aux->newFieldName, modifyField);
if(modifyValue != NULL) {
strcpy(aux->newFieldValue, modifyValue);
} else {
aux->newFieldValue[0] = '\0';
}
} else {
aux->newFieldName[0] = '\0';
aux->newFieldValue[0] = '\0';
}
aux->next = BC->first;
BC->first = aux;
BC->n++;
return 1;
}
int BC_insertSearch(char *searchField, char *searchValue, BUSCA_CAMPO_T *BC) {
CAMPO_PAR_T *aux;
if(searchField == NULL || searchValue == NULL || BC == NULL) {
return 0;
}
return BC_insertUpdate(searchField, searchValue, NULL, NULL, BC);
}
int BC_search(REGISTRO_T *reg, BUSCA_CAMPO_T *BC) {
if(reg == NULL || BC == NULL || BC_asVector(BC) != 1) {
return -1;
}
if(BC_searchMarked(BC->first, BC->n, 0, reg) >= 0) {
return 1;
}
return 0;
}
int BC_searchUpdate(REGISTRO_T *reg, FILE *stream, BUSCA_CAMPO_T *BC) {
char modified;
int pos;
if(reg == NULL || BC == NULL || BC_asVector(BC) != 1) {
return -1;
}
modified = 0;
pos = 0;
while((pos = BC_searchMarked(BC->first, BC->n, pos, reg)) >= 0) {
if(BC->first[pos].newFieldName[0] == '\0') {
pos++;
continue;
}
if(strcmp(BC->first[pos].newFieldName, "removido") == 0) { // Remover
reg->removido = R_TRUE;
} else if(strcmp(BC->first[pos].newFieldName, "estadoOrigem") == 0) {
strcpy(reg->estadoOrigem, BC->first[pos].newFieldValue);
} else if(strcmp(BC->first[pos].newFieldName, "estadoDestino") == 0) {
strcpy(reg->estadoDestino, BC->first[pos].newFieldValue);
} else if(strcmp(BC->first[pos].newFieldName, "distancia") == 0) {
reg->distancia = atoi(BC->first[pos].newFieldValue);
} else if(strcmp(BC->first[pos].newFieldName, "cidadeOrigem") == 0) {
strcpy(reg->cidadeOrigem, BC->first[pos].newFieldValue);
} else if(strcmp(BC->first[pos].newFieldName, "cidadeDestino") == 0) {
strcpy(reg->cidadeDestino, BC->first[pos].newFieldValue);
} else if(strcmp(BC->first[pos].newFieldName, "tempoViagem") == 0) {
strcpy(reg->tempoViagem, BC->first[pos].newFieldValue);
}
R_reescreverRegistro(reg, stream);
modified = 1;
pos++;
}
return modified;
}
void BC_destroy(BUSCA_CAMPO_T *BC) {
if(BC == NULL) {
return;
}
BC_asVector(BC);
free(BC->first);
free(BC);
}
<file_sep>#include <stdlib.h>
#include <iostream>
#include <map>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
void testCase() {
ll i, N, aux;
bool won;
cin >> N;
map<ll, ll> A = map<ll, ll>();
for(i = 0; i < N; i++) {
cin >> aux;
A[aux]++;
}
won = false;
for(auto& it: A) {
if(it.second % 2 == 0) {
continue;
}
won = true;
break;
}
if(won) {
cout << "Conan";
} else {
cout << "Agasa";
}
cout << endl;
}
int main(int argc, char **argv) {
ll T;
T = 1;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
Matheus
<EMAIL>
*/
int main(){
int k,n;
unsigned char byte_str[8],boys=0,girls=0;
scanf("%d",&k); // Ler entrada (k)
scanf("%d",&n); // Ler entrada (n)
if( !((k>=0) && (k<=3) && (n>=0) && (n<=1000000000)) ){ // Verificar entradas
printf("Invalid input\n");
return EXIT_FAILURE;
}
n=n>>8*k; // Shiftar o inteiro para o byte desejado (k)
// *** Agora vamos verificar o primeiro bit
if(n%2){ // Eh uma menina, porque esse bit eh '1'
byte_str[0]='1';
girls++;
}else{ // Eh um menino, porque esse bit eh '0'
byte_str[0]='0';
boys++;
}
n=n>>1; // Shiftar para o próximo bit
// *** Agora vamos verificar o segundo bit
if(n%2){
byte_str[1]='1';
girls++;
}else{
byte_str[1]='0';
boys++;
}
n=n>>1;
// *** Agora vamos verificar o terceiro bit
if(n%2){
byte_str[2]='1';
girls++;
}else{
byte_str[2]='0';
boys++;
}
n=n>>1;
// *** Agora vamos verificar o quarto bit
if(n%2){
byte_str[3]='1';
girls++;
}else{
byte_str[3]='0';
boys++;
}
n=n>>1;
// *** Agora vamos verificar o quinto bit
if(n%2){
byte_str[4]='1';
girls++;
}else{
byte_str[4]='0';
boys++;
}
n=n>>1;
// *** Agora vamos verificar o sexto bit
if(n%2){
byte_str[5]='1';
girls++;
}else{
byte_str[5]='0';
boys++;
}
n=n>>1;
// *** Agora vamos verificar o setimo bit
if(n%2){
byte_str[6]='1';
girls++;
}else{
byte_str[6]='0';
boys++;
}
n=n>>1;
// *** Agora vamos verificar o oitavo bit
if(n%2){
byte_str[7]='1';
girls++;
}else{
byte_str[7]='0';
boys++;
}
n=n>>1;
printf("%s\n",byte_str); // Imprimir a sequencia binaria reversa
printf("%d\n",boys); // Imprimir o numero de meninos (0s) na sequencia binaria
printf("%d\n",girls); // Imprimir o numero de meninas (1s) na sequencia binaria
return EXIT_SUCCESS;
}
<file_sep>
#ifndef CONSTS_H_
#define CONSTS_H_
#define LIXO '$'
#define R_REMOVIDO '0'
#define R_NAO_REMOVIDO '1'
#define STATUS_CONSISTENTE '1'
#define STATUS_INCONSISTENTE '0'
#endif<file_sep>
#
# ~ LABIRINTO ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clear -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: all
rm *.o
Prog: main.o
gcc -o Prog *.o -Wall -lm
main.o: main.c labyrinth.o labyrinth.h
gcc -c -o main.o main.c -Wall
labyrinth.o: labyrinth.c stack.o stack.h
gcc -c -o labyrinth.o labyrinth.c -Wall -I.
stack.o: stack.c stack.h
gcc -c -o stack.o stack.c -Wall
run: Prog
./Prog
clear:
rm Prog *.o
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int i,letter_count=0,int_count=0;
char str[2000];
fgets(str,sizeof(str),stdin);
for(i=0;i<strlen(str);i++){
if( ((str[i]>=65) && (str[i]<=90)) || ((str[i]>=97) && (str[i]<=122)) ){
letter_count++;
}else if((str[i]>=48) && (str[i]<=57)){
int_count++;
}
}
printf("%d\n%d",letter_count,int_count);
return EXIT_SUCCESS;
}<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
<NAME>
<EMAIL>
*/
#define ADDITION_NUMBER 5
int main(){
int i,R=0,N=0,S=1;
char c,*Str=(char *)malloc(sizeof(char)*S);
do{
c=getchar();
Str[N++]=c;
if(N>=S){
S+=ADDITION_NUMBER;
Str=(char *)realloc(Str,sizeof(char)*S);
}
} while(c>=48 && c<=57);
Str[N-1]='\0';
for(i=0;i<strlen(Str);i++){
R+=Str[i]-48;
}
printf("%d",R);
free(Str);
return EXIT_SUCCESS;
}
<file_sep>
/*
* ~ Trabalho Prático: Parte 2 ~
*
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef CABECALHO_H_
#define CABECALHO_H_
#include <stdio.h>
#define TAMANHO_CABECALHO 5
#define TAMANHO_CABECALHO_INDICE 13
typedef struct {
char status;
int topoPilha;
} CAB;
typedef struct {
char status;
int noRaiz;
int altura;
int ultimoRRN;
} CAB_INDICE;
CAB cab; /* Cabeçalho do arquivo de dados */
CAB_INDICE cabIndice; /* Cabeçalho do arquivo de índice da árvore-B */
void lerCabecalho(FILE *);
void escreverCabecalho(FILE *);
void lerCabecalhoIndice(FILE *);
void escreverCabecalhoIndice(FILE *);
#endif
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <indiceCidades.h>
#include <escreverTela.h>
#include <buscaCampos.h>
#include <graph.h>
#include <register.h>
#include <consts.h>
int f1_csvToBin(char *csvPath, char *binPath) {
FILE *csvStream, *binStream;
INDEX_T *indice;
CABECALHO_T cab;
REGISTRO_T aux;
indice = I_new();
if(indice == NULL) {
printf("Falha no carregamento do arquivo.\n");
return 0;
}
if((csvStream = fopen(csvPath, "r")) == NULL) {
I_destroy(indice);
printf("Falha no carregamento do arquivo.\n");
return 0;
}
if((binStream = fopen(binPath, "wb")) == NULL) {
I_destroy(indice);
fclose(csvStream);
printf("Falha no carregamento do arquivo.\n");
return 0;
}
cab.status = R_FALSE;
cab.numeroArestas = 0;
cab.numeroVertices = 0;
cab.dataUltimaCompactacao[0] = '\0';
R_escreverCabecalho(&cab, binStream);
aux.removido = R_FALSE;
fscanf(csvStream, "%*[^\r\n]%*c"); // Ignore first line from CSV
while(fscanf(csvStream, "%[^,]%*c%[^,]%*c%d%*c%[^,]%*c%[^,]%*c", aux.estadoOrigem, aux.estadoDestino, &aux.distancia, aux.cidadeOrigem, aux.cidadeDestino) == 5) {
if(fscanf(csvStream, "%[^\r\n]", aux.tempoViagem) != 1) {
aux.tempoViagem[0] = '\0';
}
fscanf(csvStream, "%*c");
trim(aux.estadoOrigem); // If there's any \n or \r left here, we remove it.
if(strlen(aux.cidadeOrigem) + strlen(aux.cidadeDestino) + strlen(aux.tempoViagem) > TAM_REGISTRO_DADOS_VARIAVEIS) {
printf("Ignorando registro %d (%s %s %d %s %s %s) porque os campos variáveis ultrapassam o limite máximo.\n", cab.numeroArestas + 1, aux.estadoOrigem, aux.estadoDestino, aux.distancia, aux.cidadeOrigem, aux.cidadeDestino, aux.tempoViagem);
continue;
}
R_escreverRegistro(&aux, binStream);
I_insert(aux.cidadeOrigem, indice);
I_insert(aux.cidadeDestino, indice);
cab.numeroArestas++;
}
cab.status = R_TRUE;
cab.numeroVertices = I_keyCount(indice);
R_escreverCabecalho(&cab, binStream);
I_destroy(indice);
fclose(csvStream);
fclose(binStream);
binarioNaTela1(binPath);
return 1;
}
int f2_listAll(char *binPath) {
FILE *binStream;
CABECALHO_T cab;
REGISTRO_T aux;
char found;
if((binStream = fopen(binPath, "rb")) == NULL) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_lerCabecalho(&cab, binStream);
if(cab.status != R_TRUE) {
fclose(binStream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
found = 0;
while(R_lerRegistro(&aux, binStream) == 1) {
if(aux.removido != R_FALSE) {
continue;
}
printf("%d %s %s %d %s %s", aux.RRN, aux.estadoOrigem, aux.estadoDestino, aux.distancia, aux.cidadeOrigem, aux.cidadeDestino);
if(aux.tempoViagem[0] != '\0') {
printf(" %s", aux.tempoViagem);
}
printf("\n");
found = 1;
}
if(found == 0) {
printf("Registro inexistente.\n");
}
fclose(binStream);
return 1;
}
int f3_listSearch(char *binPath) {
char nomeCampo[100], valorCampo[100];
BUSCA_CAMPO_T *BC;
FILE *binStream;
CABECALHO_T cab;
REGISTRO_T aux;
char found;
BC = BC_new();
if(BC == NULL) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
if((binStream = fopen(binPath, "rb")) == NULL) {
BC_destroy(BC);
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_lerCabecalho(&cab, binStream);
if(cab.status != R_TRUE) {
BC_destroy(BC);
fclose(binStream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
while(scanf("%s", nomeCampo) == 1) {
scan_quote_string(valorCampo);
BC_insertSearch(nomeCampo, valorCampo, BC);
}
found = 0;
while(R_lerRegistro(&aux, binStream) == 1) {
if(aux.removido != R_FALSE) {
continue;
}
if(BC_search(&aux, BC) != 1) {
continue;
}
printf("%d %s %s %d %s %s", aux.RRN, aux.estadoOrigem, aux.estadoDestino, aux.distancia, aux.cidadeOrigem, aux.cidadeDestino);
if(aux.tempoViagem[0] != '\0') {
printf(" %s", aux.tempoViagem);
}
printf("\n");
found = 1;
}
if(found == 0) {
printf("Registro inexistente.\n");
}
BC_destroy(BC);
fclose(binStream);
return 1;
}
int f4_listRRN(int RRN, char *binPath) {
FILE *binStream;
CABECALHO_T cab;
REGISTRO_T aux;
char found;
if((binStream = fopen(binPath, "rb")) == NULL) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_lerCabecalho(&cab, binStream);
if(cab.status != R_TRUE) {
fclose(binStream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
fseek(binStream, TAM_REGISTRO_CABECALHO + (TAM_REGISTRO_DADOS * RRN), SEEK_SET);
if(R_lerRegistro(&aux, binStream) == 1 && aux.removido == R_FALSE) {
printf("%d %s %s %d %s %s", aux.RRN, aux.estadoOrigem, aux.estadoDestino, aux.distancia, aux.cidadeOrigem, aux.cidadeDestino);
if(aux.tempoViagem[0] != '\0') {
printf(" %s", aux.tempoViagem);
}
printf("\n");
} else {
printf("Registro inexistente.\n");
}
fclose(binStream);
return 1;
}
int f5_remove(char *binPath) {
char nomeCampo[100], valorCampo[100];
BUSCA_CAMPO_T *BC;
FILE *binStream;
INDEX_T *indice;
CABECALHO_T cab;
REGISTRO_T aux;
indice = I_new();
BC = BC_new();
if(indice == NULL || BC == NULL || (binStream = fopen(binPath, "rb+")) == NULL) {
I_destroy(indice);
BC_destroy(BC);
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_lerCabecalho(&cab, binStream);
if(cab.status != R_TRUE) {
I_destroy(indice);
BC_destroy(BC);
fclose(binStream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
while(scanf("%s", nomeCampo) == 1) {
scan_quote_string(valorCampo);
BC_insertUpdate(nomeCampo, valorCampo, "removido", NULL, BC); // Uses "update" to remove the register.
}
cab.status = R_FALSE;
R_escreverCabecalho(&cab, binStream);
while(R_lerRegistro(&aux, binStream) == 1) {
if(aux.removido != R_FALSE) {
continue;
}
I_insert(aux.cidadeOrigem, indice);
I_insert(aux.cidadeDestino, indice);
if(BC_searchUpdate(&aux, binStream, BC) != 1) {
continue;
}
I_remove(aux.cidadeOrigem, indice);
I_remove(aux.cidadeDestino, indice);
cab.numeroArestas--;
}
cab.status = R_TRUE;
cab.numeroVertices = I_keyCount(indice);
R_escreverCabecalho(&cab, binStream);
I_destroy(indice);
BC_destroy(BC);
fclose(binStream);
binarioNaTela1(binPath);
return 1;
}
int f6_insert(char *binPath) {
char nomeCampo[100], valorCampo[100];
FILE *binStream;
INDEX_T *indice;
CABECALHO_T cab;
REGISTRO_T aux;
indice = I_new();
if(indice == NULL || (binStream = fopen(binPath, "rb+")) == NULL) {
I_destroy(indice);
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_lerCabecalho(&cab, binStream);
if(cab.status != R_TRUE) {
I_destroy(indice);
fclose(binStream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
cab.status = R_FALSE;
R_escreverCabecalho(&cab, binStream);
while(R_lerRegistro(&aux, binStream) == 1) {
if(aux.removido != R_FALSE) {
continue;
}
I_insert(aux.cidadeOrigem, indice);
I_insert(aux.cidadeDestino, indice);
}
//fseek(binStream, 0, SEEK_END); // Go to end of file.
aux.removido = R_FALSE;
while(scanf("%s %s %d", aux.estadoOrigem, aux.estadoDestino, &aux.distancia) == 3) {
scan_quote_string(aux.cidadeOrigem);
scan_quote_string(aux.cidadeDestino);
scan_quote_string(aux.tempoViagem);
I_insert(aux.cidadeOrigem, indice);
I_insert(aux.cidadeDestino, indice);
R_escreverRegistro(&aux, binStream);
cab.numeroArestas++;
}
cab.status = R_TRUE;
cab.numeroVertices = I_keyCount(indice);
R_escreverCabecalho(&cab, binStream);
I_destroy(indice);
fclose(binStream);
binarioNaTela1(binPath);
return 1;
}
int f7_update(char *binPath) {
char buscaCampoRRN[100], nomeCampo[100], valorCampo[100];
BUSCA_CAMPO_T *BC;
FILE *binStream;
INDEX_T *indice;
CABECALHO_T cab;
REGISTRO_T aux;
indice = I_new();
BC = BC_new();
if(indice == NULL || BC == NULL || (binStream = fopen(binPath, "rb+")) == NULL) {
I_destroy(indice);
BC_destroy(BC);
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_lerCabecalho(&cab, binStream);
if(cab.status != R_TRUE) {
I_destroy(indice);
BC_destroy(BC);
fclose(binStream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
while(scanf("%s %s", buscaCampoRRN, nomeCampo) == 2) {
scan_quote_string(valorCampo);
BC_insertUpdate("RRN", buscaCampoRRN, nomeCampo, valorCampo, BC); // Uses "update" to remove the register.
}
cab.status = R_FALSE;
R_escreverCabecalho(&cab, binStream);
while(R_lerRegistro(&aux, binStream) == 1) {
if(aux.removido != R_FALSE) {
continue;
}
if(BC_searchUpdate(&aux, binStream, BC) != 1) {
I_insert(aux.cidadeOrigem, indice);
I_insert(aux.cidadeDestino, indice);
continue;
}
I_insert(aux.cidadeOrigem, indice);
I_insert(aux.cidadeDestino, indice);
}
cab.status = R_TRUE;
cab.numeroVertices = I_keyCount(indice);
R_escreverCabecalho(&cab, binStream);
I_destroy(indice);
BC_destroy(BC);
fclose(binStream);
binarioNaTela1(binPath);
return 1;
}
int f8_compactar(char *oldBinPath, char *newBinPath) {
FILE *oldBinStream, *newBinStream;
INDEX_T *indice;
CABECALHO_T cab;
REGISTRO_T aux;
indice = I_new();
if(indice == NULL) {
printf("Falha no carregamento do arquivo.\n");
return 0;
}
if((oldBinStream = fopen(oldBinPath, "rb")) == NULL) {
I_destroy(indice);
printf("Falha no carregamento do arquivo.\n");
return 0;
}
R_lerCabecalho(&cab, oldBinStream);
if(cab.status != R_TRUE) {
I_destroy(indice);
fclose(oldBinStream);
printf("Falha no carregamento do arquivo.\n");
return 0;
}
if((newBinStream = fopen(newBinPath, "wb")) == NULL) {
I_destroy(indice);
fclose(oldBinStream);
printf("Falha no carregamento do arquivo.\n");
return 0;
}
cab.status = R_FALSE;
cab.numeroArestas = 0;
cab.numeroVertices = 0;
strcpy(cab.dataUltimaCompactacao, R_DATA_COMPACTACAO);
R_escreverCabecalho(&cab, newBinStream);
while(R_lerRegistro(&aux, oldBinStream) == 1) {
if(aux.removido != R_FALSE) {
continue;
}
R_escreverRegistro(&aux, newBinStream);
I_insert(aux.cidadeOrigem, indice);
I_insert(aux.cidadeDestino, indice);
cab.numeroArestas++;
}
cab.status = R_TRUE;
cab.numeroVertices = I_keyCount(indice);
R_escreverCabecalho(&cab, newBinStream);
I_destroy(indice);
fclose(oldBinStream);
fclose(newBinStream);
binarioNaTela1(newBinPath);
return 1;
}
void f9_printAresta(int vertice, int distancia, char *tempoViagem, INDEX_T *ind) {
if(tempoViagem == NULL || tempoViagem[0] == '\0') {
printf(" %s %d", I_getKeyFor(vertice, ind), distancia);
} else {
printf(" %s %d %s", I_getKeyFor(vertice, ind), distancia, tempoViagem);
}
}
int f9_gerarGrafo(char *binPath) {
FILE *binStream;
INDEX_T *indice;
CABECALHO_T cab;
GRAPH_T *grafo;
REGISTRO_T aux;
long i;
indice = I_new();
if(indice == NULL) {
printf("Falha no carregamento do arquivo.\n");
return 0;
}
if((binStream = fopen(binPath, "rb")) == NULL) {
I_destroy(indice);
printf("Falha no carregamento do arquivo.\n");
return 0;
}
R_lerCabecalho(&cab, binStream);
if(cab.status != R_TRUE) {
I_destroy(indice);
fclose(binStream);
printf("Falha no carregamento do arquivo.\n");
return 0;
}
while(R_lerRegistro(&aux, binStream) == 1) {
if(aux.removido != R_FALSE) {
continue;
}
strcat(aux.cidadeOrigem, " ");
strcat(aux.cidadeDestino, " ");
strcat(aux.cidadeOrigem, aux.estadoOrigem);
strcat(aux.cidadeDestino, aux.estadoDestino);
I_insert(aux.cidadeOrigem, indice);
I_insert(aux.cidadeDestino, indice);
}
grafo = G_new(cab.numeroVertices);
fseek(binStream, TAM_REGISTRO_CABECALHO, SEEK_SET);
while(R_lerRegistro(&aux, binStream) == 1) {
if(aux.removido != R_FALSE) {
continue;
}
strcat(aux.cidadeOrigem, " ");
strcat(aux.cidadeDestino, " ");
strcat(aux.cidadeOrigem, aux.estadoOrigem);
strcat(aux.cidadeDestino, aux.estadoDestino);
G_addEdgeInfo(I_getIndexFor(aux.cidadeOrigem, indice), I_getIndexFor(aux.cidadeDestino, indice), aux.distancia, aux.tempoViagem, grafo);
G_addEdgeInfo(I_getIndexFor(aux.cidadeDestino, indice), I_getIndexFor(aux.cidadeOrigem, indice), aux.distancia, aux.tempoViagem, grafo); // Não-direcionado
}
for(i = 0; i < cab.numeroVertices; i++) {
printf("%s", I_getKeyFor(i, indice));
G_printEdgesFor(i, (void *(*)(int, int, char *, void *)) &f9_printAresta, indice, grafo);
printf("\n");
}
I_destroy(indice);
G_destroy(grafo);
fclose(binStream);
return 1;
}
int f10_caminhoMaisCurto(char *binPath) {
char city[INDEX_KEY_MAX_LEN];
FILE *binStream;
INDEX_T *indice;
CABECALHO_T cab;
GRAPH_T *grafo;
REGISTRO_T aux;
long i, vertex;
int *pre, *dis;
scanf("%s", city);
scan_quote_string(city);
indice = I_new();
if(indice == NULL) {
printf("Falha no carregamento do arquivo.\n");
return 0;
}
if((binStream = fopen(binPath, "rb")) == NULL) {
I_destroy(indice);
printf("Falha no carregamento do arquivo.\n");
return 0;
}
R_lerCabecalho(&cab, binStream);
if(cab.status != R_TRUE) {
I_destroy(indice);
fclose(binStream);
printf("Falha no carregamento do arquivo.\n");
return 0;
}
while(R_lerRegistro(&aux, binStream) == 1) {
if(aux.removido != R_FALSE) {
continue;
}
strcat(aux.cidadeOrigem, " ");
strcat(aux.cidadeDestino, " ");
strcat(aux.cidadeOrigem, aux.estadoOrigem);
strcat(aux.cidadeDestino, aux.estadoDestino);
I_insert(aux.cidadeOrigem, indice);
I_insert(aux.cidadeDestino, indice);
}
grafo = G_new(cab.numeroVertices);
fseek(binStream, TAM_REGISTRO_CABECALHO, SEEK_SET);
while(R_lerRegistro(&aux, binStream) == 1) {
if(aux.removido != R_FALSE) {
continue;
}
strcat(aux.cidadeOrigem, " ");
strcat(aux.cidadeDestino, " ");
strcat(aux.cidadeOrigem, aux.estadoOrigem);
strcat(aux.cidadeDestino, aux.estadoDestino);
G_addEdgeInfo(I_getIndexFor(aux.cidadeOrigem, indice), I_getIndexFor(aux.cidadeDestino, indice), aux.distancia, aux.tempoViagem, grafo);
G_addEdgeInfo(I_getIndexFor(aux.cidadeDestino, indice), I_getIndexFor(aux.cidadeOrigem, indice), aux.distancia, aux.tempoViagem, grafo); // Não-direcionado
}
I_fillRestOfKey(city, indice);
vertex = I_getIndexFor(city, indice);
if(vertex < 0) {
printf("Cidade inexistente.\n");
I_destroy(indice);
G_destroy(grafo);
fclose(binStream);
return 0;
}
G_dijkstra(vertex, &pre, &dis, NULL, grafo);
for(i = 0; i < cab.numeroVertices; i++) {
if(pre[i] < 0 || i == vertex) {
continue;
}
printf("%s %s %d %s\n", city, I_getKeyFor(i, indice), dis[i], I_getKeyFor(pre[i], indice));
}
I_destroy(indice);
G_destroy(grafo);
fclose(binStream);
return 1;
}
int f11_arvoreGeradoraMinima(char *binPath) {
char city[INDEX_KEY_MAX_LEN];
long i, j, vertex;
FILE *binStream;
INDEX_T *indice;
CABECALHO_T cab;
GRAPH_T *grafo;
REGISTRO_T aux;
int *pre, *dis;
scanf("%s", city);
scan_quote_string(city);
indice = I_new();
if(indice == NULL) {
printf("Falha no carregamento do arquivo.\n");
return 0;
}
if((binStream = fopen(binPath, "rb")) == NULL) {
I_destroy(indice);
printf("Falha no carregamento do arquivo.\n");
return 0;
}
R_lerCabecalho(&cab, binStream);
if(cab.status != R_TRUE) {
I_destroy(indice);
fclose(binStream);
printf("Falha no carregamento do arquivo.\n");
return 0;
}
while(R_lerRegistro(&aux, binStream) == 1) {
if(aux.removido != R_FALSE) {
continue;
}
strcat(aux.cidadeOrigem, " ");
strcat(aux.cidadeDestino, " ");
strcat(aux.cidadeOrigem, aux.estadoOrigem);
strcat(aux.cidadeDestino, aux.estadoDestino);
I_insert(aux.cidadeOrigem, indice);
I_insert(aux.cidadeDestino, indice);
}
grafo = G_new(cab.numeroVertices);
fseek(binStream, TAM_REGISTRO_CABECALHO, SEEK_SET);
while(R_lerRegistro(&aux, binStream) == 1) {
if(aux.removido != R_FALSE) {
continue;
}
strcat(aux.cidadeOrigem, " ");
strcat(aux.cidadeDestino, " ");
strcat(aux.cidadeOrigem, aux.estadoOrigem);
strcat(aux.cidadeDestino, aux.estadoDestino);
G_addEdgeInfo(I_getIndexFor(aux.cidadeOrigem, indice), I_getIndexFor(aux.cidadeDestino, indice), aux.distancia, aux.tempoViagem, grafo);
G_addEdgeInfo(I_getIndexFor(aux.cidadeDestino, indice), I_getIndexFor(aux.cidadeOrigem, indice), aux.distancia, aux.tempoViagem, grafo); // Não-direcionado
}
I_fillRestOfKey(city, indice);
vertex = I_getIndexFor(city, indice);
if(vertex < 0) {
printf("Cidade inexistente.\n");
I_destroy(indice);
G_destroy(grafo);
fclose(binStream);
return 0;
}
G_prim(vertex, &pre, &dis, NULL, grafo);
for(i = 0; i < cab.numeroVertices; i++) {
printf("%s", I_getKeyFor(i, indice));
for(j = 0; j < cab.numeroVertices; j++) {
if(pre[j] == i) {
if(G_getInfo(i, j, grafo) == NULL || G_getInfo(i, j, grafo)[0] == '\0') {
printf(" %s %d", I_getKeyFor(j, indice), dis[j]);
} else {
printf(" %s %d %s", I_getKeyFor(j, indice), dis[j], G_getInfo(i, j, grafo));
}
}
}
printf("\n");
}
I_destroy(indice);
G_destroy(grafo);
fclose(binStream);
return 1;
}
int fx_barraR(char binary, char *filePath) {
char *buffer, fileOpening[10];
size_t i, streamLen;
FILE *stream;
if(binary == R_FALSE || binary == 0) {
strcpy(fileOpening, "r");
} else {
strcpy(fileOpening, "rb");
}
if((stream = fopen(filePath, fileOpening)) == NULL) {
printf("Falha no carregamento do arquivo.\n");
return 0;
}
fseek(stream, 0, SEEK_END);
streamLen = ftell(stream);
buffer = (char *) malloc(sizeof(char) * streamLen);
fseek(stream, 0, SEEK_SET);
fread(buffer, sizeof(char) * streamLen, 1, stream);
fclose(stream);
for(i = 0; i < streamLen; i++) {
if(buffer[i] == '\r') {
printf("Existe barra R ('\\r') nesse arquivo! Verifique a posição 0x%zx do arquivo.\n", i);
return 1;
}
}
printf("Não existe nenhum barra R ('\\r') nesse arquivo.\n");
return 1;
}
int fx_invalidate(char *filePath) {
char *buffer, aux;
FILE *stream;
if((stream = fopen(filePath, "rb+")) == NULL) {
printf("Falha no carregamento do arquivo.\n");
return 0;
}
aux = R_FALSE;
fseek(stream, 0, SEEK_SET);
fwrite(&aux, sizeof(char), 1, stream);
fclose(stream);
printf("Arquivo invalidado com sucesso.\n");
return 1;
}
int fx_validate(char *filePath) {
char *buffer, aux;
FILE *stream;
if((stream = fopen(filePath, "rb+")) == NULL) {
printf("Falha no carregamento do arquivo.\n");
return 0;
}
aux = R_TRUE;
fseek(stream, 0, SEEK_SET);
fwrite(&aux, sizeof(char), 1, stream);
fclose(stream);
printf("Arquivo revalidado com sucesso.\n");
return 1;
}
<file_sep>#include <stdlib.h>
#include <assert.h>
#include "List.h"
/*
* == Lista Enumerada ==
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
struct __ListItem_t{
LIST_EL X;
struct __ListItem_t *N;
};
struct __List_t{
int size;
struct __ListItem_t *start, *end;
};
struct __List_t *L_New(){
struct __List_t *Aux=(struct __List_t *)malloc(sizeof(struct __List_t)*1);
Aux->size=0;
Aux->start=NULL;
Aux->end=NULL;
return Aux;
}
int L_Size(struct __List_t *L){
if(L==NULL) return -1;
return L->size;
}
char L_Add(LIST_EL X,struct __List_t *L){
if(L==NULL) return -1;
if(L->size==0){
L->end=(struct __ListItem_t *)malloc(sizeof(struct __ListItem_t)*1);
L->end->X=X;
L->end->N=NULL;
L->size++;
L->start=L->end;
return 2;
}
struct __ListItem_t *Aux=L->end;
Aux->N=(struct __ListItem_t *)malloc(sizeof(struct __ListItem_t)*1);
Aux->N->X=X;
Aux->N->N=NULL;
L->end=Aux->N;
L->size++;
return 1;
}
char L_AddAt(LIST_EL X,int i,struct __List_t *L){
if(L==NULL) return -1;
if(i<0 || i>L->size) return 0;
struct __ListItem_t *Aux=L->start;
struct __ListItem_t *NewAux=(struct __ListItem_t *)malloc(sizeof(struct __ListItem_t)*1);
if(L->size==0){
NewAux->N=NULL;
NewAux->X=X;
L->start=L->end=NewAux;
}else if(i==L->size){
NewAux->N=NULL;
NewAux->X=X;
L->end->N=NewAux;
L->end=NewAux;
}else if(i==0){
NewAux->N=L->start;
NewAux->X=X;
L->start=NewAux;
}else if(i==L->size-1){
NewAux->N=L->end->N;
NewAux->X=X;
L->end->N=NewAux;
L->end=NewAux;
}else{
int p=0;
while(p<i-1){
Aux=Aux->N;
p++;
}
NewAux->N=Aux->N->N;
NewAux->X=X;
Aux->N=NewAux;
}
L->size++;
return 1;
}
char L_Remove(struct __List_t *L){
if(L==NULL) return -1;
if(L->size<=0) return 0;
struct __ListItem_t *Aux=L->start;
while(Aux->N!=L->end && Aux->N!=NULL){
Aux=Aux->N;
}
Aux->N=NULL;
free(L->end);
L->end=Aux;
L->size--;
if(L->size<=0){
L->end=L->start=NULL;
}
return 1;
}
char L_RemoveAt(int i,struct __List_t *L){
if(L==NULL) return -1;
if(i<0 || i>=L->size) return 0;
struct __ListItem_t *Aux=L->start;
struct __ListItem_t *R;
if(L->size==1){
free(Aux);
L->start=NULL;
L->end=NULL;
}else if(i==0){
R=Aux->N;
free(Aux);
L->start=R;
}else{
int p;
for(p=0;p<i-1;p++)
Aux=Aux->N;
R=Aux->N;
Aux->N=Aux->N->N;
if(i==L->size-1){
L->end=Aux;
}
free(R);
}
L->size++;
return 1;
}
LIST_EL L_Get(struct __List_t *L){
if(L==NULL) assert(0);
if(L->size<=0) assert(0);
return L->end->X;
}
LIST_EL L_GetAt(int i,struct __List_t *L){
if(L==NULL) assert(0);
if(i<0 || i>=L->size) assert(0);
struct __ListItem_t *Aux;
if(i==L->size-1){
Aux=L->end;
return Aux->X;
}
int p;
Aux=L->start;
for(p=0;p<i;p++)
Aux=Aux->N;
return Aux->X;
}
char L_Set(LIST_EL X,struct __List_t *L){
if(L==NULL) return -1;
if(L->size<=0) return 0;
L->end->X=X;
return 1;
}
char L_SetAt(LIST_EL X,int i,struct __List_t *L){
if(L==NULL) return -1;
if(i<0 || i>=L->size) return 0;
struct __ListItem_t *Aux=L->start;
int p;
for(p=0;p<i;p++)
Aux=Aux->N;
Aux->X=X;
return 1;
}
char L_Destroy(struct __List_t *L){
if(L==NULL) return 0;
if(L->size>0){
struct __ListItem_t *Aux=L->start;
struct __ListItem_t *R;
while(Aux!=NULL){
R=Aux->N;
free(Aux);
Aux=R;
}
}
free(L);
return 1;
}
<file_sep># Trabalho - Twitter Analyser
### Computação em Nuvem e Arquitetura Orientadas a Serviços (SSC-0158)
Neste repositório se encontra o trabalho de Computação em Nuvem e Arquitetura Orientadas a Serviços.
## Guia de configuração
* Instale o Docker e o 'docker-compose' em todas as máquinas que vai utilizar para a aplicação:
``` sudo apt-get install docker.io docker-compose ```
* A partir de qualquer máquina que tenha acesso às outras, execute o script abaixo e siga as instruções na tela:
``` ./cluster-install.sh ```
## Guia de execução
Ao instalar utilizando o script "./cluster-install.sh", a aplicação já se inicia automaticamente. Caso você deseje encerrar a aplicação:
* Entre em cada uma das máquinas em que a aplicação foi instalada e execute o comando:
``` docker ps ```
* Encerre todos os contâiners docker em funcionamento.
Para iniciar a aplicação novamente:
* Vá para a máquina em que o Kafka está instalado e execute o comando:
``` docker ps -a ```
* Inicie o contâiner do Zookeeper e, quando funcionando, inicie o contâiner do Kafka:
``` docker start TA_zookeeper && sleep 10 && docker start TA_kafka && sleep 10```
* Agora vá para a máquina em que o banco de dados MySQL está instalado e execute o comando:
``` docker ps -a ```
* Inicie o contâiner do MySQL:
``` docker start TA_mysql && sleep 10```
* Por fim, vá para a máquina em que o servidor web (a aplicação em si) está instalado e execute o comando:
``` docker ps -a ```
* Inicie o contâiner do servidor web:
``` docker start TA_app && sleep 10```
## Organização do Repositório
O repositório foi organizado da seguinte maneira:
* [Code/](Code): Todo o código de funcionamento da aplicação se encontra aqui.
* [Especificacao.pdf](Especificacao.pdf): Especificação do projeto fornecida pelo docente.
* [Relatorio-Parte1.pdf](Relatorio-Parte1.pdf): Relatório parcial do trabalho (parte escrita).
* [Relatorio-Parte2.pdf](Relatorio-Parte2.pdf): Relatório final do trabalho (parte escrita).
<file_sep>package enemy;
import drawable.Drawable;
import game.GameScreen;
import resources.Resources;
import resources.Utils;
import java.awt.*;
@SuppressWarnings("serial")
public class Enemy extends Drawable {
private int aspect, killScore;
public Enemy(int semester, int test) {
super();
int i;
this.life = (semester + 1) * (Utils.getRandom().nextInt(test + 1) + 1) * 5;
this.speed = 325 - (Utils.getRandom().nextInt((semester + 1) * (test + 1) * 10 + 1) + (semester + 1) * 10);
this.damage = (semester + 1) * (test + 1) * 2;
this.aspect = Utils.getRandom().nextInt(10);
this.killScore = (int) ((325 - this.speed) * this.life * this.damage);
if(this.aspect < 2) {
this.aspect = 0;
} else if(this.aspect < 6) {
this.aspect = 1;
} else {
this.aspect = 2;
}
switch(this.aspect) {
case 0:
// Object quadrado
this.resource = Utils.getRandom().nextInt(Resources.Image.SQUARY_END - Resources.Image.SQUARY_START + 1) + Resources.Image.SQUARY_START;
i = Utils.getRandom().nextInt(16) + 5;
this.size = new Dimension(i, i);
break;
case 1:
// Objeto horizontal
this.resource = Utils.getRandom().nextInt(Resources.Image.HORIZONTAL_END - Resources.Image.HORIZONTAL_START + 1) + Resources.Image.HORIZONTAL_START;
i = Utils.getRandom().nextInt(16) + 5;
this.size = new Dimension(i, (int)(i / 1.5));
break;
case 2:
// Object vertical
this.resource = Utils.getRandom().nextInt(Resources.Image.VERTICAL_END - Resources.Image.VERTICAL_START + 1) + Resources.Image.HORIZONTAL_START;
i = Utils.getRandom().nextInt(16) + 5;
this.size = new Dimension((int)(i / 1.5), i);
break;
}
this.position = new Point(-22, Utils.getRandom().nextInt(50 - this.size.height));
}
/**
* O código abaixo controla tudo relacionado ao inimigo e roda em uma thread separada.
*
*/
@Override
public void run() {
while(true) {
super.run(); // Bloqueia a thread se tiver pausado.
if(this.life <= 0) {
this.resource = Resources.Image.DIED_ENEMY;
Utils.sleep(500);
Utils.acquireLock(GameScreen.game.mutex);
GameScreen.game.score += this.killScore;
GameScreen.game.getEnemies().remove(this);
GameScreen.game.killedEnemies++;
GameScreen.game.mutex.release();
return;
}
if (this.getPosition().getX() + this.getSize().getWidth() >= GameScreen.game.getTower().getPosition().getX()) {
Utils.acquireLock(GameScreen.game.getTower().mutex);
GameScreen.game.getTower().life -= this.getDamage();
GameScreen.game.getTower().mutex.release();
} else {
Point p = new Point((int) this.getPosition().getX() + 1, (int) this.getPosition().getY());
this.setPosition(p);
}
Utils.sleep((long) (this.speed)); // Dorme a thread por speed ms (isso controla a velocidade)
}
}
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
/*
<NAME>
<EMAIL>
*/
/*
Meu RPG tem como base dois pointeiros que indicam quem esta atacando (Attack) e quem esta recebendo o dano (Defense).
Ao mesmo tempo tem os vetores PD, que contem informacoes de Drizzt, e o vetor PA, que contem informacoes de Artemis.
*/
int main(){
int N_F,n_f=0,N_DDA,R,i; // Respectivamente numero de lutas, numero da luta a qual estamos, DDA e duas variaveis usadas nos lacos abaixo (R eh o dano de cada luta e i eh o numero de vezes que o dado sera jogado)
int PD[6]={0,0,0,10,1,9}; // Numeros de vitorias, Vida na luta, Vida geral, Classe de Armadura, Forca da Arma (N. de dados) e Forca da Arma (N. de faces) de Drizzt e de Artemis
int PA[6]={0,0,0,7,2,7};
int *Attack; // Aponta para quem esta atacando (Attack) e para quem esta sofrendo o dano ou tentando defender-se (Defense) na luta
int *Defense;
scanf("%d",&N_F); // Leia as entradas do usuario
scanf("%d",&PD[2]);
scanf("%d",&PA[2]);
scanf("%d",&N_DDA);
srand(N_DDA*N_DDA); // Gerar a semente do aleatorio
while((PD[0]<((N_F>>1)+1)) && (PA[0]<((N_F>>1)+1))){ // Laco da batalha (enquanto ninguem venceu mais da metade das lutas)
printf("Luta %d\n",++n_f);
PA[1]=PA[2]; // Reseta a vida ("Vida na luta") dos personagens para o padrao ("Vida geral")
PD[1]=PD[2];
if(((rand()%N_DDA)+1)<((rand()%N_DDA)+1)){ // Decidir no DDA quem vai jogar primeiro na luta
Attack=PA; // Artemis vai comecar atacando
Defense=PD;
}else{
Attack=PD; // Drizzt vai comecar atacando
Defense=PA;
}
while((PD[1]>0) && (PA[1]>0)){ // Laco interno de cada luta (enquanto a vida de ambos for maior que zero)
if(((rand()%N_DDA)+1)>*(Defense+3)){ // Jogar o DDA para lidar com a autorizacao de ataque (saber se 'Attack' consegue quebrar a armadura de 'Defense')
R=0;
for(i=0;i<*(Attack+4);i++){ //Jogar o dado x vezes, onde x eh o "Forca da Arma (N. de faces)"
R+=(rand()%(*(Attack+5)))+1; // Adicionar dano que saiu no dado
}
if(R==(*(Attack+4))*(*(Attack+5))){
R=(int)R*1.5; // Lidar com o 'Extra Damage'
}else if(R==*(Attack+4)){
R=0; // Lidar com o 'Miss'
}
*(Defense+1)-=R; // Retirar 'R' da 'Vida na luta' de Defense
if(R>0){
if(Attack==PD){ // Imprimir dano retirado
printf("Drizzt %d\n",R);
}else{
printf("Artemis %d\n",R);
}
}
}
if(Attack==PD){ // Agora vamos trocar quem vai jogar na proxima luta (inverter 'Attack' com 'Defense')
Attack=PA;
Defense=PD;
}else{
Attack=PD;
Defense=PA;
}
}
if(PD[1]>0){ // A luta acabou. Agora vamos imprimir quem ganhou ela
PD[0]++;
printf("Fim da luta. Vencedor: Drizzt\n");
}else{
PA[0]++;
printf("Fim da luta. Vencedor: Artemis\n");
}
}
if(PD[0]>=((N_F>>1)+1)){ // A batalha acabou. Agora vamos imprimir quem ganhou ela
printf("Fim da batalha. Vencedor: DRIZZT\n");
}else{
printf("Fim da batalha. Vencedor: ARTEMIS\n");
}
return EXIT_SUCCESS;
}
<file_sep>
DBs = [ ];
UPDATING = false;
function _padInt(n) {
if(n < 10) {
return '0' + n;
} else {
return '' + n;
}
}
function updateData() {
if(UPDATING) {
return;
}
UPDATING = true;
$(".content > div").hide()
$("#content-loading").show()
document.querySelector("#content-data").innerHTML = '<div class="db-add"><a href="#" onclick="newDB(); return false;">Criar Base de Dados</a></div>';
$.ajax({
url: "server/databases",
cache: false,
method: "GET",
timeout: 30000,
success: function(reqResults) {
try {
DBs = JSON.parse(reqResults);
for(let i = 0; i < DBs.length; i++) {
db_div = document.createElement("div");
db_div.className = "db-item";
db_div.innerHTML = '<h3>Name</h3><span>Status/Number Tweets</span>'
db_div.innerHTML += '<a href="#" class="db-edit-link" data-id="' + DBs[i].id + '" onclick="editDB(this); return false;">(editar)</a><p>Description</p>'
document.querySelector("#content-data").appendChild(db_div);
db_div.querySelector("h3").textContent = DBs[i].name;
db_div.querySelector("p").textContent = DBs[i].description;
if(DBs[i].ready) {
db_div.querySelector("span").textContent = "Busca completa (" + DBs[i]['tweet_count'] + " tweets encontrados)";
db_div.querySelector("span").className += " db-item-done";
} else {
db_div.querySelector("span").textContent = "Busca em progresso (" + DBs[i]['tweet_count'] + " tweets encontrados)";
db_div.querySelector("span").className += " db-item-progress";
}
}
$(".content > div").hide()
$("#content-data").show()
} catch(e) {
$(".content > div").hide()
$("#content-error").show()
}
UPDATING = false;
},
error: function() {
$(".content > div").hide()
$("#content-error").show()
UPDATING = false;
}
});
}
function editDB(linkId) {
let i, date, db = null;
linkId = linkId.getAttribute("data-id");
for(i = 0; i < DBs.length; i++) {
if(DBs[i].id == linkId) {
db = DBs[i];
break;
}
}
if(db == null) {
return;
}
$(".content > div").hide()
document.querySelector("#content-edit form input[name='id']").value = db.id;
document.querySelector("#content-edit form input[name='timezone_offset']").value = new Date().getTimezoneOffset();
document.querySelector("#content-edit form input[name='name']").value = db.name;
document.querySelector("#content-edit form textarea[name='description']").value = db.description ? db.description : "";
document.querySelector("#content-edit form input[name='query']").value = db.query;
document.querySelector("#content-edit form select[name='lang']").value = db.lang ? db.lang : "";
if(db.tweeted_before_date != null) {
date = new Date(db.tweeted_before_date * 1000)
document.querySelector("#content-edit form input[name='before_date']").value = _padInt(date.getUTCFullYear()) + "-" + _padInt(date.getUTCMonth() + 1) + "-" + _padInt(date.getUTCDate());
document.querySelector("#content-edit form input[name='before_date']").disabled = false;
document.querySelector("#content-edit form input[name='before_date']").required = true;
document.querySelector("#content-edit form input[name='before_date_check']").checked = true;
} else {
document.querySelector("#content-edit form input[name='before_date']").value = "";
document.querySelector("#content-edit form input[name='before_date']").required = false;
document.querySelector("#content-edit form input[name='before_date']").disabled = true;
document.querySelector("#content-edit form input[name='before_date_check']").checked = false;
}
if(db.tweeted_after_date != null) {
date = new Date(db.tweeted_after_date * 1000)
document.querySelector("#content-edit form input[name='after_date']").value = _padInt(date.getFullYear()) + "-" + _padInt(date.getMonth() + 1) + "-" + _padInt(date.getDate());
document.querySelector("#content-edit form input[name='after_time']").value = _padInt(date.getHours()) + ":" + _padInt(date.getMinutes());
document.querySelector("#content-edit form input[name='after_date']").disabled = false;
document.querySelector("#content-edit form input[name='after_time']").disabled = false;
document.querySelector("#content-edit form input[name='after_date']").required = true;
document.querySelector("#content-edit form input[name='after_time']").required = true;
document.querySelector("#content-edit form input[name='after_date_check']").checked = true;
} else {
document.querySelector("#content-edit form input[name='after_date']").value = "";
document.querySelector("#content-edit form input[name='after_time']").value = "";
document.querySelector("#content-edit form input[name='after_date']").required = false;
document.querySelector("#content-edit form input[name='after_time']").required = false;
document.querySelector("#content-edit form input[name='after_date']").disabled = true;
document.querySelector("#content-edit form input[name='after_time']").disabled = true;
document.querySelector("#content-edit form input[name='after_date_check']").checked = false;
}
document.querySelector("#content-edit form input[name='update']").checked = false;
$("#content-edit").show()
}
function saveDB() {
let i, db = null;
dbId = document.querySelector("#content-edit form input[name='id']").value;
for(i = 0; i < DBs.length; i++) {
if(DBs[i].id == dbId) {
db = DBs[i];
break;
}
}
if(db == null) {
return;
}
UPDATING = true;
$(".content > div").hide()
$("#content-loading").show()
$.ajax({
url: "server/databases/" + db.id,
cache: false,
method: "POST",
data: $("#content-edit form").serializeArray(),
dataType: "text",
timeout: 30000,
success: function(reqResults) {
UPDATING = false;
updateData();
},
error: function() {
alert("Ocorreu um erro ao tentar editar esta base de dados! Certifique-se de que ela não está sendo usada em nenhuma análise antes de modificar.");
UPDATING = false;
updateData();
}
});
}
function removeDB() {
let i, db = null;
dbId = document.querySelector("#content-edit form input[name='id']").value;
for(i = 0; i < DBs.length; i++) {
if(DBs[i].id == dbId) {
db = DBs[i];
break;
}
}
if(db == null) {
return;
}
if(!confirm("Deseja realmente remover esta base de dados?")) {
return;
}
UPDATING = true;
$(".content > div").hide()
$("#content-loading").show()
$.ajax({
url: "server/databases/" + db.id,
cache: false,
method: "DELETE",
timeout: 30000,
success: function(reqResults) {
UPDATING = false;
updateData();
},
error: function() {
alert("Ocorreu um erro ao tentar remover esta base de dados! Certifique-se de que ela não está sendo usada em nenhuma análise antes de remover.");
UPDATING = false;
updateData();
}
});
}
function newDB() {
let date;
$(".content > div").hide()
document.querySelector("#content-create form input[name='timezone_offset']").value = new Date().getTimezoneOffset();
document.querySelector("#content-create form input[name='name']").value = "";
document.querySelector("#content-create form textarea[name='description']").value = "";
document.querySelector("#content-create form input[name='query']").value = "";
document.querySelector("#content-create form select[name='lang']").value = "";
document.querySelector("#content-create form input[name='before_date']").value = "";
document.querySelector("#content-create form input[name='before_date']").required = false;
document.querySelector("#content-create form input[name='before_date']").disabled = true;
document.querySelector("#content-create form input[name='before_date_check']").checked = false;
document.querySelector("#content-create form input[name='after_date']").value = "";
document.querySelector("#content-create form input[name='after_time']").value = "";
document.querySelector("#content-create form input[name='after_date']").required = false;
document.querySelector("#content-create form input[name='after_time']").required = false;
document.querySelector("#content-create form input[name='after_date']").disabled = true;
document.querySelector("#content-create form input[name='after_time']").disabled = true;
document.querySelector("#content-create form input[name='after_date_check']").checked = false;
document.querySelector("#content-create form input[name='donotupdate']").checked = false;
$("#content-create").show()
}
function createDB() {
UPDATING = true;
$(".content > div").hide()
$("#content-loading").show()
$.ajax({
url: "server/databases",
cache: false,
method: "POST",
data: $("#content-create form").serializeArray(),
dataType: "text",
timeout: 30000,
success: function(reqResults) {
UPDATING = false;
updateData();
},
error: function() {
alert("Ocorreu um erro ao tentar criar esta base de dados! Certifique-se de que os dados inseridos fazem sentido.");
UPDATING = false;
updateData();
}
});
}
function checkboxChanged(checked, inputs) {
let i;
if(checked) {
for(i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
inputs[i].required = true;
}
} else {
for(i = 0; i < inputs.length; i++) {
inputs[i].required = false;
inputs[i].disabled = true;
inputs[i].value = "";
}
}
}
function resetForm() {
updateData();
}
function windowLoaded() {
updateData();
//setTimeout('updateData();', 10000);
}
window.onload = windowLoaded;
<file_sep>#include <stdlib.h>
#include <limits.h>
#include <iostream>
#include <cmath>
using namespace std;
long N_Divisors(long N){
long i, Max, Counter;
Max = sqrt(N);
for(i = 2, Counter = 0; i <= Max; i++){
if(N % i == 0){
if(N / i == i) Counter++;
else Counter += 2;
}
}
return Counter + 2; // 1 e ele mesmo
}
int main(int argc, char **argv){
long i, j, N, Start, End, LargestId, LargestN, Aux;
cin >> N;
for(i = 0; i < N; i++){
cin >> Start >> End;
LargestN = INT_MIN;
for(j = Start; j <= End; j++){
Aux = N_Divisors(j);
if(Aux > LargestN){
LargestId = j;
LargestN = Aux;
}
}
cout << "Between " << Start << " and " << End << ", " << LargestId << " has a maximum of " << LargestN << " divisors.\n";
}
return EXIT_SUCCESS;
}
<file_sep># SSC-0108 Prática em Sistemas Digitais - 2017.2
Aqui estão todos os trabalhos que implementei em Prática em Sistemas Digitais.
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
/*
<NAME>
<EMAIL>
*/
// Definir uma estrutura capaz de lidar com nossas necessidades e armazenar todos os dados lidos da imagem.
typedef struct __ImageData {
int X,Y;
char Type;
unsigned char Max;
unsigned char Min;
unsigned char *Pixels;
} IMG;
// Declarar quais funções existem em nosso código.
char LoadImage(char *FilePath,IMG *ImgData);
void ProcessImage(char Procedure,IMG *ImgData);
void ProcessImage__FloodFill(int pixelX,int pixelY,IMG *ImgData);
void OutputImage(IMG *ImgData);
void DestroyImage(IMG *ImgData);
int main(){
IMG Carro;
char Procedure, FileName[100];
Procedure=getchar(); // Obter o procedimento (1, 2 ou 3).
fgets(FileName,100,stdin); // Liberar '\n' do buffer.
fgets(FileName,100,stdin); // Ler nome do arquivo.
if(FileName[strlen(FileName)-1]=='\n'){
FileName[strlen(FileName)-1]='\0';
}
if(LoadImage(FileName,&Carro)){ // A imagem existe e pode ser lida?
ProcessImage(Procedure,&Carro); // Sim. Processa ela, retorna o resultado e limpa a memória.
OutputImage(&Carro);
DestroyImage(&Carro);
}else{
printf("> Erro: arquivo especificado nao existe ou nao pode ser lido.\n"); // Não. Notifique o usuário.
}
return EXIT_SUCCESS;
}
char LoadImage(char *FilePath,IMG *ImgData){
/*
* Esta função faz a leitura do arquivo de imagem e salva todos os dados dela na estrutura 'ImgData'.
* Retorna 1 se a leitura ocorrer com sucesso ou 0 em caso de erros.
*/
int i,R;
char Line[100];
FILE *FStream=fopen(FilePath,"rb"); // Abrir arquivo de forma leitura binária (se for o caso).
if(FStream){ // Foi aberto com sucesso?
fgets(Line,100,FStream); // Sim. Obtenha o tipo de arquivo (ASCII ou Binário).
ImgData->Type=Line[1];
fgets(Line,100,FStream); // Leia e ignore o comentário.
fscanf(FStream,"%d %d",&ImgData->X,&ImgData->Y); // Ler as dimensões da imagem.
fscanf(FStream,"%d",&R); getc(FStream); // Ler e ignorar mais uma linha.
ImgData->Min=255;
ImgData->Max=0;
ImgData->Pixels=(unsigned char*)malloc(sizeof(unsigned char)*ImgData->X*ImgData->Y);
if(ImgData->Type=='2'){ // O arquivo é do tipo ASCII?
for(i=0;i<ImgData->X*ImgData->Y;i++){ // Sim, então para cada pixel...
fscanf(FStream,"%d",&R); // Leia um inteiro do arquivo que representa esse pixel e salva no nosso vetor de pixels.
ImgData->Pixels[i]=(unsigned char)R;
if(R>ImgData->Max){
ImgData->Max=R;
}
if(R<ImgData->Min){
ImgData->Min=R;
}
}
}else{
for(i=0;i<ImgData->X*ImgData->Y;i++){ // Não, então só pode ser do tipo Binário pela especificação. Para cada pixel...
fread(&ImgData->Pixels[i],sizeof(unsigned char),1,FStream); // Leia um byte do arquivo que representa esse pixel e salva no nosso vetor de pixels.
if(ImgData->Pixels[i]>ImgData->Max){
ImgData->Max=ImgData->Pixels[i];
}
if(ImgData->Pixels[i]<ImgData->Min){
ImgData->Min=ImgData->Pixels[i];
}
}
}
fclose(FStream);
return 1;
}
return 0;
}
void ProcessImage(char Procedure,IMG *ImgData){
/*
* Esta função faz as 3 operações possíveis na imagem.
*/
int i;
double k;
if(Procedure=='1'){ // Fazer logarítmo.
k=255/(double)log10(1+ImgData->Max);
for(i=0;i<ImgData->X*ImgData->Y;i++){
ImgData->Pixels[i]=(unsigned char)floor(k*log10(1+ImgData->Pixels[i])); // Aplica a equação padrão (logarítmo) para cada pixel.
}
}else if(Procedure=='2'){ // Fazer expansão de contraste.
k=255/(double)(ImgData->Max-ImgData->Min);
for(i=0;i<ImgData->X*ImgData->Y;i++){
ImgData->Pixels[i]=(unsigned char)floor(k*(ImgData->Pixels[i]-ImgData->Min)); // Aplica a equação padrão (razão e proporção) para cada pixel.
}
}else{ // Fazer o "Flood Fill" (Baldinho do PaintBrush).
ProcessImage__FloodFill(ImgData->X/2,ImgData->Y/2,ImgData); // Chamar função separada que faz tal operação, iniciando no centro da imagem.
}
}
void ProcessImage__FloodFill(int pixelX,int pixelY,IMG *ImgData){
/*
* Esta função é responsável por realizar a terceira operação da imagem (FloodFill ou Baldinho do PaintBrush).
*/
if( (pixelX>=0) && (pixelY>=0) && (pixelX<ImgData->X) && (pixelY<ImgData->Y) &&
(ImgData->Pixels[pixelY*ImgData->X+pixelX]!=100) &&
(ImgData->Pixels[pixelY*ImgData->X+pixelX]!=255) ){ // A operação de 'FloodFill' pode ser realizada?
ImgData->Pixels[pixelY*ImgData->X+pixelX]=100; // Sim. Tornar este pixel cinza (100).
ProcessImage__FloodFill(pixelX-1,pixelY,ImgData); // Um pixel para a esquerda.
ProcessImage__FloodFill(pixelX,pixelY-1,ImgData); // Um pixel para cima.
ProcessImage__FloodFill(pixelX+1,pixelY,ImgData); // Um pixel para a direita.
ProcessImage__FloodFill(pixelX,pixelY+1,ImgData); // Um pixel para baixo.
}
}
void OutputImage(IMG *ImgData){
/*
* Esta função imprime a imagem em 'stdout'.
*/
int i;
printf("P2\n# CREATOR: Image Generator SCC-221 - ICC I\n");
printf("%d %d\n255\n",ImgData->X,ImgData->Y);
for(i=0;i<ImgData->X*ImgData->Y;i++){
printf("%d\n",ImgData->Pixels[i]);
}
}
void DestroyImage(IMG *ImgData){
/*
* Esta função limpa a memória alocada dinamicamente.
*/
free(ImgData->Pixels);
}
<file_sep>#ifndef HEAP_H_
#define HEAP_H_
//#include <stdlib.h>
typedef struct __heap_t HEAP;
struct __heap_t *H_New(size_t, int (*)(void *, void *));
int H_Add(void *, struct __heap_t *);
int H_Get(void *, struct __heap_t *);
int H_Shift(void *, struct __heap_t *);
void H_Destroy(struct __heap_t *);
#endif<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
Por <NAME>.
<EMAIL>
*/
int main(){
unsigned int N,i;
scanf("%d",&N);
float Ni;
double MHA=0;
for(i=0;i<N;i++){
scanf("%f",&Ni);
MHA+=1.0/(double)(Ni+1);
}
MHA=(N/(double)(MHA))-1;
printf("%.2f",MHA);
return EXIT_SUCCESS;
}
<file_sep>import numpy as np
import imageio
import math
#
# ~ Trabalho 3: Filtragem 1D ~
#
# <NAME>
# <EMAIL>
# Nº USP 10369014
# Processamento de Imagens: SCC-0251 2018.1
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
# == DEFINIÇÃO DE FUNÇÕES ==
def Apply_Filter_Space(Arr, Mask):
"Esta função retorna uma imagem resultante da aplicação do filtro de máscara Mask sob a imagem Arr no domínio do espaço."
Res = np.zeros(Arr.shape, dtype=np.float)
mask_start = int(((Mask.shape[0] - 1) / 2) * -1)
for i in range(0, Arr.shape[0]): # Para cada pixel da array resultante...
j = mask_start
for u in Mask: # Fazer a soma dos pesos do filtro
Res[i] += Arr[(i - j) % Res.shape[0]] * u
j = j + 1
Res = np.floor(Res)
return Res
def Apply_Filter_Frequency(Arr, Mask):
"Esta função retorna um numpy array resultante da aplicação do filtro de máscara Mask sob o numpy array Arr no domínio das frequências."
Res = np.zeros(Arr.shape, dtype=np.float)
for i in range(0, Mask.shape[0]): # Copiar filtro para o começo do array
Res[i] = Mask[i]
Arr = DFT(Arr) # Transformada de Fourier
Res = DFT(Res) # Filtro estendido
Res = np.multiply(Arr, Res) # Multiplicar ponto a ponto
Res = np.real(DFT_Inv(Res)) # Fazer a transformada de Fourier inversa e obter apenas a parte real
return Res
def New_Gaussian_Mask(N, Sigma):
"Esta função retorna um filtro Gaussiano gerado a partir de um tamanho N e um desvio padrão Sigma."
Res = np.empty(N, dtype=np.float)
Ratio1 = math.sqrt(2 * math.pi) * Sigma
Ratio2 = 2 * Sigma * Sigma
mask_center = int((N / 2) * -1)
mask_half = int(N / 2)
j = int((N / 2) * -1)
for i in range(0, mask_half): # Gerar valores pré-centro
Res[i] = j
j = j + 1
if N % 2 != 0:
Res[mask_half] = 0 # Gerar centro
j = 1
for i in range(mask_center + 1, N): # Gerar valores pós-centro
Res[i] = j
j = j + 1
Res = np.abs(Res) / np.sum(np.abs(Res)) # Normalizar pesos
for i in range(0, N): # Aplicar equação de Gauss
Res[i] = math.exp((-1 * Res[i] * Res[i]) / Ratio2) / Ratio1
Sum = 1 / np.sum(Res)
for i in range(0, N): # Normalizar entre 0 - 1.
Res[i] = Res[i] * Sum
return Res
def DFT(Arr):
"Esta função retorna o domínio das frequências da imagem Arr, fazendo sua transformada de Fourier."
Res = np.empty(Arr.shape, dtype=np.complex64)
N = Arr.shape[0]
x = np.arange(0, N) # Fixo
for u in range(0, N): # Para cada frequência...
Res[u] = np.sum(Arr * np.exp((-1j * 2 * np.pi * x * u) / N)) # Calcular o valor resultado da equação
return Res
def DFT_Inv(Arr):
"Esta função retorna o domínio de espaço da imagem Arr, fazendo sua transformada de Fourier inversa."
Res = np.empty(Arr.shape, dtype=np.complex64)
N = Arr.shape[0]
x = np.arange(0, N) # Fixo
for u in range(0, N): # Para cada frequência...
Res[u] = np.sum(Arr * np.exp((1j * 2 * np.pi * x * u) / N)) # Calcular o valor resultado da equação
Res = np.real(Res / N) # Valores reais
return Res
# == MAIN ==
# Leitura dos dados da entrada padrão
file_name = str(input()).rstrip()
filter_type = int(input())
filter_n = int(input())
filter_definition = input()
filter_domain = int(input())
# Carregar imagem
LoadedImage = imageio.imread(file_name)
GeneratedImage = LoadedImage.flatten() # Tornar 1D
# Gerar filtros
if filter_type == 1: # Filtro Arbitrário
filter_mask = np.array(list(map(np.float, filter_definition.split(' ')))) # Processar pesos e colocar em um Numpy Array
filter_mask = np.abs(filter_mask) / np.sum(np.abs(filter_mask)) # Normalizar pesos
else:
sigma = float(filter_definition)
filter_mask = New_Gaussian_Mask(filter_n, sigma) # Criar filtro Gaussiano
# Aplicar filtros no domínio escolhido
if filter_domain == 1:
GeneratedImage = Apply_Filter_Space(GeneratedImage, filter_mask)
else:
GeneratedImage = Apply_Filter_Frequency(GeneratedImage, filter_mask)
# Voltar a imagem para 2D e em formato uint8
GeneratedImage = np.uint8(np.reshape(GeneratedImage, LoadedImage.shape))
# Calcular RMSE
RMSE = float(0)
for x in range(0, LoadedImage.shape[0]):
for y in range(0, LoadedImage.shape[1]):
RMSE += math.pow(float(GeneratedImage[x, y]) - float(LoadedImage[x, y]), 2)
RMSE = math.sqrt(RMSE / (LoadedImage.shape[0] * LoadedImage.shape[1]))
# Imprimir resultado do RMSE com 4 casas decimais
print("%.4f" % round(RMSE, 4))
# == DEBUGGING ==
# Imprimir minha imagem gerada e imagem lida do disco para comparação
imageio.imwrite("out_expected.png", LoadedImage)
imageio.imwrite("out_generated.png", GeneratedImage)
#print("")
#print(GeneratedImage)
#print("")
#print(LoadedImage)
#print("")
<file_sep># SCC-0221 Introdução à Ciência da Computação 1 - 2017.1
Aqui estão todos os trabalhos que implementei em ICC 1.
<file_sep>
/*
* ~ STACK ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __Stack_H_
#define __Stack_H_
#define STACK_ELEM int
typedef struct __stack_t STACK;
struct __stack_t *S_New();
struct __stack_t *S_NewFrom(struct __stack_t *);
char S_Cmp(struct __stack_t *,struct __stack_t *);
char S_IsEmpty(struct __stack_t *);
int S_Size(struct __stack_t *);
char S_Push(STACK_ELEM,struct __stack_t *);
STACK_ELEM S_Pop(struct __stack_t *);
STACK_ELEM S_Get(struct __stack_t *);
STACK_ELEM S_GetAt(int,struct __stack_t *);
char S_Destroy(struct __stack_t *);
#endif
<file_sep>
#
# ~ <NAME> ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -Wall -lm
objects/main.o: main.c objects/SortedHeap.o headers/SortedHeap.h
gcc -c -o objects/main.o main.c -Wall -I headers
objects/SortedHeap.o: lib/SortedHeap.c headers/SortedHeap.h
gcc -c -o objects/SortedHeap.o lib/SortedHeap.c -Wall -I headers
run: Prog
./Prog
clean:
rm Prog objects/*.o<file_sep>from flask import Flask, request, send_from_directory
import datetime
import json
from utils import Config, DBConnection, Utils
from data_worker import TaskManager, TaskNode
from api_comm import APICommunicator
app = Flask(__name__)
@app.before_first_request
def main():
# This function executes before the first request to the server.
if __name__ != '__main__':
Config.Init()
APICommunicator.Init()
TaskManager.Init()
TaskNode.Init()
@app.route('/', methods=['GET'])
@app.route('/<filename>', methods=['GET'])
def index(filename = "index.html"):
return send_from_directory('html', filename) # Serve static files.
@app.route('/server/databases', methods=['GET'])
def databases_get():
db = DBConnection()
items = db.fetchAll('SELECT `id`, `name`, `description`, `query`, `tweeted_before_date`, `tweeted_after_date`, `lang`, `ready`, (SELECT COUNT(*) FROM `tweets` WHERE `tweets`.`db_id` = `dbs`.`id`) AS `tweet_count` FROM `dbs` ORDER BY `name`')
for i in range(len(items)):
items[i] = {'id': items[i][0], 'name': items[i][1], 'description': items[i][2], 'query': items[i][3], 'tweeted_before_date': items[i][4], 'tweeted_after_date': items[i][5], 'lang': items[i][6], 'ready': True if items[i][7] == 1 else False, 'tweet_count': items[i][8]}
db.close()
return json.dumps(items) # Return all databases.
@app.route('/server/databases', methods=['POST'])
def databases_post():
formData = request.form.to_dict(flat=True)
if not Utils.ValidateField(formData, 'name', checkEmpty=True):
return 'Missing required field!', 403
if not Utils.ValidateField(formData, 'query', checkEmpty=True):
return 'Missing required field!', 403
if not Utils.ValidateField(formData, 'description', checkEmpty=True):
formData['description'] = None
if not Utils.ValidateField(formData, 'timezone_offset', checkEmpty=True, regExp=r'^[+-]?[0-9]+$'):
formData['timezone_offset'] = '+0000'
else:
formData['timezone_offset'] = -1 * int(formData['timezone_offset'])
if formData['timezone_offset'] >= 0:
formData['timezone_offset'] = '+%02d%02d' % (abs(formData['timezone_offset']) // 60, abs(formData['timezone_offset']) % 60)
else:
formData['timezone_offset'] = '-%02d%02d' % (abs(formData['timezone_offset']) // 60, abs(formData['timezone_offset']) % 60)
if not Utils.ValidateField(formData, 'lang', regExp=r'^(?:[a-zA-Z0-9]{2}|[a-zA-Z0-9]{2}-[a-zA-Z0-9]{2})$'):
formData['lang'] = None
if not Utils.ValidateField(formData, 'before_date', regExp=r'^[0-9]{4,}-[0-9]{2}-[0-9]{2}$'):
formData['before_date'] = None
else:
formData['before_date'] = datetime.datetime.timestamp(datetime.datetime.strptime(formData['before_date'] + ' 23:59 +0000', '%Y-%m-%d %H:%M %z'))
if not Utils.ValidateField(formData, 'after_date', regExp=r'^[0-9]{4,}-[0-9]{2}-[0-9]{2}$'):
formData['after_date'] = None
elif not Utils.ValidateField(formData, 'after_time', regExp=r'^[0-9]{2}:[0-9]{2}$'):
formData['after_date'] = None
else:
formData['after_date'] = datetime.datetime.timestamp(datetime.datetime.strptime(formData['after_date'] + ' ' + formData['after_time'] + ' ' + formData['timezone_offset'], '%Y-%m-%d %H:%M %z'))
if not Utils.ValidateField(formData, 'donotupdate', equals='true'):
formData['update'] = False
else:
formData['update'] = True
if (formData['after_date'] is not None and formData['before_date'] is not None) and (formData['before_date'] <= formData['after_date']):
return 'Provided dates do not make sense!', 403
newItem = (formData['name'], formData['description'], formData['query'], formData['before_date'], formData['after_date'], formData['lang'], formData['update'], )
db = DBConnection()
db.insertOne('INSERT INTO `dbs` (`name`, `description`, `query`, `tweeted_before_date`, `tweeted_after_date`, `lang`, `ready`) VALUES(%s, %s, %s, %s, %s, %s, %s)', newItem)
db.close()
return '', 204
@app.route('/server/databases/<id>', methods=['GET'])
def database_get(id):
db = DBConnection()
item = db.fetchOne('SELECT `id`, `name`, `description`, `query`, `tweeted_before_date`, `tweeted_after_date`, `lang`, `ready`, (SELECT COUNT(*) FROM `tweets` WHERE `tweets`.`db_id` = `dbs`.`id`) AS `tweet_count` FROM `dbs` WHERE `id`=%s', (id, ))
db.close()
if item is None:
return 'Database does not exist!', 404
item = {'id': item[0], 'name': item[1], 'description': item[2], 'query': item[3], 'tweeted_before_date': item[4], 'tweeted_after_date': item[5], 'lang': item[6], 'ready': True if item[7] == 1 else False, 'tweet_count': item[8]}
return json.dumps(item) # Return this database.
@app.route('/server/databases/<id>', methods=['POST'])
def database_post(id):
formData = request.form.to_dict(flat=True)
if not Utils.ValidateField(formData, 'name', checkEmpty=True):
return 'Missing required field!', 403
if not Utils.ValidateField(formData, 'query', checkEmpty=True):
return 'Missing required field!', 403
if not Utils.ValidateField(formData, 'description', checkEmpty=True):
formData['description'] = None
if not Utils.ValidateField(formData, 'timezone_offset', checkEmpty=True, regExp=r'^[+-]?[0-9]+$'):
formData['timezone_offset'] = '+0000'
else:
formData['timezone_offset'] = -1 * int(formData['timezone_offset'])
if formData['timezone_offset'] >= 0:
formData['timezone_offset'] = '+%02d%02d' % (abs(formData['timezone_offset']) // 60, abs(formData['timezone_offset']) % 60)
else:
formData['timezone_offset'] = '-%02d%02d' % (abs(formData['timezone_offset']) // 60, abs(formData['timezone_offset']) % 60)
if not Utils.ValidateField(formData, 'lang', regExp=r'^(?:[a-zA-Z0-9]{2}|[a-zA-Z0-9]{2}-[a-zA-Z0-9]{2})$'):
formData['lang'] = None
if not Utils.ValidateField(formData, 'before_date', regExp=r'^[0-9]{4,}-[0-9]{2}-[0-9]{2}$'):
formData['before_date'] = None
else:
formData['before_date'] = datetime.datetime.timestamp(datetime.datetime.strptime(formData['before_date'] + ' 23:59 +0000', '%Y-%m-%d %H:%M %z'))
if not Utils.ValidateField(formData, 'after_date', regExp=r'^[0-9]{4,}-[0-9]{2}-[0-9]{2}$'):
formData['after_date'] = None
elif not Utils.ValidateField(formData, 'after_time', regExp=r'^[0-9]{2}:[0-9]{2}$'):
formData['after_date'] = None
else:
formData['after_date'] = datetime.datetime.timestamp(datetime.datetime.strptime(formData['after_date'] + ' ' + formData['after_time'] + ' ' + formData['timezone_offset'], '%Y-%m-%d %H:%M %z'))
if not Utils.ValidateField(formData, 'update', equals='true'):
formData['update'] = False
else:
formData['update'] = True
if (formData['after_date'] is not None and formData['before_date'] is not None) and (formData['before_date'] <= formData['after_date']):
return 'Provided dates do not make sense!', 403
editedItem = (formData['name'], formData['description'], formData['query'], formData['before_date'], formData['after_date'], formData['lang'], )
db = DBConnection()
item = db.fetchOne('SELECT `id`, `query`, `tweeted_before_date`, `tweeted_after_date`, `lang`, `ready`, (SELECT COUNT(*) FROM `analysis` WHERE `analysis`.`db_id` = `dbs`.`id`) AS `analysis_count` FROM `dbs` WHERE `id`=%s', (id, ))
if item is None:
db.close()
return 'Database does not exist!', 404
if item[1] != editedItem[2] or item[2] != editedItem[3] or item[3] != editedItem[4] or item[4] != editedItem[5]:
if item[5] == 0 or item[6] > 0:
db.close()
return 'Database being used!', 403
db.execute('DELETE FROM `tweets` WHERE `db_id` = %s', (item[0], ))
db.execute('UPDATE `dbs` SET `ready` = false WHERE `id` = %s', (item[0], ))
db.execute('UPDATE `dbs` SET `name` = %s, `description` = %s, `query` = %s, `tweeted_before_date` = %s, `tweeted_after_date` = %s, `lang` = %s WHERE `id` = %s', editedItem + (item[0], ))
if formData['update']:
db.execute('UPDATE `dbs` SET `ready` = false WHERE `id` = %s', (item[0], ))
db.close()
return '', 204
@app.route('/server/databases/<id>', methods=['DELETE'])
def database_delete(id):
db = DBConnection()
id = db.fetchOne('SELECT `id`, (SELECT COUNT(*) FROM `analysis` WHERE `analysis`.`db_id` = `dbs`.`id`) FROM `dbs` WHERE `id`=%s', (id, ))
if id is None:
db.close()
return 'Database does not exist!', 404
if id[1] > 0:
db.close()
return 'Database is being used!', 403
db.execute('DELETE FROM `dbs` WHERE `id`=%s', (id[0], )) # Delete database.
db.execute('DELETE FROM `tweets` WHERE `tweets`.`db_id` NOT IN (SELECT `id` FROM `dbs`)') # Delete tweets.
db.close()
return '', 204
@app.route('/server/analysis', methods=['GET'])
def analytics_get():
db = DBConnection()
items = db.fetchAll('SELECT `id`, `db_id`, `name`, `description`, `ready`, `progress`, `results_fewinteractions`, `results_usercount`, `results_recentusercount`, `results_defaultprofilecount`, `results_defaultpicturecount`, `results_fewfollowings`, `results_fewfollowers`, `results_fewstatus`, `results_fewfavorites` FROM `analysis` ORDER BY `name`')
for i in range(len(items)):
items[i] = {'id': items[i][0], 'db': items[i][1], 'name': items[i][2], 'description': items[i][3], 'ready': True if items[i][4] == 1 else False, 'progress': items[i][5], 'results': {
'fewinteractions': items[i][6],
'usercount': items[i][7],
'recentusercount': items[i][8],
'defaultprofilecount': items[i][9],
'defaultpicturecount': items[i][10],
'fewfollowings': items[i][11],
'fewfollowers': items[i][12],
'fewstatus': items[i][13],
'fewfavorites': items[i][14],
}}
DBs = db.fetchAll('SELECT `id`, `name`, `ready`, (SELECT COUNT(*) FROM `tweets` WHERE `tweets`.`db_id` = `dbs`.`id`) AS count FROM `dbs` ORDER BY `name`')
for i in range(len(DBs)):
DBs[i] = {'id': DBs[i][0], 'name': DBs[i][1], 'ready': True if DBs[i][2] == 1 else False, 'count': DBs[i][3]}
db.close()
return json.dumps({'analysis': items, 'dbs': DBs}) # Return all analysis and databases.
@app.route('/server/analysis', methods=['POST'])
def analytics_post():
formData = request.form.to_dict(flat=True)
if not Utils.ValidateField(formData, 'name', checkEmpty=True):
return 'Missing required field!', 403
if not Utils.ValidateField(formData, 'db', checkEmpty=True):
return 'Missing required field!', 403
if not Utils.ValidateField(formData, 'description', checkEmpty=True):
formData['description'] = None
db = DBConnection()
formData['db'] = db.fetchOne('SELECT `id` FROM `dbs` WHERE `id` = %s', (formData['db'], ))
if formData['db'] is None:
db.close()
return 'Database does not exist!', 404
formData['db'] = formData['db'][0]
newItem = (formData['name'], formData['description'], formData['db'], False, )
db.insertOne('INSERT INTO `analysis` (`name`, `description`, `db_id`, `ready`) VALUES(%s, %s, %s, %s)', newItem)
db.close()
return '', 204
@app.route('/server/analysis/<id>', methods=['GET'])
def analysis_get(id):
db = DBConnection()
item = db.fetchOne('SELECT `id`, `db_id`, `name`, `description`, `ready`, `progress`, `results_fewinteractions`, `results_usercount`, `results_recentusercount`, `results_defaultprofilecount`, `results_defaultpicturecount`, `results_fewfollowings`, `results_fewfollowers`, `results_fewstatus`, `results_fewfavorites` FROM `analysis` WHERE `id`=%s', (id, ))
if item is None:
return 'Analysis does not exist!', 404
item = {'id': item[0], 'db': item[1], 'name': item[2], 'description': item[3], 'ready': True if item[4] == 1 else False, 'progress': item[5], 'results': {
'fewinteractions': item[6],
'usercount': item[7],
'recentusercount': item[8],
'defaultprofilecount': item[9],
'defaultpicturecount': item[10],
'fewfollowings': item[11],
'fewfollowers': item[12],
'fewstatus': item[13],
'fewfavorites': item[14],
}}
db.close()
return json.dumps(item)
@app.route('/server/analysis/<id>', methods=['POST'])
def analysis_post(id):
formData = request.form.to_dict(flat=True)
if not Utils.ValidateField(formData, 'name', checkEmpty=True):
return 'Missing required field!', 403
if not Utils.ValidateField(formData, 'description', checkEmpty=True):
formData['description'] = None
editedItem = (formData['name'], formData['description'], )
db = DBConnection()
item = db.fetchOne('SELECT `id` FROM `analysis` WHERE `id`=%s', (id, ))
if item is None:
db.close()
return 'Analysis does not exist!', 404
db.execute('UPDATE `analysis` SET `name` = %s, `description` = %s WHERE `id` = %s', editedItem + (item[0], ))
db.close()
return '', 204
@app.route('/server/analysis/<id>', methods=['DELETE'])
def analysis_delete(id):
db = DBConnection()
id = db.fetchOne('SELECT `id` FROM `analysis` WHERE `id`=%s', (id, ))
if id is None:
db.close()
return 'Analysis does not exist!', 404
db.execute('DELETE FROM `analysis` WHERE `id`=%s', (id[0], )) # Delete analysis.
db.close()
return '', 204
if __name__ == '__main__':
Config.Init()
APICommunicator.Init()
TaskManager.Init()
TaskNode.Init()
app.run(host='0.0.0.0', port=8080)
<file_sep>
/*
* == Lista Enumerada ==
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __List_H_
#define __List_H_
typedef int LIST_EL;
typedef struct __List_t LIST;
struct __List_t *L_New();
int L_Size(struct __List_t *);
char L_Add(LIST_EL,struct __List_t *);
char L_AddAt(LIST_EL,int,struct __List_t *);
char L_Remove(struct __List_t *);
char L_RemoveAt(int,struct __List_t *);
LIST_EL L_Get(struct __List_t *);
LIST_EL L_GetAt(int,struct __List_t *);
char L_Set(LIST_EL,struct __List_t *);
char L_SetAt(LIST_EL,int,struct __List_t *);
char L_Destroy(struct __List_t *L);
#endif
<file_sep>
#ifndef H_CONSTS
#define H_CONSTS
#define STATUS_INCONSISTENTE '0'
#define STATUS_CONSISTENTE '1'
#define R_NAO_REMOVIDO '-'
#define R_REMOVIDO '*'
#define L_NIL -1
#define BINARY_DISK_FILE "arquivoTrab.bin"
#define LIXO '@'
#endif<file_sep>#include <stdlib.h>
#include <stdio.h>
#include "List.h"
/*
* == Inteiros Ilimitados ==
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
enum __UI_bool_t { false = 0, true };
struct __UI_t {
enum __UI_bool_t Negative;
LIST *Number;
};
struct __UI_t *UI_New(){
/*
* Esta função retorna o número zero.
*/
struct __UI_t *NewUI=(struct __UI_t *)malloc(sizeof(struct __UI_t *));
NewUI->Negative=false;
NewUI->Number=L_New();
return NewUI;
}
struct __UI_t *UI_NewFromInt(long int NumberInt){
/*
* Esta função vai criar um número a partir de um inteiro padrão (long int) e retornar tal.
*/
struct __UI_t *NewUI=(struct __UI_t *)malloc(sizeof(struct __UI_t));
char R[30],RX[2]="0";
int i=0,j;
NewUI->Number=L_New();
if(NumberInt>=0) NewUI->Negative=false;
else NewUI->Negative=true;
if(NumberInt==0) return NewUI;
sprintf(R,"%ld",(unsigned long int)NumberInt);
while(R[i]!='\0') i++; // i=strlen(R);
for(j=i-1;j>=0;j--){
RX[0]=R[j];
L_Add((char)atoi(RX),NewUI->Number);
}
return NewUI;
}
struct __UI_t *UI_Read(FILE *FStream){
/*
* Esta função vai ler um número de 'FStream' e retornar tal.
* Ela funciona para números negativos.
*
* Em caso de leitura impossibilitada, irá retornar o número '0'.
*/
char R,RX[2]="0",*NewNumber=(char *)malloc(sizeof(char *)*1);
struct __UI_t *NewUI=(struct __UI_t *)malloc(sizeof(struct __UI_t));
int i,Len=0;
NewUI->Negative=false;
while( !((R=getc(FStream))>='0' && R<='9') ){
if(R=='-') NewUI->Negative=true;
if(R==EOF) break;
}
while( R>='0' && R<='9'){
NewNumber=(char *)realloc(NewNumber,sizeof(char)*(Len+2));
NewNumber[Len++]=R;
R=getc(FStream);
}
NewNumber[Len]='\0';
NewUI->Number=L_New();
if(Len>0){
for(i=Len-1;i>=0;i--){
RX[0]=NewNumber[i];
L_Add((char)atoi(RX),NewUI->Number);
}
}else{
NewUI->Negative=false;
}
for(i=L_Size(NewUI->Number)-1;i>=0;i--){
if(L_Get(NewUI->Number)==0) L_Remove(NewUI->Number);
else break;
}
free(NewNumber);
return NewUI;
}
char UI_Write(FILE *FStream, struct __UI_t *N){
/*
* Esta função vai escrever um número em 'FStream'.
*
* Retorna -1 em caso de erros, 0 quando o número escrito é o próprio zero, e 1 em caso de escrita de qualquer outro número.
*/
if(N->Number==NULL) return -1;
int i,Len=L_Size(N->Number);
if(Len<=0){
fprintf(FStream,"0");
return 0;
}
if(N->Negative==true) fprintf(FStream,"-");
for(i=Len-1;i>=0;i--){
fprintf(FStream,"%d",(int)L_GetAt(i,N->Number));
}
return 1;
}
char UI_Cmp(struct __UI_t *A, struct __UI_t *B){
/*
* Esta função compara 'A' com 'B'.
*
* Retorna -2 em caso de erros, -1 para 'A' maior que 'B', 0 para 'A' igual a 'B', e 1 para 'A' menor que 'B'.
*/
if(A->Number==NULL || B->Number==NULL) return -2;
if(A->Negative==false && B->Negative==true) return -1;
if(A->Negative==true && B->Negative==false) return 1;
int i,ALen=L_Size(A->Number),BLen=L_Size(B->Number);
char AR,BR;
if(ALen>BLen) return -1;
if(ALen<BLen) return 1;
if(A->Negative==false)
for(i=ALen-1;i>=0;i--){
AR=L_GetAt(i,A->Number);
BR=L_GetAt(i,B->Number);
if(AR>BR) return -1;
if(AR<BR) return 1;
}
else
for(i=ALen-1;i>=0;i--){
AR=L_GetAt(i,A->Number);
BR=L_GetAt(i,B->Number);
if(AR>BR) return 1;
if(AR<BR) return -1;
}
return 0;
}
struct __UI_t *UI_Abs(struct __UI_t *N){
/*
* Esta função retorna o valor absoluto (módulo) de 'N'.
*
* Em caso de erros, retorna NULL.
*/
if(N==NULL || N->Number==NULL) return NULL;
struct __UI_t *NewUI=(struct __UI_t *)malloc(sizeof(struct __UI_t));
int i;
NewUI->Negative=false;
NewUI->Number=L_New();
for(i=0;i<L_Size(N->Number);i++) L_Add(L_GetAt(i,N->Number),NewUI->Number);
return NewUI;
}
struct __UI_t *UI_Subtraction(struct __UI_t *,struct __UI_t *); // Declaração explícita.
char UI_Destroy(struct __UI_t *); // Declaração explícita.
struct __UI_t *UI_Sum(struct __UI_t *A,struct __UI_t *B){
/*
* Esta função retorna a soma de 'A' com 'B' (A+B).
*
* Em caso de erros, retorna NULL.
*/
if(A==NULL || A->Number==NULL || B==NULL || B->Number==NULL) return NULL;
struct __UI_t *RUI,*NewUI;
if(A->Negative==false && B->Negative==true){ // A-B
RUI=UI_Abs(B);
NewUI=UI_Subtraction(A,RUI);
UI_Destroy(RUI);
return NewUI;
}
if(A->Negative==true && B->Negative==false){ // B-A
RUI=UI_Abs(A);
NewUI=UI_Subtraction(B,RUI);
UI_Destroy(RUI);
return NewUI;
}
int i,ALen,BLen,Len;
char R=0;
NewUI=(struct __UI_t *)malloc(sizeof(struct __UI_t));
NewUI->Number=L_New();
if(A->Negative==false && B->Negative==false) NewUI->Negative=false; // A+B
else if(A->Negative==true && A->Negative==true) NewUI->Negative=true; // A+B
ALen=L_Size(A->Number);
BLen=L_Size(B->Number);
if(ALen<=BLen) Len=ALen;
else Len=BLen;
for(i=0;i<Len;i++){
R+=L_GetAt(i,A->Number)+L_GetAt(i,B->Number);
L_Add(R%10,NewUI->Number);
R/=10;
}
if(ALen<BLen){
for(i=ALen;i<BLen;i++){
R+=L_GetAt(i,B->Number);
L_Add(R%10,NewUI->Number);
R/=10;
}
}else if(ALen>BLen){
for(i=BLen;i<ALen;i++){
R+=L_GetAt(i,A->Number);
L_Add(R%10,NewUI->Number);
R/=10;
}
}
while(R>0){
L_Add(R%10,NewUI->Number);
R/=10;
}
return NewUI;
}
struct __UI_t *UI_Subtraction(struct __UI_t *A,struct __UI_t *B){
/*
* Esta função retorna a subtração de 'A' com 'B' (A-B).
*
* Em caso de erros, retorna NULL.
*/
if(A==NULL || A->Number==NULL || B==NULL || B->Number==NULL) return NULL;
struct __UI_t *AUI,*BUI,*NewUI;
if(A->Negative==false && B->Negative==true){ // A+B
BUI=UI_Abs(B);
NewUI=UI_Sum(A,BUI);
UI_Destroy(BUI);
return NewUI;
}
if(A->Negative==true && B->Negative==false){ // -(A+B)
AUI=UI_Abs(A);
NewUI=UI_Sum(AUI,B);
NewUI->Negative=true;
UI_Destroy(AUI);
return NewUI;
}
if(A->Negative==true && B->Negative==true){ // B-A (!= A-B)
AUI=UI_Abs(A);
BUI=UI_Abs(B);
NewUI=UI_Subtraction(BUI,AUI);
UI_Destroy(AUI);
UI_Destroy(BUI);
return NewUI;
}
char R=0,RA,RB,Sub,ABCmp;
int i,ALen,BLen,Len;
NewUI=(struct __UI_t *)malloc(sizeof(struct __UI_t));
NewUI->Number=L_New();
NewUI->Negative=false;
ABCmp=UI_Cmp(A,B);
if(ABCmp==0) return NewUI;
if(ABCmp<0){ // A-B
AUI=A;
BUI=B;
}else{ // -(B-A)
AUI=B;
BUI=A;
NewUI->Negative=true;
}
ALen=L_Size(AUI->Number);
BLen=L_Size(BUI->Number);
if(ALen<=BLen) Len=ALen;
else Len=BLen;
for(i=0;i<Len;i++){
RA=L_GetAt(i,AUI->Number)-R;
RB=L_GetAt(i,BUI->Number);
if(RA<0 && RB<=0){
R=1;
Sub=9;
}else if(RA<0){
R=1;
Sub=9-RB;
}else if(RA<RB){
R=1;
Sub=10+RA-RB;
}else{
R=0;
Sub=RA-RB;
}
L_Add(Sub,NewUI->Number);
}
if(ALen<BLen){
for(i=ALen;i<BLen;i++){
Sub=L_GetAt(i,BUI->Number)-R;
if(Sub<0){
R=1;
L_Add(9,NewUI->Number);
}else{
R=0;
L_Add(Sub,NewUI->Number);
}
}
}else if(ALen>BLen){
for(i=BLen;i<ALen;i++){
Sub=L_GetAt(i,AUI->Number)-R;
if(Sub<0){
R=1;
L_Add(9,NewUI->Number);
}else{
R=0;
L_Add(Sub,NewUI->Number);
}
}
}
for(i=L_Size(NewUI->Number)-1;i>=0;i--){
if(L_Get(NewUI->Number)==0) L_Remove(NewUI->Number);
else break;
}
return NewUI;
}
struct __UI_t *UI_Product(struct __UI_t *A,struct __UI_t *B){
/*
* Esta função vai retornar o produto de 'A' com 'B' (A*B).
*
* Em caso de erros, retorna NULL.
*/
if(A==NULL || A->Number==NULL || B==NULL || B->Number==NULL) return NULL;
if(L_Size(A->Number)<=0) return UI_NewFromInt(0);
if(L_Size(B->Number)<=0) return UI_NewFromInt(0);
struct __UI_t *ProUI,*RUI,*AUI,*BUI,*NewUI;
int i,j;
char R;
AUI=UI_Abs(A);
BUI=UI_Abs(B);
NewUI=UI_NewFromInt(0);
for(i=0;i<L_Size(BUI->Number);i++){
ProUI=UI_NewFromInt(0);
R=0;
if(L_GetAt(i,BUI->Number)!=0){
for(j=0;j<i;j++) L_Add(0,ProUI->Number);
for(j=0;j<L_Size(AUI->Number);j++){
R+=L_GetAt(i,BUI->Number)*L_GetAt(j,AUI->Number);
L_Add(R%10,ProUI->Number);
R/=10;
}
while(R>0){
L_Add(R%10,ProUI->Number);
R/=10;
}
}
RUI=NewUI;
NewUI=UI_Sum(RUI,ProUI);
UI_Destroy(RUI);
UI_Destroy(ProUI);
}
UI_Destroy(AUI);
UI_Destroy(BUI);
if(A->Negative!=B->Negative) NewUI->Negative=true;
else NewUI->Negative=false;
return NewUI;
}
struct __UI_t *UI_Quotient(struct __UI_t *A,struct __UI_t *B){
/*
* Esta função retorna o quociente de 'A' com 'B' (A/B).
*
* Em caso de erros, inclusive divisão por zero, retorna NULL.
*/
if(A==NULL || A->Number==NULL || B==NULL || B->Number==NULL) return NULL;
if(L_Size(B->Number)<=0) return NULL;
if(L_Size(A->Number)<=0) return UI_NewFromInt(0);
struct __UI_t *MinUI,*QuoUI,*RUI,*BUI,*NewUI;
int i;
char R;
BUI=UI_Abs(B);
MinUI=UI_NewFromInt(0);
QuoUI=UI_NewFromInt(0);
NewUI=UI_NewFromInt(0);
for(i=L_Size(A->Number)-1;i>=0;i--){
L_AddAt(L_GetAt(i,A->Number),0,QuoUI->Number);
if(UI_Cmp(QuoUI,BUI)>0) continue;
R=-1;
while(UI_Cmp(QuoUI,MinUI)<=0){
RUI=QuoUI;
QuoUI=UI_Subtraction(RUI,BUI);
UI_Destroy(RUI);
R++;
}
RUI=QuoUI;
QuoUI=UI_Sum(QuoUI,BUI);
UI_Destroy(RUI);
L_AddAt(R,0,NewUI->Number);
}
UI_Destroy(BUI);
UI_Destroy(MinUI);
UI_Destroy(QuoUI);
if(A->Negative!=B->Negative) NewUI->Negative=true;
else NewUI->Negative=false;
return NewUI;
}
char UI_Destroy(struct __UI_t *N){
/*
* Esta função realiza a limpeza de 'N' da memória.
*
* Ela retorna -1 em caso de erros, 0 caso parte da estrutura já esteja limpa, e 1 caso a limpeza tenha sido realizada com sucesso e por completo.
* Nota 1: Esta função é constantemente usada anteriormente, pois ela auxilia na limpeza de "flags" da memória.
*/
if(N==NULL) return -1;
if(N->Number==NULL){
free(N);
return 0;
}
L_Destroy(N->Number);
free(N);
return 1;
}
<file_sep>
#
# ~ Calculadora ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -Wall -ansi -pedantic
objects/main.o: main.c objects/calc.o headers/calc.h
gcc -c -o objects/main.o main.c -Wall -ansi -pedantic -I headers
objects/calc.o: lib/calc.c objects/super_file.o headers/super_file.h objects/stack.o headers/stack.h objects/linkedlist.o headers/linkedlist.h
gcc -c -o objects/calc.o lib/calc.c -Wall -ansi -pedantic -I headers
objects/linkedlist.o: lib/linkedlist.c headers/linkedlist.h
gcc -c -o objects/linkedlist.o lib/linkedlist.c -Wall -ansi -pedantic -I headers
objects/stack.o: lib/stack.c headers/stack.h
gcc -c -o objects/stack.o lib/stack.c -Wall -ansi -pedantic -I headers
objects/super_file.o: lib/super_file.c
gcc -c -o objects/super_file.o lib/super_file.c -Wall -ansi -pedantic
run: Prog
./Prog
clean:
rm Prog objects/*.o
<file_sep>
#ifndef REGISTER2_H_
#define REGISTER2_H_
typedef struct {
int RRN;
char removed;
int idPessoaQueSegue;
int idPessoaQueESeguida;
char grauAmizade[3];
char dataInicioQueSegue[11];
char dataFimQueSegue[11];
} REG2_DATA;
typedef struct {
char status;
int quantidadeSeguidores;
} REG2_HEADER;
int R2_readH(REG2_HEADER *dest, FILE *stream);
int R2_writeH(REG2_HEADER *src, FILE *stream);
int R2_read(REG2_DATA *dest, FILE *stream);
int R2_write(REG2_DATA *src, FILE *stream);
int R2_rewrite(REG2_DATA *src, FILE *stream);
int R2_print(REG2_DATA *reg);
#endif<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <register.h>
#include <consts.h>
int R_lerCabecalho(CABECALHO_T *dest, FILE *stream) {
char buff[TAM_REGISTRO_CABECALHO + 1], *ptr;
long pos, newPos;
pos = ftell(stream);
memset(dest, R_NIL, sizeof(CABECALHO_T));
memset(buff, R_NIL, TAM_REGISTRO_CABECALHO + 1);
if(pos < 0 || fseek(stream, 0, SEEK_SET) != 0 || fread(&dest->status, sizeof(char), 1, stream) != 1) {
dest->status = R_FALSE; // Forces FALSE state.
return 0;
}
if(dest->status != R_TRUE) { // Header was read successfully, but file is corrupt.
dest->status = R_FALSE;
return 1;
}
buff[0] = dest->status;
ptr = buff + 1;
if(fread(ptr, TAM_REGISTRO_CABECALHO - 1, 1, stream) != 1) {
return 0;
}
memcpy(&dest->numeroVertices, ptr, sizeof(int));
ptr += sizeof(int);
memcpy(&dest->numeroArestas, ptr, sizeof(int));
ptr += sizeof(int);
memcpy(dest->dataUltimaCompactacao, ptr, sizeof(char) * 10);
ptr += 10;
if((newPos = ftell(stream)) < 0) {
return 0;
}
if(newPos < pos) {
return (fseek(stream, pos, SEEK_SET) == 0) ? 1:0;
}
return 1;
}
int R_escreverCabecalho(CABECALHO_T *src, FILE *stream) {
char buff[TAM_REGISTRO_CABECALHO + 1], *ptr;
long pos, newPos;
char rewrite;
pos = ftell(stream);
if(pos < 0 || fseek(stream, 0, SEEK_SET) != 0) {
return 0;
}
rewrite = R_TRUE;
if(fread(buff, TAM_REGISTRO_CABECALHO, 1, stream) != 1) {
rewrite = R_FALSE;
}
if(fseek(stream, 0, SEEK_SET) != 0) {
return 0;
}
memset(buff, R_LIXO, TAM_REGISTRO_CABECALHO);
buff[TAM_REGISTRO_CABECALHO] = R_NIL;
ptr = buff;
memset(ptr, ((src->status == R_TRUE) ? R_TRUE:R_FALSE), sizeof(char));
ptr += 1;
if(src->status == R_TRUE) {
memcpy(ptr, &src->numeroVertices, sizeof(int));
ptr += sizeof(int);
memcpy(ptr, &src->numeroArestas, sizeof(int));
ptr += sizeof(int);
memcpy(ptr, src->dataUltimaCompactacao, strlen(src->dataUltimaCompactacao));
ptr += strlen(src->dataUltimaCompactacao);
}
if(rewrite == R_FALSE) {
if(fwrite(buff, TAM_REGISTRO_CABECALHO, 1, stream) != 1) {
return 0;
}
return 1;
}
if(fwrite(buff, ptr - buff, 1, stream) != 1) {
return 0;
}
if((newPos = ftell(stream)) < 0) {
return 0;
}
if(newPos < pos) {
return (fseek(stream, pos, SEEK_SET) == 0) ? 1:0;
}
return 1;
}
int R_lerRegistro(REGISTRO_T *dest, FILE *stream) {
char buff[TAM_REGISTRO_DADOS + 1], *ptr;
long pos;
pos = ftell(stream);
memset(buff, R_NIL, TAM_REGISTRO_DADOS + 1);
if(pos < 0 || fread(buff, TAM_REGISTRO_DADOS, 1, stream) != 1) {
return 0;
}
memset(dest, R_NIL, sizeof(REGISTRO_T));
dest->RRN = (pos - TAM_REGISTRO_CABECALHO) / TAM_REGISTRO_DADOS;
if(buff[0] == R_REMOVIDO) {
dest->removido = R_TRUE;
return 1;
}
dest->removido = R_FALSE;
ptr = buff;
memcpy(dest->estadoOrigem, ptr, sizeof(char) * 2);
ptr += 2;
memcpy(dest->estadoDestino, ptr, sizeof(char) * 2);
ptr += 2;
memcpy(&dest->distancia, ptr, sizeof(int));
ptr += sizeof(int);
// Strings written in file do not end in '\0', but '|' instead
sscanf(ptr, "%[^|]", dest->cidadeOrigem);
ptr += strlen(dest->cidadeOrigem) + 1;
sscanf(ptr, "%[^|]", dest->cidadeDestino);
ptr += strlen(dest->cidadeDestino) + 1;
sscanf(ptr, "%[^|]", dest->tempoViagem);
return 1;
}
int R_escreverRegistro(REGISTRO_T *src, FILE *stream) {
char buff[TAM_REGISTRO_DADOS + 1], *ptr;
long pos;
pos = ftell(stream);
if(pos < 0) {
return 0;
}
memset(buff, R_LIXO, TAM_REGISTRO_DADOS);
buff[TAM_REGISTRO_DADOS] = R_NIL;
ptr = buff;
if(src->removido == R_TRUE) {
memset(ptr, R_REMOVIDO, 1);
ptr += 1;
} else {
memcpy(ptr, src->estadoOrigem, sizeof(char) * 2);
ptr += 2;
memcpy(ptr, src->estadoDestino, sizeof(char) * 2);
ptr += 2;
memcpy(ptr, &src->distancia, sizeof(int));
ptr += sizeof(int);
memcpy(ptr, src->cidadeOrigem, sizeof(char) * strlen(src->cidadeOrigem));
ptr += strlen(src->cidadeOrigem);
memset(ptr, R_DELIMITADOR, sizeof(char));
ptr += 1;
memcpy(ptr, src->cidadeDestino, sizeof(char) * strlen(src->cidadeDestino));
ptr += strlen(src->cidadeDestino);
memset(ptr, R_DELIMITADOR, sizeof(char));
ptr += 1;
memcpy(ptr, src->tempoViagem, sizeof(char) * strlen(src->tempoViagem));
ptr += strlen(src->tempoViagem);
memset(ptr, R_DELIMITADOR, sizeof(char));
ptr += 1;
}
src->RRN = (pos - TAM_REGISTRO_CABECALHO) / TAM_REGISTRO_DADOS;
if(fwrite(buff, TAM_REGISTRO_DADOS, 1, stream) != 1) {
return 0;
}
return 1;
}
int R_reescreverRegistro(REGISTRO_T *src, FILE *stream) {
char buff[TAM_REGISTRO_DADOS + 1], *ptr;
long len, pos;
if(src->RRN < 0) {
return 0;
}
pos = ftell(stream);
len = TAM_REGISTRO_CABECALHO + (src->RRN * TAM_REGISTRO_DADOS);
if(pos < 0 || fseek(stream, len, SEEK_SET) != 0) {
return 0;
}
if(fread(buff, TAM_REGISTRO_DADOS, 1, stream) != 1) { // Verificar se realmente já tem um registro escrito aqui.
return 0;
}
if(fseek(stream, len, SEEK_SET) != 0) {
return 0;
}
memset(buff, R_LIXO, TAM_REGISTRO_DADOS);
buff[TAM_REGISTRO_DADOS] = R_NIL;
ptr = buff;
if(src->removido == R_TRUE) {
memset(ptr, R_REMOVIDO, 1);
ptr += 1;
} else {
memcpy(ptr, src->estadoOrigem, sizeof(char) * 2);
ptr += 2;
memcpy(ptr, src->estadoDestino, sizeof(char) * 2);
ptr += 2;
memcpy(ptr, &src->distancia, sizeof(int));
ptr += sizeof(int);
memcpy(ptr, src->cidadeOrigem, sizeof(char) * strlen(src->cidadeOrigem));
ptr += strlen(src->cidadeOrigem);
memset(ptr, R_DELIMITADOR, sizeof(char));
ptr += 1;
memcpy(ptr, src->cidadeDestino, sizeof(char) * strlen(src->cidadeDestino));
ptr += strlen(src->cidadeDestino);
memset(ptr, R_DELIMITADOR, sizeof(char));
ptr += 1;
memcpy(ptr, src->tempoViagem, sizeof(char) * strlen(src->tempoViagem));
ptr += strlen(src->tempoViagem);
memset(ptr, R_DELIMITADOR, sizeof(char));
ptr += 1;
}
if(fwrite(buff, ptr - buff, 1, stream) != 1) {
return 0;
}
if(fseek(stream, pos, SEEK_SET) != 0) {
return 0;
}
return 1;
}
<file_sep># SCC-0211 Laboratório de Algoritmos Avançados II - 2020.2
Aqui estão alguns dos exercícios que implementei em Laboratório de Algoritmos Avançados II.
<file_sep>
#
# ~ Dicionário ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -Wall -ansi -pedantic
objects/main.o: main.c objects/skiplist.o headers/skiplist.h
gcc -c -o objects/main.o main.c -Wall -ansi -pedantic -I headers
objects/skiplist.o: lib/skiplist.c headers/skiplist.h
gcc -c -o objects/skiplist.o lib/skiplist.c -Wall -ansi -pedantic -I headers
run: Prog
./Prog
clean:
rm Prog objects/*.o
<file_sep>
#ifndef REGISTER_H_
#define REGISTER_H_
typedef struct {
int RRN;
char removed;
int idPessoa;
char nomePessoa[100];
int idadePessoa;
char twitterPessoa[100];
} REG_DATA;
typedef struct {
char status;
int quantidadePessoas;
} REG_HEADER;
int R_readH(REG_HEADER *dest, FILE *stream);
int R_writeH(REG_HEADER *src, FILE *stream);
int R_read(REG_DATA *dest, FILE *stream);
int R_write(REG_DATA *src, FILE *stream);
int R_rewrite(REG_DATA *src, FILE *stream);
int R_print(REG_DATA *reg);
#endif<file_sep># FormRobber
Extensão de navegador que captura todos os dados submetidos em formulários na web e envia para um servidor externo. Compatível com Google Chrome e Opera.
Note que este projeto tem objetivo único o conhecimento de segurança da informação, mais especificamente relacionado a ataques web XSS (cross-site scripting). O projeto não deve ser usado intencionalmente para outros fins, especialmente se tais fins forem ilegais ou antiéticos.
## Organização do Repositório
* [Extensao](Extensao): aqui se encontram os arquivos da extensão de navegador, que atacará as páginas web e enviará ao servidor externo dados submetidos.
* [Servidor](Servidor): aqui se encontram os arquivos do servidor, que receberá os dados enviados pela extensão.
<file_sep>
/*
* ~ LABYRINTH ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __Labyrinth_H_
#define __Labyrinth_H_
typedef struct __lab_t LABYRINTH;
struct __lab_t *ReadLab(FILE *);
char FindSolutionsWithoutTreasure(struct __lab_t *);
char FindSolutionsWithTreasure(struct __lab_t *);
char SortSolutions(struct __lab_t *);
char PrintSolutions(struct __lab_t *,FILE *);
char DestroyLab(struct __lab_t *);
#endif
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
<NAME>
<EMAIL>
*/
int main(){
unsigned int i,j,ic=0,n;
double s=0;
char is_prime;
scanf("%d",&n);
for(i=2;i<=n;i++){
is_prime=1;
for(j=2;j<=sqrt(n);j++){
if(i!=j && !(i%j)){
is_prime=0;
break;
}
}
if(is_prime){
if(ic%2){
s-=1/(double)i;
}else{
s+=1/(double)i;
}
ic++;
}
}
printf("%.7lf",s);
return EXIT_SUCCESS;
}<file_sep>#include <stdio.h>
#include "stack.h"
/*
* ~ MATRIOSKA ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
enum __Matrioska_LastStackAction_t { Popped = 0, Pushed };
int Matrioska_Check(FILE *FStream){
/*
* Esta função verifica se em 'FStream' há uma sequência que descreve uma "Matrioska" aguardando para ser lida.
*
* Ela retorna o número de Matrioskas possíveis de ser criadas com a sequência, ou -1 em caso de erros de empilhamento, e -2 em caso de erros de chegar ao fim sem terminar de fato a sequência.
*/
STACK *DoolStack;
int N=0,R;
enum __Matrioska_LastStackAction_t Last=Popped;
fscanf(FStream,"%d",&R);
if(R==0){
return 0; // Começou finalizando.
}else if(R>0){
return -2; // O primeiro valor da sequência já indica que não é uma Matroska.
}
DoolStack=S_New();
S_Push(R,DoolStack);
while(R!=0){
if(R<0){
if(S_Size(DoolStack)>0 && Last==Pushed && R<S_Get(DoolStack)){
S_Destroy(DoolStack);
return -2;
}
S_Push(R,DoolStack);
if(Last==Popped){
N++;
}
Last=Pushed;
}else if(R>0){
if(S_Size(DoolStack)<=0 || (R*-1)!=S_Get(DoolStack)){
S_Destroy(DoolStack);
return -2;
}
S_Pop(DoolStack);
Last=Popped;
}
fscanf(FStream,"%d",&R);
}
if(S_Size(DoolStack)!=1){
S_Destroy(DoolStack);
return -1;
}
S_Destroy(DoolStack);
return N; // Sucesso na sequência.
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
Por <NAME>.
<EMAIL>
*/
int main(){
unsigned int N,i,k;
scanf("%d",&N);
float Ni[N];
double DCT;
for(k=0;k<N;k++){
scanf("%f",&Ni[k]);
}
for(k=0;k<N;k++){
DCT=0;
for(i=0;i<N;i++){
DCT+=Ni[i]*cos((M_PI/N)*(i+0.5)*k);
}
printf("%.6lf\n",DCT);
}
return EXIT_SUCCESS;
}
<file_sep>
#include <stdlib.h>
#include <stdio.h>
/*
* Abaixo seguem funções que fazem a escrita do binário em "stdout" (tela) pra poder ser comparado no run.codes.
*
* Funciona assim: você faz tudo o que tiver que fazer na funcionalidade no arquivo em disco, assim como ensinado nas aulas da disciplina.
* Ao fim da funcionalidade, você escolhe uma das funções abaixo (a que achar mais fácil de usar de acordo com sua implementação) e a função já cuida de tudo para você. É só chamar a função.
*
* "Qual função escolher?"
* As duas fazem A MESMA coisa: escrever na tela o arquivo binário para funcionar com o sistema do run.codes.
* - Você escolhe a binarioNaTela1 se você ainda não fez o fclose no arquivo binário. Você passa o ponteiro 'FILE *' para ela e ela vai ler tudo e escrever na tela.
* - Você escolhe a binarioNaTela2 se você já fez o fclose no arquivo binário. Você passa o nome do arquivo binário ("arquivoTrabX.bin") pra ela e ela vai ler tudo e escrever na tela.
*
* Você pode colocar isso num módulo .h separado, ou incluir as funções no próprio código .c: como preferir.
* VOCÊ NÃO PRECISA ENTENDER ESSAS FUNÇÕES. É só usar elas da forma certa depois de acabar a funcionalidade.
*
* Tá tudo testado e funcionando, mas qualquer dúvida acerca dessas funções, falar com o monitor Matheus (<EMAIL>).
*/
// Se você for incluir no .h separado, tá abaixo:
#ifndef H_ESCREVERNATELA_
#define H_ESCREVERNATELA_
#include <stdio.h>
void binarioNaTela1(FILE *ponteiroArquivoBinario);
void binarioNaTela2(char *nomeArquivoBinario);
#endif
// Acabou o código que vai no .h
// Abaixo vai em algum .c
void binarioNaTela1(FILE *ponteiroArquivoBinario) {
/* Escolha essa função se você ainda tem o ponteiro de arquivo 'FILE *' aberto.
* Lembrando que você tem que ter aberto ele no fopen para leitura também pra funcionar (exemplo: rb, rb+, wb+, ...) */
size_t fl;
char *mb;
fseek(ponteiroArquivoBinario, 0, SEEK_END);
fl = ftell(ponteiroArquivoBinario);
fseek(ponteiroArquivoBinario, 0, SEEK_SET);
mb = (char *) malloc(fl);
fread(mb, 1, fl, ponteiroArquivoBinario);
fwrite(mb, 1, fl, stdout);
free(mb);
}
void binarioNaTela2(char *nomeArquivoBinario) {
/* Escolha essa função se você já fechou o ponteiro de arquivo 'FILE *'.
* Ela vai abrir de novo para leitura e depois fechar. */
size_t fl;
FILE *fs;
char *mb;
if(nomeArquivoBinario == NULL || !(fs = fopen(nomeArquivoBinario, "rb"))) {
fprintf(stderr, "ERRO AO ESCREVER O BINARIO NA TELA (função binarioNaTela2): não foi possível abrir o arquivo que me passou para leitura. Ele existe e você tá passando o nome certo? Você lembrou de fechar ele com fclose depois de usar? Se você não fechou ele, pode usar a outra função, binarioNaTela1, ou pode fechar ele antes de chamar essa função!\n");
return;
}
fseek(fs, 0, SEEK_END);
fl = ftell(fs);
fseek(fs, 0, SEEK_SET);
mb = (char *) malloc(fl);
fread(mb, 1, fl, fs);
fwrite(mb, 1, fl, stdout);
free(mb);
fclose(fs);
}
<file_sep>#include <iostream>
#include <vector>
using namespace std;
typedef struct {
int v;
bool a;
} number;
void array_insert(vector<int> el, vector< vector<int> > *to){
unsigned int i, j, nto, nel;
bool valid = true;
nto = (*to).size();
for(i = 0; i < nto; i++){
nel = (*to)[i].size();
if(nel != el.size()) continue;
for(j = 0; j < nel; j++){
if(el[j] != (*to)[i][j]) goto end_continue;
}
valid = false;
break;
end_continue: ;
}
if(valid){
(*to).push_back(el);
}
}
void combine(vector<number> *numbers, vector< vector<int> > *results, int t, int pos){
unsigned int i, nn;
int sum;
nn = (*numbers).size();
vector<int> aux = vector<int>();
for(i = sum = 0; i < nn; i++){
if((*numbers)[i].a){
sum += (*numbers)[i].v;
aux.push_back((*numbers)[i].v);
}
}
if(sum == t && aux.size() > 0){
array_insert(aux, results);
}
if(aux.size() >= nn) return;
for(i = pos; i < nn; i++){
if((*numbers)[i].a == false){
(*numbers)[i].a = true;
combine(numbers, results, t, pos+1);
(*numbers)[i].a = false;
}
}
}
void print_results(vector< vector<int> > results){
unsigned int n, nr, i, j;
n = results.size();
for(i = 0; i < n; i++){
nr = results[i].size();
if(nr <= 0) continue;
cout << results[i][0];
for(j = 1; j < nr; j++){
cout << "+" << results[i][j];
}
cout << "\n";
}
if(n <= 0) cout << "NONE\n";
}
int main(int argc, char **argv){
unsigned int n, t, i;
cin >> t >> n;
while(n > 0 && t > 0){
vector<number> numbers = vector<number>();
vector< vector<int> > results = vector< vector<int> >();
for(i = 0; i < n; i++){
number aux;
aux.a = false;
cin >> aux.v;
numbers.push_back(aux);
}
cout << "Sums of " << t << ":\n";
combine(&numbers, &results, t, 0);
print_results(results);
cin >> t >> n;
}
return 0;
}<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "soccer.h"
/*
* ~ FUTEBOL ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv){
int i,N;
SOCCER_TOUR *Aux;
scanf("%d",&N); // Quantos torneios serão?
for(i=0;i<N;i++){ // Para cada torneio...
if(i>0) printf("\n");
Aux=S_NewFrom(stdin); // Ler torneio da entrada padrão.
S_Calc(Aux); // Calcular pontuação de cada equipe.
S_Sort(Aux); // Ordenar da forma correta.
S_Print(Aux,stdout); // Imprimir na saída padrão.
S_Destroy(Aux); // Limpar da memória.
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <vector>
#include <stack>
#include <queue>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
enum { left = 0, right = 1 };
int main(int argc, char **argv) {
long i, j, N, M, counter;
double L, l, carL;
int ferryAt;
char aux[20];
queue<double> carQueues[2];
scanf("%ld", &N);
for(i = 0; i < N; i++) {
scanf("%lf %ld", &L, &M);
ferryAt = left;
counter = 0;
L *= 100.0;
l = L;
carQueues[left] = queue<double>();
carQueues[right] = queue<double>();
for(j = 0; j < M; j++) { // Para cada carro nas filas...
scanf("%lf %s", &carL, aux);
if(*aux == 'l' || *aux == 'L') { // Carro chegou na fila da esquerda...
carQueues[left].push(carL);
} else { // Carro chegou na fila da direita...
carQueues[right].push(carL);
}
}
while(!carQueues[left].empty() || !carQueues[right].empty()) { // Processar filas...
while(!carQueues[ferryAt].empty() && l - carQueues[ferryAt].front() >= 0) { // Entrar no ferry enquanto couber...
l -= carQueues[ferryAt].front();
carQueues[ferryAt].pop();
}
// Não cabe mais OU acabou a fila.
ferryAt = (ferryAt + 1) % 2; // ferryAt = !ferryAt;
l = L; // Descarregar.
counter++;
}
printf("%ld\n", counter);
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <iostream>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b) {
if(b > 0) {
return gcd(b, a % b);
}
return a;
}
void testCase() {
ll S, A, N, takes;
bool Sturn;
cin >> S >> A >> N;
Sturn = true;
while(N > 0) {
if(Sturn) {
takes = gcd(S, N);
N -= takes;
} else {
takes = gcd(A, N);
N -= takes;
}
Sturn = !Sturn;
}
if(!Sturn) {
cout << '0';
} else {
cout << '1';
}
cout << endl;
}
int main(int argc, char **argv) {
ll T, N, K;
T = 1;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>#include <iostream>
#include <vector>
#include <cmath>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef struct {
int G[8][8];
int Q[8];
vector< vector<int> > solutions;
} Game;
void insert_solution(Game *G){
unsigned int i, j, nG, nS;
vector<int> S = vector<int>();
for(i = 0; i < 8; i++){
for(j = 0; j < 8; j++){
if(G->G[j][i] < 0){
S.push_back(j);
break;
}
}
}
if(S.size() != 8) return;
nG = G->solutions.size();
for(i = 0; i < nG; i++){
nS = G->solutions[i].size();
if(nS != S.size()) continue;
for(j = 0; j < nS; j++){
if(S[j] != G->solutions[i][j]) goto end_check;
}
return;
end_check: ;
}
G->solutions.push_back(S);
}
bool mark(int Row, int Column, int id, Game *G){
int i, DiagA, DiagB, Aux1, Aux2;
if(Row < 0 || Row >= 8 || Column < 0 || Column >= 8) return false;
if(G->G[Row][Column] != 0) return false;
G->G[Row][Column] = (G->G[Row][Column] | id) | 0b10000000000000000000000000000000;
DiagA = Column - Row;
DiagB = Column + Row;
for(i = 0; i < 8; i++){
G->G[Row][i] = G->G[Row][i] | id;
G->G[i][Column] = G->G[i][Column] | id;
Aux1 = i+DiagA;
Aux2 = (-1*i)+DiagB;
if(Aux1 >= 0 && Aux1 < 8) G->G[i][Aux1] = G->G[i][Aux1] | id;
if(Aux2 >= 0 && Aux2 < 8) G->G[i][Aux2] = G->G[i][Aux2] | id;
}
return true;
}
bool unmark(int Row, int Column, int id, Game *G){
int i, DiagA, DiagB, Aux1, Aux2;
if(Row < 0 || Row >= 8 || Column < 0 || Column >= 8) return false;
G->G[Row][Column] = (G->G[Row][Column] & ~id) & 0b01111111111111111111111111111111;
DiagA = Column - Row;
DiagB = Column + Row;
for(i = 0; i < 8; i++){
G->G[Row][i] = G->G[Row][i] & ~id;
G->G[i][Column] = G->G[i][Column] & ~id;
Aux1 = i+DiagA;
Aux2 = (-1*i)+DiagB;
if(Aux1 >= 0 && Aux1 < 8) G->G[i][Aux1] = G->G[i][Aux1] & ~id;
if(Aux2 >= 0 && Aux2 < 8) G->G[i][Aux2] = G->G[i][Aux2] & ~id;
}
return true;
}
void combine(int Row, int Column, int id, Game *G){
int i;
if(id >= 8){
insert_solution(G);
return;
}
if(mark(Row, Column, pow(2, id), G)){
for(i = 0; i < 8; i++){
combine(i, Column + 1, id + 1, G);
combine(i, Column + 2, id + 1, G);
}
unmark(Row, Column, pow(2, id), G);
}
}
void print_solutions(Game *G){
int i, j, nA, nB;
nA = G->solutions.size();
cout << "SOLN COLUMN\n" << " #\t\t1 2 3 4 5 6 7 8\n\n";
for(i = 0; i < nA; i++){
printf("%2d ", i+1);
nB = G->solutions[i].size();
for(j = 0; j < nB; j++){
cout << " " << G->solutions[i][j] + 1;
}
cout << "\n";
}
}
int main(int argc, char **argv){
int N, i, Row, j, Column;
Game Aux;
cin >> N;
for(i = 0; i < N; i++){
if(i) cout << "\n";
cin >> Row >> Column;
Row--;
Column--;
memset(&Aux, 0, sizeof(Game));
Aux.solutions = vector< vector<int> >();
mark(Row, Column, 1, &Aux);
for(j = 0; j < 8; j++){
combine(j, 0, 1, &Aux);
}
for(j = 0; j < 8; j++){
combine(j, Column + 1, 1, &Aux);
}
unmark(Row, Column, 1, &Aux);
print_solutions(&Aux);
}
return EXIT_SUCCESS;
}
<file_sep>FROM python:3.10-rc
ADD . /code
WORKDIR /code
RUN pip3 install -r requirements.txt
CMD python3 main.py<file_sep># Trabalho Prático de Sistemas Operacionais - 2018.2
Trabalho prático de Sistemas Operacionais.
## Membros do Grupo
- <NAME> (Nº 10258876)
- <NAME> <NAME> (Nº 10425420)
- <NAME> (Nº 10369014)
## Como executar
Para executar o trabalho, abra o arquivo [Calculus.jar](Calculus.jar) - necessário compilar - na Java Virtual Machine.
- Em alguns sistemas operacionais, basta clicar duas vezes [no arquivo](Calculus.jar).
- Em outros sistemas operacionais, é possível executar no terminal (bash) através do comando `java -jar Calculus.jar`.
## Workspace (Diretório de trabalho ou execução)
O projeto referencia os seus recursos (áudio e imagem) de forma relativa ao diretório de trabalho ou diretório de execução. Dentro deste, portanto, deve existir o diretório "src" com o código-fonte e recursos da aplicação.
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
#define N_DIAS_NO_MES 31
int main(){
int i,dias[N_DIAS_NO_MES],maior=-1,iinserted,iindex=-1;
for(i=1;i<=N_DIAS_NO_MES;i++){
scanf("%d",&iinserted);
if(iinserted>maior){
maior=iinserted;
dias[0]=i;
iindex=0;
}else if(iinserted==maior){
dias[++iindex]=i;
}
}
if(maior>-1){
printf("%d\n",maior);
for(i=0;i<=iindex;i++){
printf("%d\n",dias[i]);
}
}
return EXIT_SUCCESS;
}<file_sep>import sys
import csv
#
# ~ Contador de Presenças Ganesh ~
# Este programa vai listar os membros presentes em alguma reunião específica.
# Ele recebe como entrada o arquivo *.CSV da tabela dos feedbacks separado
# por COMMA.
#
# <NAME> (017)
# Secretário (2018.2)
# <EMAIL>
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
COMMA = ',' # Delimitador de coluna do *.CSV
if len(sys.argv) < 3 or len(sys.argv) > 4:
print("Este programa lista os membros presentes em alguma reunião específica do Ganesh com base na tabela disponível no Google Drive.")
print("É necessário baixar essa tabela e utilizar a COMMA como separador.")
print("Uso do programa:")
print("\tpython3 " + sys.argv[0] + " CAMINHO_CSV FILTRO [JUSTIFICADO]")
print("Onde:")
print("\tCAMINHO_CSV -> caminho para o arquivo *.CSV da tabela com colunas separadas por COMMA")
print("\tFILTRO -> filtro que será usado para retornar os nomes")
print("\t[JUSTIFICADO] -> opcional: se for igual a 1, considera as justificativas como presença")
sys.exit(0);
with open(sys.argv[1], mode='r') as fStream:
lines = csv.reader(fStream, delimiter=COMMA)
lines = list(lines)
justified = False
frequency = { }
if len(sys.argv) == 4:
if sys.argv[3] == '1':
justified = True
for key in range(8, len(lines[0])):
for member in lines[2:]:
if member[key] != 'P' and (not justified or member[key] != 'J'):
continue
if not lines[0][key] in frequency:
frequency[lines[0][key]] = []
frequency[lines[0][key]].append(member)
for date in frequency:
if sys.argv[2] not in date:
continue
print("== Reunião geral " + date + ": " + str(len(frequency[date])) + " membros presentes ==")
for member in frequency[date]:
print(member[1])
print()
<file_sep># FormRobber (Servidor)
Aqui está o código (HTML, PHP e SQL) que fica armazenado no servidor que receberá os dados capturados pela extensão de navegador.
## Como configurar os arquivos do servidor
* Carregue todos os arquivos deste diretório ([config.php](config.php), [capture.php](capture.php), [admin.php](admin.php), [index.html](index.html), [jquery.min.js](jquery.min.js), [sleep.txt](sleep.txt) e [FormRobber.zip](FormRobber.zip)) em algum diretório do servidor. Deve haver suporte para PHP (com MySQLi) e MySQL Server.
* Atualize o *.ZIP [FormRobber.zip](FormRobber.zip) se for desejável: a variável "formSubmitURL" do arquivo [main.js](../Extensao/main.js) presente neste arquivo não está atualizada com o endereço do servidor (deve ser o endereço completo para a página [capture.php](capture.php)).
* Configure o arquivo [config.php](config.php): é necessário definir o endereço do servidor MySQL (ou _localhost_ caso seja na mesma máquina), o usuário do banco de dados, a senha do banco de dados e o nome do banco de dados. Além disso, é necessário definir uma senha de acesso ao painel de administrador ([admin.php](admin.php)), que por padrão é "admin".
## Como configurar o banco de dados MySQL
* Crie um novo banco de dados com o nome que desejar (utf8mb4_general_ci).
* Neste banco de dados, crie uma tabela com o nome "submits".
* Segue estrutura da tabela _submits_ que deve ser seguida à risca:
- id: char(128), not null, INDEX (PRIMARY, BTREE, unique, cardinality 10, collation A, not null)
- clientId: char(255), null, INDEX (BTREE, not unique, cardinality 2, collation A, null)
- time: timestamp, not null, INDEX (BTREE, not unique, cardinality 10, collation A, not null)
- ip: char(64), null
- data: mediumtext, null
- url: text, not null
- referrer: text, null
- userAgent: text, null
- cookie: text, null
* Crie um usuário do MySQL com o nome e senha desejados. Este será usado para acesso a este banco de dados.
* Dê permissões a este usuário de acessar e modificar a tabela _submits_ criada anteriormente.
* Pronto.
<file_sep>#include <stdlib.h>
#include <stdio.h>
/*
<NAME>
<EMAIL>
*/
/*
* Meu programa baseia-se principalmente no conceito de Matriz (para representar o Labirinto) e recursao (para caminhar sob ele).
*
* A funcao principal main() vai chamar GenerateLabyrinth() para gerar o labirinto e chamar WalkTowards() para verificar o caminho a ser tomado ate o fim
* do labirinto.
*
*/
// Gerar um "pseudo bool" na linguagem.
#define bool char
#define true 1
#define false 0
// Declarar as funcoes que existem no codigo para o compilador.
void GenerateLabyrinth(char (*Lab)[7]);
bool WalkTowards(int O_L,int O_C,int L,int C,int *Solution, char (*Lab)[7]);
int main(){
int i,start_point;
char Labyrinth[7][7]; // O labirinto sera armazenado nessa variavel.
int PathToSolution[21]={0}; // Vetor de solucao do labirinto. O primeiro elemento eh a contagem de passos que andamos.
GenerateLabyrinth(Labyrinth); // Gerar labirinto.
scanf(" %d",&start_point); // Por onde vamos comecar nesse labirinto?
if(start_point/7==6){
WalkTowards(6,start_point%7,5,start_point%7,PathToSolution,Labyrinth); // Comecamos por baixo do labirinto. Comeca a andar!
}else if(start_point/7==0){
WalkTowards(0,start_point%7,1,start_point%7,PathToSolution,Labyrinth); // Comecamos por cima...
}else if(start_point%7==6){
WalkTowards(start_point/7,6,start_point/7,5,PathToSolution,Labyrinth); // Comecamos pela direita...
}else{
WalkTowards(start_point/7,0,start_point/7,1,PathToSolution,Labyrinth); // Comecamos pela esquerda...
}
printf("%d ",start_point); // Imprime por onde comecamos.
for(i=PathToSolution[0];i>=1;i--){ // Imprime todo o caminho que fizemos pelo labirinto ate o fim.
printf("%d ",PathToSolution[i]);
}
printf("\n");
return EXIT_SUCCESS;
}
void GenerateLabyrinth(char (*Lab)[7]){ // Esta funcao gera o labirinto.
int L,C;
for(L=0;L<7;L++){ // Para cada linha...
for(C=0;C<7;C++){ // Para cada coluna...
scanf(" %d",(int *)&Lab[L][C]); // Ler cada valor de entrada do labirinto. Obs.: O casting eh necessario porque usei uma matriz de char para o labirinto.
}
}
}
bool WalkTowards(int O_L,int O_C,int L,int C,int *Solution, char (*Lab)[7]){ // Esta funcao caminha pelo labirinto.
bool ReturningValue=false;
if(!Lab[L][C]){ // Se o caminho estiver livre (ou seja, for igual a zero), vamos caminhar.
if(L+1!=O_L && L+1<=6 && !Lab[L+1][C]){ // Pode ir para cima?
ReturningValue=WalkTowards(L,C,L+1,C,Solution,Lab); // Sim! Vamos subir entao.
if(ReturningValue){ // O caminho para cima resulta no fim?
Solution[++Solution[0]]=L*7+C; // Sim! Salva todo o caminho no nosso vetor de solucao.
return ReturningValue; // Ja achamos o fim, pode encerrar todas as tentaivas aqui.
}
}
if(L-1!=O_L && L-1>=0 && !Lab[L-1][C]){ // Pode ir para baixo?
ReturningValue=WalkTowards(L,C,L-1,C,Solution,Lab);
if(ReturningValue){
Solution[++Solution[0]]=L*7+C;
return ReturningValue;
}
}
if(C+1!=O_C && C+1<=6 && !Lab[L][C+1]){ // Pode ir para a direita?
ReturningValue=WalkTowards(L,C,L,C+1,Solution,Lab);
if(ReturningValue){
Solution[++Solution[0]]=L*7+C;
return ReturningValue;
}
}
if(C-1!=O_C && C-1>=0 && !Lab[L][C-1]){ // Pode ir para a esquerda?
ReturningValue=WalkTowards(L,C,L,C-1,Solution,Lab);
if(ReturningValue){
Solution[++Solution[0]]=L*7+C;
return ReturningValue;
}
}
if((L==0) || (L==6) || (C==0) || (C==6)){ // Aparentemente nao pode ir para lugar nenhum. Chegamos no fim?
Solution[++Solution[0]]=L*7+C; // Sim! Salva as coordenadas do fim.
return true; // Chegamos no fim, entao retorna isso para que a funcao possa salvar todo o caminho que usamos para chegar aqui.
}
}
return ReturningValue; // Nao podemos nos mover e nem chegamos no fim! Retorna que estamos em um beco sem fim para a funcao sair dele e pegar outro caminho!
}
<file_sep>
#ifndef H_REGISTER
#define H_REGISTER
typedef struct {
long byteOffset;
char removed;
int size;
long next;
int idServidor;
double salarioServidor;
char telefoneServidor[14];
char nomeServidor[5000];
char cargoServidor[5000];
} REG_DATA;
typedef struct {
char status;
long first;
char desCampos[5][40];
} REG_HEADER;
int R_readH(REG_HEADER *dest, FILE *stream);
int R_writeH(REG_HEADER *src, FILE *stream);
int R_read(REG_DATA *dest, FILE *stream);
int R_write(REG_DATA *src, FILE *stream, long *lastOffset);
int R_rewriteBack(REG_DATA *src, FILE *stream);
int R_calculateSize(REG_DATA *r);
#endif<file_sep># SCC-0220 Laboratório de Introdução à Ciência da Computação 2 - 2017.2
Aqui estão todos os trabalhos que implementei em Laboratório de ICC 2.
<file_sep>package control;
import elements.*;
import utils.Consts;
import utils.Drawing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Janela principal do Jogo em ação
* <p>
* Classe que implementa o jogo propriamente dito
* </p>
*
*
*
* @author <NAME>, <NAME>, <NAME>.
* - Baseado em material do Prof. <NAME>
*/
public class GameFrame extends javax.swing.JFrame {
private static final boolean FREE = false;
private static final boolean OCCUPED = true;
private ArrayList<Element> elemArray;
private GameController controller;
private Pontuation points;
protected TetrisObject currentTetrisObject;
private Square[][] gameSquares; // Cada quadrado do game
private boolean isFull;
private int gameScreenWidth;
private int gameScreenHeight;
/*Placar provisório*/
private static JDialog placar;
private static JLabel placarScore;
static {
placar = new JDialog();
placarScore = new JLabel("Score: 0");
//placarScore.setFont(Consts.SCORE_FONT);
placar.add(placarScore);
placar.setSize(200,100);
}
/**
* Inicializa uma tela de jogo com seus elementos e obstáculos.
* @param elemArray elementos no jogo
* @param gameSquares inicia com os obstáculos (se houverem)
*/
public GameFrame(ArrayList<Element> elemArray, Square[][] gameSquares) {
Drawing.setGameFrame(this);
initComponents();
controller = new GameController(this); /*Controlador para o jogo atual*/
points = new Pontuation(Consts.BASE_POINT_INC); /*Sistema de pontuação*/
/*O objeto GameController controller passa a "ouvir" o teclado*/
this.addKeyListener(controller);
gameScreenWidth = Consts.NUM_COLUMNS * Consts.CELL_SIZE + getInsets().left + getInsets().right;
gameScreenHeight = Consts.NUM_LINES * Consts.CELL_SIZE + getInsets().top + getInsets().bottom;
/*Cria a janela do tamanho do tabuleiro + insets (bordas) da janela*/
this.setSize(gameScreenWidth, gameScreenHeight);
this.elemArray = elemArray;
/*Inicializa matriz de controle de blocos ocupados na tela do game*/
this.gameSquares = gameSquares;
isFull = false;
currentTetrisObject = null;
initScore();
/*Lança a primeira peça*/
playGame();
}
/**
* Inicializa um jogo salvo em disco.
* @param gameFile o Stream que representa o arquivo em disco
* @throws IOException
* @throws ClassNotFoundException
*/
public GameFrame(ObjectInputStream gameFile) throws IOException, ClassNotFoundException {
Drawing.setGameFrame(this);
initComponents();
this.elemArray = (ArrayList<Element>) gameFile.readObject();
this.points = (Pontuation) gameFile.readObject();
this.gameSquares = (Square[][]) gameFile.readObject();
this.isFull = gameFile.readBoolean();
this.gameScreenWidth = gameFile.readInt();
this.gameScreenHeight = gameFile.readInt();
this.controller = new GameController(this);
this.addKeyListener(controller);
this.setSize(gameScreenWidth, gameScreenHeight);
this.currentTetrisObject = null;
initScore();
playGame();
}
/**
* Inicializa o Frame do Score.
*
*/
private void initScore() {
placar.setLocation(gameScreenWidth+15,0);
placar.transferFocus();
placarScore.setText("Score: "+ points.getPoints());
placar.setVisible(true);
this.requestFocus();
}
/**
* Método que inicia a lógica do game
*
* <p>
* Enquanto a "matriz" do game não está coberta até o topo com peças,
* é mandado mais peças para o jogador alocar
* </p>
*/
private void playGame() {
/*Gera aleatóriamente peças do game até chegar ao topo*/
if (!isFull) {
currentTetrisObject = new TetrisObject(this);
/*Adiciona os blocos da peça ao array de elementos do frame*/
for (int i = 0; i < 4; i++) {
this.addElement(currentTetrisObject.pieces[i]);
}
}
}
/**
* Método que finaliza o jogo e retorna para o Menu
*/
private void finishGame() {
Main.MAIN_MENU.setVisible(true);
this.setVisible(false);
placar.setVisible(false);
}
/**
* Método que serializa o GameFrame atual, salvando o jogo
*/
void saveGame() {
JFileChooser fileSaverDialog;
fileSaverDialog = new JFileChooser();
fileSaverDialog.setDialogTitle("Salvar jogo...");
fileSaverDialog.setApproveButtonText("Salvar");
fileSaverDialog.setDialogType(JFileChooser.SAVE_DIALOG);
fileSaverDialog.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileSaverDialog.setMultiSelectionEnabled(false);
if(fileSaverDialog.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
ObjectOutputStream saveStream = null;
try {
//currentTetrisObject = null;
for (int i = 0; i < 4; i++) {
this.removeElement(currentTetrisObject.pieces[i]);
}
saveStream = new ObjectOutputStream(new FileOutputStream(fileSaverDialog.getSelectedFile()));
saveStream.writeObject(elemArray);
saveStream.writeObject(points);
//saveStream.writeObject(currentTetrisObject);
saveStream.writeObject(gameSquares);
saveStream.writeBoolean(isFull);
saveStream.writeInt(gameScreenWidth);
saveStream.writeInt(gameScreenHeight);
saveStream.close();
finishGame();
JOptionPane.showMessageDialog(Main.MAIN_MENU, "Jogo salvo",
"Salvo com sucesso", JOptionPane.WARNING_MESSAGE);
} catch(IOException e) {
JOptionPane.showMessageDialog(this, e.getMessage(),
"Problema no salvamento", JOptionPane.WARNING_MESSAGE);
}
}
}
private void addElement(Element elem) {
elemArray.add(elem);
}
public void removeElement(Element elem) {
elemArray.remove(elem);
}
@Override
/**
* Método que aparentemente desenha o jogo constantemente (Brendon)
*/
public void paint(Graphics gOld) {
Graphics g = getBufferStrategy().getDrawGraphics();
/*Criamos um contexto grafico*/
Graphics g2 = g.create(getInsets().right, getInsets().top, getWidth() - getInsets().left, getHeight() - getInsets().bottom);
/* DESENHA CENARIO
Trocar essa parte por uma estrutura mais bem organizada
Utilizando a classe Stage
*/
for (int i = 0; i < Consts.NUM_LINES; i++) {
for (int j = 0; j < Consts.NUM_COLUMNS; j++) {
try {
Image newImage = Toolkit.getDefaultToolkit().getImage(new java.io.File(".").getCanonicalPath() + Consts.IMG_PATH + "bricks.png");
g2.drawImage(newImage, j * Consts.CELL_SIZE,
i * Consts.CELL_SIZE,
Consts.CELL_SIZE,
Consts.CELL_SIZE, null);
} catch (IOException ex) {
Logger.getLogger(GameFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/*Desenha todos os elementos do "elemArray" na tela e escreve a peça atual*/
this.controller.drawAllElements(elemArray, g2);
this.controller.processAllElements(elemArray);
this.setTitle("Next: " + currentTetrisObject.getNextType().toString());
/*------------CONDICIONAIS IMPORTANTES----------------------
*--------------------------------------------------------------------
* 1º Verifica se a peça tocou em algo e se já deu o "TIME_FIRE"
* 2º Ocupa a "gameSquares" com cada Square do GameObject (peça)
* -------------------------------------------------------------------*/
if (objLowerBoundsIsOccuped(currentTetrisObject) && currentTetrisObject.pieces[0].getContIntervals() == Square.TIMER_FIRE - 1) {
setDeactivatedPiece();
}
g2.drawString("Pontuação: " + points.getPoints(), 0, 0);
g.dispose();
g2.dispose();
if (!getBufferStrategy().contentsLost()) {
getBufferStrategy().show();
}
}
/**
* Método que adiciona um objeto do tipo "GameObject" quadrado por quadrado
* na matriz "gameSquares" que representa a tela do jogo.
* @param obj objeto a ser adicionado
*/
private void addGameObjectSquares(GameObject obj) {
for (Square s : obj.pieces) {
gameSquares[s.getPos().getX()][s.getPos().getY()] = s;
}
}
/**
* Verifica se há alguma linha preenchida atualmente
* @return true, se sim, false, se não.
*/
private boolean hasFilledRow() {
/*Para cada linha, verificar se todos seus quadrados estão preenchidos*/
for (int i = Consts.NUM_LINES-1; i >= 0 ; i--)
if (isFilledRow(i)) return true;
return false;
}
/**
* Verifica se uma linha está preenchida
* @param rowNumber número da linha a ser verificada
* @return true, se estiver, false, se não estiver.
*/
private boolean isFilledRow(int rowNumber) {
for(Square s : gameSquares[rowNumber])
if (s == null) return false;
return true;
}
/**
* Libera as linhas preenchidas
* @return número de linhas liberadas
*/
private int freeFilledRows() {
int freedRows = 0;
/*Para cada linha preenchida, libero seus squares para descerem*/
for (int i = Consts.NUM_LINES-1; i >= 0; i--) {
/*Enquanto ela estiver preenchida*/
while (isFilledRow(i)) {
freedRows++;
/*1. Removo seus elementos*/
for (Square s : gameSquares[i]) {
gameSquares[s.getPos().getX()][s.getPos().getY()] = null;
s.erase();
}
/*2. Desço todos os Squares que estavam acima*/
for(int j = i; j > 0; j--) {
for(int k = 0; k < Consts.NUM_COLUMNS; k++) {
if (gameSquares[j][k] != null && gameSquares[j][k].isObstacle)
continue;
gameSquares[j][k] = gameSquares[j - 1][k];
if(gameSquares[j][k] != null)
gameSquares[j][k].setPosition(gameSquares[j][k].getPos().getX() + 1, gameSquares[j][k].getPos().getY());
}
}
for(int j = 0; j < Consts.NUM_COLUMNS; j++)
gameSquares[0][j] = null;
}
}
return freedRows;
}
/**
* Método que verifica se o objeto está encostando em algo em baixo
* <p>
* Para cada um dos Squares que compõem o objeto, é testado se há bloco
* bloqueado na "gameSquares" em baixo, se houver, é retornado
* <em>true</em>, se não houver nada, <em>false</em>.
* </p>
* @param obj um GameObject qualquer
* @return true or false
*/
public boolean objLowerBoundsIsOccuped(GameObject obj) {
int x, y;
for (Square s : obj.pieces) {
x = s.getPos().getX(); y = s.getPos().getY();
/*Se o Square atual está adjacente ao chão, true*/
if (x == Consts.NUM_LINES-1) return true;
/*Se está adjacente a qualquer outro obstaculo de "gameSquares", true*/
else if (gameSquares[x + 1][y] != null) return true;
}
return false;
}
public boolean objUpperBoundsAreOccupied(GameObject obj) {
int x, y;
for (Square s : obj.pieces) {
x = s.getPos().getX(); y = s.getPos().getY();
/*Se o Square atual está adjacente ao chão, true*/
if (x == 0) return true;
/*Se está adjacente a qualquer outro obstaculo de "gameSquares", true*/
else if (gameSquares[x - 1][y] != null) return true;
}
return false;
}
/**
* Método que verifica se o objeto está encostando em algo a esquerda
* <p>
* Para cada um dos Squares que compõem o objeto, é testado se há bloco
* bloqueado na "gameSquares" a esquerda, se houver, é retornado
* <em>true</em>, se não houver nada, <em>false</em>.
* </p>
* @param obj um GameObject qualquer
* @return true or false
*/
public boolean objLeftBoundsIsOccuped(GameObject obj) {
int x, y;
for (Square s : obj.pieces) {
x = s.getPos().getX();
y = s.getPos().getY();
/*O Square atual não pode estar adjacente a parede esquerda*/
if (y == 0) return true;
/*A posição adjacente esquerda não pode estar ocupada*/
else if (gameSquares[x][y-1] != null) return true;
}
return false;
}
/**
* Método que verifica se o objeto está encostando em algo a direita
* <p>
* Para cada um dos Squares que compõem o objeto, é testado se há bloco
* bloqueado na "gameSquares" a direita, se houver, é retornado
* <em>true</em>, se não houver nada, <em>false</em>.
* </p>
* @param obj um GameObject qualquer
* @return true or false
*/
public boolean objRightBoundsIsOccuped(GameObject obj) {
int x, y;
for (Square s : obj.pieces) {
x = s.getPos().getX();
y = s.getPos().getY();
/*O Square atual não pode estar adjacente a parede esquerda*/
if (y == Consts.NUM_COLUMNS - 1) return true;
/*A posição adjacente esquerda não pode estar ocupada*/
else if (gameSquares[x][y+1] != null) return true;
}
return false;
}
/**
* Método que cria um TimerTask para dar constantes "repaint()" ao frame
* até que "isFull" seja verdadeiro
*/
public void go() {
TimerTask task = new TimerTask() {
public void run() {
repaint();
}
};
Timer timer = new Timer();
timer.schedule(task, 0, Consts.DELAY_SCREEN_UPDATE);
}
/**
* Desativa uma peça.
*
*/
public void setDeactivatedPiece() {
currentTetrisObject.desactivatePieces();
/*MARCA COMO OCUPADO ONDE A PEÇA CAIU e adiciona seus squares a "rowsSquares"*/
addGameObjectSquares(currentTetrisObject);
/*VERIFICA SE HOUVE PONTUAÇÃO*/
if (hasFilledRow()) {
int multPontuation = freeFilledRows();
points.gain(multPontuation);
placarScore.setText("Score: "+ points.getPoints());
System.out.println("Pontuação: " + points.getPoints());
}
/*Possível GAME_OVER*/
else if (currentTetrisObject.getObjectBoundaries().highestX < 3) {
System.out.println("GAME OVER");
isFull = true;
finishGame();
JOptionPane.showMessageDialog(Main.MAIN_MENU, "Game Over",
"Game Over", JOptionPane.WARNING_MESSAGE);
}
/*Lança uma NOVA PEÇA*/
playGame();
}
/*Provavelmente Trecho herdado do GUI Form do netbeans, onde foi originalmente implementado o frame*/
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle(Consts.GAME_NAME);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setLocation(new java.awt.Point(20, 20));
setResizable(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
<NAME>
<EMAIL>
*/
typedef struct user_data {
char CPF[15];
char Nome[100];
int Idade;
} USUARIO;
USUARIO **ReadUsersFrom(char *,int *,USUARIO **);
int main(){
char File1[50],File2[50];
USUARIO **UserData=NULL,*Rc;
int i,j,N=0;
fgets(File1,sizeof(File1),stdin);
fgets(File2,sizeof(File2),stdin);
File1[strlen(File1)-1]='\0';
if(File2[strlen(File2)-1]=='\n'){
File2[strlen(File2)-1]='\0';
}
UserData=ReadUsersFrom(File1,&N,UserData);
UserData=ReadUsersFrom(File2,&N,UserData);
for(i=0;i<N;i++){
for(j=i+1;j<N;j++){
if(strcmp(UserData[i]->CPF,UserData[j]->CPF)>0){
Rc=UserData[i];
UserData[i]=UserData[j];
UserData[j]=Rc;
}
}
printf("%s\n%s\n%d\n",UserData[i]->CPF,UserData[i]->Nome,UserData[i]->Idade);
free(UserData[i]);
}
free(UserData);
return EXIT_SUCCESS;
}
USUARIO **ReadUsersFrom(char *FilePath,int *n,USUARIO **UserOld){
FILE *FStream=fopen(FilePath,"r");
USUARIO **UserVet=UserOld;
char Line[500];
int N=*n;
if(FStream){
while(!feof(FStream)){
fgets(Line,100,FStream);
UserVet=(USUARIO **)realloc(UserVet,sizeof(USUARIO *)*(N+1));
UserVet[N]=(USUARIO *)malloc(sizeof(USUARIO));
strncpy(UserVet[N]->CPF,Line,14);
UserVet[N]->CPF[14]='\0';
fgets(UserVet[N]->Nome,100,FStream);
UserVet[N]->Nome[strlen(UserVet[N]->Nome)-1]='\0';
fscanf(FStream,"%d ",&UserVet[N]->Idade);
N++;
}
}
fclose(FStream);
*n=N;
return UserVet;
}
<file_sep>import numpy as np
import math
import re
#
# ~ Trabalho 1: Implementação de MLP ~
#
# Grupo:
# <NAME> (N 10349540)
# <NAME> (N 10369014)
# <NAME> (N 9081453)
#
# Introdução à Redes Neurais: SCC-0570 2019.1
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
# Constantes do programa
N_PERCEPTRONS_1ST_LAYER = 32 # Número de neurônios na camada oculta
LEARNING_RATE = 1 # Taxa de aprendizado
ERROR_THRESHOLD = 0.3 # Erro máximo pra ser considerado teste incorreto (recomendado: algo entre 0.1 e 0.3)
# Configuração inicial dos pesos w de cada neurônio de cada camada:
# 256 pontos de entrada (não considerado aqui) + N_PERCEPTRONS_1ST_LAYER neurônios na camada escondida + 10 neurônios de saída (0-9)
weights = np.array([ 0.1 * np.random.rand(N_PERCEPTRONS_1ST_LAYER, 256), 0.1 * np.random.rand(10, N_PERCEPTRONS_1ST_LAYER) ])
biases = np.array([ 0.1 * np.random.rand(N_PERCEPTRONS_1ST_LAYER), 0.1 * np.random.rand(10) ])
newWeights = np.array([ np.zeros((N_PERCEPTRONS_1ST_LAYER, 256)), np.zeros((10, N_PERCEPTRONS_1ST_LAYER)) ])
newBiases = np.array([ np.zeros(N_PERCEPTRONS_1ST_LAYER), np.zeros(10) ])
learned = 0
# Função que lê o arquivo de entrada.
def readData(filePath):
v = [ ]
try:
with open(filePath, "r") as fStream:
lines = fStream.readlines()
for line in lines:
aux = line.strip()
if aux == '':
print("Linha vazia encontrada no arquivo. Ignorando linha...")
continue
items = re.split(r'\s+', aux)
if(len(items) != 266):
print("Linha em formato inválido encontrada no arquivo. Ignorando linha...")
continue
v.append([ items[:256], items[256:266] ])
for i in range(len(v)):
for j in range(256):
v[i][0][j] = int(float(v[i][0][j]))
for j in range(10):
v[i][1][j] = int(float(v[i][1][j]))
except:
return None
return v
# Função de ativação (sigmóide)
def sigmoid(v, derivative = False):
if derivative:
return sigmoid(v) * (1 - sigmoid(v))
return 1 / (1 + math.exp(-1 * v))
# Função que realiza o aprendizado a partir de uma única dada entrada (256 bits da imagem).
def learn(inputDigit, inputClass, activationFunction):
global newBiases, newWeights, weights, biases, learned
values = np.array(inputDigit, copy=True, dtype=np.float)
x = [ ]
for i in range(weights.shape[0]): # Para cada camada...
v = np.empty(weights[i].shape[0], dtype=np.float)
for j in range(weights[i].shape[0]): # Para cada neurônio na camada...
aux = np.multiply(values, weights[i][j]) # Multiplicar valores pelos pesos.
aux = np.sum(aux) + biases[i][j] # Somar tudo
v[j] = aux
x.append(v.copy())
for j in range(weights[i].shape[0]): # Para cada neurônio na camada...
v[j] = activationFunction(v[j])
values = v
# Agora, já temos os valores obtidos na iteração em "values".
# Calcular erro com derivadas
x = np.array(x)
aux = np.empty(x[1].shape[0])
for i in range(aux.shape[0]):
aux[i] = activationFunction(x[1][i], True)
error_2 = np.multiply(-2 * (np.array(inputClass, copy=True, dtype=np.float) - values), aux)
aux = np.empty(x[0].shape[0])
for i in range(aux.shape[0]):
aux[i] = activationFunction(x[0][i])
for i in range(weights[1].shape[0]):
newWeights[1][i] += 1 * error_2[i] * aux
newBiases[1] = newBiases[1] + 1 * error_2
aux = np.empty(x[0].shape[0])
for i in range(x[0].shape[0]):
aux[i] = activationFunction(x[0][i], True)
inputNp = np.array(inputDigit, copy=True)
error_1 = 0
for i in range(weights[0].shape[0]):
error_1 = np.sum(error_2 * weights[1].T[i]) * aux[i]
newWeights[0][i] += 1 * (error_1 * inputNp)
newBiases[0][i] += 1 * error_1
# Atualizar pesos
biases -= LEARNING_RATE * newBiases
weights -= LEARNING_RATE * newWeights
newBiases *= 0
newWeights *= 0
learned += 1
# Função que testa uma única entrada na rede neural.
def test(inputDigit, inputClass, activationFunction):
global weights, biases
values = np.array(inputDigit, copy=True, dtype=np.float)
for i in range(weights.shape[0]): # Para cada camada...
v = np.empty(weights[i].shape[0], dtype=np.float)
for j in range(weights[i].shape[0]): # Para cada neurônio na camada...
aux = np.multiply(values, weights[i][j]) # Multiplicar valores pelos pesos.
aux = np.sum(aux) + biases[i][j] # Somar tudo
v[j] = activationFunction(aux)
values = v
return [ np.abs(np.array(inputClass, dtype=np.float) - values), values ]
# Função que divide o conjunto de dados em k partes.
def splitData(inputData, k):
list = [ ]
groupSize = int(len(inputData) / k)
for i in range(k):
list.append(inputData[i * groupSize:i * groupSize + groupSize])
return list
# Implementação do menu principal
print("Bem-vinde à nossa rede neural artificial, implementada através de uma MLP.")
while True:
print()
print("== Opções ==")
print("1. Treinar com conjunto de dados")
print("2. Testar com conjunto de dados")
print("3. Treinar e testar com conjunto de dados (k-fold)")
print("4. Testar com conjunto de dados (com detalhes)")
print("5. Listar pesos")
print("6. Informações da Rede")
print("0. Sair")
print()
option = 0
option = int(input("Escolha uma opção (0-6) > "))
if option == 1: # treinar com um arquivo de dados
data = readData(input("Entre com um arquivo com o conjunto de dados (imagens) > ").strip())
if data == None:
print("Erro: o arquivo de dados não pode ser lido (não existe, sem permissões, ...) ou não está no formato adequado.")
continue
n = int(input("Entre com o número de iterações para aprendizado (n: 1-inf) > "))
if n < 1:
print("Erro: n deve ser maior ou igual à 1.")
continue
print()
for it in range(n):
print("\r%6.2lf%% processado... (não pressione nenhuma tecla ainda)" % (float(100 * it/n)), end='')
np.random.shuffle(data)
for item in data:
learn(item[0], item[1], sigmoid)
print("\r%6.2lf%% processado... (não pressione nenhuma tecla ainda)" % (float(100)), end='')
print()
print("# A rede aprendeu com o conjunto de dados submetido! Pesos atualizados.")
elif option == 2: # testar com um arquivo de dados
data = readData(input("Entre com um arquivo com o conjunto de dados (imagens) > ").strip())
if data == None:
print("Erro: o arquivo de dados não pode ser lido (não existe, sem permissões, ...) ou não está no formato adequado.")
continue
errorTotal = 0
corrects = 0
total = 0
for item in data:
itemStats = test(item[0], item[1], sigmoid)
correct = True
for error in itemStats[0]:
errorTotal += error
if error >= ERROR_THRESHOLD:
correct = False
if correct:
corrects += 1
total += 1
print()
print("# Teste terminou.")
print("Acertos: %d de %d (%.2lf%%)." % (corrects, total, 100 * corrects/total))
print("Erro: total de %.2lf e médio de %.2lf." % (errorTotal, errorTotal/total))
elif option == 3: # k-fold através de um arquivo de dados
data = readData(input("Entre com um arquivo com o conjunto de dados (imagens) > ").strip())
if data == None:
print("Erro: o arquivo de dados não pode ser lido (não existe, sem permissões, ...) ou não está no formato adequado.")
continue
n = int(input("Entre com o número de iterações para aprendizado (n) > "))
if n < 1:
print("Erro: n deve ser maior ou igual à 1.")
continue
k = int(input("Entre com o número de blocos usados k (k) > "))
if k < 2 or k > len(data):
print("Erro: k deve ser maior ou igual à 2 e deve ser menor ou igual ao número de exemplos no arquivo (" + str(len(data)) + ").")
continue
np.random.shuffle(data)
errorTotal = 0
corrects = 0
total = 0
groupsOfData = splitData(data, k)
print()
for kt in range(k):
testData = groupsOfData[kt]
learnData = [ ]
for it in range(kt):
learnData += groupsOfData[it]
for it in range(kt + 1, k):
learnData += groupsOfData[it]
for it in range(n):
print("\r%6.2lf%% processado... (não pressione nenhuma tecla ainda)" % (float(100 * (kt * n + it)/(k * n))), end='')
for item in learnData:
learn(item[0], item[1], sigmoid)
errorKt = 0
correctsKt = 0
totalKt = 0
for item in testData:
itemStats = test(item[0], item[1], sigmoid)
correct = True
for error in itemStats[0]:
errorKt += error
if error >= ERROR_THRESHOLD:
correct = False
if correct:
correctsKt += 1
totalKt += 1
errorTotal += errorKt
corrects += correctsKt
total += totalKt
print("\r# A execução para a iteração k = " + str(kt + 1) + " do " + str(k) + "-fold foi completa.")
print("Acertos: %d de %d (%.2lf%%)." % (correctsKt, totalKt, 100 * correctsKt/totalKt))
print("Erro: total de %.2lf e médio de %.2lf." % (errorKt, errorKt/totalKt))
print("\r%6.2lf%% processado... (não pressione nenhuma tecla ainda)" % (float(100)), end='')
print()
print("# A rede aprendeu com o conjunto de dados submetido! Pesos atualizados. Além disso também foi testada.")
print("Acertos: %d de %d (%.2lf%%)." % (corrects, total, 100 * corrects/total))
print("Erro: total de %.2lf e médio de %.2lf." % (errorTotal, errorTotal/total))
elif option == 4: # testar com um arquivo de dados (detalhes)
data = readData(input("Entre com um arquivo com o conjunto de dados (imagens) > ").strip())
if data == None:
print("Erro: o arquivo de dados não pode ser lido (não existe, sem permissões, ...) ou não está no formato adequado.")
continue
errorTotal = 0
corrects = 0
total = 0
print()
print("[saída esperada] -> [saída produzida] (acerto/erro)")
for item in data:
itemStats = test(item[0], item[1], sigmoid)
correct = True
errorItem = 0
for error in itemStats[0]:
errorItem += error
if error >= ERROR_THRESHOLD:
correct = False
if correct:
print("%s -> %s (acerto: com erro total de %.2lf)" % (str(np.array(item[1], dtype=np.float)), str(itemStats[1]), errorItem))
corrects += 1
else:
print("%s -> %s (erro: de %.2lf)" % (str(np.array(item[1], dtype=np.float)), str(itemStats[1]), errorItem))
total += 1
errorTotal += errorItem
print()
print("# Teste terminou.")
print("Acertos: %d de %d (%.2lf%%)." % (corrects, total, 100 * corrects/total))
print("Erro: total de %.2lf e médio de %.2lf." % (errorTotal, errorTotal/total))
elif option == 5: # pesos de um neurônio
layer = int(input("Entre com a camada a qual deseja obter os pesos (layer: 1-" + str(weights.shape[0]) + ") > "))
layer -= 1
if layer < 0 or layer > 1:
print("Erro: camada " + str(layer + 1) + " não existe.")
continue
i = int(input("Entre com o neurônio da camada " + str(layer) + " a qual deseja obter os pesos (i: 1-" + str(weights[layer].shape[0]) + ") > "))
i -= 1
n = weights[layer].shape[0]
if i < 0 or i >= n:
print("Erro: neurônio " + str(i + 1) + " não existe na camada " + str(layer + 1) + ".")
continue
print()
print("# Pesos do neurônio " + str(i + 1) + " da camada " + str(layer + 1) + ":")
print(weights[layer][i])
print("Bias: " + str(biases[layer][i]))
elif option == 6: # informações da rede neural
print()
print("# Informações da rede:")
if learned > 0:
print("Já foi treinada? Sim. Foi treinada usando um total de " + str(learned) + " exemplos.")
else:
print("Já foi treinada? Não. Os pesos são aleatórios.")
print("Entrada: 256 inteiros ou floats")
print("Saída esperada e produzida: 10 floats")
print("Estrutura: " + str(weights.shape[0]) + " camadas, " + str(weights.shape[0] - 1) + " escondida/s e 1 de saída")
for i in range(weights.shape[0]):
print("\tNeurônios na camada " + str(i + 1) + ": " + str(weights[i].shape[0]))
else: # sair
print()
print("# Saindo do programa...")
break
<file_sep># Imagens Originais
Aqui se encontram as imagens originais, da forma como foram baixadas diretamente do website.
<file_sep># SSC-0570 Introdução a Redes Neurais - 2019.1
Aqui estão todos os trabalhos que implementei em Redes Neurais.
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <consts.h>
#include <buffer.h>
#include <register.h>
#include <index.h>
#include <bindex.h>
#include <escreverTela.h>
#include <vector_builder.h>
#include <merge_sort.h>
typedef struct {
char campo[1000];
char valor[1000];
char campoMod[1000];
char valorMod[1000];
} TO_BE_MODIFIED_FIELD;
typedef struct {
long byteOffset;
long nextByteOffset;
int size;
int level;
} REMOVED_LIST_NODE;
int node_cmps(REMOVED_LIST_NODE *A, REMOVED_LIST_NODE *B) {
return B->size - A->size;
}
int node_cmpb(REMOVED_LIST_NODE *A, REMOVED_LIST_NODE *B) {
return B->byteOffset - A->byteOffset;
}
int node_cmpbr(REMOVED_LIST_NODE *A, REMOVED_LIST_NODE *B) {
return A->byteOffset - B->byteOffset;
}
int node_cmplr(REMOVED_LIST_NODE *A, REMOVED_LIST_NODE *B) {
return A->level - B->level;
}
int regData_cmp(REG_DATA *A, REG_DATA *B) {
return B->idServidor - A->idServidor;
}
int field_isMarked(REG_DATA *aux, unsigned long n, unsigned long i, TO_BE_MODIFIED_FIELD *fields) {
for(; i < n; i++) {
if(strcmp(fields[i].campo, "idServidor") == 0) {
if(atoi(fields[i].valor) == aux->idServidor) {
return i;
}
} else if(strcmp(fields[i].campo, "salarioServidor") == 0) {
if((fields[i].valor[0] == '\0' && aux->salarioServidor < 0 ) || atof(fields[i].valor) == aux->salarioServidor) {
return i;
}
} else if(strcmp(fields[i].campo, "telefoneServidor") == 0) {
if(strncmp(fields[i].valor, aux->telefoneServidor, 14) == 0) {
return i;
}
} else if(strcmp(fields[i].campo, "nomeServidor") == 0) {
if(strcmp(fields[i].valor, aux->nomeServidor) == 0) {
return i;
}
} else if(strcmp(fields[i].campo, "cargoServidor") == 0) {
if(strcmp(fields[i].valor, aux->cargoServidor) == 0) {
return i;
}
}
}
return -1;
}
int f1_csvBuild(char *binPath, char *csvPath) {
FILE *csvStream, *binStream;
long ultimoSize;
REG_HEADER auxH;
REG_DATA aux;
int i, auxN;
csvStream = fopen(csvPath, "r");
if(!csvStream) {
printf("Falha no carregamento do arquivo.\n");
return 0;
}
binStream = fopen(binPath, "w+b");
if(!binStream) {
fclose(csvStream);
printf("Falha no carregamento do arquivo.\n");
return 0;
}
auxH.status = STATUS_INCONSISTENTE;
auxH.first = -1;
fscanf(csvStream, "%[^,]%*c%[^,]%*c%[^,]%*c%[^,]%*c%[^\r\n]", auxH.desCampos[0], auxH.desCampos[1], auxH.desCampos[2], auxH.desCampos[3], auxH.desCampos[4]);
R_writeH(&auxH, binStream);
ultimoSize = -1;
while(fscanf(csvStream, "%d%*c%lf%*c", &aux.idServidor, &aux.salarioServidor) == 2) {
memset(aux.telefoneServidor, LIXO, sizeof(char) * 14);
if(fscanf(csvStream, "%[^,]", aux.telefoneServidor) != 1) {
aux.telefoneServidor[0] = '\0';
}
if(fscanf(csvStream, "%*c%[^,]", aux.nomeServidor) != 1) {
aux.nomeServidor[0] = '\0';
}
if(fscanf(csvStream, "%*c%[^\r\n]", aux.cargoServidor) != 1) {
aux.cargoServidor[0] = '\0';
}
R_write(&aux, binStream, &ultimoSize);
}
// COMENTADO PQ: não faz padding mais na última página.
//R_writePad(binStream);
auxH.status = STATUS_CONSISTENTE;
R_writeH(&auxH, binStream);
fclose(csvStream);
fclose(binStream);
return 1;
}
int f2_list(char *binPath) {
REG_HEADER auxH;
FILE *stream;
REG_DATA aux;
char found;
int i;
stream = fopen(binPath, "rb");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
found = 0;
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO) {
continue;
}
found = 1;
/*int rnd = rand() % 10;
switch(rnd) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
printf("%s %d\n", "idServidor", aux.idServidor);
break;
case 6:
if(aux.salarioServidor < 0) {
printf("%s %s\n", "salarioServidor", "NULO");
} else {
printf("%s %lf\n", "salarioServidor", aux.salarioServidor);
}
break;
case 7:
if(aux.telefoneServidor[0] == '\0') {
printf("%s %s\n", "telefoneServidor", "NULO");
} else {
printf("%s \"%.14s\"\n", "telefoneServidor", aux.telefoneServidor);
}
break;
case 8:
if(aux.nomeServidor[0] == '\0') {
printf("%s %s\n", "nomeServidor", "NULO");
} else {
printf("%s \"%s\"\n", "nomeServidor", aux.nomeServidor);
}
break;
case 9:
if(aux.cargoServidor[0] == '\0') {
printf("%s %s\n", "cargoServidor", "NULO");
} else {
printf("%s \"%s\"\n", "cargoServidor", aux.cargoServidor);
}
break;
}
continue;/**/
printf("%d ", aux.idServidor);
if(aux.salarioServidor >= 0) {
printf("%.2lf", aux.salarioServidor);
} else {
for(i = 0; i < 8; i++) {
printf(" ");
}
}
if(strncmp(aux.telefoneServidor, "", 14) != 0) {
printf(" %.14s", aux.telefoneServidor);
} else {
printf(" ");
for(i = 0; i < 14; i++) {
printf(" ");
}
}
if(strcmp(aux.nomeServidor, "") != 0) {
printf(" %ld %s", strlen(aux.nomeServidor), aux.nomeServidor);
}
if(strcmp(aux.cargoServidor, "") != 0) {
printf(" %ld %s", strlen(aux.cargoServidor), aux.cargoServidor);
}
printf("\n");
}
if(!found) {
printf("Registro inexistente.\n");
} else {
printf("Número de páginas de disco acessadas: %ld\n", B_count(stream));
}
fclose(stream);
return 1;
}
int f3_search(char *binPath, char *field, char *value) {
REG_HEADER auxH;
FILE *stream;
REG_DATA aux;
char found;
double k;
int i, j;
stream = fopen(binPath, "rb");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
found = 0;
if(strcmp(field, "idServidor") == 0) { // idServidor
j = atoi(value);
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO || aux.idServidor != j) {
continue;
}
found = 1;
printf("%s: %d\n%s: ", auxH.desCampos[0], aux.idServidor, auxH.desCampos[1]);
if(aux.salarioServidor >= 0) {
printf("%.2lf\n%s: ", aux.salarioServidor, auxH.desCampos[2]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[2]);
}
if(strncmp(aux.telefoneServidor, "", 14) != 0) {
printf("%.14s\n%s: ", aux.telefoneServidor, auxH.desCampos[3]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[3]);
}
if(strcmp(aux.nomeServidor, "") != 0) {
printf("%s\n%s: ", aux.nomeServidor, auxH.desCampos[4]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[4]);
}
if(strcmp(aux.cargoServidor, "") != 0) {
printf("%s\n", aux.cargoServidor);
} else {
printf("valor nao declarado\n");
}
printf("\n");
break;
}
} else if(strcmp(field, "salarioServidor") == 0) { // salarioServidor
k = (double) atof(value);
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO || aux.salarioServidor != k) {
continue;
}
found = 1;
printf("%s: %d\n%s: ", auxH.desCampos[0], aux.idServidor, auxH.desCampos[1]);
if(aux.salarioServidor >= 0) {
printf("%.2lf\n%s: ", aux.salarioServidor, auxH.desCampos[2]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[2]);
}
if(strncmp(aux.telefoneServidor, "", 14) != 0) {
printf("%.14s\n%s: ", aux.telefoneServidor, auxH.desCampos[3]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[3]);
}
if(strcmp(aux.nomeServidor, "") != 0) {
printf("%s\n%s: ", aux.nomeServidor, auxH.desCampos[4]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[4]);
}
if(strcmp(aux.cargoServidor, "") != 0) {
printf("%s\n", aux.cargoServidor);
} else {
printf("valor nao declarado\n");
}
printf("\n");
}
} else if(strcmp(field, "telefoneServidor") == 0) { // telefoneServidor
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO || strncmp(aux.telefoneServidor, value, 14) != 0) {
continue;
}
found = 1;
printf("%s: %d\n%s: ", auxH.desCampos[0], aux.idServidor, auxH.desCampos[1]);
if(aux.salarioServidor >= 0) {
printf("%.2lf\n%s: ", aux.salarioServidor, auxH.desCampos[2]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[2]);
}
if(strncmp(aux.telefoneServidor, "", 14) != 0) {
printf("%.14s\n%s: ", aux.telefoneServidor, auxH.desCampos[3]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[3]);
}
if(strcmp(aux.nomeServidor, "") != 0) {
printf("%s\n%s: ", aux.nomeServidor, auxH.desCampos[4]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[4]);
}
if(strcmp(aux.cargoServidor, "") != 0) {
printf("%s\n", aux.cargoServidor);
} else {
printf("valor nao declarado\n");
}
printf("\n");
}
} else if(strcmp(field, "nomeServidor") == 0) { // nomeServidor
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO || strcmp(aux.nomeServidor, value) != 0) {
continue;
}
found = 1;
printf("%s: %d\n%s: ", auxH.desCampos[0], aux.idServidor, auxH.desCampos[1]);
if(aux.salarioServidor >= 0) {
printf("%.2lf\n%s: ", aux.salarioServidor, auxH.desCampos[2]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[2]);
}
if(strncmp(aux.telefoneServidor, "", 14) != 0) {
printf("%.14s\n%s: ", aux.telefoneServidor, auxH.desCampos[3]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[3]);
}
if(strcmp(aux.nomeServidor, "") != 0) {
printf("%s\n%s: ", aux.nomeServidor, auxH.desCampos[4]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[4]);
}
if(strcmp(aux.cargoServidor, "") != 0) {
printf("%s\n", aux.cargoServidor);
} else {
printf("valor nao declarado\n");
}
printf("\n");
}
} else if(strcmp(field, "cargoServidor") == 0) { // cargoServidor
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO || strcmp(aux.cargoServidor, value) != 0) {
continue;
}
found = 1;
printf("%s: %d\n%s: ", auxH.desCampos[0], aux.idServidor, auxH.desCampos[1]);
if(aux.salarioServidor >= 0) {
printf("%.2lf\n%s: ", aux.salarioServidor, auxH.desCampos[2]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[2]);
}
if(strncmp(aux.telefoneServidor, "", 14) != 0) {
printf("%.14s\n%s: ", aux.telefoneServidor, auxH.desCampos[3]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[3]);
}
if(strcmp(aux.nomeServidor, "") != 0) {
printf("%s\n%s: ", aux.nomeServidor, auxH.desCampos[4]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[4]);
}
if(strcmp(aux.cargoServidor, "") != 0) {
printf("%s\n", aux.cargoServidor);
} else {
printf("valor nao declarado\n");
}
printf("\n");
}
} else {
printf("Campo buscado inexistente.\n");
}
if(!found) {
printf("Registro inexistente.\n");
} else {
printf("Número de páginas de disco acessadas: %ld\n", B_count(stream));
}
fclose(stream);
return 1;
}
int f4_removeRegs(char *binPath, int n, FILE *input) {
char found, field[5000], value[5000];
int i, j, nRemoved;
TO_BE_MODIFIED_FIELD *fields;
REMOVED_LIST_NODE *removed, removedAux;
VECTOR_T *builder;
REG_HEADER auxH;
FILE *stream;
REG_DATA aux;
long offset;
double k;
stream = fopen(binPath, "r+b");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
auxH.status = STATUS_INCONSISTENTE;
R_writeH(&auxH, stream);
// Ler todos os campos de análise de stdin
builder = V_new(sizeof(TO_BE_MODIFIED_FIELD));
fields = (TO_BE_MODIFIED_FIELD *) malloc(sizeof(TO_BE_MODIFIED_FIELD));
for(i = 0; i < n; i++) {
scanf("%s", fields->campo);
scan_quote_string(fields->valor);
V_pushback(fields, builder);
}
free(fields);
n = V_build(&fields, builder);
V_destroy(builder);
// Ler todos os registros pra ver quais serão removidos
removed = (REMOVED_LIST_NODE *) malloc(sizeof(REMOVED_LIST_NODE));
builder = V_new(sizeof(REMOVED_LIST_NODE));
found = 0;
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO) {
continue;
}
if((removed->level=field_isMarked(&aux, n, 0, fields)) < 0) {
continue;
}
found = 1;
removed->level++;
removed->byteOffset = aux.byteOffset;
removed->size = aux.size;
V_pushback(removed, builder);
}
free(fields);
free(removed);
nRemoved = V_build(&removed, builder);
V_destroy(builder);
if(nRemoved > 0) {
// Ordenar crescentemente por level e depois por tamanho
MS_sort(removed, nRemoved, sizeof(REMOVED_LIST_NODE), (int (*)(const void *, const void *)) node_cmpbr);
builder = V_new(sizeof(REMOVED_LIST_NODE));
offset = auxH.first;
while(offset != L_NIL) {
fseek(stream, offset, SEEK_SET);
R_read(&aux, stream);
removedAux.nextByteOffset = aux.next;
removedAux.byteOffset = offset;
removedAux.size = aux.size;
removedAux.level = 0;
V_pushback(&removedAux, builder);
offset = aux.next;
}
removed = (REMOVED_LIST_NODE *) realloc(removed, sizeof(REMOVED_LIST_NODE) * (nRemoved + V_size(builder)));
V_copy(&removed[nRemoved], builder);
nRemoved += V_size(builder);
V_destroy(builder);
MS_sort(removed, nRemoved, sizeof(REMOVED_LIST_NODE), (int (*)(const void *, const void *)) node_cmplr);
MS_sort(removed, nRemoved, sizeof(REMOVED_LIST_NODE), (int (*)(const void *, const void *)) node_cmps);
// Ajustar encadeamento da lista
for(i = 1; i < nRemoved; i++) {
removed[i - 1].nextByteOffset = removed[i].byteOffset;
}
removed[nRemoved - 1].nextByteOffset = L_NIL;
auxH.first = removed[0].byteOffset;
// Ordenar crescentemente por byteOffset: melhora desempenho na escrita final dependendo do S.O.
MS_sort(removed, nRemoved, sizeof(REMOVED_LIST_NODE), (int (*)(const void *, const void *)) node_cmpb);
}
for(i = 0; i < nRemoved; i++) {
aux.removed = R_REMOVIDO;
aux.size = removed[i].size;
aux.next = removed[i].nextByteOffset;
aux.byteOffset = removed[i].byteOffset;
R_rewriteBack(&aux, stream);
}
auxH.status = STATUS_CONSISTENTE;
R_writeH(&auxH, stream);
free(removed);
fclose(stream);
return 1;
}
int f5_addRegs(char *binPath, int n, FILE *input) {
char found, field[5000];
long offset;
int i, j, nRemoved;
REMOVED_LIST_NODE *removed;
VECTOR_T *builder;
REG_HEADER auxH;
FILE *stream;
REG_DATA aux, *toBeAdded;
double k;
stream = fopen(binPath, "r+b");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
auxH.status = STATUS_INCONSISTENTE;
R_writeH(&auxH, stream);
// Ler lista de removidos
builder = V_new(sizeof(REMOVED_LIST_NODE));
removed = (REMOVED_LIST_NODE *) malloc(sizeof(REMOVED_LIST_NODE));
offset = auxH.first;
while(offset != L_NIL) {
fseek(stream, offset, SEEK_SET);
R_read(&aux, stream);
removed->nextByteOffset = aux.next;
removed->byteOffset = offset;
removed->size = aux.size;
V_pushback(removed, builder);
offset = aux.next;
}
free(removed);
nRemoved = V_build(&removed, builder);
V_destroy(builder);
// Adiciona um por um: tenta na lista de removidos da RAM. Caso não dê: adiciona em lista na RAM pra adicionar ao fim.
builder = V_new(sizeof(REG_DATA));
aux.removed = R_NAO_REMOVIDO;
for(i = 0; i < n; i++) {
scanf("%d", &aux.idServidor);
scan_quote_string(field);
if(field[0] == '\0') {
aux.salarioServidor = -1;
} else {
aux.salarioServidor = atof(field);
}
scan_quote_string(field);
strncpy(aux.telefoneServidor, field, 14);
scan_quote_string(aux.nomeServidor);
scan_quote_string(aux.cargoServidor);
aux.size = R_calculateSize(&aux);
for(j = 0; j < nRemoved; j++) {
if(removed[j].size >= aux.size) {
break;
}
}
if(j >= nRemoved) { // não cabe em nenhum
V_pushback(&aux, builder);
continue;
}
aux.size = removed[j].size;
aux.byteOffset = removed[j].byteOffset;
R_rewriteBack(&aux, stream);
memmove(&removed[j], &removed[j + 1], sizeof(REMOVED_LIST_NODE) * (nRemoved - j - 1));
nRemoved--;
}
n = V_build(&toBeAdded, builder);
V_destroy(builder);
// Encontrar fim do arquivo.
fseek(stream, 0, SEEK_END);
offset = ftell(stream);
if(offset % 32000 == 0) {
offset = -1;
} else {
while(R_read(&aux, stream) == 1) {
offset = aux.size;
}
}
// Adicionar os que faltam
for(i = 0; i < n; i++) {
R_write(&toBeAdded[i], stream, &offset);
}
// Atualizar lista
if(nRemoved > 0) {
// Não ordena: pra manter ordem original.
// Ajustar encadeamento da lista
for(i = 1; i < nRemoved; i++) {
removed[i - 1].nextByteOffset = removed[i].byteOffset;
}
removed[nRemoved - 1].nextByteOffset = L_NIL;
auxH.first = removed[0].byteOffset;
// Ordenar crescentemente por byteOffset: melhora desempenho na escrita final dependendo do S.O.
MS_sort(removed, nRemoved, sizeof(REMOVED_LIST_NODE), (int (*)(const void *, const void *)) node_cmpb);
} else {
auxH.first = L_NIL;
}
for(i = 0; i < nRemoved; i++) {
aux.removed = R_REMOVIDO;
aux.size = removed[i].size;
aux.next = removed[i].nextByteOffset;
aux.byteOffset = removed[i].byteOffset;
R_rewriteBack(&aux, stream);
}
auxH.status = STATUS_CONSISTENTE;
R_writeH(&auxH, stream);
fclose(stream);
return 1;
}
int f6_updateRegsSlowly_remove(REG_DATA *reg, REG_HEADER *header, FILE *stream) {
REMOVED_LIST_NODE *removed;
VECTOR_T *builder;
REG_DATA aux;
int nRemoved;
long offset;
builder = V_new(sizeof(REMOVED_LIST_NODE));
removed = (REMOVED_LIST_NODE *) malloc(sizeof(REMOVED_LIST_NODE));
offset = header->first;
while(offset != L_NIL) {
fseek(stream, offset, SEEK_SET);
R_read(&aux, stream);
removed->nextByteOffset = aux.next;
removed->byteOffset = offset;
removed->size = aux.size;
removed->level = 0;
V_pushback(removed, builder);
offset = aux.next;
}
free(removed);
nRemoved = V_build(&removed, builder);
V_destroy(builder);
}
int f6_updateRegsSlowly(char *binPath, int n, FILE *input) {
char found, rewrite, field[5000];
long offset, seekbackByteoffset, lastOffset, lastSize, lastI;
int i, j, k, nRemoved, nUpdated, level;
TO_BE_MODIFIED_FIELD auxF;
REMOVED_LIST_NODE *removed;
VECTOR_T *builder;
REG_HEADER auxH;
FILE *stream;
REG_DATA aux, auxR, auxT, original, *updated;
stream = fopen(binPath, "r+b");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
auxH.status = STATUS_INCONSISTENTE;
R_writeH(&auxH, stream);
/*builder = V_new(sizeof(REMOVED_LIST_NODE));
removed = (REMOVED_LIST_NODE *) malloc(sizeof(REMOVED_LIST_NODE));
offset = auxH.first;
while(offset != L_NIL) {
fseek(stream, offset, SEEK_SET);
R_read(&aux, stream);
removed->nextByteOffset = aux.next;
removed->byteOffset = offset;
removed->size = aux.size;
removed->level = 0;
V_pushback(removed, builder);
offset = aux.next;
}
free(removed);
nRemoved = V_build(&removed, builder);
V_destroy(builder);*/
lastSize = -1;
for(i = 0; i < n; i++) {
scanf("%s", auxF.campo);
scan_quote_string(auxF.valor);
scanf("%s", auxF.campoMod);
scan_quote_string(auxF.valorMod);
fseek(stream, PAGE_SIZE, SEEK_SET);
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO) { // Removido: ignorar
continue;
}
if(field_isMarked(&aux, 1, 0, &auxF) < 0) {
continue;
}
if(strcmp(auxF.campoMod, "idServidor") == 0) {
aux.idServidor = atoi(auxF.valorMod);
} else if(strcmp(auxF.campoMod, "salarioServidor") == 0) {
if(auxF.valorMod[0] == '\0') {
aux.salarioServidor = -1;
} else {
aux.salarioServidor = atof(auxF.valorMod);
}
} else if(strcmp(auxF.campoMod, "telefoneServidor") == 0) {
strncpy(aux.telefoneServidor, auxF.valorMod, 14);
} else if(strcmp(auxF.campoMod, "nomeServidor") == 0) {
strcpy(aux.nomeServidor, auxF.valorMod);
} else if(strcmp(auxF.campoMod, "cargoServidor") == 0) {
strcpy(aux.cargoServidor, auxF.valorMod);
}
memcpy(&original, &aux, sizeof(REG_DATA));
// AQUI VAI COMEÇAR REINSERÇÃO OU REESCRITA
if(aux.size >= R_calculateSize(&aux)) { // Coube. Continua ali.
R_rewriteBack(&aux, stream);
continue;
}
/*// Não coube. Ver na lista de removidos ou inserir ao fim.
removed = (REMOVED_LIST_NODE *) realloc(removed, sizeof(REMOVED_LIST_NODE) * (nRemoved + 1));
for(j = 0; j < nRemoved; j++) {
if(removed[j].size >= aux.size) {
break;
}
}
memmove(&removed[j + 1], &removed[j], sizeof(REMOVED_LIST_NODE) * (nRemoved - j));
removed[j].byteOffset = aux.byteOffset;
removed[j].level = i + 1;
removed[j].size = aux.size;
nRemoved++;
for(; j < nRemoved; j++) {
if(removed[j].size >= R_calculateSize(&aux)) {
break;
}
}
if(j >= nRemoved) { // não cabe em nenhum
aux.size = R_calculateSize(&aux);
seekbackByteoffset = ftell(stream);
fseek(stream, 0, SEEK_END);
R_write(&aux, stream, &lastSize);
fseek(stream, seekbackByteoffset, SEEK_SET);
continue;
}
aux.size = removed[j].size;
aux.byteOffset = removed[j].byteOffset;
memmove(&removed[j], &removed[j + 1], sizeof(REMOVED_LIST_NODE) * (nRemoved - j - 1));
nRemoved--;
continue;*/
seekbackByteoffset = ftell(stream);
lastOffset = L_NIL;
offset = auxH.first;
while(offset != L_NIL) {
fseek(stream, offset, SEEK_SET);
R_read(&auxR, stream);
if(auxR.size >= aux.size) {
break;
}
lastOffset = offset;
offset = auxR.next;
}
aux.next = offset;
aux.removed = R_REMOVIDO;
R_rewriteBack(&aux, stream);
if(lastOffset != L_NIL) {
fseek(stream, lastOffset, SEEK_SET);
R_read(&auxT, stream);
auxT.next = aux.byteOffset;
R_rewriteBack(&auxT, stream);
} else {
auxH.first = aux.byteOffset;
}
// Inserido na lista de removidos. Agora, procurar se cabe em algum de lá.
rewrite = 0;
while(offset != L_NIL) {
fseek(stream, offset, SEEK_SET);
R_read(&auxR, stream);
if(auxR.size >= R_calculateSize(&original)) {
rewrite = 1;
break;
}
lastOffset = offset;
offset = auxR.next;
}
if(rewrite) { // Achou posição que cabe.
if(lastOffset != L_NIL) {
fseek(stream, lastOffset, SEEK_SET);
R_read(&auxT, stream);
auxT.next = auxR.next;
R_rewriteBack(&auxT, stream);
} else {
auxH.first = auxR.next;
}
original.removed = R_NAO_REMOVIDO;
original.byteOffset = auxR.byteOffset;
original.size = auxR.size;
original.next = -1;
R_rewriteBack(&original, stream);
} else { // Escrever ao fim mesmo.
fseek(stream, 0, SEEK_END);
original.size = R_calculateSize(&original);
R_write(&original, stream, &lastSize);
}
fseek(stream, seekbackByteoffset, SEEK_SET);
}
}
/*if(nRemoved > 0) {
// Ajustar encadeamento da lista
for(i = 1; i < nRemoved; i++) {
removed[i - 1].nextByteOffset = removed[i].byteOffset;
}
removed[nRemoved - 1].nextByteOffset = L_NIL;
auxH.first = removed[0].byteOffset;
// Ordenar crescentemente por byteOffset: melhora desempenho na escrita final dependendo do S.O.
MS_sort(removed, nRemoved, sizeof(REMOVED_LIST_NODE), (int (*)(const void *, const void *)) node_cmpb);
} else {
auxH.first = L_NIL;
}
for(i = 0; i < nRemoved; i++) {
aux.removed = R_REMOVIDO;
aux.size = removed[i].size;
aux.next = removed[i].nextByteOffset;
aux.byteOffset = removed[i].byteOffset;
R_rewriteBack(&aux, stream);
}*/
auxH.status = STATUS_CONSISTENTE;
R_writeH(&auxH, stream);
fclose(stream);
return 1;
}
int f6_updateRegs(char *binPath, int n, FILE *input) {
char found, rewrite, field[5000];
long offset, lastOffset, lastI;
int i, j, k, nRemoved, nUpdated, level;
TO_BE_MODIFIED_FIELD auxF, *fields;
REMOVED_LIST_NODE *removed;
VECTOR_T *builder;
REG_HEADER auxH;
FILE *stream;
REG_DATA aux, original, *updated;
stream = fopen(binPath, "r+b");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
auxH.status = STATUS_INCONSISTENTE;
R_writeH(&auxH, stream);
// Ler todos os campos de análise de stdin
builder = V_new(sizeof(TO_BE_MODIFIED_FIELD));
fields = (TO_BE_MODIFIED_FIELD *) malloc(sizeof(TO_BE_MODIFIED_FIELD));
for(i = 0; i < n; i++) {
scanf("%s", fields->campo);
scan_quote_string(fields->valor);
scanf("%s", fields->campoMod);
scan_quote_string(fields->valorMod);
V_pushback(fields, builder);
}
free(fields);
n = V_build(&fields, builder);
V_destroy(builder);
// Ler todos os registros pra ver quais já podem ser atualizados no próprio local.
builder = V_new(sizeof(REG_DATA));
aux.size = -1;
found = 0;
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO) { // Removido: ignorar
continue;
}
memcpy(&original, &aux, sizeof(REG_DATA));
rewrite = 0;
level = -1;
aux.size = R_calculateSize(&aux);
while((level = field_isMarked(&aux, n, level + 1, fields)) >= 0) { // Se tiver marcado e enquanto tá cabendo no próprio local...
found = rewrite = 1;
if(strcmp(fields[level].campoMod, "idServidor") == 0) {
aux.idServidor = atoi(fields[level].valorMod);
} else if(strcmp(fields[level].campoMod, "salarioServidor") == 0) {
if(fields[level].valorMod[0] == '\0') {
aux.salarioServidor = -1;
} else {
aux.salarioServidor = atof(fields[level].valorMod);
}
} else if(strcmp(fields[level].campoMod, "telefoneServidor") == 0) {
strncpy(aux.telefoneServidor, fields[level].valorMod, 14);
} else if(strcmp(fields[level].campoMod, "nomeServidor") == 0) {
strcpy(aux.nomeServidor, fields[level].valorMod);
} else if(strcmp(fields[level].campoMod, "cargoServidor") == 0) {
strcpy(aux.cargoServidor, fields[level].valorMod);
}
if(aux.size < R_calculateSize(&aux)) {
V_pushback(&original, builder);
rewrite = 0;
break;
}
}
if(rewrite) {
R_rewriteBack(&aux, stream);
}
}
lastOffset = aux.size;
lastI = -1;
nUpdated = V_build(&updated, builder);
V_destroy(builder);
// Ler lista de removidos
builder = V_new(sizeof(REMOVED_LIST_NODE));
removed = (REMOVED_LIST_NODE *) malloc(sizeof(REMOVED_LIST_NODE));
offset = auxH.first;
while(offset != L_NIL) {
fseek(stream, offset, SEEK_SET);
R_read(&aux, stream);
removed->nextByteOffset = aux.next;
removed->byteOffset = offset;
removed->size = aux.size;
removed->level = 0;
V_pushback(removed, builder);
offset = aux.next;
}
free(removed);
nRemoved = V_build(&removed, builder);
V_destroy(builder);
// Iterar para atualizar os que não couberam antes...
fseek(stream, 0, SEEK_END);
for(level = 0; level < n; level++) {
for(i = 0; i < nUpdated; i++) {
if(field_isMarked(&updated[i], level + 1, level, fields) >= 0) {
if(strcmp(fields[level].campoMod, "idServidor") == 0) {
updated[i].idServidor = atoi(fields[level].valorMod);
} else if(strcmp(fields[level].campoMod, "salarioServidor") == 0) {
if(fields[level].valorMod[0] == '\0') {
updated[i].salarioServidor = -1;
} else {
updated[i].salarioServidor = atof(fields[level].valorMod);
}
} else if(strcmp(fields[level].campoMod, "telefoneServidor") == 0) {
strncpy(updated[i].telefoneServidor, fields[level].valorMod, 14);
} else if(strcmp(fields[level].campoMod, "nomeServidor") == 0) {
strcpy(updated[i].nomeServidor, fields[level].valorMod);
} else if(strcmp(fields[level].campoMod, "cargoServidor") == 0) {
strcpy(updated[i].cargoServidor, fields[level].valorMod);
}
if(updated[i].size < R_calculateSize(&updated[i])) {
removed = (REMOVED_LIST_NODE *) realloc(removed, sizeof(REMOVED_LIST_NODE) * (nRemoved + 1));
for(j = 0; j < nRemoved; j++) {
if(removed[j].size >= updated[i].size) {
break;
}
}
memmove(&removed[j + 1], &removed[j], sizeof(REMOVED_LIST_NODE) * (nRemoved - j));
removed[j].byteOffset = updated[i].byteOffset;
removed[j].level = level + 1;
removed[j].size = updated[i].size;
nRemoved++;
for(; j < nRemoved; j++) {
if(removed[j].size >= R_calculateSize(&updated[i])) {
break;
}
}
if(j >= nRemoved) { // não cabe em nenhum
updated[i].size = R_calculateSize(&updated[i]);
if(R_write(&updated[i], stream, &lastOffset) == 2 && lastI >= 0) {
for(k = 0; k < nRemoved; k++) {
if(removed[k].byteOffset == lastI) {
removed[k].size = PAGE_SIZE - (removed[k].byteOffset % PAGE_SIZE) - sizeof(char) - sizeof(int);
}
}
for(k = 0; k < nUpdated; k++) {
if(updated[k].byteOffset == lastI) {
updated[k].size = PAGE_SIZE - (updated[k].byteOffset % PAGE_SIZE) - sizeof(char) - sizeof(int);
}
}
}
lastI = updated[i].byteOffset;
lastOffset = updated[i].size;
continue;
}
updated[i].size = removed[j].size;
updated[i].byteOffset = removed[j].byteOffset;
memmove(&removed[j], &removed[j + 1], sizeof(REMOVED_LIST_NODE) * (nRemoved - j - 1));
nRemoved--;
}
}
}
}
// Iterar para salvar os atualizados...
for(i = 0; i < nUpdated; i++) {
R_rewriteBack(&updated[i], stream);
}
if(nRemoved > 0) {
// Ajustar encadeamento da lista
for(i = 1; i < nRemoved; i++) {
removed[i - 1].nextByteOffset = removed[i].byteOffset;
}
removed[nRemoved - 1].nextByteOffset = L_NIL;
auxH.first = removed[0].byteOffset;
// Ordenar crescentemente por byteOffset: melhora desempenho na escrita final dependendo do S.O.
MS_sort(removed, nRemoved, sizeof(REMOVED_LIST_NODE), (int (*)(const void *, const void *)) node_cmpb);
} else {
auxH.first = L_NIL;
}
for(i = 0; i < nRemoved; i++) {
aux.removed = R_REMOVIDO;
aux.size = removed[i].size;
aux.next = removed[i].nextByteOffset;
aux.byteOffset = removed[i].byteOffset;
R_rewriteBack(&aux, stream);
}
auxH.status = STATUS_CONSISTENTE;
R_writeH(&auxH, stream);
free(removed);
free(fields);
fclose(stream);
return 1;
}
int f7_sort(char *inPath, char *outPath) {
FILE *inStream, *outStream;
long ultimoSize;
VECTOR_T *builder;
REG_HEADER auxH;
REG_DATA aux, *auxV;
int i, auxN;
inStream = fopen(inPath, "rb");
if(!inStream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, inStream);
if(auxH.status == STATUS_INCONSISTENTE) {
fclose(inStream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
outStream = fopen(outPath, "w+b");
if(!outStream) {
fclose(inStream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
auxH.status = STATUS_INCONSISTENTE;
auxH.first = -1;
R_writeH(&auxH, outStream);
builder = V_new(sizeof(REG_DATA));
while(R_read(&aux, inStream) == 1) {
if(aux.removed == R_REMOVIDO) {
continue;
}
V_pushback(&aux, builder);
}
auxN = V_build(&auxV, builder);
V_destroy(builder);
fclose(inStream);
MS_sort(auxV, auxN, sizeof(REG_DATA), (int (*)(const void *, const void *)) regData_cmp);
ultimoSize = -1;
for(i = 0; i < auxN; i++) {
R_write(&auxV[i], outStream, &ultimoSize);
}
// COMENTADO PQ: não faz padding mais na última página.
//R_writePad(outStream);
auxH.status = STATUS_CONSISTENTE;
R_writeH(&auxH, outStream);
fclose(outStream);
return 1;
}
int f8_merge(char *in1Path, char *in2Path, char *outPath) {
FILE *in1Stream, *in2Stream, *outStream;
REG_DATA aux1, aux2;
REG_HEADER auxH;
long ultimoSize;
int eof1, eof2;
in2Stream = fopen(in2Path, "rb");
if(!in2Stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, in2Stream);
if(auxH.status == STATUS_INCONSISTENTE) {
fclose(in2Stream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
in1Stream = fopen(in1Path, "rb");
if(!in1Stream) {
fclose(in2Stream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, in1Stream);
if(auxH.status == STATUS_INCONSISTENTE) {
fclose(in1Stream);
fclose(in2Stream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
outStream = fopen(outPath, "wb+");
if(!outStream) {
fclose(in1Stream);
fclose(in2Stream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
auxH.status = STATUS_INCONSISTENTE;
auxH.first = -1;
R_writeH(&auxH, outStream);
// Iniciar leitura do primeiro registro
while((eof1 = R_read(&aux1, in1Stream)) == 1 && aux1.removed == R_REMOVIDO);
while((eof2 = R_read(&aux2, in2Stream)) == 1 && aux2.removed == R_REMOVIDO);
ultimoSize = -1;
while(eof1 == 1 && eof2 == 1) {
if(aux1.idServidor < aux2.idServidor) {
R_write(&aux1, outStream, &ultimoSize);
while((eof1 = R_read(&aux1, in1Stream)) == 1 && aux1.removed == R_REMOVIDO);
} else if(aux1.idServidor > aux2.idServidor) {
R_write(&aux2, outStream, &ultimoSize);
while((eof2 = R_read(&aux2, in2Stream)) == 1 && aux2.removed == R_REMOVIDO);
} else { // id1 == id2
R_write(&aux1, outStream, &ultimoSize);
while((eof1 = R_read(&aux1, in1Stream)) == 1 && aux1.removed == R_REMOVIDO);
while((eof2 = R_read(&aux2, in2Stream)) == 1 && aux2.removed == R_REMOVIDO);
}
}
if(eof1 == 1) { // Chegou no fim do arquivo 2.
if(aux1.removed != R_REMOVIDO) {
R_write(&aux1, outStream, &ultimoSize);
}
while(R_read(&aux1, in1Stream) == 1) {
if(aux1.removed == R_REMOVIDO) {
continue;
}
R_write(&aux1, outStream, &ultimoSize);
}
}
if(eof2 == 1) { // Chegou no fim do arquivo 1.
if(aux2.removed != R_REMOVIDO) {
R_write(&aux2, outStream, &ultimoSize);
}
while(R_read(&aux2, in2Stream) == 1) {
if(aux2.removed == R_REMOVIDO) {
continue;
}
R_write(&aux2, outStream, &ultimoSize);
}
}
fclose(in1Stream);
fclose(in2Stream);
// COMENTADO PQ: não faz padding mais na última página.
//R_writePad(outStream);
auxH.status = STATUS_CONSISTENTE;
R_writeH(&auxH, outStream);
fclose(outStream);
return 1;
}
int f9_match(char *in1Path, char *in2Path, char *outPath) {
FILE *in1Stream, *in2Stream, *outStream;
REG_DATA aux1, aux2;
REG_HEADER auxH;
long ultimoSize;
int eof1, eof2;
in2Stream = fopen(in2Path, "rb");
if(!in2Stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, in2Stream);
if(auxH.status == STATUS_INCONSISTENTE) {
fclose(in2Stream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
in1Stream = fopen(in1Path, "rb");
if(!in1Stream) {
fclose(in2Stream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, in1Stream);
if(auxH.status == STATUS_INCONSISTENTE) {
fclose(in1Stream);
fclose(in2Stream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
outStream = fopen(outPath, "wb+");
if(!outStream) {
fclose(in1Stream);
fclose(in2Stream);
printf("Falha no processamento do arquivo.\n");
return 0;
}
auxH.status = STATUS_INCONSISTENTE;
auxH.first = -1;
R_writeH(&auxH, outStream);
// Iniciar leitura do primeiro registro
while((eof1 = R_read(&aux1, in1Stream)) == 1 && aux1.removed == R_REMOVIDO);
while((eof2 = R_read(&aux2, in2Stream)) == 1 && aux2.removed == R_REMOVIDO);
ultimoSize = -1;
while(eof1 == 1 && eof2 == 1) {
if(aux1.idServidor < aux2.idServidor) {
while((eof1 = R_read(&aux1, in1Stream)) == 1 && aux1.removed == R_REMOVIDO);
} else if(aux1.idServidor > aux2.idServidor) {
while((eof2 = R_read(&aux2, in2Stream)) == 1 && aux2.removed == R_REMOVIDO);
} else { // id1 == id2
R_write(&aux1, outStream, &ultimoSize);
while((eof1 = R_read(&aux1, in1Stream)) == 1 && aux1.removed == R_REMOVIDO);
while((eof2 = R_read(&aux2, in2Stream)) == 1 && aux2.removed == R_REMOVIDO);
}
}
fclose(in1Stream);
fclose(in2Stream);
// COMENTADO PQ: não faz padding mais na última página.
//R_writePad(outStream);
auxH.status = STATUS_CONSISTENTE;
R_writeH(&auxH, outStream);
fclose(outStream);
return 1;
}
int f10_index(char *binPath, char *indPath) {
REG_HEADER auxH;
FILE *stream;
REG_DATA aux;
IND_T *index;
int i;
stream = fopen(binPath, "rb");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
index = I_init(NULL);
if(index == NULL) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO) {
continue;
}
if(strcmp(aux.nomeServidor, "") != 0) {
I_push(&aux, index);
}
}
fclose(stream);
if(I_write(index, indPath) != 1) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
return 1;
}
int f11_searchKey(char *binPath, char *indPath, char *value) {
long lastPage, pageCount;
REG_HEADER auxH;
IND_DATA *items;
FILE *stream;
REG_DATA aux;
IND_T *index;
char found;
int i, n;
stream = fopen(binPath, "rb");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
index = I_init(indPath);
if(index == NULL) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
items = I_iterate(&n, value, index);
found = 0;
for(i = 0; i < n; i++) {
fseek(stream, items[i].byteOffset, SEEK_SET);
if(R_read(&aux, stream) != 1 || aux.removed == R_REMOVIDO) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
if(strcmp(aux.nomeServidor, value) != 0) {
continue;
}
found = 1;
printf("%s: %d\n%s: ", auxH.desCampos[0], aux.idServidor, auxH.desCampos[1]);
if(aux.salarioServidor >= 0) {
printf("%.2lf\n%s: ", aux.salarioServidor, auxH.desCampos[2]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[2]);
}
if(strncmp(aux.telefoneServidor, "", 14) != 0) {
printf("%.14s\n%s: ", aux.telefoneServidor, auxH.desCampos[3]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[3]);
}
if(strcmp(aux.nomeServidor, "") != 0) {
printf("%s\n%s: ", aux.nomeServidor, auxH.desCampos[4]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[4]);
}
if(strcmp(aux.cargoServidor, "") != 0) {
printf("%s\n", aux.cargoServidor);
} else {
printf("valor nao declarado\n");
}
printf("\n");
}
pageCount = 1;
lastPage = -1;
for(i = 0; i < n; i++) {
if(items[i].byteOffset/PAGE_SIZE != lastPage) {
pageCount++;
}
lastPage = items[i].byteOffset / PAGE_SIZE;
}
if(!found) {
printf("Registro inexistente.\n");
} else {
printf("Número de páginas de disco para carregar o arquivo de índice: %ld\n", I_count(index));
printf("Número de páginas de disco para acessar o arquivo de dados: %ld\n", pageCount);
}
fclose(stream);
return 1;
}
int f12_removeRegsKey(char *binPath, char *indPath, int n, FILE *input) {
char found, field[5000], value[5000];
int i, j, nRemoved;
TO_BE_MODIFIED_FIELD *fields;
REMOVED_LIST_NODE *removed, removedAux;
VECTOR_T *builder;
REG_HEADER auxH;
FILE *stream;
REG_DATA aux;
IND_T *index;
long offset;
double k;
stream = fopen(binPath, "r+b");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
auxH.status = STATUS_INCONSISTENTE;
R_writeH(&auxH, stream);
index = I_init(indPath);
if(index == NULL) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
// Ler todos os campos de análise de stdin
builder = V_new(sizeof(TO_BE_MODIFIED_FIELD));
fields = (TO_BE_MODIFIED_FIELD *) malloc(sizeof(TO_BE_MODIFIED_FIELD));
for(i = 0; i < n; i++) {
scanf("%s", fields->campo);
scan_quote_string(fields->valor);
V_pushback(fields, builder);
}
free(fields);
n = V_build(&fields, builder);
V_destroy(builder);
// Ler todos os registros pra ver quais serão removidos
removed = (REMOVED_LIST_NODE *) malloc(sizeof(REMOVED_LIST_NODE));
builder = V_new(sizeof(REMOVED_LIST_NODE));
found = 0;
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO) {
continue;
}
if((removed->level=field_isMarked(&aux, n, 0, fields)) < 0) {
continue;
}
found = 1;
removed->level++;
removed->byteOffset = aux.byteOffset;
removed->size = aux.size;
V_pushback(removed, builder);
I_pop(&aux, index);
}
free(fields);
free(removed);
nRemoved = V_build(&removed, builder);
V_destroy(builder);
if(nRemoved > 0) {
// Ordenar crescentemente por level e depois por tamanho
MS_sort(removed, nRemoved, sizeof(REMOVED_LIST_NODE), (int (*)(const void *, const void *)) node_cmpbr);
builder = V_new(sizeof(REMOVED_LIST_NODE));
offset = auxH.first;
while(offset != L_NIL) {
fseek(stream, offset, SEEK_SET);
R_read(&aux, stream);
removedAux.nextByteOffset = aux.next;
removedAux.byteOffset = offset;
removedAux.size = aux.size;
removedAux.level = 0;
V_pushback(&removedAux, builder);
offset = aux.next;
}
removed = (REMOVED_LIST_NODE *) realloc(removed, sizeof(REMOVED_LIST_NODE) * (nRemoved + V_size(builder)));
V_copy(&removed[nRemoved], builder);
nRemoved += V_size(builder);
V_destroy(builder);
MS_sort(removed, nRemoved, sizeof(REMOVED_LIST_NODE), (int (*)(const void *, const void *)) node_cmplr);
MS_sort(removed, nRemoved, sizeof(REMOVED_LIST_NODE), (int (*)(const void *, const void *)) node_cmps);
// Ajustar encadeamento da lista
for(i = 1; i < nRemoved; i++) {
removed[i - 1].nextByteOffset = removed[i].byteOffset;
}
removed[nRemoved - 1].nextByteOffset = L_NIL;
auxH.first = removed[0].byteOffset;
// Ordenar crescentemente por byteOffset: melhora desempenho na escrita final dependendo do S.O.
MS_sort(removed, nRemoved, sizeof(REMOVED_LIST_NODE), (int (*)(const void *, const void *)) node_cmpb);
}
for(i = 0; i < nRemoved; i++) {
aux.removed = R_REMOVIDO;
aux.size = removed[i].size;
aux.next = removed[i].nextByteOffset;
aux.byteOffset = removed[i].byteOffset;
R_rewriteBack(&aux, stream);
}
auxH.status = STATUS_CONSISTENTE;
R_writeH(&auxH, stream);
I_rewrite(index);
I_destroy(index);
free(removed);
fclose(stream);
return 1;
}
int f13_addRegsKey(char *binPath, char *indPath, int n, FILE *input) {
char found, field[5000];
long offset;
int i, j, nRemoved;
REMOVED_LIST_NODE *removed;
VECTOR_T *builder;
REG_HEADER auxH;
FILE *stream;
IND_T *index;
REG_DATA aux, *toBeAdded;
double k;
stream = fopen(binPath, "r+b");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
auxH.status = STATUS_INCONSISTENTE;
R_writeH(&auxH, stream);
index = I_init(indPath);
if(index == NULL) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
// Ler lista de removidos
builder = V_new(sizeof(REMOVED_LIST_NODE));
removed = (REMOVED_LIST_NODE *) malloc(sizeof(REMOVED_LIST_NODE));
offset = auxH.first;
while(offset != L_NIL) {
fseek(stream, offset, SEEK_SET);
R_read(&aux, stream);
removed->nextByteOffset = aux.next;
removed->byteOffset = offset;
removed->size = aux.size;
V_pushback(removed, builder);
offset = aux.next;
}
free(removed);
nRemoved = V_build(&removed, builder);
V_destroy(builder);
// Adiciona um por um: tenta na lista de removidos da RAM. Caso não dê: adiciona em lista na RAM pra adicionar ao fim.
builder = V_new(sizeof(REG_DATA));
aux.removed = R_NAO_REMOVIDO;
for(i = 0; i < n; i++) {
scanf("%d", &aux.idServidor);
scan_quote_string(field);
if(field[0] == '\0') {
aux.salarioServidor = -1;
} else {
aux.salarioServidor = atof(field);
}
scan_quote_string(field);
strncpy(aux.telefoneServidor, field, 14);
scan_quote_string(aux.nomeServidor);
scan_quote_string(aux.cargoServidor);
aux.size = R_calculateSize(&aux);
for(j = 0; j < nRemoved; j++) {
if(removed[j].size >= aux.size) {
break;
}
}
if(j >= nRemoved) { // não cabe em nenhum
V_pushback(&aux, builder);
continue;
}
aux.size = removed[j].size;
aux.byteOffset = removed[j].byteOffset;
if(aux.nomeServidor[0] != '\0') {
I_push(&aux, index);
}
R_rewriteBack(&aux, stream);
memmove(&removed[j], &removed[j + 1], sizeof(REMOVED_LIST_NODE) * (nRemoved - j - 1));
nRemoved--;
}
n = V_build(&toBeAdded, builder);
V_destroy(builder);
// Encontrar fim do arquivo.
fseek(stream, 0, SEEK_END);
offset = ftell(stream);
if(offset % 32000 == 0) {
offset = -1;
} else {
while(R_read(&aux, stream) == 1) {
offset = aux.size;
}
}
// Adicionar os que faltam
for(i = 0; i < n; i++) {
R_write(&toBeAdded[i], stream, &offset);
if(toBeAdded[i].nomeServidor[0] != '\0') {
I_push(&toBeAdded[i], index);
}
}
// Atualizar lista
if(nRemoved > 0) {
// Não ordena: pra manter ordem original.
// Ajustar encadeamento da lista
for(i = 1; i < nRemoved; i++) {
removed[i - 1].nextByteOffset = removed[i].byteOffset;
}
removed[nRemoved - 1].nextByteOffset = L_NIL;
auxH.first = removed[0].byteOffset;
// Ordenar crescentemente por byteOffset: melhora desempenho na escrita final dependendo do S.O.
MS_sort(removed, nRemoved, sizeof(REMOVED_LIST_NODE), (int (*)(const void *, const void *)) node_cmpb);
} else {
auxH.first = L_NIL;
}
for(i = 0; i < nRemoved; i++) {
aux.removed = R_REMOVIDO;
aux.size = removed[i].size;
aux.next = removed[i].nextByteOffset;
aux.byteOffset = removed[i].byteOffset;
R_rewriteBack(&aux, stream);
}
auxH.status = STATUS_CONSISTENTE;
R_writeH(&auxH, stream);
I_rewrite(index);
I_destroy(index);
fclose(stream);
return 1;
}
int f14_searchKeyStats(char *binPath, char *indPath, char *value) {
long lastPage, pageCount;
REG_HEADER auxH;
IND_DATA *items;
FILE *stream;
REG_DATA aux;
IND_T *index;
char found;
int i, n;
stream = fopen(binPath, "rb");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
index = I_init(indPath);
if(index == NULL) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
items = I_iterate(&n, value, index);
/*if(n <= 0) {
printf("Registro inexistente.\n");
return 0;
}*/
printf("*** Realizando a busca sem o auxílio de índice\n");
found = 0;
// Rodar sem o índice.
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO || strcmp(aux.nomeServidor, value) != 0) {
continue;
}
found = 1;
printf("%s: %d\n%s: ", auxH.desCampos[0], aux.idServidor, auxH.desCampos[1]);
if(aux.salarioServidor >= 0) {
printf("%.2lf\n%s: ", aux.salarioServidor, auxH.desCampos[2]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[2]);
}
if(strncmp(aux.telefoneServidor, "", 14) != 0) {
printf("%.14s\n%s: ", aux.telefoneServidor, auxH.desCampos[3]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[3]);
}
if(strcmp(aux.nomeServidor, "") != 0) {
printf("%s\n%s: ", aux.nomeServidor, auxH.desCampos[4]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[4]);
}
if(strcmp(aux.cargoServidor, "") != 0) {
printf("%s\n", aux.cargoServidor);
} else {
printf("valor nao declarado\n");
}
printf("\n");
}
if(!found) {
printf("Registro inexistente.\n");
}
printf("Número de páginas de disco acessadas: %ld\n", B_count(stream));
printf("*** Realizando a busca com o auxílio de um índice secundário fortemente ligado\n");
found = 0;
for(i = 0; i < n; i++) {
fseek(stream, items[i].byteOffset, SEEK_SET);
if(R_read(&aux, stream) != 1 || aux.removed == R_REMOVIDO) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
if(strcmp(aux.nomeServidor, value) != 0) {
continue;
}
found = 1;
printf("%s: %d\n%s: ", auxH.desCampos[0], aux.idServidor, auxH.desCampos[1]);
if(aux.salarioServidor >= 0) {
printf("%.2lf\n%s: ", aux.salarioServidor, auxH.desCampos[2]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[2]);
}
if(strncmp(aux.telefoneServidor, "", 14) != 0) {
printf("%.14s\n%s: ", aux.telefoneServidor, auxH.desCampos[3]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[3]);
}
if(strcmp(aux.nomeServidor, "") != 0) {
printf("%s\n%s: ", aux.nomeServidor, auxH.desCampos[4]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[4]);
}
if(strcmp(aux.cargoServidor, "") != 0) {
printf("%s\n", aux.cargoServidor);
} else {
printf("valor nao declarado\n");
}
printf("\n");
}
pageCount = 1;
lastPage = -1;
for(i = 0; i < n; i++) {
if(items[i].byteOffset/PAGE_SIZE != lastPage) {
pageCount++;
}
lastPage = items[i].byteOffset / PAGE_SIZE;
}
if(!found) {
printf("Registro inexistente.\n");
}
printf("Número de páginas de disco para carregar o arquivo de índice: %ld\n", I_count(index));
printf("Número de páginas de disco para acessar o arquivo de dados: %ld\n", pageCount);
fseek(stream, 0, SEEK_END);
pageCount = B_count(stream) - pageCount;
printf("\nA diferença no número de páginas de disco acessadas: %ld\n", pageCount);
I_destroy(index);
fclose(stream);
return 1;
}
int f15_indexB(char *binPath, char *indPath) {
REG_HEADER auxH;
FILE *stream;
REG_DATA aux;
BTR_T *index;
int i;
stream = fopen(binPath, "rb");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
index = BT_new(indPath);
if(index == NULL) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
//char teste[100];
//fgets(teste, 100, stdin);
while(R_read(&aux, stream) == 1) {
if(aux.removed == R_REMOVIDO) {
continue;
}
//printf("pressione [ENTER] para inserir [%d = 0x%x]. ", aux.idServidor, (unsigned int) aux.idServidor);
//fgets(teste, 100, stdin);
if(aux.idServidor >= 0) {
BT_push(&aux, index);
}
//BT_flush(index);
}
fclose(stream);
if(BT_close(index) != 1) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
return 1;
}
int f16_searchKeyB(char *binPath, char *indPath, char *value) {
long levelCount, offset;
REG_HEADER auxH;
FILE *stream;
REG_DATA aux;
BTR_T *index;
char found;
int i;
stream = fopen(binPath, "rb");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
index = BT_init(indPath);
if(index == NULL) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
offset = BT_search(atoi(value), index);
found = 0;
fseek(stream, offset, SEEK_SET);
if(R_read(&aux, stream) != 1 || aux.removed == R_REMOVIDO) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
if(aux.idServidor == atoi(value)) {
found = 1;
printf("%s: %d\n%s: ", auxH.desCampos[0], aux.idServidor, auxH.desCampos[1]);
if(aux.salarioServidor >= 0) {
printf("%.2lf\n%s: ", aux.salarioServidor, auxH.desCampos[2]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[2]);
}
if(strncmp(aux.telefoneServidor, "", 14) != 0) {
printf("%.14s\n%s: ", aux.telefoneServidor, auxH.desCampos[3]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[3]);
}
if(strcmp(aux.nomeServidor, "") != 0) {
printf("%s\n%s: ", aux.nomeServidor, auxH.desCampos[4]);
} else {
printf("valor nao declarado\n%s: ", auxH.desCampos[4]);
}
if(strcmp(aux.cargoServidor, "") != 0) {
printf("%s\n", aux.cargoServidor);
} else {
printf("valor nao declarado\n");
}
printf("\n");
}
levelCount = BT_count(index);
BT_close(index);
if(!found) {
printf("Registro inexistente.\n");
} else {
printf("Número de níveis do índice árvore-B percorridos: %ld\n", levelCount);
}
fclose(stream);
return 1;
}
int fx_listRemoved(char *binPath) {
REG_HEADER auxH;
REG_DATA aux;
FILE *stream;
long offset;
stream = fopen(binPath, "rb");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R_readH(&auxH, stream);
if(auxH.status != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
offset = auxH.first;
printf("Começa em 0x%016lX\n", offset);
while(offset != L_NIL) {
fseek(stream, offset, SEEK_SET);
R_read(&aux, stream);
printf("[0x%016lX] tamanho = %d próximo = 0x%016lX\n", offset, aux.size, aux.next);
offset = aux.next;
}
fclose(stream);
return 1;
}
int fx_invalidate(char *binPath) {
FILE *stream;
char R;
stream = fopen(binPath, "rb+");
if(!stream) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R = fgetc(stream);
if(R != STATUS_CONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
R = STATUS_INCONSISTENTE;
if(fseek(stream, 0, SEEK_SET) != 0 || fwrite(&R, sizeof(char), 1, stream) != 1) {
printf("Falha no processamento do arquivo.\n");
return 0;
}
printf("Arquivo invalidado.\n");
fclose(stream);
return 1;
}
<file_sep>package main;
import gerenciador.Gerenciador;
import java.io.IOException;
import console.Console;
public class Main {
public static void main(String[] args) {
Gerenciador g;
Console c;
int p;
c = Console.getInstance();
System.out.println("Bem-vinde ao Servidor Gerenciador da Sala Inteligente.");
System.out.println();
do {
p = c.readInt("Em qual porta o servidor do gerenciador deve iniciar? (recomendado = 9000)");
if (p < 1 || p > 65535) {
System.out.println("Porta invalida! Deve ser um valor entre 1-65535.");
}
} while(p < 1 || p > 65535);
try {
g = new Gerenciador(p);
System.out.println("O servidor esta hospedado em: " + g.getHostAddress() + ":" + g.getPort());
g.execute();
} catch(IOException ex) {
System.err.println("Nao foi possivel iniciar o servidor. :(");
System.err.println(ex);
ex.printStackTrace();
}
}
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int N=0;
FILE *Stream;
char FileName[100];
scanf("%s",FileName);
FileName[99]='\0';
Stream=fopen(FileName,"r");
while(!feof(Stream)){
getc(Stream);
N++;
}
fclose(Stream);
printf("%d",--N);
return EXIT_SUCCESS;
}
<file_sep>
/*
* == Inteiros Ilimitados ==
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __UnlimitedInteger_H_
#define __UnlimitedInteger_H_
typedef struct __UI_t UI;
struct __UI_t *UI_New();
struct __UI_t *UI_NewFromInt(long int);
struct __UI_t *UI_Read(FILE *);
char UI_Write(FILE *, struct __UI_t *);
char UI_Cmp(struct __UI_t *, struct __UI_t *);
struct __UI_t *UI_Abs(struct __UI_t *);
struct __UI_t *UI_Sum(struct __UI_t *,struct __UI_t *);
struct __UI_t *UI_Subtraction(struct __UI_t *,struct __UI_t *);
struct __UI_t *UI_Product(struct __UI_t *,struct __UI_t *);
struct __UI_t *UI_Quotient(struct __UI_t *,struct __UI_t *);
char UI_Destroy(struct __UI_t *);
#endif
<file_sep># SSC-0118 Sistemas Digitais - 2017.2
Aqui estão todos os trabalhos que implementei em Sistemas Digitais.
<file_sep>#include <stdlib.h>
#include <iostream>
#include <map>
using namespace std;
void count(long *cents, long n, long limit, map<long, long> &counter) {
long i, j;
for(i = 0; i < n; i++){
for(j = cents[i]; j < limit; j++){
counter[j] += counter[j - cents[i]];
}
}
}
int main(int argc, char **argv) {
long cents[] = { 50, 25, 10, 5, 1 };
map<long, long> counter;
long n, value;
n = 5;
counter[0] = 1;
count(cents, n, 400000, counter);
while(cin >> value) {
cout << counter[value] << '\n';
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
<NAME>
<EMAIL>
*/
int main(){
short int i,R;
for(i=1000;i<9999;i++){
R=(i/100)+(i-((i/100)*100));
if(sqrt(i)==R){
printf("%hi\n",i);
}
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int N,Ni,Max,Min;
scanf("%d",&N);
scanf("%d",&Ni);
Max=Ni;
Min=Ni;
N--;
for(N=N;N>0;N--){
scanf("%d",&Ni);
if(Ni>Max){
Max=Ni;
}
if(Ni<Min){
Min=Ni;
}
}
printf("max: %d\n",Max);
printf("min: %d",Min);
return EXIT_SUCCESS;
}
<file_sep>package main;
import message.Message;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class Ar extends JDialog implements ActionListener {
private String serverAddr;
private int serverPort;
JButton btnArOn;
JButton btnArOff;
JButton btnGetTemperatura;
JButton btnSetTemperatura;
public Ar(String serverAddr, int serverPort) {
setTitle("Ar");
getContentPane().setLayout(new FlowLayout());
setSize(300, 155);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(dim.width / 2 - this.getSize().width / 2, dim.height
/ 2 - this.getSize().height / 2);
setResizable(false);
btnArOn = new JButton("Ligar ar");
btnArOn.addActionListener(this);
btnArOn.setSize(95, 100);
getContentPane().add(btnArOn);
btnArOff = new JButton("Desligar ar");
btnArOff.addActionListener(this);
btnArOff.setSize(95, 100);
getContentPane().add(btnArOff);
btnGetTemperatura = new JButton("Obter temperatura");
btnGetTemperatura.setSize(200, 200);
btnGetTemperatura.addActionListener(this);
btnGetTemperatura.setSize(160, 100);
getContentPane().add(btnGetTemperatura);
btnSetTemperatura = new JButton("Mudar temperatura");
btnSetTemperatura.addActionListener(this);
btnSetTemperatura.setSize(160, 100);
getContentPane().add(btnSetTemperatura);
this.serverAddr = serverAddr;
this.serverPort = serverPort;
setModal(true);
}
public void actionPerformed(ActionEvent e) {
Object src;
String s;
double d;
src = e.getSource();
if (src == btnArOn) {
try {
s = new Message(new Message("INTERFACE_CLIENTE", "ARON", "").send(this.serverAddr, this.serverPort)).getBody();
JOptionPane.showMessageDialog(this, s, "Ar-condicionado", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception exc) {
JOptionPane.showMessageDialog(this, "Não foi possível comunicar com o gerenciador!", "Ar-condicionado", JOptionPane.ERROR_MESSAGE);
}
} else if (src == btnArOff) {
try {
s = new Message(new Message("INTERFACE_CLIENTE", "AROFF", "").send(this.serverAddr, this.serverPort)).getBody();
JOptionPane.showMessageDialog(this, s, "Ar-condicionado", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception exc) {
JOptionPane.showMessageDialog(this, "Não foi possível comunicar com o gerenciador!", "Ar-condicionado", JOptionPane.ERROR_MESSAGE);
}
} else if (src == btnGetTemperatura) {
try {
s = new Message(new Message("INTERFACE_CLIENTE", "GET_TEMP", "").send(this.serverAddr, this.serverPort)).getBody();
JOptionPane.showMessageDialog(this, s, "Temperatura", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception exc) {
JOptionPane.showMessageDialog(this, "Não foi possível comunicar com o gerenciador!", "Temperatura", JOptionPane.ERROR_MESSAGE);
}
} else if (src == btnSetTemperatura) {
try {
s = (String) JOptionPane.showInputDialog(this, "Qual a nova temperatura? (entre com um numero real entre 10-25, em graus)", "Temperatura", JOptionPane.PLAIN_MESSAGE);
if (s != null) {
d = Double.parseDouble(s);
if (d < 10 || d > 25) {
throw new NumberFormatException();
}
s = new Message(new Message("INTERFACE_CLIENTE", "SET_TEMP", Double.toString(d)).send(this.serverAddr, this.serverPort)).getBody();
JOptionPane.showMessageDialog(this, s, "Temperatura", JOptionPane.INFORMATION_MESSAGE);
}
} catch (NumberFormatException exc) {
JOptionPane.showMessageDialog(this, "Numero invalido!", "Temperatura", JOptionPane.ERROR_MESSAGE);
} catch (Exception exc) {
JOptionPane.showMessageDialog(this, "Não foi possível comunicar com o gerenciador!", "Temperatura", JOptionPane.ERROR_MESSAGE);
}
}
}
}
<file_sep>
/* Usado para poder exportar a arquitetura para carregar de arquivo posteriomente */
var definition = {
memoryAlgorithm: "",
nCores: "",
cacheLines: "",
cacheBlocks: "",
cacheAlgorithm: "",
memInitValues: [ ],
coreRequests: [ ]
};
/* Usado para simulação em tempo real */
var simulation = {
running: false,
currentPosition: null,
initialState: null,
speed: 1000,
requests: null
};
var scriptsLoaded = true;
function confirmDialog(message, okText, okAction, abortText, abortAction) {
if(okText == null) {
okText = "OK";
}
if(okAction == null) {
okAction = "";
}
if(abortText == null) {
abortText = "Cancelar";
}
if(abortAction == null) {
abortAction = "";
}
document.getElementById("dialogMessage").innerHTML = message;
document.getElementById("dialogButtons").innerHTML = "<a href='javascript:void(0);' onclick='closeDialog(" + okAction + ");'>" + okText + "</a>";
document.getElementById("dialogButtons").innerHTML += "<a href='javascript:void(0);' onclick='closeDialog(" + abortAction + ");'>" + abortText + "</a>";
$("#blurBackground").stop().fadeIn(500);
$("#dialog").stop().slideDown(1000);
}
function alertDialog(message, okText, okAction) {
if(okText == null) {
okText = "Fechar";
}
if(okAction == null) {
okAction = "";
}
document.getElementById("dialogMessage").innerHTML = message;
document.getElementById("dialogButtons").innerHTML = "<a href='javascript:void(0);' onclick='closeDialog(" + okAction + ");'>" + okText + "</a>";
$("#blurBackground").stop().fadeIn(500);
$("#dialog").stop().slideDown(1000);
}
function closeDialog(action) {
$("#dialog").stop().slideUp(500);
$("#blurBackground").stop().fadeOut(1000);
if(action != null) {
try { action(); } catch(exc) { }
}
}
function bytesToString(nBytes) {
if(nBytes < 0) {
return;
}
if(nBytes > 1048570756) {
return (nBytes/1073741824).toFixed(2) + " GiB (" + nBytes.toLocaleString() + " bytes)";
} else if(nBytes > 1023992) {
return (nBytes/1048576).toFixed(2) + " MiB (" + nBytes.toLocaleString() + " bytes)";
} else if(nBytes >= 1024) {
return (nBytes/1024).toFixed(2) + " KiB (" + nBytes.toLocaleString() + " bytes)";
} else if(nBytes != 1) {
return nBytes.toLocaleString() + " bytes";
} else {
return "1 byte";
}
}
function calculateMemBytes() {
var nBytes, element;
element = document.getElementById("memorySizeBytes");
nBytes = document.getElementById("memorySize").value;
if(nBytes == "" || parseInt(nBytes, 10) < 0 || parseInt(nBytes, 10) > 536870912) {
element.innerHTML = "";
return;
}
nBytes = parseInt(nBytes, 10) * 4;
element.innerHTML = "RAM: " + bytesToString(nBytes);
}
function calculateCacheBytes() {
var nLines, nBlocks, nBytes, element;
element = document.getElementById("cacheSizeBytes");
nLines = document.getElementById("cacheLines").value;
nBlocks = document.getElementById("cacheBlocks").value;
if(nLines == "" || nBlocks == "") {
element.innerHTML = "";
return;
}
nLines = parseInt(nLines, 10);
nBlocks = parseInt(nBlocks, 10);
nBytes = nLines * nBlocks;
if(nBytes < 0 || nBytes > 536870912) {
element.innerHTML = "";
return;
}
nBytes *= 4;
element.innerHTML = "Cache: " + bytesToString(nBytes);
}
function submitHome() {
var i, algorithm, memSize, nCores, cacheLines, cacheBlocks, cacheAlgorithm;
algorithm = document.getElementById("memoryAlgorithm").value;
memSize = document.getElementById("memorySize").value;
nCores = document.getElementById("nCores").value;
cacheLines = document.getElementById("cacheLines").value;
cacheBlocks = document.getElementById("cacheBlocks").value;
cacheAlgorithm = document.getElementById("cacheAlgorithm").value;
if(algorithm == "" || memSize == "" || nCores == "" || cacheLines == "" ||
cacheBlocks == "" || cacheAlgorithm == "") {
alertDialog("Por favor, defina todos os campos!");
return false;
}
memSize = parseInt(memSize, 10);
nCores = parseInt(nCores, 10);
cacheLines = parseInt(cacheLines, 10);
cacheBlocks = parseInt(cacheBlocks, 10);
if(memSize < 0 || memSize > 536870912) {
alertDialog("A capacidade da memória principal (em palavras) deve estar entre 0 e 536870912!");
} else if(nCores < 0 || nCores > 4096) {
alertDialog("O número de núcleos no processador deve estar entre 0 e 4096!");
} else if(cacheLines < 0 || cacheBlocks < 0) {
alertDialog("O número de linhas na cache e palavras por linha devem ser maiores que 0!");
} else if(cacheLines * cacheBlocks > 536870912) {
alertDialog("A capacidade total da cache em palavras deve estar entre 0 e 536870912!");
} else if(cacheLines * cacheBlocks >= memSize) {
alertDialog("Não faz sentido a cache ter capacidade maior ou igual a da memória principal!");
} else {
document.getElementById("homeDefinition").style.display = "none";
document.getElementById("memInitValues").innerHTML = "";
for(i = 0; i < memSize; i++) {
document.getElementById("memInitValues").innerHTML += "<tr><td>0x" + (i*4).toString(16).toUpperCase() + "</td><td><input type='number' min='0' max='4294967295' step='1' placeholder='(valor inicial)' required='required'></td></tr>";
}
$("#memoryDefinition").stop().fadeIn(1000);
return true;
}
return false;
}
function backToHome() {
document.getElementById("memoryDefinition").style.display = "none";
$("#homeDefinition").stop().fadeIn(1000);
}
function autoFillMem(method) {
var i, j, elements;
elements = document.getElementById("memInitValues").getElementsByTagName("input");
switch(method) {
case 0:
for(i = 0; i < elements.length; i++) {
elements[i].value = Math.floor(Math.random() * 4294967296);
}
break;
case 1:
for(i = 0; i < elements.length; i++) {
elements[i].value = Math.floor(Math.random() * 1000);
}
break;
case 2:
for(i = 0; i < elements.length; i++) {
elements[i].value = i;
}
break;
case 3:
for(i = 0; i < elements.length; i++) {
elements[i].value = i + 100;
}
break;
case 4:
for(i = 0; i < elements.length; i++) {
elements[i].value = (i * 4 * 10) % 4294967295;
}
break;
}
closeDialog();
}
function submitMemory() {
var i, elements, memSize, value;
elements = document.getElementById("memInitValues").getElementsByTagName("input");
memSize = document.getElementById("memorySize").value;
memSize = parseInt(memSize, 10);
for(i = 0; i < elements.length; i++) {
if(elements[i].value == "") {
alertDialog("Por favor, defina todos os campos!");
return false;
}
value = parseInt(elements[i].value, 10);
if(value < 0 || value > 4294967295) {
alertDialog("O valor de uma palavra de 32 bits deve estar entre 0 e 4294967295. Verifique os valores digitados!");
return false;
}
}
document.getElementById("memoryDefinition").style.display = "none";
document.getElementById("coreRequests").innerHTML = "";
$("#requestsDefinition").stop().fadeIn(1000);
return true;
}
function backToMemory() {
document.getElementById("requestsDefinition").style.display = "none";
$("#memoryDefinition").stop().fadeIn(1000);
}
function addRequestItem() {
var element, newElement, nCores, memSize;
element = document.getElementById("coreRequests");
memSize = document.getElementById("memorySize").value;
memSize = parseInt(memSize, 10);
nCores = document.getElementById("nCores").value;
nCores = parseInt(nCores, 10);
newElement = document.createElement("tr");
newElement.innerHTML = "<td><input type='number' placeholder='(N)' step='1' min='0' max='" + (nCores - 1) + "' required='required'></td><td><select required='required' onchange='requestTypeChanged(this.value, this.parentNode);'><option value='' disabled='disabled' selected='selected'>(selecione)</option><option value='read'>lê</option><option value='write'>escreve</option></select> <input type='number' value='0' placeholder='(valor)' min='0' max='4294967295' required='required' style='display: none;'></td><td><input type='number' placeholder='(0, 4, ...)' min='0' max='" + (memSize - 1) * 4 + "' step='4' required='required'></td><td><a href='javascript:void(0);' onclick='moveRequestItemUp(this.parentNode.parentNode);'>↑</a><a href='javascript:void(0);' onclick='moveRequestItemDown(this.parentNode.parentNode);'>↓</a><a href='javascript:void(0);' onclick='removeRequestItem(this.parentNode.parentNode);'>×</a></td>";
element.appendChild(newElement);
element = newElement.getElementsByTagName("input");
element[element.length - 3].focus();
return newElement;
}
function removeRequestItem(item) {
var element;
element = document.getElementById("coreRequests");
element.removeChild(item);
}
function moveRequestItemUp(item) {
var parent, previous;
parent = item.parentNode;
previous = item.previousElementSibling;
if(previous != null)
parent.insertBefore(item, previous);
}
function moveRequestItemDown(item) {
var parent, next;
parent = item.parentNode;
next = item.nextElementSibling;
if(next != null)
parent.insertBefore(next, item);
}
function requestTypeChanged(value, item) {
var element;
element = item.getElementsByTagName("input")[0];
if(value == "write") {
element.value = "";
element.style.display = "inline";
} else {
element.value = "0";
element.style.display = "none";
}
}
function findInLine(line, addr) {
var i;
for(i = 0; i < line.length; i++) {
if(line[i].a == addr) {
return i;
}
}
return -1;
}
function invalidateInLine(line, pos) {
var i, aux;
aux = [ ];
for(i = 0; i < line.length; i++) {
if(i != pos) {
aux.push({ a: line[i].a, v: line[i].v, s: line[i].s, c: line[i].c });
}
}
return aux;
}
function updateInLine(line, pos, newValue, addr, state, counter) {
var i, aux, aux2;
aux = [ ];
switch(definition.cacheAlgorithm) {
case "fifo":
if(pos < 0) { // adicionar
for(i = 0; i < line.length; i++) {
console.log(line[i]);
aux.push(line[i]);
console.log(aux);
}
aux.push({a: addr, v: newValue, s: state, c: -1});
} else { // atualizar
for(i = 0; i < line.length; i++) {
aux.push(line[i]);
}
aux[pos].v = newValue;
}
break;
case "lru":
if(pos < 0) { // adicionar
aux.push({a: addr, v: newValue, s: state, c: -1});
for(i = 0; i < line.length; i++) {
aux.push(line[i]);
}
} else { // atualizar
for(i = 0; i < line.length; i++) {
aux.push(line[i]);
}
aux[pos].v = newValue;
aux2 = aux[0];
aux[0] = aux[pos];
aux[pos] = aux2;
}
break;
default: // lfu
if(pos < 0) { // adicionar
for(i = 0; i < line.length && line[i].c <= counter; i++) {
aux.push(line[i]);
}
aux.push({a: addr, v: newValue, s: state, c: counter});
for(; i < line.length; i++) {
aux.push(line[i]);
}
} else { // atualizar
aux2 = line[pos];
aux2.c++;
for(i = 0; i < pos; i++) {
aux.push(line[i]);
}
i++;
for(; i < line.length && line[i].c < aux2.c; i++) {
aux.push(line[i]);
}
aux.push(aux2);
for(; i < line.length; i++) {
aux.push(line[i]);
}
}
}
return aux;
}
function lineToString(line) {
var aux;
aux = "";
for(i = 0; i < line.length; i++) {
aux += "<span title='No endereço 0x" + (parseInt(line[i].a, 10) * 4).toString(16).toUpperCase() + "'>" + line[i].v + "</span>";
}
return aux;
}
function submitRequests() {
var i, j, n, elements, inputs, element, state, nCores, cacheLines, defaultCacheLines, memSize;
elements = document.getElementById("coreRequests").childNodes;
element = document.getElementById("requests");
memSize = document.getElementById("memorySize").value;
memSize = parseInt(memSize, 10);
nCores = document.getElementById("nCores").value;
nCores = parseInt(nCores, 10);
cacheLines = document.getElementById("cacheLines").value;
cacheLines = parseInt(cacheLines, 10);
if(elements.length < 1) {
alertDialog("Adicione ao menos uma requisição de um núcleo!");
return false;
}
for(i = 0; i < elements.length; i++) {
inputs = elements[i].getElementsByTagName("input");
if(inputs[0].value == "" || inputs[1].value == "" || inputs[2].value == "" || elements[i].getElementsByTagName("select")[0].value == "") {
alertDialog("Por favor, defina todos os campos!");
return false;
}
inputs = [parseInt(inputs[0].value, 10), parseInt(inputs[1].value, 10), parseInt(inputs[2].value, 10)]
if(inputs[0] < 0 || inputs[0] >= nCores) {
alertDialog("O valor do núcleo deve estar entre 0 e " + (nCores - 1) + ". Verifique os valores digitados!");
return false;
}
if(inputs[1] < 0 || inputs[1] > 4294967295) {
alertDialog("O valor de uma palavra de 32 bits deve estar entre 0 e 4294967295. Verifique os valores digitados!");
return false;
}
if(inputs[2] < 0 || inputs[2] > (memSize - 1) * 4 || inputs[2] % 4 != 0) {
alertDialog("O endereço de acesso deve estar entre 0 e " + ((memSize - 1) * 4) + ", sendo múltiplo de 4. Verifique os valores digitados!");
return false;
}
}
document.getElementById("requestsDefinition").style.display = "none";
definition.memoryAlgorithm = document.getElementById("memoryAlgorithm").value;
definition.nCores = document.getElementById("nCores").value;
definition.cacheLines = document.getElementById("cacheLines").value;
definition.cacheBlocks = document.getElementById("cacheBlocks").value;
definition.cacheAlgorithm = document.getElementById("cacheAlgorithm").value;
definition.coreRequests = [ ];
element.innerHTML = "";
for(i = 0; i < elements.length; i++) {
inputs = elements[i].getElementsByTagName("input");
definition.coreRequests.push([ inputs[0].value, elements[i].getElementsByTagName("select")[0].value, inputs[1].value, inputs[2].value / 4 ]);
aux = (definition.coreRequests[i][1] == "write") ? "escreve " + definition.coreRequests[i][2] + " no" : "lê do";
element.innerHTML += "<div class='request'><a href='javascript:void(0);' onclick='simClick(" + i + ", this.parentNode);'>P" + definition.coreRequests[i][0] + " " + aux + " endereço 0x" + (definition.coreRequests[i][3] * 4).toString(16).toUpperCase() + "</a></div>";
}
definition.memInitValues = [ ];
elements = document.getElementById("memInitValues").getElementsByTagName("input");
document.getElementById("mainMemoryWords").innerHTML = "";
for(i = 0; i < elements.length; i++) {
definition.memInitValues.push(elements[i].value);
document.getElementById("mainMemoryWords").innerHTML += "<tr><td>0x" + (i*4).toString(16).toUpperCase() + "</td><td>" + elements[i].value + "</td></tr>";
}
defaultCacheLines = "";
for(i = 0; i < cacheLines; i++) {
defaultCacheLines += "<tr><td>" + (i) + "</td><td></td></tr>";
}
n = parseInt(definition.nCores, 10);
document.getElementById("coresCPU").innerHTML = "";
for(i = 0; i < n; i++) {
document.getElementById("coresCPU").innerHTML += "<div class='core'><div class='bus'></div><div class='notification' style='display: none;'></div><div class='coreCPU'>CPU " + i + "</div><div class='coreCache'><table><thead><tr><th>Linha</th><th>Palavras</th></tr></thead><tbody>" + defaultCacheLines + "</tbody></table></div></div>";
}
/* EXECUÇÃO DO ALGORITMO */
state = { mem: [], cores: [ ] };
simulation.initialState = [ ];
for(i = 0; i < memSize; i++) {
element = parseInt(definition.memInitValues[i], 10);
state.mem.push(element);
simulation.initialState.push(element);
}
for(i = 0; i < nCores; i++) {
state.cores.push([ ]);
for(j = 0; j < cacheLines; j++) {
state.cores[i].push([ ]);
}
}
simulation.requests = [ ];
simulation.currentPosition = -1;
simulation.running = null;
elements = document.getElementById("coreRequests").childNodes;
switch(definition.memoryAlgorithm) {
case "msi":
for(i = 0; i < definition.coreRequests.length; i++) {
simulation.requests.push([ {action: "focus", value: definition.coreRequests[i][0]} ]);
element = findInLine(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines], definition.coreRequests[i][3]);
if(definition.coreRequests[i][1] == "write") {
simulation.requests[i].push({action: "notify", value: [definition.coreRequests[i][0], "PrWrite"]});
simulation.requests[i].push({action: "write-bus", value: "BusWrite (" + definition.coreRequests[i][0] + ")"});
if(element >= 0) {
if(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines][element].s == "M") {
state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines] = updateInLine(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines], element, definition.coreRequests[i][2]);
simulation.requests[i].push({action: "update-line", value: [definition.coreRequests[i][0], definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines])] });
} else { // .s == "S"
moved = false;
for(j = 0; j < nCores; j++) {
if(j == definition.coreRequests[i][0]) {
continue;
}
elementAux = findInLine(state.cores[j][definition.coreRequests[i][3] % cacheLines], definition.coreRequests[i][3]);
if(elementAux < 0) {
continue;
}
if(state.cores[j][definition.coreRequests[i][3] % cacheLines][elementAux].s != "S") {
continue;
}
moved = true;
simulation.requests[i].push({action: "focus", value: j});
simulation.requests[i].push({action: "notify", value: [j, "Observed BusWrite!"]});
state.cores[j][definition.coreRequests[i][3] % cacheLines] = invalidateInLine(state.cores[j][definition.coreRequests[i][3] % cacheLines], elementAux);
simulation.requests[i].push({action: "update-line", value: [j, definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[j][definition.coreRequests[i][3] % cacheLines])] });
}
if(moved == true) {
simulation.requests[i].push({action: "focus", value: definition.coreRequests[i][0]});
}
state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines] = updateInLine(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines], element, definition.coreRequests[i][2]);
state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines][element].s = "M";
simulation.requests[i].push({action: "update-line", value: [definition.coreRequests[i][0], definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines])] });
}
} else {
moved = false;
for(j = 0; j < nCores; j++) {
if(j == definition.coreRequests[i][0]) {
continue;
}
elementAux = findInLine(state.cores[j][definition.coreRequests[i][3] % cacheLines], definition.coreRequests[i][3]);
if(elementAux < 0) {
continue;
}
moved = true;
simulation.requests[i].push({action: "focus", value: j});
if(state.cores[j][definition.coreRequests[i][3] % cacheLines][elementAux].s == "M") {
simulation.requests[i].push({action: "notify", value: [j, "Observed BusWrite: flush..."]});
simulation.requests[i].push({action: "update-ram", value: [state.cores[j][definition.coreRequests[i][3] % cacheLines][elementAux].a, state.cores[j][definition.coreRequests[i][3] % cacheLines][elementAux].v] });
state.mem[state.cores[j][definition.coreRequests[i][3] % cacheLines][elementAux].a] = state.cores[j][definition.coreRequests[i][3] % cacheLines][elementAux].v;
} else {
simulation.requests[i].push({action: "notify", value: [j, "Observed BusWrite!"]});
}
state.cores[j][definition.coreRequests[i][3] % cacheLines] = invalidateInLine(state.cores[j][definition.coreRequests[i][3] % cacheLines], elementAux);
simulation.requests[i].push({action: "update-line", value: [j, definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[j][definition.coreRequests[i][3] % cacheLines])] });
}
if(moved == true) {
simulation.requests[i].push({action: "focus", value: definition.coreRequests[i][0]});
}
if(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines].length >= definition.cacheBlocks) {
elementAux2 = state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines].shift();
if(elementAux2.s == "M") {
simulation.requests[i].push({action: "update-ram", value: [elementAux2.a, elementAux2.v] });
state.mem[elementAux2.a] = elementAux2.v;
}
}
console.log(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines]);
state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines] = updateInLine(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines], element, definition.coreRequests[i][2], definition.coreRequests[i][3], "M", 0);
simulation.requests[i].push({action: "update-line", value: [definition.coreRequests[i][0], definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines])] });
}
} else { // read
simulation.requests[i].push({action: "notify", value: [definition.coreRequests[i][0], "PrRead"]});
simulation.requests[i].push({action: "write-bus", value: "BusRead (" + definition.coreRequests[i][0] + ")"});
if(element >= 0) {
state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines] = updateInLine(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines], element, state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines][element].v);
simulation.requests[i].push({action: "update-line", value: [definition.coreRequests[i][0], definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines])] });
} else {
moved = false;
for(j = 0; j < nCores; j++) {
if(j == definition.coreRequests[i][0]) {
continue;
}
elementAux = findInLine(state.cores[j][definition.coreRequests[i][3] % cacheLines], definition.coreRequests[i][3]);
if(elementAux < 0) {
continue;
}
if(state.cores[j][definition.coreRequests[i][3] % cacheLines][elementAux].s == "S") {
continue;
}
moved = true;
simulation.requests[i].push({action: "focus", value: j});
simulation.requests[i].push({action: "notify", value: [j, "Observed BusRead: flush..."]});
simulation.requests[i].push({action: "update-ram", value: [state.cores[j][definition.coreRequests[i][3] % cacheLines][elementAux].a, state.cores[j][definition.coreRequests[i][3] % cacheLines][elementAux].v] });
state.mem[state.cores[j][definition.coreRequests[i][3] % cacheLines][elementAux].a] = state.cores[j][definition.coreRequests[i][3] % cacheLines][elementAux].v;
simulation.requests[i].push({action: "update-line", value: [j, definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[j][definition.coreRequests[i][3] % cacheLines])] });
state.cores[j][definition.coreRequests[i][3] % cacheLines][elementAux].s = "S";
}
if(moved == true) {
simulation.requests[i].push({action: "focus", value: definition.coreRequests[i][0]});
}
if(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines].length >= definition.cacheBlocks) {
elementAux2 = state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines].shift();
if(elementAux2.s == "M") {
simulation.requests[i].push({action: "update-ram", value: [elementAux2.a, elementAux2.v] });
state.mem[elementAux2.a] = elementAux2.v;
}
}
state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines] = updateInLine(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines], element, state.mem[definition.coreRequests[i][3]], definition.coreRequests[i][3], "S", 0);
simulation.requests[i].push({action: "update-line", value: [definition.coreRequests[i][0], definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines])] });
}
}
}
break;
case "mesi":
for (i = 0; i < definition.coreRequests.length; i++) {
const processor = definition.coreRequests[i][0];
const operation = definition.coreRequests[i][1];
const writeValue = definition.coreRequests[i][2];
const address = definition.coreRequests[i][3];
const cacheLine = address % cacheLines;
const element = findInLine(state.cores[processor][cacheLine], address);
simulation.requests.push([ {action: "focus", value: processor} ]);
if (operation == "write") {
simulation.requests[i].push({action: "notify", value: [processor, "PrWrite"]});
if (element == -1 || state.cores[processor][cacheLine][element].s == 'S') {
// current state is Invalid or Shared
simulation.requests[i].push({action: "write-bus", value: "BusRdX (" + processor + ")"});
moved = false;
for (j = 0; j < nCores; j++) if (j != processor) {
const elementAux = findInLine(state.cores[j][cacheLine], address);
if (elementAux < 0) {
continue;
}
const foreignLine = state.cores[j][cacheLine];
const foreignState = foreignLine[elementAux].s;
moved = true;
simulation.requests[i].push({action: "focus", value: j});
simulation.requests[i].push({action: "notify", value: [j, "Observed BusRdX" + (foreignState == "M" ? ": flush..." : "!")]});
if (foreignState == "M") {
simulation.requests[i].push({action: "update-ram", value: [address, foreignLine[elementAux].v] });
state.mem[address] = foreignLine[elementAux].v;
}
state.cores[j][cacheLine] = invalidateInLine(foreignLine, elementAux);
simulation.requests[i].push({action: "update-line", value: [j, cacheLine, lineToString(state.cores[j][cacheLine])] });
if (foreignState == "M" || foreignState == "E") {
break;
}
}
if (moved == true) {
simulation.requests[i].push({action: "focus", value: processor});
}
if (element == -1 && state.cores[processor][cacheLine].length >= definition.cacheBlocks) {
elementAux2 = state.cores[processor][cacheLine].shift();
if (elementAux2.s == "M") {
simulation.requests[i].push({action: "update-ram", value: [elementAux2.a, elementAux2.v] });
state.mem[elementAux2.a] = elementAux2.v;
}
}
state.cores[processor][cacheLine] = updateInLine(state.cores[processor][cacheLine], element, writeValue, address, "M", 0);
simulation.requests[i].push({action: "update-line", value: [processor, cacheLine, lineToString(state.cores[processor][cacheLine])] });
} else {
// current state is Exclusive or Modified
state.cores[processor][cacheLine] = updateInLine(state.cores[processor][cacheLine], element, writeValue);
simulation.requests[i].push({action: "update-line", value: [processor, cacheLine, lineToString(state.cores[processor][cacheLine])] });
}
} else { // operation == "read"
simulation.requests[i].push({action: "notify", value: [processor, "PrRead"]});
if (element == -1) {
// current state is Invalid
simulation.requests[i].push({action: "write-bus", value: "BusRd (" + processor + ")"});
var shared = false; // whether another processor has this line
moved = false;
for (j = 0; j < nCores; j++) if (j != processor) {
const elementAux = findInLine(state.cores[j][cacheLine], address);
if (elementAux < 0) {
continue;
}
shared = true;
const foreignLine = state.cores[j][cacheLine];
const foreignState = foreignLine[elementAux].s;
moved = true;
if(foreignState == "S") {
continue; // Soh pra nao mudar o foco sem necessidade na interface.
}
simulation.requests[i].push({action: "focus", value: j});
simulation.requests[i].push({action: "notify", value: [j, "Observed BusRd" + (foreignState == "M" ? ": flush..." : "!")]});
if (foreignState == "M") {
simulation.requests[i].push({action: "update-ram", value: [address, foreignLine[elementAux].v] });
state.mem[address] = foreignLine[elementAux].v;
state.cores[j][cacheLine][elementAux].s = "S";
simulation.requests[i].push({action: "update-line", value: [j, cacheLine, lineToString(state.cores[j][cacheLine])] });
break;
} else if (foreignState == "E") {
state.cores[j][cacheLine][elementAux].s = "S";
simulation.requests[i].push({action: "update-line", value: [j, cacheLine, lineToString(state.cores[j][cacheLine])] });
break;
}
}
if (moved == true) {
simulation.requests[i].push({action: "focus", value: processor});
}
if (state.cores[processor][cacheLine].length >= definition.cacheBlocks) {
elementAux2 = state.cores[processor][cacheLine].shift();
if (elementAux2.s == "M") {
simulation.requests[i].push({action: "update-ram", value: [elementAux2.a, elementAux2.v] });
state.mem[elementAux2.a] = elementAux2.v;
}
}
state.cores[processor][cacheLine] = updateInLine(state.cores[processor][cacheLine], element, state.mem[address], address, shared ? "S" : "E", 0);
simulation.requests[i].push({action: "update-line", value: [processor, cacheLine, lineToString(state.cores[processor][cacheLine])] });
} else {
// current state is Exclusive, Shared or Modified
state.cores[processor][cacheLine] = updateInLine(state.cores[processor][cacheLine], element, state.cores[processor][cacheLine][element].v);
simulation.requests[i].push({action: "update-line", value: [processor, cacheLine, lineToString(state.cores[processor][cacheLine])] });
}
}
}
break;
default: // vi
for(i = 0; i < definition.coreRequests.length; i++) {
simulation.requests.push([ {action: "focus", value: definition.coreRequests[i][0]} ]);
element = findInLine(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines], definition.coreRequests[i][3]);
if(definition.coreRequests[i][1] == "write") {
simulation.requests[i].push({action: "notify", value: [definition.coreRequests[i][0], "PrWrite"]});
simulation.requests[i].push({action: "write-bus", value: "BusWrite (" + definition.coreRequests[i][0] + ")"});
moved = false;
for(j = 0; j < nCores; j++) {
if(j == definition.coreRequests[i][0]) {
continue;
}
elementAux = findInLine(state.cores[j][definition.coreRequests[i][3] % cacheLines], definition.coreRequests[i][3]);
if(elementAux < 0) {
continue;
}
moved = true;
simulation.requests[i].push({action: "focus", value: j});
simulation.requests[i].push({action: "notify", value: [j, "Observed BusWrite!"]});
state.cores[j][definition.coreRequests[i][3] % cacheLines] = invalidateInLine(state.cores[j][definition.coreRequests[i][3] % cacheLines], elementAux);
simulation.requests[i].push({action: "update-line", value: [j, definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[j][definition.coreRequests[i][3] % cacheLines])] });
}
if(moved == true) {
simulation.requests[i].push({action: "focus", value: definition.coreRequests[i][0]});
}
if(element >= 0) {
state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines] = updateInLine(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines], element, definition.coreRequests[i][2]);
simulation.requests[i].push({action: "update-line", value: [definition.coreRequests[i][0], definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines])] });
state.mem[definition.coreRequests[i][3]] = definition.coreRequests[i][2];
simulation.requests[i].push({action: "update-ram", value: [definition.coreRequests[i][3], definition.coreRequests[i][2]] });
} else {
if(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines].length >= definition.cacheBlocks) {
state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines].shift();
}
state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines] = updateInLine(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines], element, definition.coreRequests[i][2], definition.coreRequests[i][3], "V", 0);
simulation.requests[i].push({action: "update-line", value: [definition.coreRequests[i][0], definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines])] });
state.mem[definition.coreRequests[i][3]] = definition.coreRequests[i][2];
simulation.requests[i].push({action: "update-ram", value: [definition.coreRequests[i][3], definition.coreRequests[i][2]] });
}
} else { // read
simulation.requests[i].push({action: "notify", value: [definition.coreRequests[i][0], "PrRead"]});
simulation.requests[i].push({action: "write-bus", value: "BusRead (" + definition.coreRequests[i][0] + ")"});
if(element >= 0) {
state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines] = updateInLine(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines], element, state.cores[j][definition.coreRequests[i][3] % cacheLines][element].v);
simulation.requests[i].push({action: "update-line", value: [definition.coreRequests[i][0], definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines])] });
} else {
if(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines].length >= definition.cacheBlocks) {
state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines].shift();
}
state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines] = updateInLine(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines], element, state.mem[definition.coreRequests[i][3]], definition.coreRequests[i][3], "V", 0);
simulation.requests[i].push({action: "update-line", value: [definition.coreRequests[i][0], definition.coreRequests[i][3] % cacheLines, lineToString(state.cores[definition.coreRequests[i][0]][definition.coreRequests[i][3] % cacheLines])] });
}
}
}
}
for(i = 0; i < definition.coreRequests.length; i++) {
definition.coreRequests[i][3] = (definition.coreRequests[i][3] * 4).toString();
}
document.getElementById("simulation").style.display = "block";
return true;
}
function backToRequests() {
document.getElementById("simulation").style.display = "none";
$("#requestsDefinition").stop().fadeIn(1000);
}
function toggleSidebarFixed(fixed) {
var element;
element = document.getElementById("sidebar");
if(fixed == true) {
element.classList.add("fixed");
} else {
element.classList.remove("fixed");
}
}
function toggleSpeed(newSpeed, max) {
simulation.speed = parseInt(max, 10) - parseInt(newSpeed, 10) + 500;
}
function exportMachine() {
var element;
element = document.getElementById("downloadLink");
element.href = "data:text/plain;charset=utf-8," + encodeURIComponent(JSON.stringify(definition));
element.click();
}
function importMachine(file) {
var i, fStream, stringJSON, element, elements;
if(file.length != 1) {
return;
}
if(file[0].size > 1073741824) { // 50 MiB
alertDialog("O arquivo é muito comprido para ser processado! Tente algum menor que 1GiB.");
return;
}
fStream = new FileReader();
fStream.onload = function(e) {
stringJSON = e.target.result;
try {
stringJSON = JSON.parse(stringJSON);
} catch(exc) {
alertDialog("Não é um arquivo JSON válido! Use o botão 'Exportar' na simulação.");
return;
}
document.getElementById("memoryAlgorithm").value = stringJSON.memoryAlgorithm;
document.getElementById("memorySize").value = stringJSON.memInitValues.length;
document.getElementById("nCores").value = stringJSON.nCores;
document.getElementById("cacheLines").value = stringJSON.cacheLines;
document.getElementById("cacheBlocks").value = stringJSON.cacheBlocks;
document.getElementById("cacheAlgorithm").value = stringJSON.cacheAlgorithm;
if(submitHome() != true) {
alertDialog("Não é um arquivo JSON válido! Use o botão 'Exportar' na simulação.");
return;
}
elements = document.getElementById("memInitValues").getElementsByTagName("input");
for(i = 0; i < stringJSON.memInitValues.length; i++) {
elements[i].value = stringJSON.memInitValues[i];
}
if(submitMemory() != true) {
alertDialog("Não é um arquivo JSON válido! Use o botão 'Exportar' na simulação.");
return;
}
for(i = 0; i < stringJSON.coreRequests.length; i++) {
element = addRequestItem();
elements = element.getElementsByTagName("input");
elements[0].value = stringJSON.coreRequests[i][0];
elements[1].value = stringJSON.coreRequests[i][2];
elements[2].value = stringJSON.coreRequests[i][3];
element.getElementsByTagName("select")[0].value = stringJSON.coreRequests[i][1];
}
if(submitRequests() != true) {
alertDialog("Não é um arquivo JSON válido! Use o botão 'Exportar' na simulação.");
return;
}
document.getElementById("fileInput").value = "";
}
fStream.readAsText(file[0]);
}
function resetMachine() {
var elements;
if(simulation.running !== null) {
return;
}
elements = document.getElementById("coresCPU").getElementsByClassName("coreCache");
for(i = 0; i < elements.length; i++) {
elements2 = elements[i].getElementsByTagName("tbody")[0].childNodes;
for(j = 0; j < elements2.length; j++) {
elements2[j].childNodes[1].innerHTML = "";
}
}
elements = document.getElementById("mainMemoryWords").childNodes;
for(i = 0; i < simulation.initialState.length; i++) {
elements[i].childNodes[1].innerHTML = simulation.initialState[i];
}
elements = document.getElementById("requests").getElementsByClassName("request");
for(i = 0; i < elements.length; i++) {
elements[i].classList.remove("done");
}
simulation.currentPosition = -1;
}
/*function debug() {
document.getElementById("memoryAlgorithm").value = "msi";
document.getElementById("memorySize").value = "5";
document.getElementById("nCores").value = "40";
document.getElementById("cacheLines").value = "2";
document.getElementById("cacheBlocks").value = "1";
document.getElementById("cacheAlgorithm").value = "fifo";
submitHome();
autoFillMem(3);
submitMemory();
newElement = document.getElementById("coreRequests");
newElement.innerHTML = "<td><input value='9'></td><td><select><option value='read' selected='selected'>action</option></select><input value='512'></td><td><input value='0'></td><td></td>";
newElement.innerHTML += "<td><input value='20'></td><td><select><option value='write' selected='selected'>action</option></select><input value='512'></td><td><input value='4'></td><td></td>";
newElement.innerHTML += "<td><input value='27'></td><td><select><option value='read' selected='selected'>action</option></select><input value='512'></td><td><input value='4'></td><td></td>";
newElement.innerHTML += "<td><input value='9'></td><td><select><option value='write' selected='selected'>action</option></select><input value='1024'></td><td><input value='4'></td><td></td>";
newElement.innerHTML += "<td><input value='15'></td><td><select><option value='read' selected='selected'>action</option></select><input value='1024'></td><td><input value='4'></td><td></td>";
newElement.innerHTML += "<td><input value='10'></td><td><select><option value='read' selected='selected'>action</option></select><input value='512'></td><td><input value='0'></td><td></td>";
newElement.innerHTML += "<td><input value='10'></td><td><select><option value='read' selected='selected'>action</option></select><input value='512'></td><td><input value='4'></td><td></td>";
submitRequests();
}*/
/* Funções para Simulação */
function simFocus(at) {
var element, elements;
element = document.getElementById("coresCPU");
elements = element.getElementsByClassName("core");
$(element).stop().animate({scrollLeft: elements[at].offsetLeft - element.offsetWidth/2 + 125}, 500);
}
function simNotify(at, text) {
var element, elements;
element = document.getElementById("coresCPU").getElementsByClassName("core")[at].getElementsByClassName("notification")[0];
element.innerHTML = text;
element.style.display = "block";
$(element).stop();
element.style.opacity = 1;
$(element).fadeOut(simulation.speed, "easeInExpo");
}
function simWriteBus(text) {
var element, elements;
element = document.getElementById("memoryBus");
element.innerHTML = text;
if(text == "") {
element.classList.remove("animated");
} else {
element.classList.add("animated");
}
}
function simSetLine(at, line, text) {
var elements;
element = document.getElementsByClassName("coreCache")[at];
elements = element.getElementsByTagName("tbody")[0].childNodes[line].childNodes[1];
elements.innerHTML = text;
elements.style.backgroundColor = "rgba(255, 255, 0, 0.5)";
element.scrollTop = elements.offsetTop - 36;
$(elements).stop().animate({backgroundColor: "transparent"}, simulation.speed, "easeOutExpo");
}
function simSetMemory(at, value) {
var elements;
element = document.getElementById("mainMemoryWords");
elements = element.childNodes[at].childNodes[1];
elements.innerHTML = value;
elements.style.backgroundColor = "rgba(255, 255, 0, 0.5)";
document.getElementById("mainMemory").scrollTop = elements.offsetTop - 36;
$(elements).stop().animate({backgroundColor: "transparent"}, simulation.speed, "easeOutExpo");
}
function sim(req, n) {
var simType, element;
simulation.running = true;
if(n >= simulation.requests[req].length) {
simWriteBus("");
element = document.getElementById("requests").getElementsByClassName("request")[req];
element.classList.remove("running");
element.classList.add("done");
simulation.running = null;
return;
}
simType = simulation.requests[req][n];
switch(simType.action) {
case "focus":
simFocus(simType.value);
if(simulation.speed > 0) {
simulation.running = setTimeout(function() { sim(req, n + 1); }, 500);
} else {
sim(req, n + 1);
}
return;
break;
case "notify":
simNotify(simType.value[0], simType.value[1])
sim(req, n + 1);
return;
break;
case "write-bus":
simWriteBus(simType.value);
break;
case "update-line":
simSetLine(simType.value[0], simType.value[1], simType.value[2]);
break;
case "update-ram": // update-ram
simSetMemory(simType.value[0], simType.value[1]);
break;
default: // do-nothing
;
}
if(simulation.speed > 0) {
simulation.running = setTimeout(function() { sim(req, n + 1); }, simulation.speed);
} else {
sim(req, n + 1);
}
}
function simClick(request, element) {
var i, speed;
if(simulation.running !== null) {
return;
}
if(request <= simulation.currentPosition) {
return;
}
speed = simulation.speed;
simulation.speed = 0;
elements = document.getElementById("requests").getElementsByClassName("request");
if(simulation.currentPosition < 0) {
i = 0;
} else {
i = simulation.currentPosition;
}
for(; i < request; i++) {
elements[i].classList.add("done");
sim(i, 0);
}
simulation.speed = speed;
simulation.currentPosition = request;
elements[request].classList.add("running");
sim(request, 0);
}
function showWindow() {
$("#splashScreen").stop().fadeOut(1000);
$("#homeDefinition").stop().fadeIn(1000);
}
function windowLoad() {
var elements;
$("#scrollLeft").mouseenter(function(){
var element;
if(simulation.running === null) {
element = document.getElementById("coresCPU");
$(element).stop().animate({scrollLeft: 0}, element.scrollLeft*3, "linear");
}
}).mouseleave(function(){
if(simulation.running === null) {
$(document.getElementById("coresCPU")).stop();
}
});
$("#scrollRight").mouseenter(function(){
var element;
if(simulation.running === null) {
element = document.getElementById("coresCPU");
$(element).stop().animate({scrollLeft: element.scrollWidth}, (element.scrollWidth - element.scrollLeft)*3, "linear");
}
}).mouseleave(function(){
if(simulation.running === null) {
$(document.getElementById("coresCPU")).stop();
}
});
elements = document.getElementById("sidebar").getElementsByClassName("settings")[0].getElementsByTagName("input");
toggleSidebarFixed(elements[0].checked);
toggleSpeed(elements[1].value, elements[1].max)
setTimeout(showWindow, 1500);
console.log("Scripts iniciados com sucesso.");
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <stack>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
void dfs(int n, stack<int> &sortedVertex, vector<char> &markStatus, vector< vector<int> > &G) {
int i;
if(markStatus[n] == 2) {
return;
}
if(markStatus[n] == 1) {
return; // STOP NOT A DAG
}
markStatus[n] = 1;
for(i = 0; i < G[n].size(); i++) {
dfs(G[n][i], sortedVertex, markStatus, G);
}
markStatus[n] = 2;
sortedVertex.push(n);
}
void testCase(int N, int M) {
int i, m, n;
vector< vector<int> > G = vector< vector<int> >();
vector<char> markStatus = vector<char>();
stack<int> sortedVertex = stack<int>();
for(i = 0; i < N; i++) {
G.push_back( vector<int>() );
markStatus.push_back( 0 );
}
for(i = 0; i < M; i++) {
cin >> m >> n;
G[m - 1].push_back(n - 1);
}
for(i = 0; i < N; i++) {
if(markStatus[i] == 2) {
continue;
}
dfs(i, sortedVertex, markStatus, G);
}
while(sortedVertex.size() > 0) {
cout << sortedVertex.top() + 1 << ' ';
sortedVertex.pop();
}
cout << endl;
}
int main(int argc, char **argv) {
int N, M;
cin >> N >> M;
while(N > 0) {
testCase(N, M);
cin >> N >> M;
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <utility>
#include <vector>
using namespace std;
bool DFS(long V, long Colour, long *visited, vector< vector< pair<long, long> > > &G){
long i, N;
visited[V] = Colour;
N = G[V].size();
for(i = 0; i < N; i++){
if(visited[G[V][i].first] < 0 && !DFS(G[V][i].first, (Colour) ? 0:1, visited, G))
return false;
if(visited[G[V][i].first] == Colour)
return false;
}
return true;
}
int main(int argc, char **argv){
long i, N, K, A, B, *visited;
while(cin >> N){
if(N < 1)
break;
cin >> K;
vector< vector< pair<long, long> > > G(N);
visited = (long *) malloc(sizeof(long) * N);
memset(visited, -1, sizeof(long) * N);
for(i = 0; i < K; i++){
cin >> A >> B;
G[A].push_back(make_pair(B, 0));
G[B].push_back(make_pair(A, 0));
}
if(DFS(0, 0, visited, G))
cout << "BICOLORABLE.\n";
else
cout << "NOT BICOLORABLE.\n";
free(visited);
}
return EXIT_SUCCESS;
}<file_sep>
/*
* ~ Filas ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef QUEUE_H_
#define QUEUE_H_
#include <stdlib.h>
typedef struct __queue_t QUEUE;
typedef struct __priority_queue_t PRIORITY_QUEUE;
struct __queue_t *Q_New(size_t);
long Q_Size(struct __queue_t *);
int Q_Push(void *, struct __queue_t *);
int Q_Front(void *, struct __queue_t *);
int Q_Back(void *, struct __queue_t *);
int Q_Shift(void *, struct __queue_t *);
void Q_Destroy(struct __queue_t *);
struct __priority_queue_t *PQ_New(size_t, int (*)(void *, void *));
long PQ_Size(struct __priority_queue_t *);
int PQ_Push(void *, struct __priority_queue_t *);
int PQ_Front(void *, struct __priority_queue_t *);
int PQ_Back(void *, struct __priority_queue_t *);
int PQ_Shift(void *, struct __priority_queue_t *);
void PQ_Destroy(struct __priority_queue_t *);
#endif
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "consts.h"
#include "register2.h"
int R2_readH(REG2_HEADER *dest, FILE *stream) {
REG2_HEADER aux;
char reg[32];
int i, n;
if(fseek(stream, 0, SEEK_SET) != 0) {
return 0;
}
if(fread(reg, sizeof(char), 32, stream) != 32) {
return 0;
}
aux.status = reg[0];
memcpy(&aux.quantidadeSeguidores, ®[1], sizeof(int));
memcpy(dest, &aux, sizeof(REG2_HEADER));
return 1;
}
int R2_writeH(REG2_HEADER *src, FILE *stream) {
char reg[32];
int i, n;
memset(reg, LIXO, sizeof(char) * 32);
if(fseek(stream, 0, SEEK_SET) != 0) {
return 0;
}
memcpy(reg, &src->status, sizeof(char));
memcpy(®[1], &src->quantidadeSeguidores, sizeof(int));
if(fwrite(reg, sizeof(char), 32, stream) != 32) {
return 0;
}
return 1;
}
int R2_read(REG2_DATA *dest, FILE *stream) {
char reg[32], *R;
REG2_DATA aux;
long offset;
int i, n;
memset(reg, LIXO, sizeof(char) * 32);
aux.RRN = (ftell(stream) - 32) / 32;
if(aux.RRN < 0 || fread(reg, sizeof(char), 32, stream) != 32) {
return 0;
}
R = reg;
memcpy(&aux.removed, R, sizeof(char));
R += sizeof(char);
memcpy(&aux.idPessoaQueSegue, R, sizeof(int));
R += sizeof(int);
memcpy(&aux.idPessoaQueESeguida, R, sizeof(int));
R += sizeof(int);
memcpy(&aux.grauAmizade, R, sizeof(char) * 3);
R += sizeof(char) * 3;
memcpy(&aux.dataInicioQueSegue, R, sizeof(char) * 10);
R += sizeof(char) * 10;
memcpy(&aux.dataFimQueSegue, R, sizeof(char) * 10);
R += sizeof(char) * 10;
aux.dataInicioQueSegue[10] = '\0';
aux.dataFimQueSegue[10] = '\0';
memcpy(dest, &aux, sizeof(REG2_DATA));
return 1;
}
int R2_write(REG2_DATA *src, FILE *stream) {
char reg[32], *R;
REG2_DATA aux;
memset(reg, LIXO, sizeof(char) * 32);
src->removed = R_NAO_REMOVIDO;
src->RRN = (ftell(stream) - 32) / 32;
if(src->RRN < 0) {
return 0;
}
src->grauAmizade[1] = '\0';
src->grauAmizade[2] = LIXO;
R = reg;
memcpy(R, &src->removed, sizeof(char));
R += sizeof(char);
memcpy(R, &src->idPessoaQueSegue, sizeof(int));
R += sizeof(int);
memcpy(R, &src->idPessoaQueESeguida, sizeof(int));
R += sizeof(int);
memcpy(R, &src->grauAmizade, sizeof(char) * 3);
R += sizeof(char) * 3;
memcpy(R, &src->dataInicioQueSegue, sizeof(char) * 10);
R += sizeof(char) * 10;
memcpy(R, &src->dataFimQueSegue, sizeof(char) * 10);
R += sizeof(char) * 10;
if(fwrite(reg, sizeof(char), 32, stream) != 32) {
return 0;
}
return 1;
}
int R2_rewrite(REG2_DATA *src, FILE *stream) {
char reg[32], *R;
REG2_DATA aux;
memset(reg, LIXO, sizeof(char) * 32);
if(src->RRN < 0 || fseek(stream, 32 + 32 * src->RRN, SEEK_SET) != 0) {
return 0;
}
if(src->removed == R_REMOVIDO) {
reg[0] = R_REMOVIDO;
if(fwrite(reg, sizeof(char), 32, stream) != 32) {
return 0;
}
return 1;
}
src->grauAmizade[1] = '\0';
src->grauAmizade[2] = LIXO;
R = reg;
*R = R_NAO_REMOVIDO;
R += sizeof(char);
memcpy(R, &src->idPessoaQueSegue, sizeof(int));
R += sizeof(int);
memcpy(R, &src->idPessoaQueESeguida, sizeof(int));
R += sizeof(int);
memcpy(R, &src->grauAmizade, sizeof(char) * 3);
R += sizeof(char) * 3;
memcpy(R, &src->dataInicioQueSegue, sizeof(char) * 10);
R += sizeof(char) * 10;
memcpy(R, &src->dataFimQueSegue, sizeof(char) * 10);
R += sizeof(char) * 10;
if(fwrite(reg, sizeof(char), 32, stream) != 32) {
return 0;
}
return 1;
}
int R2_print(REG2_DATA *reg) {
if(reg->removed == R_REMOVIDO) {
return 0;
}
printf("Segue a pessoa de código: %d\n", reg->idPessoaQueESeguida);
printf("Justificativa para seguir: ");
switch(reg->grauAmizade[0]) {
case '0':
printf("segue porque é uma celebridade\n");
break;
case '1':
printf("segue porque é amiga de minha amiga\n");
break;
case '2':
printf("segue porque é minha amiga\n");
break;
default:
printf("-\n");
}
printf("Começou a seguir em: %s\n", reg->dataInicioQueSegue);
printf("Parou de seguir em: %s\n\n", reg->dataFimQueSegue);
return 1;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
Matheus
<EMAIL>
*/
int main(){
int a,b,c,calc;
float root1,root2;
scanf("%d %d %d",&a,&b,&c);
calc=(pow(b,2)-4*a*c);
if(calc>0){
root1=((-b)+sqrt(calc))/(2.0*a);
root2=((-b)-sqrt(calc))/(2.0*a);
if(root1>root2)
printf("%.3f %.3f",root2,root1);
else
printf("%.3f %.3f",root1,root2);
}else if(calc<0){
printf("NAO EXISTE RAIZ REAL");
}else{
root1=(-b)/(2.0*a);
printf("%.3f",root1);
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <super_file.h>
#include "stack.h"
/*
* ~ JSON ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
// GetTrue ontém de 'Fl' um tipo "true".
#define GetTrue(Str,St,Fl) { \
fscanf(Fl,"%4s",Str); \
if(strcmp(Str,"true")!=0){ \
S_Destroy(St); \
fclose(Fl); \
return 0; \
} \
}
// GetFalse obtém de 'Fl' um tipo "false".
#define GetFalse(Str,St,Fl) { \
fscanf(Fl,"%5s",Str); \
if(strcmp(Str,"false")!=0){ \
S_Destroy(St); \
fclose(Fl); \
return 0; \
} \
}
// GetNull obtém de 'Fl' um tipo "null".
#define GetNull(Str,St,Fl) { \
fscanf(Fl,"%4s",Str); \
if(strcmp(Str,"null")!=0){ \
S_Destroy(St); \
fclose(Fl); \
return 0; \
} \
}
// GetString obtém de 'Fl' uma string formatada de acordo com a especificação.
#define GetString(Ch,St,Fl) { \
if(getc(Fl)!='"'){ \
S_Destroy(St); \
fclose(Fl); \
return 0; \
} \
while( (Ch=getc(Fl))!=EOF && Ch!='"' ) { \
if(Ch=='\\' && ( (Ch=getc(Fl))=='"' || Ch=='b' || Ch=='f' || Ch=='n' || Ch=='r' || Ch=='t' || Ch=='u' || Ch=='\\' ) ){ \
S_Destroy(St); \
fclose(Fl); \
return 0; \
} \
} \
if(Ch==EOF || Ch=='\\'){ \
S_Destroy(St); \
fclose(Fl); \
return 0; \
} \
}
// GetNumber obtém de 'Fl' um número, seja ele real ou inteiro.
#define GetNumber(Ch,Aux,St,Fl) { \
if( (Ch=SF_PreviewChar(Fl))=='+' || Ch=='-') getc(FStream); \
Aux=0; \
while( (Ch=SF_PreviewChar(Fl))!=EOF && Ch>='0' && Ch<='9') { getc(Fl); Aux++; } \
if(Aux<1){ \
S_Destroy(St); \
fclose(Fl); \
return 0; \
} \
if(SF_PreviewChar(Fl)=='.'){ \
getc(Fl); \
Aux=0; \
while( (Ch=SF_PreviewChar(Fl))!=EOF && Ch>='0' && Ch<='9') { getc(Fl); Aux++; } \
if(Aux<1){ \
S_Destroy(St); \
fclose(Fl); \
return 0; \
} \
} \
if( (Ch=SF_PreviewChar(Fl))=='e' || Ch=='E' ){ \
getc(Fl); \
if( (Ch=SF_PreviewChar(Fl))=='+' || Ch=='-') getc(Fl); \
Aux=0; \
while( (Ch=SF_PreviewChar(Fl))!=EOF && Ch>='0' && Ch<='9') { getc(Fl); Aux++; } \
if(Aux<1){ \
S_Destroy(St); \
fclose(Fl); \
return 0; \
} \
} \
}
enum __json_set_types_t { Set_Comma=1, Set_Array, Set_Object }; // Representa os tipos possíveis de um empilhamento.
char JSON_Check(char *JSON_Expression,int *ObjectN,int *ArrayN,int *PairN,int *StringN,int *NumberN,int *TrueN,int *FalseN,int *NullN){
/*
* Esta função verifica se 'JSON_Expression' segue a gramática "G" dada por um "Value" de JSON.
* NOTA: EU NÃO USEI REGEX.
*
* Ela retorna 0 se 'JSON_Expression' não concorda com a gramática, 1 se concorda, e -1 em caso de erros na verificação.
*/
if(JSON_Expression==NULL) return -1;
STACK *Set=S_New();
FILE *FStream;
char R,S[10];
int T;
FStream=fmemopen(JSON_Expression,strlen(JSON_Expression),"r"); // Abrir stream a partir da string.
do { // Ler todos os 'Values' da string...
SF_ReadWhites(FStream); // Esta função é chamada frequentemente para ignorar espaçamentos entre os elementos.
R=SF_PreviewChar(FStream);
if(S_Size(Set)>1 && S_Get(Set)==Set_Comma){ // Esperando uma vírgula porque é um novo par para um "Array" ou "Object", ou desempilhamento.
S_Pop(Set);
if(R==','){
getc(FStream); // Consumir vírgula.
if(S_Get(Set)==Set_Object){
(*PairN)++;
SF_ReadWhites(FStream);
GetString(R,Set,FStream); // Ler a "key" do par.
(*StringN)++;
SF_ReadWhites(FStream);
if(getc(FStream)!=':'){ // Não é um par "key-value" válido.
S_Destroy(Set);
fclose(FStream);
return 0;
}
}
}else if(R=='}'){
(*PairN)++; // Fechamos um objeto. Incrementar o valor correspondente ao último par.
}else if(R!=']'){
S_Destroy(Set);
fclose(FStream);
return 0;
}
continue;
}else if(R=='{'){ // Só pode ser um "Object".
getc(FStream);
S_Push(Set_Object,Set); // Empilhar.
SF_ReadWhites(FStream);
if(SF_PreviewChar(FStream)=='}') continue; // Caso em que o "Object" não possui nada dentro.
GetString(R,Set,FStream); // Ler "key" do primeiro par.
(*StringN)++;
SF_ReadWhites(FStream);
if(getc(FStream)!=':'){ // Não é um par "key-value" válido.
S_Destroy(Set);
fclose(FStream);
return 0;
}
continue;
}else if(R=='}'){ // Só pode ser o fim de um "Object".
getc(FStream);
if(S_Size(Set)>0 && S_Get(Set)==Set_Object){
S_Pop(Set); // Desempilhar
}else{ // Esse "}" não é esperado aqui.
S_Destroy(Set);
fclose(FStream);
return 0;
}
(*ObjectN)++;
}else if(R=='['){ // Só pode ser um "Array".
getc(FStream);
S_Push(Set_Array,Set); // Empilhar.
continue;
}else if(R==']'){ // Só pode ser o fim de um "Array".
getc(FStream);
if(S_Size(Set)>0 && S_Get(Set)==Set_Array){
S_Pop(Set); // Desempilhar.
}else{ // Esse "]" não é esperado aqui.
S_Destroy(Set);
fclose(FStream);
return 0;
}
(*ArrayN)++;
}else if(R=='t'){ // Só pode ser "true".
GetTrue(S,Set,FStream);
if( (R=SF_PreviewChar(FStream))!=EOF && R!=' ' && R!=',' && R!=']' && R!='}' ){ // Verificar integridade do "true.
S_Destroy(Set);
fclose(FStream);
return 0;
}
(*TrueN)++;
}else if(R=='f'){ // Só pode ser "false".
GetFalse(S,Set,FStream);
if( (R=SF_PreviewChar(FStream))!=EOF && R!=' ' && R!=',' && R!=']' && R!='}' ){ // Verificar integridade do "false".
S_Destroy(Set);
fclose(FStream);
return 0;
}
(*FalseN)++;
}else if(R=='n'){ // Só pode ser "null".
GetNull(S,Set,FStream);
if( (R=SF_PreviewChar(FStream))!=EOF && R!=' ' && R!=',' && R!=']' && R!='}' ){ // Verificar integridade do "null".
S_Destroy(Set);
fclose(FStream);
return 0;
}
(*NullN)++;
}else if(R=='"'){ // Só poder ser uma "String".
GetString(R,Set,FStream);
if( (R=SF_PreviewChar(FStream))=='"' ){ // Verificar integridade da "String".
S_Destroy(Set);
fclose(FStream);
return 0;
}
(*StringN)++;
}else if(R=='+' || R=='-' || (R>='0' && R<='9')){ // Só pode ser um "Number".
GetNumber(R,T,Set,FStream);
if( (R=SF_PreviewChar(FStream))!=EOF && R!=' ' && R!=',' && R!=']' && R!='}' ){ // Verificar integridade do "Number".
S_Destroy(Set);
fclose(FStream);
return 0;
}
(*NumberN)++;
}else if(R==','){
getc(FStream); // Consumir vírgulas perdidas por aí. (Atenção: isso não é aceito oficialmente pela gramática do JSON, mas o PDF do trabalho permite).
continue;
}else{ // Algum caractere não identificado apareceu. Não é uma expressão válida.
S_Destroy(Set);
fclose(FStream);
return 0;
}
if(S_Size(Set)>0) S_Push(Set_Comma,Set); // Caso em que esperamos uma vírgula e um novo elemento.
} while( S_Size(Set)>0 );
S_Destroy(Set);
SF_ReadWhites(FStream);
if(getc(FStream)!=EOF){ // Há caracteres após o "Value" do JSON que não são válidos?
fclose(FStream); // Sim. Expressão inválida.
return 0;
}
fclose(FStream);
return 1; // Passou por todos os testes e é válido.
}
<file_sep># NYAN CAT GAME
O projeto do Quartus está na pasta [NyanCat\_Projeto\_Quartus](NyanCat_Projeto_Quartus).
O relatório completo está no *.PDF.
O jogo foi compilado e executado com sucesso na placa DE0-CV.
Está em total funcionamento.
Para executar, o clock correto deve estar selecionado.
Para isso, deixe todos os "switches" (SW) dele como "000...00101".
Ou seja, apenas o Switch 0 e 2, da direita para esquerda, devem estar ativados.
Integrantes:
* <NAME> (Nº 9326688)
* <NAME> (Nº 10369014)
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <processman.h>
/*
* ~ Gerenc. de Processos ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv){
PROC_LIST *Processes;
if(getchar()=='f'){
Processes=NewSession(proc_fifo);
}else{
fseek(stdin,-1,SEEK_CUR); // Voltar para escanear os números da forma correta.
Processes=NewSession(proc_round_robin);
}
IncludeProcessesFrom(stdin,Processes); // Ler processos considerando que tenham a mesma prioridade (FIFO).
RunProcesses(Processes); // Rodar como se fosse uma fila.
PrintResults(stdout,Processes);
DestroySession(Processes);
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <string.h>
/*
* ~ HashTable ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
struct __hashtable_element_t{
void *data;
unsigned long n;
struct __hashtable_element_t *next;
};
struct __hashtable_t {
struct __hashtable_element_t *table, *first;
size_t memsize;
unsigned long M;
void (*ffree)(void *);
};
struct __hashtable_t *New_HashTable(size_t memsize, void (*ffree)(void *), unsigned long M){
/*
* Esta função aloca uma HashTable na memória e retorna um ponteiro para tal.
*
* Ela retorna um ponteiro para a HashTable alocada, ou NULL em caso de erros.
*/
if(memsize<1 || M<1) return NULL;
struct __hashtable_t *Aux=(struct __hashtable_t *)malloc(sizeof(struct __hashtable_t));
Aux->table=(struct __hashtable_element_t *)calloc(M, sizeof(struct __hashtable_element_t));
Aux->first=NULL;
Aux->memsize=memsize;
Aux->M=M;
Aux->ffree=ffree;
return Aux;
}
unsigned long HashTable_Function(long Key, unsigned long M){
/*
* Função Hash.
*/
return abs(Key)%M;
}
int Insert_Into_HashTable(long Key, void *Data, struct __hashtable_t *HT){
/*
* Esta função insere um elemento 'Data' de chave 'Key' na HashTable 'HT'.
* A colisão é solucionada de modo "Chaining", utilizando um vetor dinâmico.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
if(HT==NULL) return 0;
unsigned long key_position;
struct __hashtable_element_t *Aux=HT->first, *LastAux=NULL;
key_position=HashTable_Function(Key, HT->M); // Achar posição da chave através da função hashing.
HT->table[key_position].data=(void *)realloc(HT->table[key_position].data, HT->memsize*(++HT->table[key_position].n));
memcpy(HT->table[key_position].data+(HT->table[key_position].n-1)*HT->memsize, Data, HT->memsize); // Copiar dados da chave.
if(HT->table[key_position].n > 1) return 1;
while(Aux!=NULL && Aux < (&HT->table[key_position])){
LastAux=Aux;
Aux=Aux->next;
}
if(LastAux==NULL) HT->first=&HT->table[key_position];
else LastAux->next=&HT->table[key_position];
HT->table[key_position].next=Aux;
return 1;
}
unsigned long Search_From_HashTable(long Key, void *Dest, struct __hashtable_t *HT){
/*
* Esta função verifica se existe na HashTable 'HT' um elemento de chave 'Key'.
*
* Ela retorna o número de elementos existentes com essa chave (colisão), ou 0 em caso de erros.
*/
if(Dest==NULL || HT==NULL) return 0;
unsigned long n, key_position;
key_position=HashTable_Function(Key, HT->M); // Achar posição da chave através da função hashing.
if( (n=HT->table[key_position].n) > 0){
memcpy(Dest, &HT->table[key_position].data, sizeof(void *));
}
return n;
}
int Traverse_HashTable(void (*fact)(void *), struct __hashtable_t *HT){
/*
* Esta função passa por todos os elementos da HashTable em que há algum tipo de elemento.
* É utilizado ponteiros para melhor performance.
*
* Ela retorna 1 em caso de sucesso, ou 0 em caso de erros.
*/
if(fact==NULL || HT==NULL) return 0;
struct __hashtable_element_t *Aux=HT->first;
while(Aux!=NULL){
fact(Aux->data);
Aux=Aux->next;
}
return 1;
}
void Destroy_HashTable(struct __hashtable_t *HT){
/*
* Esta função limpa da memória a HashTable 'HT' e todos os elementos dentro dela.
*
* Ela retorna nada.
*/
if(HT==NULL) return;
struct __hashtable_element_t *Aux=HT->first;
if(HT->ffree==NULL){
while(Aux!=NULL){
free(Aux->data);
Aux=Aux->next;
}
}else{
while(Aux!=NULL){
HT->ffree(Aux->data);
free(Aux->data);
Aux=Aux->next;
}
}
free(HT->table);
free(HT);
}
<file_sep># Objeto
Objeto obtido do website [free3d](https://free3d.com/3d-model/aquarium-skull-v1--509330.html): licença para uso pessoal.
<file_sep># SSC-0541 Sistemas Operacionais I - 2018.2
Aqui estão todos os trabalhos que implementei em Sistemas Operacionais.
<file_sep>#include <stdlib.h>
#include <limits.h>
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
typedef struct {
long pos;
long aux;
char type;
} ACTION;
enum { FUEL_CONSUMPTION, LEAK, GAS_STATION, MECHANIC, GOAL };
double solve(vector<ACTION> &actlist){
long normal_consumption, leaked_consumption, last_pos;
double min = LONG_MIN, current;
vector<ACTION>::iterator it = actlist.begin();
leaked_consumption = last_pos = 0;
normal_consumption = it->aux;
for(current = 0, it++; it != actlist.end(); it++){
current += (it->pos - last_pos) * ((normal_consumption/100.0) + leaked_consumption);
last_pos = it->pos;
switch(it->type){
case FUEL_CONSUMPTION:
normal_consumption = it->aux;
break;
case LEAK:
leaked_consumption++;
break;
case MECHANIC:
leaked_consumption = 0;
break;
case GAS_STATION:
if(current > min) min = current;
current = 0;
break;
default: ;
}
}
if(current > min) min = current;
return min;
}
int main(int argc, char **argv) {
string aux;
ACTION a;
do {
a.type = FUEL_CONSUMPTION;
cin >> a.pos;
cin >> aux >> aux;
cin >> a.aux;
if(a.aux < 1) continue;
vector<ACTION> v;
v.push_back(a);
do {
cin >> a.pos >> aux;
if(aux == "Leak"){
a.type = LEAK;
}else if(aux == "Fuel"){
a.type = FUEL_CONSUMPTION;
cin >> aux >> a.aux;
}else if(aux == "Gas"){
a.type = GAS_STATION;
cin >> aux;
}else if(aux == "Mechanic"){
a.type = MECHANIC;
}else{
a.type = GOAL;
}
v.push_back(a);
} while(a.type != GOAL);
printf("%.3lf\n", solve(v));
} while(a.aux > 0);
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/* POSIX */
#include <semaphore.h>
#include <pthread.h>
#include <sched.h>
/*
*
* == Simulador de uma CPU MIPS Multiciclo de 32 bits ==
*
* Organização de Computadores Digitais I (SSC-0112 2018.1)
* Professor <NAME>
* ICMC - Universidade de São Paulo
*
*
* OBS: O projeto foi desenvolvido utilizando POSIX Threads. Para compilar utilizando o GCC é necessário
* incluir "-pthread". É compatível também com a versão padrão do C. Foi desenvolvido e testado nos
* ambientes Linux Mint e Canonical Ubuntu, apresentando-se totalmente funcional.
*
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
/* == Definições de pré-compilação == */
#define MEM_SIZE 512 /* Tamanho da memória: 512 bytes */
#define RegDst0 0
#define RegDst1 1
#define RegWrite 2
#define ALUSrcA 3
#define ALUSrcB0 4
#define ALUSrcB1 5
#define ALUOp0 6
#define ALUOp1 7
#define PCSource0 8
#define PCSource1 9
#define PCWriteCond 10
#define PCWrite 11
#define IorD 12
#define MemRead 13
#define MemWrite 14
#define BNE 15
#define IRWrite 16
#define MemtoReg0 17
#define MemtoReg1 18
#define BIT_CONTROLE(bit) (1 << bit) /* Para obter o bit de determinado Sinal de Controle */
#define CONTROLE(bit) ((SinaisDeControle & BIT_CONTROLE(bit)) ? -1 : 0) /* Para obter o valor de determinado Sinal de Controle */
/* == Threads para os elementos lógicos do caminho de dados == */
pthread_t
pthread_ControlUnity,
pthread_PCRegister,
pthread_MemoryAddressMux,
pthread_Memory,
pthread_InstructionRegister,
pthread_MemoryDataRegister,
pthread_WriteRegisterMux,
pthread_WriteDataMux,
pthread_Registers,
pthread_SignExtend,
pthread_ShiftLeft,
pthread_ARegister,
pthread_BRegister,
pthread_ALUAMux,
pthread_ALUBMux,
pthread_ALUControl,
pthread_ShiftLeftConcatenate,
pthread_ALU,
pthread_ALUOutRegister,
pthread_PCMux,
pthread_BNEMux,
pthread_PortaAND,
pthread_PortaOR;
/* Semáfaros que determinaram a lógica dos elementos no caminho de dados */
sem_t
sem_ControlUnity,
sem_PCRegister,
sem_MemoryAddressMux,
sem_Memory,
sem_InstructionRegister,
sem_MemoryDataRegister,
sem_WriteRegisterMux,
sem_WriteDataMux,
sem_Registers,
sem_SignExtend,
sem_ShiftLeft,
sem_ARegister,
sem_BRegister,
sem_ALUAMux,
sem_ALUBMux,
sem_ALUControl,
sem_ShiftLeftConcatenate,
sem_ALU,
sem_ALUOutRegister,
sem_PCMux,
sem_BNEMux,
sem_PortaAND,
sem_PortaOR,
sem_SemafaroContador;
/* Registradores ao longo do caminho de dados */
int
PC,
IR,
MDR,
A,
B,
ALUOut,
/* Variáveis que armazenam o valor que será atribuído apenas no próximo ciclo: como se fossem os barramentos */
_PC,
_IR,
_MDR,
_A,
_B,
_ALUOut,
/* Barramentos que representam a saída de alguns Muxes, Extensor de Sinal, Shift Left ou Portas Lógicas */
_MemoryAddressMux,
_WriteRegisterMux,
_WriteDataMux,
_SignExtend,
_ShiftLeft,
_ALUAMux,
_ALUBMux,
_ALUControl,
_ShiftLeftConcatenate,
_ALUZero,
_BNEMux,
_PortaAND,
_PortaOR;
/* == Sinais de controle == */
unsigned int SinaisDeControle;
unsigned int _SinaisDeControle; /* Último ciclo válido (para impressão apenas) */
/* Indica para as Threads se elas podem rodar, ou se o programa será encerrado */
char Run;
/* Contador de Clock (extra) */
int ClockCounter;
/* Indica se houve algum erro na execução de um elemento lógico: ULA, instrução inválida, ... */
char ProgramError;
/* Banco de Registradores */
int RegistersArray[32];
/* Memória Principal, endereçada a byte (char) */
char MainMemory[MEM_SIZE];
/* == Definição de funções == */
void LiberarSemafaros();
void ImprimirTudoSair(int, int);
void *ControlUnity(void *);
void *PCRegister(void *);
void *MemoryAddressMux(void *);
void *Memory(void *);
void *InstructionRegister(void *);
void *MemoryDataRegister(void *);
void *WriteRegisterMux(void *);
void *WriteDataMux(void *);
void *Registers(void *);
void *SignExtend(void *);
void *ShiftLeft(void *);
void *ARegister(void *);
void *BRegister(void *);
void *ALUAMux(void *);
void *ALUBMux(void *);
void *ALUControl(void *);
void *ShiftLeftConcatenate(void *);
void *ALU(void *);
void *ALUOutRegister(void *);
void *PCMux(void *);
void *BNEMux(void *);
void *PortaAND(void *);
void *PortaOR(void *);
/* == MAIN == */
int main(int argc, char **argv) {
FILE *BinaryFile;
int PCEnd;
PCEnd = ClockCounter = ProgramError = 0;
/* Boas vindas */
printf("Bem-vind@ ao nosso programa.\n");
printf("Grupo:\n");
printf("\t<NAME> (Nº 10295332)\n");
printf("\t<NAME> (Nº 10295711)\n");
printf("\t<NAME> (Nº 10369014)\n");
printf("\t<NAME> (Nº 10295346)\n\n");
if(argc != 2) { /* Erro: não passou o binário "code.bin" */
printf("Você passou os argumentos do programa de forma incorreta.\n");
printf("É necessário passar o binário (\"code.bin\") para ser executado:\n\t%s [BINARIO]\n\n", argv[0]);
return EXIT_FAILURE;
}
/* Iniciar todos os registradores, "barramentos", sinais de controle e memória com zero */
memset(&PC, 0, sizeof(int));
memset(&IR, 0, sizeof(int));
memset(&MDR, 0, sizeof(int));
memset(&A, 0, sizeof(int));
memset(&B, 0, sizeof(int));
memset(&ALUOut, 0, sizeof(int));
memset(&_PC, 0, sizeof(int));
memset(&_IR, 0, sizeof(int));
memset(&_MDR, 0, sizeof(int));
memset(&_A, 0, sizeof(int));
memset(&_B, 0, sizeof(int));
memset(&_ALUOut, 0, sizeof(int));
memset(&_MemoryAddressMux, 0, sizeof(int));
memset(&_WriteRegisterMux, 0, sizeof(int));
memset(&_WriteDataMux, 0, sizeof(int));
memset(&_SignExtend, 0, sizeof(int));
memset(&_ShiftLeft, 0, sizeof(int));
memset(&_ALUAMux, 0, sizeof(int));
memset(&_ALUBMux, 0, sizeof(int));
memset(&_ALUControl, 0, sizeof(int));
memset(&_ShiftLeftConcatenate, 0, sizeof(int));
memset(&_ALUZero, 0, sizeof(int));
memset(&_BNEMux, 0, sizeof(int));
memset(&_PortaAND, 0, sizeof(int));
memset(&_PortaOR, 0, sizeof(int));
memset(&SinaisDeControle, 0, sizeof(int));
memset(&RegistersArray, 0, sizeof(int) * 32);
memset(&MainMemory, 0, sizeof(char) * MEM_SIZE);
/* Abrir arquivo de entrada para ler programa */
BinaryFile = fopen(argv[1], "r");
if(!BinaryFile) {
printf("Não foi possível abrir o arquivo binário \"%s\".\n", argv[1]);
printf("Verifique se este realmente existe e se o programa tem permissão para ler tal.\n\n");
return EXIT_FAILURE;
}
printf("Lendo binário e colocando na memória...\n");
/* Ler arquivo de entrada (programa) e colocar na memória */
while(fscanf(BinaryFile, "%u", (unsigned int *) &MainMemory[PCEnd]) != EOF) {
PCEnd += sizeof(int);
}
fclose(BinaryFile);
printf("Leitura completa. Executando binário...\n");
/* Inicializar todos os semáfaros */
sem_init(&sem_ControlUnity, 0, 0);
sem_init(&sem_PCRegister, 0, 0);
sem_init(&sem_MemoryAddressMux, 0, 0);
sem_init(&sem_Memory, 0, 0);
sem_init(&sem_InstructionRegister, 0, 0);
sem_init(&sem_MemoryDataRegister, 0, 0);
sem_init(&sem_WriteRegisterMux, 0, 0);
sem_init(&sem_WriteDataMux, 0, 0);
sem_init(&sem_Registers, 0, 0);
sem_init(&sem_SignExtend, 0, 0);
sem_init(&sem_ShiftLeft, 0, 0);
sem_init(&sem_ARegister, 0, 0);
sem_init(&sem_BRegister, 0, 0);
sem_init(&sem_ALUAMux, 0, 0);
sem_init(&sem_ALUBMux, 0, 0);
sem_init(&sem_ALUControl, 0, 0);
sem_init(&sem_ShiftLeftConcatenate, 0, 0);
sem_init(&sem_ALU, 0, 0);
sem_init(&sem_ALUOutRegister, 0, 0);
sem_init(&sem_PCMux, 0, 0);
sem_init(&sem_BNEMux, 0, 0);
sem_init(&sem_PortaAND, 0, 0);
sem_init(&sem_PortaOR, 0, 0);
/* Criar Threads */
pthread_create(&pthread_ControlUnity, NULL, ControlUnity, NULL);
pthread_create(&pthread_PCRegister, NULL, PCRegister, NULL);
pthread_create(&pthread_MemoryAddressMux, NULL, MemoryAddressMux, NULL);
pthread_create(&pthread_Memory, NULL, Memory, NULL);
pthread_create(&pthread_InstructionRegister, NULL, InstructionRegister, NULL);
pthread_create(&pthread_MemoryDataRegister, NULL, MemoryDataRegister, NULL);
pthread_create(&pthread_WriteRegisterMux, NULL, WriteRegisterMux, NULL);
pthread_create(&pthread_WriteDataMux, NULL, WriteDataMux, NULL);
pthread_create(&pthread_Registers, NULL, Registers, NULL);
pthread_create(&pthread_SignExtend, NULL, SignExtend, NULL);
pthread_create(&pthread_ShiftLeft, NULL, ShiftLeft, NULL);
pthread_create(&pthread_ARegister, NULL, ARegister, NULL);
pthread_create(&pthread_BRegister, NULL, BRegister, NULL);
pthread_create(&pthread_ALUAMux, NULL, ALUAMux, NULL);
pthread_create(&pthread_ALUBMux, NULL, ALUBMux, NULL);
pthread_create(&pthread_ALUControl, NULL, ALUControl, NULL);
pthread_create(&pthread_ShiftLeftConcatenate, NULL, ShiftLeftConcatenate, NULL);
pthread_create(&pthread_ALU, NULL, ALU, NULL);
pthread_create(&pthread_ALUOutRegister, NULL, ALUOutRegister, NULL);
pthread_create(&pthread_PCMux, NULL, PCMux, NULL);
pthread_create(&pthread_BNEMux, NULL, BNEMux, NULL);
pthread_create(&pthread_PortaAND, NULL, PortaAND, NULL);
pthread_create(&pthread_PortaOR, NULL, PortaOR, NULL);
Run = 1;
while(PC < PCEnd) { /* Enquanto o programa não tiver finalizado */
LiberarSemafaros();
ClockCounter++;
}
ImprimirTudoSair(0, 0); /* O programa terminou e nenhum erro foi encontrado */
return EXIT_SUCCESS;
}
/* == Funções == */
void LiberarSemafaros() {
/*
* O trabalho foi implementado utilizando threads e de forma paralela.
* Contudo, no caminho de dados nem tudo é "executado" desta maneira.
* Para isso, criamos esta função, que controla o que precisa ser
* executado antes do que.
*
* Por exemplo: A ULA faz o resultado de uma operação baseando-se em
* um sinal que indique qual a operação, e sob quais valores ela
* vai operar. Sendo assim, ela PRECISA que os dois Muxes e a
* Unidade de Controle sejam executados primeiro, para que
* possa colocar o resultado da operação de forma correta.
* Esta função sabe disso, e só vai executar a ULA quando seus sinais
* e Muxes estiverem prontos.
*
* Ela faz isso usando um Semáfaro Contador e a função do POSIX "sched_yield".
* Com "sched_yield", podemos mandar nossa thread principal para o fim da fila
* de prioridade de processos do sistema operacional até que todas as outras
* threads que precisamos tenham sido executadas.
*/
int Aux;
/*
* Primeiramente, os Registradores são processados, pois estes não têm dependência
* linear de sinais ou bits de outros elementos no caminho de dados.
* São os primeiros elementos executados, no exato momento da subida do clock.
*/
sem_init(&sem_SemafaroContador, 0, 7);
sem_post(&sem_PCRegister);
sem_post(&sem_InstructionRegister);
sem_post(&sem_MemoryDataRegister);
sem_post(&sem_Registers); /* Banco de registradores: fazer possível escrita */
sem_post(&sem_ARegister);
sem_post(&sem_BRegister);
sem_post(&sem_ALUOutRegister);
do {
sched_yield();
sem_getvalue(&sem_SemafaroContador, &Aux);
} while(Aux); /* Aguarda todos acima serem executados */
sem_destroy(&sem_SemafaroContador);
/* Erro: acesso inválido ao banco de registradores */
if(ProgramError) {
ImprimirTudoSair(4, _WriteRegisterMux);
}
/*
* Agora vamos executar a Unidade de Controle, a Extensão de Sinal e o Shift Left Concatenado com PC.
* Isso porque estes dois últimos dependem de IR, que já foi executado.
*/
sem_init(&sem_SemafaroContador, 0, 3);
sem_post(&sem_ControlUnity);
sem_post(&sem_SignExtend);
sem_post(&sem_ShiftLeftConcatenate);
do {
sched_yield();
sem_getvalue(&sem_SemafaroContador, &Aux);
} while(Aux); /* Aguarda execução dos acima */
sem_destroy(&sem_SemafaroContador);
/* Erro: instrução inválida */
if(ProgramError) {
ImprimirTudoSair(1, IR >> 26);
}
/*
* Agora que a Unidade de Controle foi executada, tudo o que depende de seus sinais pode ser executado.
* Isso inclue alguns Muxes e a Unidade de Controle secundária.
*
* Além disso, podemos executar o Shift Left do endereço relativo, visto que já foi feita a Extensão de Sinal.
*/
sem_init(&sem_SemafaroContador, 0, 6);
sem_post(&sem_MemoryAddressMux);
sem_post(&sem_WriteRegisterMux);
sem_post(&sem_WriteDataMux);
sem_post(&sem_ShiftLeft);
sem_post(&sem_ALUAMux);
sem_post(&sem_ALUControl);
do {
sched_yield();
sem_getvalue(&sem_SemafaroContador, &Aux);
} while(Aux); /* Aguarda execução dos acima */
sem_destroy(&sem_SemafaroContador);
/*
* Agora podemos ler da Memória, porque o Mux já selecionou o endereço correto, podemos ler
* do banco de Registradores, e podemos executar o Mux da segunda entrada da ULA.
*/
sem_init(&sem_SemafaroContador, 0, 3);
sem_post(&sem_Memory);
sem_post(&sem_Registers);
sem_post(&sem_ALUBMux);
do {
sched_yield();
sem_getvalue(&sem_SemafaroContador, &Aux);
} while(Aux); /* Aguarda execução dos acima */
sem_destroy(&sem_SemafaroContador);
/* Erro: acesso a endereço inválido na memória */
if(ProgramError) {
ImprimirTudoSair(2, _MemoryAddressMux);
}
/* Agora sim a ULA tem todo o necessário para funcionar (não depende de mais nada no caminho de dados) */
sem_init(&sem_SemafaroContador, 0, 1);
sem_post(&sem_ALU);
do {
sched_yield();
sem_getvalue(&sem_SemafaroContador, &Aux);
} while(Aux); /* Espera a ULA */
sem_destroy(&sem_SemafaroContador);
/* Erro: operação inválida no campo de função para ULA */
if(ProgramError) {
ImprimirTudoSair(3, _ALUControl);
}
/*
* Agora que a ULA executou, podemos executar o Mux que escolhe o que vai escrever no PC e o Mux BNE.
*/
sem_init(&sem_SemafaroContador, 0, 2);
sem_post(&sem_PCMux);
sem_post(&sem_BNEMux);
do {
sched_yield();
sem_getvalue(&sem_SemafaroContador, &Aux);
} while(Aux); /* Espera esses Muxes */
/*
* Agora que o Mux do BNE foi executado, podemos fazer a porta AND.
*/
sem_post(&sem_SemafaroContador);
sem_post(&sem_PortaAND);
do {
sched_yield();
sem_getvalue(&sem_SemafaroContador, &Aux);
} while(Aux); /* Espera a AND */
/*
* Por fim, a porta OR é executada.
*/
sem_post(&sem_SemafaroContador);
sem_post(&sem_PortaOR);
do {
sched_yield();
sem_getvalue(&sem_SemafaroContador, &Aux);
} while(Aux); /* Espera a OR */
sem_destroy(&sem_SemafaroContador);
_SinaisDeControle = SinaisDeControle; /* Executou sem erros: ciclo válido */
}
void ImprimirTudoSair(int Status, int Details) {
/*
* Esta função imprime todos os registradores e as primeiras 32 posições (palavras) da memória principal.
* Após, ela solicita que todas as Threads sejam encerradas e encerra o programa.
*
* EXTRA: Nos terminais compatíveis (geralmente UNIX), vai imprimir colorido!
*/
char Binary[50];
int i;
printf("\n\n\x1b[1m\x1b[40m\x1b[33m== Programa finalizado no clock %d ==\x1b[0m\n", ClockCounter);
printf("\x1b[5mStatus da Saída:\x1b[0m ");
switch(Status) { /* Imprimir o tipo de código de erro (ou sucesso, no caso deste) e detalhes, se houverem */
case 0:
printf("(0) programa encerrado com sucesso.\n");
break;
case 1:
printf("(1) término devido a tentativa de execução de instrução inválida com campo de operação de valor [%d].\n", Details);
break;
case 2:
printf("(2) término devido a acesso inválido de memória no endereço [0x%x].\n", Details);
break;
case 3:
printf("(3) término devido a operação inválida na unidade lógica e aritmética com campo de função de valor [%d].\n", Details);
break;
case 4:
printf("(4) término devido a acesso inválido ao banco de registradores no índice [%d].\n", Details);
break;
default:
printf("(-1) erro indeterminado forçou término.\n");
}
/* Imprimir registradores */
printf("\nPC = %-10u\tIR = %-10u\t MDR = %-10u\n", PC, IR, MDR);
printf(" A = %-10u\t B = %-10u\tALUOut = %-10u\n", A, B, ALUOut);
/* Sinais de controle (bits), na ordem do mais significativo para o menos (de acordo com a especificação *.PDF) */
SinaisDeControle = _SinaisDeControle;
for(i = RegDst0; i <= MemtoReg1; i++)
Binary[MemtoReg1 - i] = (CONTROLE(i)) ? '1' : '0';
Binary[i] = '\0';
printf("Controle (bits) = %s (%u em decimal)\n", Binary, SinaisDeControle);
/* Banco de registradores */
printf("\n\x1b[1mBanco de Registradores:\x1b[0m\n");
printf("R00(r0) = %-11d\tR08(t0) = %-11d\tR16(s0) = %-11d\tR24(t8) = %-11d\n", RegistersArray[0], RegistersArray[8], RegistersArray[16], RegistersArray[24]);
printf("R01(at) = %-11d\tR09(t1) = %-11d\tR17(s1) = %-11d\tR25(t9) = %-11d\n", RegistersArray[1], RegistersArray[9], RegistersArray[17], RegistersArray[25]);
printf("R02(v0) = %-11d\tR10(t2) = %-11d\tR18(s2) = %-11d\tR26(k0) = %-11d\n", RegistersArray[2], RegistersArray[10], RegistersArray[18], RegistersArray[26]);
printf("R03(v1) = %-11d\tR11(t3) = %-11d\tR19(s3) = %-11d\tR27(k1) = %-11d\n", RegistersArray[3], RegistersArray[11], RegistersArray[19], RegistersArray[27]);
printf("R04(a0) = %-11d\tR12(t4) = %-11d\tR20(s4) = %-11d\tR28(gp) = %-11d\n", RegistersArray[4], RegistersArray[12], RegistersArray[20], RegistersArray[28]);
printf("R05(a1) = %-11d\tR13(t5) = %-11d\tR21(s5) = %-11d\tR29(sp) = %-11d\n", RegistersArray[5], RegistersArray[13], RegistersArray[21], RegistersArray[29]);
printf("R06(a2) = %-11d\tR14(t6) = %-11d\tR22(s6) = %-11d\tR30(fp) = %-11d\n", RegistersArray[6], RegistersArray[14], RegistersArray[22], RegistersArray[30]);
printf("R07(a3) = %-11d\tR15(t7) = %-11d\tR23(s7) = %-11d\tR31(ra) = %-11d\n", RegistersArray[7], RegistersArray[15], RegistersArray[23], RegistersArray[31]);
/* Memória primária principal */
printf("\n\x1b[1mMemória (endereçada a byte):\x1b[0m\n");
for(i = 0; i <= 28; i += 4) {
printf("[%03d] = %-10u\t[%03d] = %-10u\t", i, *((unsigned int *) &MainMemory[i]), i + 32, *((unsigned int *) &MainMemory[i + 32]));
printf("[%03d] = %-10u\t[%03d] = %-10u\n", i + 64, *((unsigned int *) &MainMemory[i + 64]), i + 96, *((unsigned int *) &MainMemory[i + 96]));
}
printf("\n");
/* Terminar todas as threads dos elementos lógicos no caminho de dados */
Run = 0;
sem_post(&sem_PCRegister);
sem_post(&sem_InstructionRegister);
sem_post(&sem_MemoryDataRegister);
sem_post(&sem_Registers);
sem_post(&sem_ARegister);
sem_post(&sem_BRegister);
sem_post(&sem_ALUOutRegister);
sem_post(&sem_ControlUnity);
sem_post(&sem_SignExtend);
sem_post(&sem_ShiftLeftConcatenate);
sem_post(&sem_MemoryAddressMux);
sem_post(&sem_WriteRegisterMux);
sem_post(&sem_WriteDataMux);
sem_post(&sem_ShiftLeft);
sem_post(&sem_ALUAMux);
sem_post(&sem_ALUControl);
sem_post(&sem_Memory);
sem_post(&sem_ALUBMux);
sem_post(&sem_ALU);
sem_post(&sem_PCMux);
sem_post(&sem_BNEMux);
sem_post(&sem_PortaAND);
sem_post(&sem_PortaOR);
pthread_join(pthread_ControlUnity, NULL);
pthread_join(pthread_PCRegister, NULL);
pthread_join(pthread_MemoryAddressMux, NULL);
pthread_join(pthread_Memory, NULL);
pthread_join(pthread_InstructionRegister, NULL);
pthread_join(pthread_MemoryDataRegister, NULL);
pthread_join(pthread_WriteRegisterMux, NULL);
pthread_join(pthread_WriteDataMux, NULL);
pthread_join(pthread_Registers, NULL);
pthread_join(pthread_SignExtend, NULL);
pthread_join(pthread_ShiftLeft, NULL);
pthread_join(pthread_ARegister, NULL);
pthread_join(pthread_BRegister, NULL);
pthread_join(pthread_ALUAMux, NULL);
pthread_join(pthread_ALUBMux, NULL);
pthread_join(pthread_ALUControl, NULL);
pthread_join(pthread_ShiftLeftConcatenate, NULL);
pthread_join(pthread_ALU, NULL);
pthread_join(pthread_ALUOutRegister, NULL);
pthread_join(pthread_PCMux, NULL);
pthread_join(pthread_BNEMux, NULL);
pthread_join(pthread_PortaAND, NULL);
pthread_join(pthread_PortaOR, NULL);
/* Destruir semáfaros da memória (free) */
sem_destroy(&sem_ControlUnity);
sem_destroy(&sem_PCRegister);
sem_destroy(&sem_MemoryAddressMux);
sem_destroy(&sem_Memory);
sem_destroy(&sem_InstructionRegister);
sem_destroy(&sem_MemoryDataRegister);
sem_destroy(&sem_WriteRegisterMux);
sem_destroy(&sem_WriteDataMux);
sem_destroy(&sem_Registers);
sem_destroy(&sem_SignExtend);
sem_destroy(&sem_ShiftLeft);
sem_destroy(&sem_ARegister);
sem_destroy(&sem_BRegister);
sem_destroy(&sem_ALUAMux);
sem_destroy(&sem_ALUBMux);
sem_destroy(&sem_ALUControl);
sem_destroy(&sem_ShiftLeftConcatenate);
sem_destroy(&sem_ALU);
sem_destroy(&sem_ALUOutRegister);
sem_destroy(&sem_PCMux);
sem_destroy(&sem_BNEMux);
sem_destroy(&sem_PortaAND);
sem_destroy(&sem_PortaOR);
/* Sair com código de erro ou sucesso */
exit((Status == 0) ? EXIT_SUCCESS : EXIT_FAILURE);
}
/* == Agora começam as implementações de cada elemento lógico no caminho de dados == */
void *ControlUnity(void *args) {
/*
* A Unidade de Controle foi implementada através de uma tabela verdade bit a bit.
*/
char CurrentState; /* Representa o estado atual. Apenas os 5 primeiros bits são necessários. */
char _CurrentState; /* Representa o estado no próximo ciclo de clock. Apenas os 5 primeiros bits são necessários. */
#define ESTADO(bit) ((CurrentState & (1 << bit)) ? -1 : 0) /* Para obter o valor de um bit do estado atual */
#define OP(bit) (((IR >> 26) & (1 << bit)) ? -1 : 0) /* Para obter o valor de um bit do campo de operação de IR */
CurrentState = _CurrentState = 0;
while(1) {
sem_wait(&sem_ControlUnity);
if(!Run) { /* Finalizar thread */
return NULL;
}
CurrentState = _CurrentState;
SinaisDeControle = 0;
_CurrentState = 0;
/* A partir de agora começa a tabela verdade que fizemos para cada bit que a Unidade de Controle gerencia */
SinaisDeControle |= BIT_CONTROLE(RegDst0) & (ESTADO(0) & ESTADO(1) & ESTADO(2) & ~ESTADO(3) & ~ESTADO(4));
SinaisDeControle |= BIT_CONTROLE(RegDst1) & (ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4));
SinaisDeControle |= BIT_CONTROLE(RegWrite) & ((~ESTADO(0) & ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ESTADO(1) & ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)));
SinaisDeControle |= BIT_CONTROLE(ALUSrcA) & ((ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ESTADO(1) & ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)));
SinaisDeControle |= BIT_CONTROLE(ALUSrcB0) & ((ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)));
SinaisDeControle |= BIT_CONTROLE(ALUSrcB1) & ((ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ESTADO(4)));
SinaisDeControle |= BIT_CONTROLE(ALUOp0) & ((ESTADO(0) & ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)));
SinaisDeControle |= BIT_CONTROLE(ALUOp1) & ((ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ESTADO(1) & ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)));
SinaisDeControle |= BIT_CONTROLE(PCSource0) & ((ESTADO(0) & ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)));
SinaisDeControle |= BIT_CONTROLE(PCSource1) & ((ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)));
SinaisDeControle |= BIT_CONTROLE(PCWriteCond) & ((ESTADO(0) & ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)));
SinaisDeControle |= BIT_CONTROLE(PCWrite) & ((~ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)));
SinaisDeControle |= BIT_CONTROLE(IorD) & ((ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)));
SinaisDeControle |= BIT_CONTROLE(MemRead) & ((~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)));
SinaisDeControle |= BIT_CONTROLE(MemWrite) & (ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ~ESTADO(3) & ~ESTADO(4));
SinaisDeControle |= BIT_CONTROLE(BNE) & (ESTADO(0) & ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4));
SinaisDeControle |= BIT_CONTROLE(IRWrite) & (~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4));
SinaisDeControle |= BIT_CONTROLE(MemtoReg0) & (~ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ~ESTADO(3) & ~ESTADO(4));
SinaisDeControle |= BIT_CONTROLE(MemtoReg1) & ((~ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ESTADO(3) & ~ESTADO(4)));
/* Função Próximo Estado */
_CurrentState |= BIT_CONTROLE(0) & ((~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ESTADO(1) & ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & ~OP(0) & OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & ~OP(0) & ~OP(1) & OP(2) & OP(3) & ~OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & ~OP(1) & OP(2) & ~OP(3) & ~OP(4) & ~OP(5)));
_CurrentState |= BIT_CONTROLE(1) & ((~ESTADO(0) & ESTADO(1) & ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ESTADO(4)) |
(ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & OP(1) & ~OP(2) & OP(3) & ~OP(4) & OP(5)) |
(~ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & ~OP(0) & ~OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & ~OP(0) & ~OP(1) & OP(2) & ~OP(3) & OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & ~OP(1) & OP(2) & ~OP(3) & ~OP(4) & ~OP(5)));
_CurrentState |= BIT_CONTROLE(2) & ((ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ESTADO(1) & ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ESTADO(4)) |
(~ESTADO(0) & ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & OP(1) & ~OP(2) & OP(3) & ~OP(4) & OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & ~OP(0) & ~OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & ~OP(1) & OP(2) & ~OP(3) & OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & ~OP(0) & ~OP(1) & OP(2) & OP(3) & ~OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & ~OP(1) & OP(2) & ~OP(3) & ~OP(4) & ~OP(5)));
_CurrentState |= BIT_CONTROLE(3) & ((~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ESTADO(4)) |
(ESTADO(0) & ~ESTADO(1) & ESTADO(2) & ESTADO(3) & ~ESTADO(4)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & ~OP(0) & ~OP(1) & OP(2) & ~OP(3) & ~OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & ~OP(0) & OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & ~OP(0) & ~OP(1) & OP(2) & ~OP(3) & OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & ~OP(1) & OP(2) & ~OP(3) & OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & ~OP(0) & ~OP(1) & OP(2) & OP(3) & ~OP(4) & ~OP(5)) |
(ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & OP(0) & ~OP(1) & OP(2) & ~OP(3) & ~OP(4) & ~OP(5)));
_CurrentState |= BIT_CONTROLE(4) & (ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4) & ~OP(0) & ~OP(1) & ~OP(2) & OP(3) & ~OP(4) & ~OP(5));
/* Sinal que indica se é uma instrução válida ou não, para encerrar o programa se for inválida */
ProgramError = (~ESTADO(0) & ~ESTADO(1) & ~ESTADO(2) & ~ESTADO(3) & ~ESTADO(4)) | (OP(0) & OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & OP(5)) |
(OP(0) & OP(1) & ~OP(2) & OP(3) & ~OP(4) & OP(5)) |
(~OP(0) & ~OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & ~OP(5)) |
(~OP(0) & ~OP(1) & OP(2) & ~OP(3) & ~OP(4) & ~OP(5)) |
(~OP(0) & OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & ~OP(5)) |
(~OP(0) & ~OP(1) & OP(2) & ~OP(3) & OP(4) & ~OP(5)) |
(OP(0) & OP(1) & ~OP(2) & ~OP(3) & ~OP(4) & ~OP(5)) |
(OP(0) & ~OP(1) & OP(2) & ~OP(3) & OP(4) & ~OP(5)) |
(~OP(0) & ~OP(1) & OP(2) & OP(3) & ~OP(4) & ~OP(5)) |
(~OP(0) & ~OP(1) & ~OP(2) & OP(3) & ~OP(4) & ~OP(5)) |
(OP(0) & ~OP(1) & OP(2) & ~OP(3) & ~OP(4) & ~OP(5));
ProgramError = ~ProgramError;
sem_trywait(&sem_SemafaroContador);
}
}
void *PCRegister(void *args) {
/*
* PC: atualiza valor na subida do ciclo de clock.
*/
while(1) {
sem_wait(&sem_PCRegister);
if(!Run) { /* Finalizar thread */
return NULL;
}
if(_PortaOR) {
PC = _PC; /* Escreve se a Porta OR for verdadeira */
}
sem_trywait(&sem_SemafaroContador);
}
}
void *MemoryAddressMux(void *args) {
/*
* Esse é o Mux que fica entre o PC e a Memória Principal, que seleciona o endereço que
* será acessado para leitura ou escrita na memória.
*/
while(1) {
sem_wait(&sem_MemoryAddressMux);
if(!Run) { /* Finalizar thread */
return NULL;
}
if(CONTROLE(IorD)) {
_MemoryAddressMux = ALUOut; /* 1 */
} else {
_MemoryAddressMux = PC; /* 0 */
}
sem_trywait(&sem_SemafaroContador);
}
}
void *Memory(void *args) {
/*
* Esse é o componente que acessa a memória fazendo leituras e escritas.
*/
while(1) {
sem_wait(&sem_Memory);
if(!Run) { /* Finalizar thread */
return NULL;
}
if((CONTROLE(MemWrite) || CONTROLE(MemRead)) && (_MemoryAddressMux < 0 || _MemoryAddressMux >= MEM_SIZE)) {
ProgramError = 1; /* Endereço de memória não é válido */
} else {
if(CONTROLE(MemWrite)) {
memcpy(&MainMemory[_MemoryAddressMux], &B, sizeof(int)); /* Escrita */
}
if(CONTROLE(MemRead)) {
memcpy(&_MDR, &MainMemory[_MemoryAddressMux], sizeof(int)); /* Leitura */
_IR = _MDR;
}
}
sem_trywait(&sem_SemafaroContador);
}
}
void *InstructionRegister(void *args) {
/*
* IR: atualiza valor na subida do ciclo de clock.
*/
while(1) {
sem_wait(&sem_InstructionRegister);
if(!Run) { /* Finalizar thread */
return NULL;
}
if(CONTROLE(IRWrite)) {
IR = _IR; /* Escreve se o sinal IRWrite estiver ativo */
}
sem_trywait(&sem_SemafaroContador);
}
}
void *MemoryDataRegister(void *args) {
/*
* MDR, atualiza valor na subida do ciclo de clock.
*/
while(1) {
sem_wait(&sem_MemoryDataRegister);
if(!Run) { /* Finalizar thread */
return NULL;
}
MDR = _MDR; /* Escreve */
sem_trywait(&sem_SemafaroContador);
}
}
void *WriteRegisterMux(void *args) {
/*
* Esse é o Mux que fica entre o IR e o Banco de Registradores, que seleciona em qual registrador
* do Banco de Registradores será feita uma determinada escrita.
*/
while(1) {
sem_wait(&sem_WriteRegisterMux);
if(!Run) { /* Finalizar thread */
return NULL;
}
if(CONTROLE(RegDst1)) {
_WriteRegisterMux = 31; /* 2 */
} else if(CONTROLE(RegDst0)) {
_WriteRegisterMux = (IR >> 11) & 0x1F; /* 1 */
} else {
_WriteRegisterMux = (IR >> 16) & 0x1F; /* 0 */
}
sem_trywait(&sem_SemafaroContador);
}
}
void *WriteDataMux(void *args) {
/*
* Esse é o Mux que fica entre o MDR e o Banco de Registradores, que seleciona qual dado
* será escrito em um determinado registrador do Banco de Registradores.
*/
while(1) {
sem_wait(&sem_WriteDataMux);
if(!Run) { /* Finalizar thread */
return NULL;
}
if(CONTROLE(MemtoReg1)) {
_WriteDataMux = PC; /* 2 */
} else if(CONTROLE(MemtoReg0)) {
_WriteDataMux = MDR; /* 1 */
} else {
_WriteDataMux = ALUOut; /* 0 */
}
sem_trywait(&sem_SemafaroContador);
}
}
void *Registers(void *args) {
/*
* Esse é o componente que acessa o Banco de Registradores fazendo leituras e escritas.
*
* Na lógica sequencial, ele é "executado" duas vezes:
* - uma na subida do clock, para apenas escrita do ciclo anterior;
* - uma posteriormente, para apenas leituras.
*/
while(1) {
sem_wait(&sem_Registers);
if(!Run) { /* Finalizar thread */
return NULL;
}
if(CONTROLE(RegWrite)) {
if(_WriteRegisterMux == 0){
ProgramError = 1; /* Erro porque não pode escrever no registrador zero */
} else {
RegistersArray[_WriteRegisterMux] = _WriteDataMux; /* Escrita */
}
}
sem_trywait(&sem_SemafaroContador);
sem_wait(&sem_Registers); /* Esperar de novo para hora de ler... */
if(!Run) { /* Finalizar thread */
return NULL;
}
_A = RegistersArray[(IR >> 21) & 0x1F]; /* Ler para A */
_B = RegistersArray[(IR >> 16) & 0x1F]; /* Ler para B */
sem_trywait(&sem_SemafaroContador);
}
}
void *SignExtend(void *args) {
/*
* Esse é o Extensor de Sinal que fica em baixo do Banco de Registradores, usado
* para calcular endereço relativo a PC ou operar com imediato.
*/
while(1) {
sem_wait(&sem_SignExtend);
if(!Run) { /* Finalizar thread */
return NULL;
}
if(IR & 0x8000) {
_SignExtend = (IR & 0xFFFF) | (-1 ^ 0xFFFF); /* Negativo, estender tudo para 1 */
} else {
_SignExtend = IR & 0xFFFF; /* Positivo, estender tudo para 0 */
}
sem_trywait(&sem_SemafaroContador);
}
}
void *ShiftLeft(void *args) {
/*
* Esse é o Shift Left que fica em baixo do Banco de Registradores e ao lado do
* Extensor de Sinal, usado para calcular endereço relativo a PC.
*/
while(1) {
sem_wait(&sem_ShiftLeft);
if(!Run) { /* Finalizar thread */
return NULL;
}
_ShiftLeft = _SignExtend << 2; /* Multiplicado por 4: tamanho da palavra (Byte Offset) */
sem_trywait(&sem_SemafaroContador);
}
}
void *ARegister(void *args) {
/*
* Registrador A: atualiza valor na subida do ciclo de clock.
*/
while(1) {
sem_wait(&sem_ARegister);
if(!Run) { /* Finalizar thread */
return NULL;
}
A = _A; /* Escreve */
sem_trywait(&sem_SemafaroContador);
}
}
void *BRegister(void *args) {
/*
* Registrador B: atualiza valor na subida do ciclo de clock.
*/
while(1) {
sem_wait(&sem_BRegister);
if(!Run) { /* Finalizar thread */
return NULL;
}
B = _B; /* Escreve */
sem_trywait(&sem_SemafaroContador);
}
}
void *ALUAMux(void *args) {
/*
* Esse é o Mux que fica entre o Registrador A e a ULA, que seleciona o primeiro
* valor a ser operado na ULA.
*/
while(1) {
sem_wait(&sem_ALUAMux);
if(!Run) { /* Finalizar thread */
return NULL;
}
if(CONTROLE(ALUSrcA)) {
_ALUAMux = A; /* 1 */
} else {
_ALUAMux = PC; /* 0 */
}
sem_trywait(&sem_SemafaroContador);
}
}
void *ALUBMux(void *args) {
/*
* Esse é o Mux que fica entre o Registrador B e a ULA, que seleciona o segundo
* valor a ser operado na ULA.
*/
while(1) {
sem_wait(&sem_ALUBMux);
if(!Run) { /* Finalizar thread */
return NULL;
}
if(CONTROLE(ALUSrcB1) && CONTROLE(ALUSrcB0)) {
_ALUBMux = _ShiftLeft; /* 3 */
} else if(CONTROLE(ALUSrcB1) && !CONTROLE(ALUSrcB0)) {
_ALUBMux = _SignExtend; /* 2 */
} else if(CONTROLE(ALUSrcB0)) {
_ALUBMux = 4; /* 1 */
} else {
_ALUBMux = B; /* 0 */
}
sem_trywait(&sem_SemafaroContador);
}
}
void *ALUControl(void *args) {
/*
* Essa é a Unidade de Controle Secundária, que fica em baixo da ULA e é responsável por selecionar
* se a ULA fará adição, subtração, 'e', ou operação determinada no campo de função de IR.
*
* A implementação desta foi feita por tabela verdade.
*/
while(1) {
sem_wait(&sem_ALUControl);
if(!Run) { /* Finalizar thread */
return NULL;
}
_ALUControl = (0x20 & ~CONTROLE(ALUOp1) & ~CONTROLE(ALUOp0)) | /* Soma */
(0x22 & ~CONTROLE(ALUOp1) & CONTROLE(ALUOp0)) | /* Subtração */
((IR & 0x3F) & CONTROLE(ALUOp1) & ~CONTROLE(ALUOp0)) | /* Campo função */
(0x24 & CONTROLE(ALUOp1) & CONTROLE(ALUOp0)); /* And */
sem_trywait(&sem_SemafaroContador);
}
}
void *ShiftLeftConcatenate(void *args) {
/*
* Esse é o Shift Left que fica em cima da ULA, usado para um pulo (branch)
* incondicional. Ele é concatenado com conteúdo de PC.
*/
while(1) {
sem_wait(&sem_ShiftLeftConcatenate);
if(!Run) { /* Finalizar thread */
return NULL;
}
_ShiftLeftConcatenate = (IR & 0x3FFFFFF) << 2; /* Multiplicado por 4: tamanho da palavra (Byte Offset) */
_ShiftLeftConcatenate |= PC & ~0xFFFFFFF; /* Concatenar os bits restantes com valor de PC */
sem_trywait(&sem_SemafaroContador);
}
}
void *ALU(void *args) {
/*
* Essa é a ULA, que vai realizar as operações aritméticas.
*
* Não foi implementada todas as operações que a ULA da arquitetura MIPS é capaz
* de realizar, mas apenas as relevantes a este trabalho.
*/
while(1) {
sem_wait(&sem_ALU);
if(!Run) { /* Finalizar thread */
return NULL;
}
switch(_ALUControl) {
case 0x20:
_ALUOut = _ALUAMux + _ALUBMux; /* add */
_ALUZero = !_ALUOut;
break;
case 0x22:
_ALUOut = _ALUAMux - _ALUBMux; /* sub */
_ALUZero = !_ALUOut;
break;
case 0x2A:
_ALUOut = (_ALUAMux < _ALUBMux) ? 1 : 0; /* slt */
_ALUZero = !_ALUOut;
break;
case 0x24:
_ALUOut = _ALUAMux & _ALUBMux; /* and */
_ALUZero = !_ALUOut;
break;
case 0x25:
_ALUOut = _ALUAMux | _ALUBMux; /* or */
break;
default:
if(CONTROLE(ALUOp1) && !CONTROLE(ALUOp0)) /* Tipo-R */
ProgramError = 1; /* A ULA não é compatível com esta operação */
}
_ALUZero = !_ALUOut;
sem_trywait(&sem_SemafaroContador);
}
}
void *ALUOutRegister(void *args) {
/*
* ALUOut: atualiza valor na subida do ciclo de clock.
*/
while(1) {
sem_wait(&sem_ALUOutRegister);
if(!Run) { /* Finalizar thread */
return NULL;
}
ALUOut = _ALUOut; /* Escreve */
sem_trywait(&sem_SemafaroContador);
}
}
void *PCMux(void *args) {
/*
* Esse é o Mux que fica após a ULA e o Registrador ALUOut, que seleciona o próximo
* valor (endereço de instrução na memória) que PC assumirá.
*/
while(1) {
sem_wait(&sem_PCMux);
if(!Run) { /* Finalizar thread */
return NULL;
}
if(CONTROLE(PCSource1) && CONTROLE(PCSource0)) {
_PC = A; /* 3 */
} else if(CONTROLE(PCSource1) && !CONTROLE(PCSource0)) {
_PC = _ShiftLeftConcatenate; /* 2 */
} else if (CONTROLE(PCSource0)) {
_PC = ALUOut; /* 1 */
} else {
_PC = _ALUOut; /* 0 */
}
sem_trywait(&sem_SemafaroContador);
}
}
void *BNEMux(void *args) {
/*
* Esse é o Mux que fica acima de tudo, que seleciona o bit correto:
* - se a ULA deu zero (no caso de BEQ);
* - ou não (no caso de BNE).
*/
while(1) {
sem_wait(&sem_BNEMux);
if(!Run) { /* Finalizar thread */
return NULL;
}
if(CONTROLE(BNE)) {
_BNEMux = (_ALUZero) ? 0 : 1; /* É BNE */
} else {
_BNEMux = _ALUZero; /* Não é BNE */
}
sem_trywait(&sem_SemafaroContador);
}
}
void *PortaAND(void *args) {
/*
* Esta porta lógica combina o Mux acima com o fato de ser mesmo BEQ ou BNE.
*/
while(1) {
sem_wait(&sem_PortaAND);
if(!Run) { /* Finalizar thread */
return NULL;
}
_PortaAND = (CONTROLE(PCWriteCond) && _BNEMux) ? 1 : 0; /* É BEQ ou BNE */
sem_trywait(&sem_SemafaroContador);
}
}
void *PortaOR(void *args) {
/*
* Esta porta lógica determina se a instrução em execução altera o valor de
* PC nesse ciclo (para ser usado no próximo).
*/
while(1) {
sem_wait(&sem_PortaOR);
if(!Run) { /* Finalizar thread */
return NULL;
}
_PortaOR = (CONTROLE(PCWrite) || _PortaAND) ? 1 : 0; /* Escreve em PC */
sem_trywait(&sem_SemafaroContador);
}
}
<file_sep>
#ifndef H_BUFFER
#define H_BUFFER
#include <stdio.h>
#define PAGE_SIZE 32000
#define BTREE_PAGE_SIZE 105
unsigned long B_count(FILE *stream);
unsigned long B_offset(FILE *stream);
#endif
<file_sep># Projeto 3: Iluminação
Este é o repositório do Projeto 3 de **SCC-0250 Computação Gráfica - 2020.1**.
## Integrantes do grupo:
* <NAME> (Nº USP 9875952)
* <NAME> (Nº USP 10369014)
## Organização do repositório:
Este repositório se organiza da seguinte maneira:
* [Projeto.ipynb](Projeto.ipynb): é o código em Python do Jupyter Notebook. Está totalmente documentado e organizado por ordem das funcionalidades do trabalho.
* [Codigo.py](Codigo.py): é o código em Python, que pode ser executado sem a necessidade do Jupyter Notebook.
* [objects/](objects): contém todos os objetos que são rendenizados na tela (arquivos *.obj e texturas).
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
vector<int> crivo = vector<int>(100000);
long crivoCount = 0;
void CalcularCrivo(){
int i, j, N, m[crivo.size() * 10];
memset(m, 0, sizeof(m));
N = crivo.size();
for(i = 2; i < N; i++)
if(m[i] == 0) {
crivo[crivoCount++] = i;
for(j = i + i; j < N; j += i)
m[j] = 1;
}
}
bool Divides(long N, long Div){
if(Div == 0) return false;
if(N >= Div || Div == 1) return true;
long tmp, cnt2;
int i, cnt;
for(i = 0; i < crivoCount && crivo[i]*crivo[i] <= Div; i++) {
if(Div % crivo[i] == 0) {
cnt = 0;
while(Div % crivo[i] == 0){
cnt++;
Div /= crivo[i];
}
tmp = crivo[i];
cnt2 = 0;
while(tmp <= N) {
cnt2 += N/tmp;
tmp *= crivo[i];
}
if(cnt2 < cnt) return false;
}
}
if(Div != 1 && N < Div) return false;
return true;
}
int main(int argc, char **argv){
long N, Div;
CalcularCrivo();
while(scanf("%ld %ld", &N, &Div) == 2){
if(Divides(N, Div))
cout << Div << " divides " << N << "!\n";
else
cout << Div << " does not divide " << N << "!\n";
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
long max_this_person_can_take(long limitW, long takingW, long takingP, vector< pair<long, long> > &objects, bool *visited) {
long i, j, N, aux, counter;
bool *visitedAux;
if(takingW > limitW)
return 0;
if(takingW == limitW)
return takingP;
N = objects.size();
visitedAux = (bool *) malloc(sizeof(bool) * N);
for(i = counter = 0; i < N; i++){
if(visited[i] == true)
continue;
for(j = 0; j < N; j++)
visitedAux[j] = visited[j];
visitedAux[i] = true;
aux = max_this_person_can_take(limitW, takingW + objects[i].second, objects[i].first, objects, visitedAux);
if(aux >= counter)
counter = aux;
}
free(visitedAux);
return takingP + counter;
}
int main(int argc, char **argv) {
long i, j, T, N, P, W, G, S;
vector< pair<long, long> > objects;
vector<long> family;
bool *visitedAux;
cin >> T;
for(i = 0; i < T; i++){
cin >> N;
objects = vector< pair<long, long> >(N);
visitedAux = (bool *) malloc(sizeof(bool) * N);
for(j = 0; j < N; j++) {
cin >> P >> W;
objects[j] = make_pair(P, W);
visitedAux[j] = false;
}
cin >> G;
family = vector<long>(G);
for(j = 0; j < G; j++) {
cin >> family[j];
}
for(S = j = 0; j < G; j++) {
S += max_this_person_can_take(family[j], 0, 0, objects, visitedAux);
}
free(visitedAux);
cout << S << '\n';
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <unordered_map>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
int main(int argc, char **argv) {
long i, j, n, m, tmp, c, *cMatrix;
char *matrix;
int aux, T;
scanf("%d", &T);
for(; T > 0; T--) {
scanf("%ld %ld", &n, &m); // Ler
matrix = (char *) malloc(sizeof(char) * n * m); // Alocar
cMatrix = (long *) malloc(sizeof(long) * n * m);
memset(cMatrix, 0, sizeof(long) * (n + m)); // Set para zero
for(i = 0; i < n; i++) { // Ler matriz
for(j = 0; j < m; j++) {
scanf("%d", &aux);
matrix[i * m + j] = aux;
}
}
for(i = 0; i < n; i++) { // Calcular
for(j = 0; j < m; j++) {
tmp = min(i + j, n + m - i - j - 2);
if(tmp < (n + m - 1)/2) {
cMatrix[tmp * 2 + matrix[i * m + j]]++;
}
}
}
for(i = c = 0; i < (n + m - 1) / 2; i++) { // Somar
c += min(cMatrix[i * 2 + 0], cMatrix[i * 2 + 1]);
}
printf("%ld\n", c); // Imprimir
free(matrix); // Free
free(cMatrix);
}
return EXIT_SUCCESS;
}
<file_sep>
#ifndef FUNCIONALIDADES_H_
#define FUNCIONALIDADES_H_
void f1_readCsv(char *csvPath, char *dataPath, char *indexPath);
void f2_listAll(char *dataPath);
void f3_search(char *dataPath, char *indexPath);
void f4_insert(char *dataPath, char *indexPath);
void f5_update(char *dataPath, char *indexPath);
void f6_readCsv(char *csvPath, char *dataPath);
void f7_sort(char *dataPath, char *sortedDataPath);
void f8_listMatch(char *f1Path, char *f1IndPath, char *f2Path, char *key);
void f9_graph(char *f1Path, char *f1IndPath, char *f2Path);
void f10_graphInverted(char *f1Path, char *f1IndPath, char *f2Path);
void f11_bfs(char *f1Path, char *f1IndPath, char *f2Path, char *key);
void f12_dfsCycle(char *f1Path, char *f1IndPath, char *f2Path, char *key);
void fx_invalidadeStatus(char *filePath);
void fx_compressFile2(char *file2Path);
#endif<file_sep>#include <stdlib.h>
#include <limits.h>
#include <iostream>
#include <vector>
using namespace std;
long solve(long camp, long remain, vector< vector<long> > &memo, vector<long> &dist) {
if (camp == 0 && remain == 0) return 0;
if (remain == 0 || camp == 0) return LONG_MAX;
if (memo[camp][remain] != -1) return memo[camp][remain];
long prev, result;
for (prev = remain - 1; prev < camp; prev++) {
result = max(solve(prev, remain - 1, memo, dist), dist[camp] - dist[prev]);
if (memo[camp][remain] == -1 || memo[camp][remain] > result){
memo[camp][remain] = result;
}
}
return memo[camp][remain];
}
int main(int argc, char **argv) {
long i, N, K;
cin >> N >> K;
N += 2;
K += 1;
vector<long> dist(N);
for (i = 1; i < N; i++) {
cin >> dist[i];
dist[i] += dist[i - 1];
}
vector< vector<long> > memo(N, vector<long>(K + 1, -1));
cout << solve(N - 1, K, memo, dist) << "\n";
return EXIT_SUCCESS;
}<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
<NAME>
<EMAIL>
*/
void ParaMaiusculo(char *str){
int i;
for(i=0;i<strlen(str);i++){
if((str[i]>=97) && (str[i]<=122)){
str[i]=str[i]-32;
}
}
}
void AntesDe(char *str,char *before,int position){
int i;
for(i=0;i<position;i++){
before[i]=str[i];
}
}
void DepoisDe(char *str,char *after,int position){
int i=strlen(str);
for(i=i;i>position;i--){
after[i-position-1]=str[i];
}
}
int UltimaPosicaoDe(char *str,char ch){
int i,last_position=-1;
for(i=0;i<strlen(str);i++){
if(str[i]==ch){
last_position=i;
}
}
return last_position;
}
int main(){
char FullName[5000];
fgets(FullName,sizeof(FullName),stdin);
FullName[strlen(FullName)-1]='\0';
char AntesDeChar[UltimaPosicaoDe(FullName,' ')+1],DepoisDeChar[strlen(FullName)-UltimaPosicaoDe(FullName,' ')];
AntesDeChar[UltimaPosicaoDe(FullName,' ')]='\0';
DepoisDeChar[strlen(FullName)-UltimaPosicaoDe(FullName,' ')-1]='\0';
AntesDe(FullName,AntesDeChar,UltimaPosicaoDe(FullName,' '));
DepoisDe(FullName,DepoisDeChar,UltimaPosicaoDe(FullName,' '));
ParaMaiusculo(DepoisDeChar);
printf("%s, %s",DepoisDeChar, AntesDeChar);
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <Image.h>
/*
* == IMAGENS P&B ==
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv){
IMG *A,*B,*Sum; // Flags para uso no código.
int i,N;
scanf("%d%*c",&N); // Ler número de operações.
for(i=0;i<N;i++){ // Para cada operação...
A=New_Img(); // Alocar imagem A.
B=New_Img(); // Alocar imagem B.
Read_Img(stdin,A); getchar(); // Ler A.
Read_Img(stdin,B); getchar(); // Ler B.
Sum=Join_Img(A,B); // Realizar a soma entre as duas.
Destroy_Img(A); // Destruir A.
Destroy_Img(B); // Destruir B.
printf("%d %d pixels pretos.\n",i+1,Count_Img_Filled_Pixels(1024,Sum)/1024); // Imprimir o número de pixels/1024.
Destroy_Img(Sum); // Destruir a soma.
}
return EXIT_SUCCESS;
}
<file_sep>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
/*
* Abaixo seguem funções que fazem a escrita do binário em "stdout" (tela) pra poder ser comparado no run.codes.
*
* Funciona assim: você faz tudo o que tiver que fazer na funcionalidade no arquivo em disco, assim como ensinado nas aulas da disciplina.
* Ao fim da funcionalidade, use a função "binarioNaTela" e a função já cuida de tudo para você. É só chamar a função.
*
* Note que ao usar a binarioNaTela1, o fclose no arquivo binário já deve ter sido feito anteriormente. Você passa o nome do arquivo binário ("arquivoTrabX.bin") pra ela e ela vai ler tudo e escrever na tela.
*
* Você pode colocar isso num módulo .h separado, ou incluir as funções no próprio código .c: como preferir.
* VOCÊ NÃO PRECISA ENTENDER ESSAS FUNÇÕES. É só usar elas da forma certa depois de acabar a funcionalidade.
*
* Tá tudo testado e funcionando, mas qualquer dúvida acerca dessas funções, falar com o monitor Matheus (<EMAIL>).
*/
// Se você for incluir no .h separado, tá abaixo:
#ifndef H_ESCREVERNATELA_
#define H_ESCREVERNATELA_
#include <stdio.h>
void binarioNaTela1(char *nomeArquivoBinario);
void trim(char *str);
void scan_quote_string(char *str);
#endif
// Acabou o código que vai no .h
// Abaixo vai em algum .c
void binarioNaTela1(char *nomeArquivoBinario) {
/* Use essa função para comparação no run.codes. Lembre-se de ter fechado (fclose) o arquivo anteriormente.
* Ela vai abrir de novo para leitura e depois fechar. */
unsigned long i, cs;
unsigned char *mb;
size_t fl;
FILE *fs;
if(nomeArquivoBinario == NULL || !(fs = fopen(nomeArquivoBinario, "rb"))) {
fprintf(stderr, "ERRO AO ESCREVER O BINARIO NA TELA (função binarioNaTela1): não foi possível abrir o arquivo que me passou para leitura. Ele existe e você tá passando o nome certo? Você lembrou de fechar ele com fclose depois de usar?\n");
return;
}
fseek(fs, 0, SEEK_END);
fl = ftell(fs);
fseek(fs, 0, SEEK_SET);
mb = (unsigned char *) malloc(fl);
fread(mb, 1, fl, fs);
cs = 0;
for(i = 0; i < fl; i++) {
cs += (unsigned long) mb[i];
}
printf("%lf\n", (cs / (double) 100));
free(mb);
fclose(fs);
}
void trim(char *str) {
/*
* Essa função arruma uma string de entrada "str".
* Manda pra ela uma string que tem '\r' e ela retorna sem.
* Ela remove do início e do fim da string todo tipo de espaçamento (\r, \n, \t, espaço, ...).
* Por exemplo:
*
* char minhaString[] = " \t TESTE DE STRING COM BARRA R \t \r\n ";
* trim(minhaString);
* printf("[%s]", minhaString); // vai imprimir "[TESTE DE STRING COM BARRA R]"
*
*/
size_t len;
char *p;
for(len = strlen(str); len > 0 && isspace(str[len - 1]); len--); // remove espaçamentos do fim
str[len] = '\0';
for(p = str; *p != '\0' && isspace(*p); p++); // remove espaçamentos do começo
len = strlen(p);
memmove(str, p, sizeof(char) * (len + 1));
}
void scan_quote_string(char *str) {
/*
* Use essa função para ler um campo string delimitado entre aspas (").
* Chame ela na hora que for ler tal campo. Por exemplo:
*
* A entrada está da seguinte forma:
* nomeDoCampo "<NAME>"
*
* Para ler isso para as strings já alocadas str1 e str2 do seu programa, você faz:
* scanf("%s", str1); // Vai salvar nomeDoCampo em str1
* scan_quote_string(str2); // Vai salvar <NAME> em str2 (sem as aspas)
*
*/
char R;
while((R = getchar()) != EOF && isspace(R)); // ignorar espaços, \r, \n...
if(R == 'N' || R == 'n') { // campo NULO
getchar(); getchar(); getchar(); // ignorar o "ULO" de NULO.
strcpy(str, ""); // copia string vazia
} else if(R == '\"') {
if(scanf("%[^\"]", str) != 1) { // ler até o fechamento das aspas
strcpy(str, "");
}
getchar(); // ignorar aspas fechando
} else if(R != EOF){ // vc tá tentando ler uma string que não tá entre aspas! Fazer leitura normal %s então...
str[0] = R;
scanf("%s", &str[1]);
} else { // EOF
strcpy(str, "");
}
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#define ALPHABET_START ('a')
#define ALPHABET_END ('z')
#define ALPHABET_SIZE (ALPHABET_END - ALPHABET_START + 1)
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
ll dp[2001][2001];
// Competitive Programming sometimes requires global variables - particularly not my favorite coding style, but they're not used to the best practices anyway...
// Better solution would be to use a MAP, but a MAP is very slow for this because they can't wait a few more miliseconds, so let's use this shi**y array solution.
// In Brazil country this is called "gambiarra", and competitive programmers know how to do this pretty well.
void testCase() {
ll valueTable[ALPHABET_SIZE], i, j, N, M;
char a[2001], b[2001];
memset(dp, 0, sizeof(ll) * 2001 * 2001);
cin >> N >> M;
for(i = 0; i < ALPHABET_SIZE; i++) {
cin >> valueTable[i];
}
//gets(a);
//gets(b);
cin >> a >> b;
for(i = 0; i < N; i++) {
for(j = 0; j < M; j++) {
if(a[i] == b[j]) {
dp[i + 1][j + 1] = dp[i][j] + valueTable[a[i] - ALPHABET_START];
continue;
}
dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]);
}
}
cout << dp[N][M] << endl;
}
int main(int argc, char **argv) {
ll T;
T = 1;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>#include <vectorutils.h>
#define ROOT 0
#define right(pos) pos*2+2
#define left(pos) pos*2+1
void max_heapify(void *vector, int size, int (*cmp)(void *,void *), int n, int position, int *CmpN, int *MovN) {
int largestId, leftId, rightId;
largestId = position;
leftId = left(position);
rightId = right(position);
if (leftId < n && ++(*CmpN) && cmp(vector+leftId*size,vector+largestId*size)<0)
largestId = leftId;
if (rightId < n && ++(*CmpN) && cmp(vector+rightId*size,vector+largestId*size)<0)
largestId = rightId;
if (largestId != position) {
(*MovN)+=3;
gswap(vector+largestId*size, vector+position*size, size);
max_heapify(vector, size, cmp, n, largestId, CmpN, MovN);
}
}
void heapsort(void *vector, int size, int (*cmp)(void *,void *), int n, int *CmpN, int *MovN) {
int i, C = 0, M = 0;
for (i = n/2-1; i >= 0; i--) max_heapify(vector, size, cmp, n, i, &C, &M);
for (i = n-1; i > ROOT; i--) {
M+=3;
gswap(vector+ROOT*size, vector+i*size, size);
max_heapify(vector, size, cmp, i, ROOT, &C, &M);
}
*CmpN = C;
*MovN = M;
}
<file_sep>
#
# ~ Qual é a estrutura? ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -Wall
objects/main.o: main.c objects/stack.o headers/stack.h objects/queue.o headers/queue.h objects/heap.o headers/heap.h
gcc -c -o objects/main.o main.c -Wall -I headers
objects/stack.o: lib/stack.c headers/stack.h
gcc -c -o objects/stack.o lib/stack.c -Wall -I headers
objects/queue.o: lib/queue.c headers/queue.h
gcc -c -o objects/queue.o lib/queue.c -Wall -I headers
objects/heap.o: lib/heap.c headers/heap.h
gcc -c -o objects/heap.o lib/heap.c -Wall -I headers
run: Prog
./Prog
clean:
rm Prog objects/*.o
<file_sep>#include <stdlib.h>
#include <iostream>
#include <set>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014) - based on https://www.geeksforgeeks.org/common-divisors-of-n-numbers/
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
ll count_divisors(ll *A, ll N) {
ll i, j, gcd_all;
set<ll> list = set<ll>();
gcd_all = A[0];
for(i = 1; i < N; i++) {
gcd_all = gcd(gcd_all, A[i]);
}
for(i = 1; i*i <= gcd_all; i++) {
if(gcd_all % i != 0) {
continue;
}
list.insert(i);
if(gcd_all / i == i) {
continue;
}
list.insert(gcd_all / i);
}
return list.size();
}
void testCase() {
ll i, N, *A;
cin >> N;
A = (ll *) malloc(sizeof(ll) * N);
for(i = 0; i < N; i++) {
cin >> A[i];
}
cout << count_divisors(A, N) << endl;
free(A);
}
int main(int argc, char **argv) {
testCase();
return EXIT_SUCCESS;
}
<file_sep>#ifndef QUEUE_H_
#define QUEUE_H_
//#include <stdlib.h>
typedef struct __queue_t QUEUE;
struct __queue_t *Q_New(size_t);
int Q_Size(struct __queue_t *);
char Q_Add(void *, struct __queue_t *);
int Q_Get(void *, struct __queue_t *);
int Q_Shift(void *, struct __queue_t *);
void Q_Destroy(struct __queue_t *);
#endif<file_sep>
/*
* ~ ATM ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef ATM_H_
#define ATM_H_
#include <hashtable.h>
enum { audit_transfer = 0, audit_withdraw, audit_deposit };
typedef struct {
int Bank1, Bank2;
double Money;
} OPERATION;
typedef struct {
int Bank;
double DepositedMoney, WithdrawnMoney;
double TransfersTo, TransfersFrom;
} BANK;
int ReadOperation(char *, int *, int *, int *, int *, double *);
int Withdraw(double, int, HASHTABLE *);
int Deposit(double, int, HASHTABLE *);
int TransferFrom(double, int, HASHTABLE *);
int TransferTo(double, int, HASHTABLE *);
int AddAudit(int, char, int, int, double, HASHTABLE *);
int PrintATM(HASHTABLE *);
int PrintAudit(int, char, unsigned long, HASHTABLE *);
#endif<file_sep>package gerenciador;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Message {
private String type;
private int id;
private int len;
private String action;
private String body;
private static final String MSG_REGEX = "^\\s*SALA_INTEL\\s*[\\r\\n]+\\s*TYPE:\\s*([^\\r\\n]+)\\s*[\\r\\n]+\\s*"
+ "ID:\\s*([^\\r\\n]+)\\s*[\\r\\n]+\\s*LEN:\\s*([^\\r\\n]+)\\s*[\\r\\n]+\\s*ACTION:\\s*([^\\r\\n]+)\\s*([\\r\\n]+\\s*.*)?$";
private static final Pattern MSG_PATTERN = Pattern.compile(MSG_REGEX, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
/* Construtores */
/**
* Cria uma mensagem a partir de um TYPE, ID, LEN, ACTION e BODY.
*
* @param type
* @param id
* @param len
* @param action
* @param body
*/
public Message(String type, int id, int len, String action, String body) {
this.type = type;
this.id = id;
this.len = len;
this.action = action;
this.body = body;
}
/**
* Cria uma mensagem a partir de um TYPE, ID, ACTION e BODY. O LEN é calculado a partir de BODY.
*
* @param type
* @param id
* @param action
* @param body
*/
public Message(String type, int id, String action, String body) {
this(type, id, body.length(), action, body);
}
/**
* Cria uma mensagem a partir de um TYPE, ACTION e BODY. O LEN é calculado a partir de BODY e o ID é definido aleatoriamente.
*
* @param type
* @param action
* @param body
*/
public Message(String type, String action, String body) {
this(type, (int)(Math.random() * Integer.MAX_VALUE), action, body);
}
/**
* Cria uma mensagem a partir de uma string formatada da maneira de nosso relatório.
*
* @param fullMessage a string
*/
public Message(String fullMessage) {
Matcher m;
m = MSG_PATTERN.matcher(fullMessage);
if(!m.matches()) {
throw new IllegalArgumentException("Invalid message.");
}
this.type = m.group(1);
this.id = Integer.parseInt(m.group(2));
this.len = Integer.parseInt(m.group(3));
this.action = m.group(4);
this.body = m.group(5);
if(this.body == null || this.body.trim().isEmpty()) {
this.body = "";
}
this.body = this.body.trim();
}
/* Methods */
/**
* Verifica se uma string pode ser usada para instanciar uma nova mensagem. (é válida de acordo com o nosso relatório?)
*
* @param fullMessage a string que será validada
* @return
*/
public static boolean valid(String fullMessage) {
Matcher m;
m = MSG_PATTERN.matcher(fullMessage);
return m.matches();
}
/**
* Cria uma nova Mensagem a partir da resposta de um socket.
*
* @param receivingSocket o socket
* @return a nova mensagem
* @throws IOException
*/
public static Message getFromSocket(Socket receivingSocket) throws IOException {
BufferedReader socketStream;
String l, input;
socketStream = new BufferedReader(new InputStreamReader(receivingSocket.getInputStream(), "UTF-8"));
input = "";
while((l = socketStream.readLine()) != null) {
l += System.lineSeparator();
input += l;
}
return new Message(input);
}
/**
* Envia esta instância de Mensagem como socket para um servidor e retorna uma string que é toda a resposta dele pra essa mensagem.
* Idealmente, essa string de resposta também é uma mensagem válida e pode ser instanciada nessa classe.
*
* @param hostAddr o endereço do servidor
* @param hostPort a porta do servidor
* @return a string da mensagem de resposta do servidor
* @throws UnknownHostException
* @throws IOException
*/
public String send(String hostAddr, int hostPort) throws UnknownHostException, IOException {
Socket sendingSocket;
BufferedWriter s;
BufferedReader r;
String l, input;
sendingSocket = new Socket(hostAddr, hostPort);
s = new BufferedWriter(new OutputStreamWriter(sendingSocket.getOutputStream(), "UTF-8"));
s.write(this.toString());
s.flush();
sendingSocket.shutdownOutput();
r = new BufferedReader(new InputStreamReader(sendingSocket.getInputStream(), "UTF-8"));
input = "";
while((l = r.readLine()) != null) {
l += System.lineSeparator();
input += l;
}
sendingSocket.close();
return input;
}
/* Getters */
public String getType() {
return this.type;
}
public int getId() {
return this.id;
}
public int getLen() {
return this.len;
}
public String getAction() {
return this.action;
}
public String getBody() {
return this.body;
}
/**
* Retorna essa instância de Mensagem da forma como descrito no nosso relatório em uma string.
*
* @return a string
*/
@Override
public String toString() {
String fullMessage;
fullMessage = "SALA_INTEL" + System.lineSeparator();
fullMessage += "TYPE: " + this.type + System.lineSeparator();
fullMessage += "ID: " + this.id + System.lineSeparator();
fullMessage += "LEN: " + this.len + System.lineSeparator();
fullMessage += "ACTION: " + this.action;
if(this.body != null && !this.body.trim().isEmpty()) {
fullMessage += System.lineSeparator() + this.body;
}
return fullMessage;
}
/* Setters */
public void setType(String newType) {
this.type = newType;
}
public void setId(int newId) {
this.id = newId;
}
public void setLen(int newLen) {
this.len = newLen;
}
public void setAction(String newAction) {
this.action = newAction;
}
public void setBody(String newBody, boolean adjustLen) {
this.body = newBody;
if(adjustLen) {
this.len = newBody.length();
}
}
public void setBody(String newBody) {
this.setBody(newBody, true);
}
}
<file_sep>#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <vector>
#include <cmath>
using namespace std;
int main(int argc, char **argv){
int Aux, NA, i, j, Largest;
while(1){
Largest = INT_MAX;
vector<int> Numbers = vector<int>();
cin >> Aux;
while(Aux != 0) {
Numbers.push_back(Aux);
cin >> Aux;
}
NA = Numbers.size();
if(NA < 2) break;
for(i = 0; i < NA; i++){
if(Numbers[i] < 0) Numbers[i] = abs(Numbers[i]) + 1;
if(Numbers[i] < Largest) Largest = Numbers[i];
}
for(i = Largest; i >= 1; i--){
if(Numbers[0] != i) Aux = Numbers[0] % i;
else Aux = Numbers[1] % i;
for(j = 1; j < NA; j++){
if(Numbers[j] == i) continue;
if(Numbers[j] % i != Aux) goto Next_Int;
}
break;
Next_Int: ;
}
cout << i << '\n';
}
}<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
Por <NAME>.
<EMAIL>
*/
int main(){
int mynumber=0;
scanf("%d", &mynumber);
printf("%d",2*(mynumber));
return EXIT_SUCCESS;
}
<file_sep>package main;
import alimentador.Alimentador;
import java.util.regex.*;
import console.Console;
public class Main {
private static final String ADDR_REGEX = "^\\s*([^:]+):([0-9]+)\\s*$";
private static final Pattern ADDR_PATTERN = Pattern.compile(ADDR_REGEX);
public static void main(String[] args) {
Alimentador a;
Console c;
Matcher m;
String s;
int p;
c = Console.getInstance();
System.out.println("Bem-vinde ao Alimentador do Ar-condicionado.");
System.out.println();
do {
p = c.readInt("Em qual porta o servidor do alimentador deve iniciar? (recomendado = 9001-9999)");
if (p < 1 || p > 65535) {
System.out
.println("Porta invalida! Deve ser um valor entre 1-65535.");
}
} while (p < 1 || p > 65535);
do {
s = c.readLine("E qual o endereco do servidor do gerenciador? (formato = endereco:porta)");
m = ADDR_PATTERN.matcher(s);
if (s == null || !m.matches()) {
System.out
.println("Endereco invalido! Deve ser no formato endereco:porta. Exemplos: dominio.com:9000 ou 192.168.0.110:8500.");
}
} while (s == null || !m.matches());
try {
a = new Alimentador(m.group(1).trim(),
Integer.parseInt(m.group(2)), p);
System.out.println("O servidor esta hospedado em: "
+ a.getHostAddress() + ":" + a.getPort());
a.execute();
} catch (Exception ex) {
System.err.println("Nao foi possivel iniciar o servidor. :(");
System.err.println(ex);
ex.printStackTrace();
}
}
}
<file_sep>
ANs = [ ];
DBs = [ ];
UPDATING = false;
function updateData() {
if(UPDATING) {
return;
}
UPDATING = true;
$(".content > div").hide()
$("#content-loading").show()
document.querySelector("#content-data").innerHTML = '<div class="an-add"><a href="#" onclick="newAN(); return false;">Criar Análise</a></div>';
$.ajax({
url: "server/analysis",
cache: false,
method: "GET",
timeout: 30000,
success: function(reqResults) {
try {
reqResults = JSON.parse(reqResults);
ANs = reqResults['analysis'];
DBs = reqResults['dbs'];
for(let i = 0; i < ANs.length; i++) {
db = null;
for(let j = 0; j < DBs.length; j++) {
if(ANs[i].db == DBs[j].id) {
db = DBs[j];
break;
}
}
an_div = document.createElement("div");
an_div.className = "an-item";
an_div.innerHTML = '<h3>Name</h3><span>Status</span>'
an_div.innerHTML += '<a href="#" class="an-edit-link" data-id="' + ANs[i].id + '" onclick="editAN(this); return false;">(editar)</a><p>Description</p>'
an_div.innerHTML += '<div class="an-results"></div>'
document.querySelector("#content-data").appendChild(an_div);
an_div.querySelector("h3").textContent = ANs[i].name;
an_div.querySelector("p").textContent = ANs[i].description;
if(ANs[i].ready) {
an_div.querySelector(".an-results").innerHTML = "Número de tweets: " + db.count;
an_div.querySelector(".an-results").innerHTML += "<br>Número de tweets com poucas interações: " + ANs[i].results["fewinteractions"] + " (" + (100*ANs[i].results["fewinteractions"]/db.count).toFixed(2) + "%)";
an_div.querySelector(".an-results").innerHTML += "<br>Número de contas: " + ANs[i].results["usercount"];
an_div.querySelector(".an-results").innerHTML += "<br>Número de contas recentes: " + ANs[i].results["recentusercount"] + " (" + (100*ANs[i].results["recentusercount"]/ANs[i].results["usercount"]).toFixed(2) + "%)";
an_div.querySelector(".an-results").innerHTML += "<br>Número de contas com perfil padrão: " + ANs[i].results["defaultprofilecount"] + " (" + (100*ANs[i].results["defaultprofilecount"]/ANs[i].results["usercount"]).toFixed(2) + "%)";
an_div.querySelector(".an-results").innerHTML += "<br>Número de contas com foto de perfil padrão: " + ANs[i].results["defaultpicturecount"] + " (" + (100*ANs[i].results["defaultpicturecount"]/ANs[i].results["usercount"]).toFixed(2) + "%)";
an_div.querySelector(".an-results").innerHTML += "<br>Número de contas com poucos 'seguindo': " + ANs[i].results["fewfollowings"] + " (" + (100*ANs[i].results["fewfollowings"]/ANs[i].results["usercount"]).toFixed(2) + "%)";
an_div.querySelector(".an-results").innerHTML += "<br>Número de contas com poucos seguidores: " + ANs[i].results["fewfollowers"] + " (" + (100*ANs[i].results["fewfollowers"]/ANs[i].results["usercount"]).toFixed(2) + "%)";
an_div.querySelector(".an-results").innerHTML += "<br>Número de contas com poucos tweets publicados: " + ANs[i].results["fewstatus"] + " (" + (100*ANs[i].results["fewstatus"]/ANs[i].results["usercount"]).toFixed(2) + "%)";
an_div.querySelector(".an-results").innerHTML += "<br>Número de contas com poucos tweets favoritados: " + ANs[i].results["fewfavorites"] + " (" + (100*ANs[i].results["fewfavorites"]/ANs[i].results["usercount"]).toFixed(2) + "%)";
an_div.querySelector("span").textContent = "Processamento completo (" + db.name + ")";
an_div.querySelector("span").className += " an-item-done";
} else {
an_div.querySelector("span").textContent = "Processamento em progresso (" + db.name + ")";
an_div.querySelector("span").className += " an-item-progress";
}
}
$(".content > div").hide()
$("#content-data").show()
} catch(e) {
$(".content > div").hide()
$("#content-error").show()
}
UPDATING = false;
},
error: function() {
$(".content > div").hide()
$("#content-error").show()
UPDATING = false;
}
});
}
function editAN(linkId) {
let i, an = null;
linkId = linkId.getAttribute("data-id");
for(i = 0; i < ANs.length; i++) {
if(ANs[i].id == linkId) {
an = ANs[i];
break;
}
}
if(an == null) {
return;
}
$(".content > div").hide()
document.querySelector("#content-edit form input[name='id']").value = an.id;
document.querySelector("#content-edit form input[name='name']").value = an.name;
document.querySelector("#content-edit form textarea[name='description']").value = an.description ? an.description : "";
$("#content-edit").show()
}
function saveAN() {
let i, an = null;
anId = document.querySelector("#content-edit form input[name='id']").value;
for(i = 0; i < ANs.length; i++) {
if(ANs[i].id == anId) {
an = ANs[i];
break;
}
}
if(an == null) {
return;
}
UPDATING = true;
$(".content > div").hide()
$("#content-loading").show()
$.ajax({
url: "server/analysis/" + an.id,
cache: false,
method: "POST",
data: $("#content-edit form").serializeArray(),
dataType: "text",
timeout: 30000,
success: function(reqResults) {
UPDATING = false;
updateData();
},
error: function() {
alert("Ocorreu um erro ao tentar editar esta análise!");
UPDATING = false;
updateData();
}
});
}
function removeAN() {
let i, an = null;
anId = document.querySelector("#content-edit form input[name='id']").value;
for(i = 0; i < ANs.length; i++) {
if(ANs[i].id == anId) {
an = ANs[i];
break;
}
}
if(an == null) {
return;
}
if(!confirm("Deseja realmente remover esta análise?")) {
return;
}
UPDATING = true;
$(".content > div").hide()
$("#content-loading").show()
$.ajax({
url: "server/analysis/" + an.id,
cache: false,
method: "DELETE",
timeout: 30000,
success: function(reqResults) {
UPDATING = false;
updateData();
},
error: function() {
alert("Ocorreu um erro ao tentar remover esta análise!");
UPDATING = false;
updateData();
}
});
}
function newAN() {
let i, option;
$(".content > div").hide()
document.querySelector("#content-create form input[name='name']").value = "";
document.querySelector("#content-create form textarea[name='description']").value = "";
document.querySelector("#content-create form select[name='db']").innerHTML = '<option value="" disabled selected>(Base de Dados)</option>';
for(i = 0; i < DBs.length; i++) {
option = document.createElement("option");
option.value = DBs[i].id;
option.textContent = DBs[i].name;
if(!DBs[i].ready) {
option.disabled = true;
}
document.querySelector("#content-create form select[name='db']").appendChild(option);
}
document.querySelector("#content-create form select[name='db']").value = "";
$("#content-create").show()
}
function createAN() {
UPDATING = true;
$(".content > div").hide()
$("#content-loading").show()
$.ajax({
url: "server/analysis",
cache: false,
method: "POST",
data: $("#content-create form").serializeArray(),
dataType: "text",
timeout: 30000,
success: function(reqResults) {
UPDATING = false;
updateData();
},
error: function() {
alert("Ocorreu um erro ao tentar criar esta análise!");
UPDATING = false;
updateData();
}
});
}
function resetForm() {
updateData();
}
function windowLoaded() {
updateData();
//setTimeout('updateData();', 10000);
}
window.onload = windowLoaded;
<file_sep>Flask==2.0.1
kafka-python==2.0.2
mysql-connector-python==8.0.25
tweepy==3.10.0<file_sep># Trabalho Prático
Trabalho Prático de Organização de Arquivos
## Integrantes
* <NAME>
* <NAME>
* <NAME>
* <NAME>
## Organização do Repositório
* [headers](headers): aqui se encontram os arquivos de cabeçalho (_\#include_) utilizados no código.
* [lib](lib): aqui se encontra toda a implementação do trabalho.
- [lib/arvore-b.c](lib/arvore-b.c) implementação do índice árvore-B integrado com um Buffer-Pool com política de substituição SCA (Second-Chance Algorithm).
- [lib/cabecalho.c](lib/cabecalho.c) implementação de leituras e escritas dos cabeçalhos nos arquivos binários.
- [lib/funcionalidades.c](lib/funcionalidades.c) implementação de todas as funcionalidades do trabalho.
* [objects](objects): aqui se encontram objetos de compilação, usados apenas para compilação e nada mais.
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <redblacktree.h>
/*
* ~ <NAME> ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int compare_integer(void *, void *);
void print_integer(void *);
int main(int argc, char **argv){
int i, N, Operation, Aux;
RBT *Tree=RBT_New(sizeof(int), compare_integer, NULL); /* Alocar rubro-negra */
scanf("%d", &N);
for(i=0; i<N; i++){
scanf("%d", &Operation);
switch(Operation){
case 1: /* Inserção */
scanf("%d", &Aux);
RBT_Insert(&Aux, Tree);
break;
case 2: /* Sucessor */
scanf("%d", &Aux);
if(RBT_Successor(&Aux, &Aux, Tree)==1) printf("%d\n", Aux);
else printf("erro\n");
break;
case 3: /* Predecessor */
scanf("%d", &Aux);
if(RBT_Predecessor(&Aux, &Aux, Tree)==1) printf("%d\n", Aux);
else printf("erro\n");
break;
case 4: /* Máximo */
if(RBT_Max(&Aux, Tree)==1) printf("%d\n", Aux);
else printf("erro\n");
break;
case 5: /* Mínimo */
if(RBT_Min(&Aux, Tree)==1) printf("%d\n", Aux);
else printf("erro\n");
break;
case 6: /* Pré-ordem */
RBT_PreOrder(print_integer, Tree);
printf("\n");
break;
case 7: /* Em-ordem */
RBT_InOrder(print_integer, Tree);
printf("\n");
break;
case 8: /* Pós-ordem */
RBT_PostOrder(print_integer, Tree);
printf("\n");
break;
default: /* Operação inválida */
printf("erro\n");
}
}
RBT_Destroy(Tree); /* Destruir rubro-negra */
return EXIT_SUCCESS;
}
int compare_integer(void *PA, void *PB){
/*
* Como criei um TAD genérico, essa função apenas compara dois inteiros.
*/
int *A=PA, *B=PB;
return (*B)-(*A);
}
void print_integer(void *A){
/*
* Como criei um TAD genérico, essa função apenas imprime um inteiro na saída padrão.
*/
printf("%d ", *((int *)A));
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <consts.h>
#include <register.h>
#include <buffer.h>
int R_readH(REG_HEADER *dest, FILE *stream) {
char reg[PAGE_SIZE], *R;
REG_HEADER aux;
int i, n;
if(fseek(stream, 0, SEEK_SET) != 0) {
return 0;
}
if(fread(reg, sizeof(char), PAGE_SIZE, stream) != PAGE_SIZE) {
return 0;
}
R = reg;
aux.status = *R;
R++;
memcpy(&aux.first, R, sizeof(long));
R += sizeof(long) + sizeof(char);
memcpy(aux.desCampos[0], R, sizeof(char) * 40);
R += sizeof(char) * 41;
memcpy(aux.desCampos[1], R, sizeof(char) * 40);
R += sizeof(char) * 41;
memcpy(aux.desCampos[2], R, sizeof(char) * 40);
R += sizeof(char) * 41;
memcpy(aux.desCampos[3], R, sizeof(char) * 40);
R += sizeof(char) * 41;
memcpy(aux.desCampos[4], R, sizeof(char) * 40);
R += sizeof(char) * 41;
memcpy(dest, &aux, sizeof(REG_HEADER));
return 1;
}
int R_writeH(REG_HEADER *src, FILE *stream) {
char reg[PAGE_SIZE], *R, str[41];
int i, n;
memset(reg, LIXO, sizeof(char) * PAGE_SIZE);
if(fseek(stream, 0, SEEK_SET) != 0) {
return 0;
}
R = reg;
memcpy(R, &src->status, sizeof(char));
R++;
memcpy(R, &src->first, sizeof(long));
R += sizeof(long);
memset(str, LIXO, sizeof(char) * 41);
str[0] = 'i';
strcpy(str + 1, src->desCampos[0]);
memcpy(R, str, sizeof(char) * 41);
R += sizeof(char) * 41;
memset(str, LIXO, sizeof(char) * 41);
str[0] = 's';
strcpy(str + 1, src->desCampos[1]);
memcpy(R, str, sizeof(char) * 41);
R += sizeof(char) * 41;
memset(str, LIXO, sizeof(char) * 41);
str[0] = 't';
strcpy(str + 1, src->desCampos[2]);
memcpy(R, str, sizeof(char) * 41);
R += sizeof(char) * 41;
memset(str, LIXO, sizeof(char) * 41);
str[0] = 'n';
strcpy(str + 1, src->desCampos[3]);
memcpy(R, str, sizeof(char) * 41);
R += sizeof(char) * 41;
memset(str, LIXO, sizeof(char) * 41);
str[0] = 'c';
strcpy(str + 1, src->desCampos[4]);
memcpy(R, str, sizeof(char) * 41);
R += sizeof(char) * 41;
if(fwrite(reg, sizeof(char), PAGE_SIZE, stream) != PAGE_SIZE) {
return 0;
}
return 1;
}
int R_read(REG_DATA *dest, FILE *stream) {
char reg[PAGE_SIZE], *R;
REG_DATA aux;
long offset;
int i, n;
memset(reg, LIXO, sizeof(char) * PAGE_SIZE);
while((reg[0] = getc(stream)) == LIXO && reg[0] != EOF); // Se ele tiver lendo lixo (como no finalzinho de uma página por exemplo)
if(reg[0] == EOF) { // Fim do arquivo
return 0;
}
offset = ftell(stream) - sizeof(char);
if(fread(®[1], sizeof(int), 1, stream) != 1) { // Ler tamanho registro
return -1;
}
R = reg;
aux.removed = *R;
aux.byteOffset = offset;
R++;
memcpy(&aux.size, R, sizeof(int));
R += sizeof(int);
if(fread(R, sizeof(char), aux.size, stream) != aux.size) {
return -1;
}
memcpy(&aux.next, R, sizeof(long));
R += sizeof(long);
memcpy(&aux.idServidor, R, sizeof(int));
R += sizeof(int);
memcpy(&aux.salarioServidor, R, sizeof(double));
R += sizeof(double);
memcpy(&aux.telefoneServidor, R, sizeof(char) * 14);
R += sizeof(char) * 14;
memcpy(&n, R, sizeof(int));
R += sizeof(int);
if(*R == 'n') { // Nome não é nulo
R++;
strcpy(aux.nomeServidor, R);
R += n - 1;
memcpy(&n, R, sizeof(int));
R += sizeof(int);
if(*R == 'c') { // Cargo não é nulo
R++;
strcpy(aux.cargoServidor, R);
} else { // Os dois são nulos
aux.cargoServidor[0] = '\0';
}
} else if(*R == 'c') { // Nome é nulo, mas cargo não
aux.nomeServidor[0] = '\0';
R++;
strcpy(aux.cargoServidor, R);
} else { // Os dois são nulos
aux.nomeServidor[0] = '\0';
aux.cargoServidor[0] = '\0';
}
memcpy(dest, &aux, sizeof(REG_DATA));
return 1;
}
int R_write(REG_DATA *src, FILE *stream, long *lastSize) {
char reg[PAGE_SIZE], *R;
int i, n, sn, filledPage;
unsigned long pn;
REG_DATA aux;
memset(reg, LIXO, sizeof(char) * PAGE_SIZE);
n = sizeof(long) + sizeof(int) + sizeof(double) + sizeof(char) * 14;
if(strcmp(src->nomeServidor, "") != 0) {
n += strlen(src->nomeServidor) + sizeof(int) + 2;
}
if(strcmp(src->cargoServidor, "") != 0) {
n += strlen(src->cargoServidor) + sizeof(int) + 2;
}
pn = B_offset(stream);
if(pn < 0) {
return -1;
}
filledPage = 1;
pn = PAGE_SIZE - pn;
if(pn < n + sizeof(int) + sizeof(char)) { // Registro não cabe nessa página, preencher com lixo e ir pra próxima pra poder escrever
if(fwrite(reg, sizeof(char), pn, stream) != pn) {
return -1;
}
if(*lastSize >= 0) {
fseek(stream, -1 * ((*lastSize) + sizeof(int) + pn), SEEK_CUR);
sn = pn + (*lastSize);
fwrite(&sn, sizeof(int), 1, stream);
fseek(stream, 0, SEEK_END);
filledPage = 2;
}
}
src->removed = R_NAO_REMOVIDO;
src->size = n;
src->next = -1;
R = reg;
memcpy(R, &src->removed, sizeof(char));
R += sizeof(char);
memcpy(R, &src->size, sizeof(int));
R += sizeof(int);
memcpy(R, &src->next, sizeof(long));
R += sizeof(long);
memcpy(R, &src->idServidor, sizeof(int));
R += sizeof(int);
memcpy(R, &src->salarioServidor, sizeof(double));
R += sizeof(double);
if(src->telefoneServidor[0] == '\0') {
memset(src->telefoneServidor + sizeof(char), LIXO, sizeof(char) * 13);
}
memcpy(R, &src->telefoneServidor, sizeof(char) * 14);
R += sizeof(char) * 14;
if(strcmp(src->nomeServidor, "") != 0) {
sn = strlen(src->nomeServidor) + 2;
memcpy(R, &sn, sizeof(int));
R += sizeof(int);
*R = 'n';
R++;
strcpy(R, src->nomeServidor);
R += sn - 1;
*(R - 1) = '\0';
}
if(strcmp(src->cargoServidor, "") != 0) {
sn = strlen(src->cargoServidor) + 2;
memcpy(R, &sn, sizeof(int));
R += sizeof(int);
*R = 'c';
R++;
strcpy(R, src->cargoServidor);
R += sn - 1;
*(R - 1) = '\0';
}
*lastSize = n;
src->byteOffset = ftell(stream);
if(fwrite(reg, sizeof(char), n + sizeof(int) + sizeof(char), stream) != n + sizeof(int) + sizeof(char)) {
return -1;
}
return filledPage;
}
int R_rewriteBack(REG_DATA *src, FILE *stream) {
char reg[PAGE_SIZE], *R;
unsigned long pn;
REG_DATA aux;
int i, /*n,*/ lastn, sn;
memset(reg, LIXO, sizeof(char) * PAGE_SIZE);
lastn = src->size + sizeof(int) + sizeof(char);
if(fseek(stream, src->byteOffset, SEEK_SET) != 0) {
return -1;
}
R = reg;
memcpy(R, &src->removed, sizeof(char));
R += sizeof(char);
memcpy(R, &src->size, sizeof(int));
R += sizeof(int);
memcpy(R, &src->next, sizeof(long));
R += sizeof(long);
if(src->removed == R_NAO_REMOVIDO) {
memcpy(R, &src->idServidor, sizeof(int));
R += sizeof(int);
memcpy(R, &src->salarioServidor, sizeof(double));
R += sizeof(double);
if(src->telefoneServidor[0] == '\0') {
memset(src->telefoneServidor + sizeof(char), LIXO, sizeof(char) * 13);
}
memcpy(R, &src->telefoneServidor, sizeof(char) * 14);
R += sizeof(char) * 14;
if(strcmp(src->nomeServidor, "") != 0) {
sn = strlen(src->nomeServidor) + 2;
memcpy(R, &sn, sizeof(int));
R += sizeof(int);
*R = 'n';
R++;
strcpy(R, src->nomeServidor);
R += sn - 1;
*(R - 1) = '\0';
}
if(strcmp(src->cargoServidor, "") != 0) {
sn = strlen(src->cargoServidor) + 2;
memcpy(R, &sn, sizeof(int));
R += sizeof(int);
*R = 'c';
R++;
strcpy(R, src->cargoServidor);
R += sn - 1;
*(R - 1) = '\0';
}
}
if(fwrite(reg, sizeof(char), lastn, stream) != lastn) {
return -1;
}
return 1;
}
int R_calculateSize(REG_DATA *r) {
int n;
n = sizeof(long) + sizeof(int) + sizeof(double) + sizeof(char) * 14;
if(strcmp(r->nomeServidor, "") != 0) {
n += strlen(r->nomeServidor) + sizeof(int) + 2;
}
if(strcmp(r->cargoServidor, "") != 0) {
n += strlen(r->cargoServidor) + sizeof(int) + 2;
}
return n;
}
int R_writePad(FILE *stream) { // OBSOLETA: faz o padding de LIXO na última página do arquivo binário.
char reg[PAGE_SIZE];
unsigned long pn;
memset(reg, '@', sizeof(char) * PAGE_SIZE);
pn = B_offset(stream);
if(pn < 0) {
return -1;
}
pn = PAGE_SIZE - pn;
if(pn > 0) {
if(fwrite(reg, sizeof(char), pn, stream) != pn) {
return -1;
}
return 1;
}
return 1;
}
<file_sep>#include <stdlib.h>
#include <string.h>
/*
* ~ Filas ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
struct __queue_node_t {
void *value;
struct __queue_node_t *next;
};
struct __queue_t {
struct __queue_node_t *first, *last;
unsigned long nitems;
size_t memsize;
};
struct __priority_queue_t {
struct __queue_node_t *first, *last;
int (*fcmp)(void *, void*);
unsigned long nitems;
size_t memsize;
};
struct __queue_t *Q_New(size_t memsize){
struct __queue_t *Aux;
if(memsize < 1) return NULL;
Aux = (struct __queue_t *) malloc(sizeof(struct __queue_t));
Aux->first = Aux->last = NULL;
Aux->memsize = memsize;
Aux->nitems = 0;
return Aux;
}
long Q_Size(struct __queue_t *Q){
if(Q == NULL) return -1;
return Q->nitems;
}
int Q_Push(void *X, struct __queue_t *Q){
struct __queue_node_t *Aux;
if(Q == NULL || X == NULL) return 0;
Aux = (struct __queue_node_t *) malloc(sizeof(struct __queue_node_t));
Aux->value = (void *) malloc(Q->memsize);
Aux->next = NULL;
memcpy(Aux->value, X, Q->memsize);
if(Q->nitems > 0)
Q->last->next = Aux;
else
Q->first = Aux;
Q->last = Aux;
Q->nitems++;
return 1;
}
int Q_Front(void *X, struct __queue_t *Q){
if(Q == NULL || X == NULL) return 0;
if(Q->nitems < 1) return 0;
memcpy(X, Q->first->value, Q->memsize);
return 1;
}
int Q_Back(void *X, struct __queue_t *Q){
if(Q == NULL || X == NULL) return 0;
if(Q->nitems < 1) return 0;
memcpy(X, Q->last->value, Q->memsize);
return 1;
}
int Q_Shift(void *X, struct __queue_t *Q){
struct __queue_node_t *Aux;
if(Q == NULL) return 0;
if(Q->nitems < 1) return 0;
if(X != NULL)
memcpy(X, Q->first->value, Q->memsize);
Aux = Q->first;
Q->first = Q->first->next;
Q->nitems--;
if(Q->nitems < 1)
Q->last = NULL;
free(Aux->value);
free(Aux);
return 1;
}
void Q_Destroy(struct __queue_t *Q){
struct __queue_node_t *P, *Aux;
if(Q == NULL) return;
P = Q->first;
while(P != NULL) {
Aux = P;
P = P->next;
free(Aux->value);
free(Aux);
}
free(Q);
}
struct __priority_queue_t *PQ_New(size_t memsize, int (*fcmp)(void *, void *)){
struct __priority_queue_t *Aux;
if(memsize < 1 || fcmp == NULL) return NULL;
Aux = (struct __priority_queue_t *) malloc(sizeof(struct __priority_queue_t));
Aux->first = Aux->last = NULL;
Aux->memsize = memsize;
Aux->fcmp = fcmp;
Aux->nitems = 0;
return Aux;
}
long PQ_Size(struct __priority_queue_t *Q){
if(Q == NULL) return -1;
return Q->nitems;
}
int PQ_Push(void *X, struct __priority_queue_t *Q){
struct __queue_node_t *Aux, *P, **Last;
if(Q == NULL || X == NULL) return 0;
Aux = (struct __queue_node_t *) malloc(sizeof(struct __queue_node_t));
Aux->value = (void *) malloc(Q->memsize);
memcpy(Aux->value, X, Q->memsize);
if(Q->nitems < 1) {
Aux->next = NULL;
Q->first = Q->last = Aux;
} else if(Q->fcmp(Aux->value, Q->last->value) <= 0){
Aux->next = NULL;
Q->last = Q->last->next = Aux;
} else {
P = Q->first;
Last = &Q->first;
while(P != NULL) {
if(Q->fcmp(Aux->value, P->value) > 0)
break;
Last = &P->next;
P = P->next;
}
Aux->next = P;
*Last = Aux;
}
Q->nitems++;
return 1;
}
int PQ_Front(void *X, struct __priority_queue_t *Q){
if(Q == NULL || X == NULL) return 0;
if(Q->nitems < 1) return 0;
memcpy(X, Q->first->value, Q->memsize);
return 1;
}
int PQ_Back(void *X, struct __priority_queue_t *Q){
if(Q == NULL || X == NULL) return 0;
if(Q->nitems < 1) return 0;
memcpy(X, Q->last->value, Q->memsize);
return 1;
}
int PQ_Shift(void *X, struct __priority_queue_t *Q){
struct __queue_node_t *Aux;
if(Q == NULL) return 0;
if(Q->nitems < 1) return 0;
if(X != NULL)
memcpy(X, Q->first->value, Q->memsize);
Aux = Q->first;
Q->first = Q->first->next;
Q->nitems--;
if(Q->nitems < 1)
Q->last = NULL;
free(Aux->value);
free(Aux);
return 1;
}
void PQ_Destroy(struct __priority_queue_t *Q){
struct __queue_node_t *P, *Aux;
if(Q == NULL) return;
P = Q->first;
while(P != NULL) {
Aux = P;
P = P->next;
free(Aux->value);
free(Aux);
}
free(Q);
}
<file_sep>import csv
import sys
import random
import unicodedata
import re
csvDel = ',' # Delimitador do CSV de saída
maxCount = 5000 #maximo de itens
Null1 = 100 # Qtd de campos NOME nulos
Null2 = 100 # Qtd de campos CARGO nulos
Null3 = 200 # Qtd de campos TELEFONE nulos
Null4 = 500 # Qtd de campos SALARIO nulos
tamVariaveis = 2000 # Tamanho maximo total dos dois campos variaveis
if len(sys.argv) != 3 and len(sys.argv) != 4:
print("Passe o nome do arquivo csv de entrada de cadastro, de salarios/remoneracoes, e o nome do inicio do csv de saida respectivamente junto ao terminal.")
print("\tpython3 codigo.py CADASTRO.CSV SALARIOS.CSV SAIDA")
sys.exit()
def gerarFone():
phone = '('
phone += str(random.randint(11, 99)) # ddds disponiveis no BR
phone += ')9' # celulares comecam com 9
phone += str(random.randint(8000, 9999)) # 4 digitos
phone += '-'
phone += str(random.randint(1000, 9999)) # +4 digitos
return phone
def truncarCamposVariaveis(nome, cargo):
# remove acentuação e trunca tamanho
nome = ''.join(c for c in unicodedata.normalize('NFD', nome)
if unicodedata.category(c) != 'Mn')
cargo = ''.join(c for c in unicodedata.normalize('NFD', cargo)
if unicodedata.category(c) != 'Mn')
nome = nome.upper().replace('Ç', 'C').replace(csvDel, '').strip()
cargo = cargo.upper().replace('Ç', 'C').replace(csvDel, '').strip()
nome = re.sub(r'[^a-zA-Z0-9\-\_\s\.]+', ' ', nome)
cargo = re.sub(r'[^a-zA-Z0-9\-\_\s\.]+', ' ', cargo)
if len(nome+cargo) <= tamVariaveis:
return [nome, cargo]
i = 0
while len(nome+cargo) > tamVariaveis:
nomeT = re.split(r'\s+', nome)
cargoT = re.split(r'\s+', cargo)
if i > 30 or len(nomeT) < 2 or len(cargoT) < 2:
if i > 30:
print("parece que um campo não foi devidamente trucado")
nome = nome[:int(tamVariaveis/2)]
cargo = cargo[:int(tamVariaveis/2)]
break
i += 1
rnd = random.randint(1, len(nomeT) - 1)
nomeT[rnd] = nomeT[rnd][0]
rnd = random.randint(1, len(cargoT) - 1)
cargoT[rnd] = cargoT[rnd][0]
nome = ' '.join(nomeT)
cargo = ' '.join(cargoT)
return [nome, cargo]
listI = { }
ignore = True
count = 0
with open(sys.argv[1]) as csvfile: # cadastro de servidores
spamreader = csv.reader(csvfile, delimiter=';')
for row in spamreader:
if ignore:
ignore = False
continue
if not row[0] or row[0].lower().strip().startswith('sem '): #id
continue
if not row[1] or row[1].lower().strip().startswith('sem'): #nome
continue
if not row[4] or row[4].lower().strip().startswith('sem') or row[4].lower().strip().startswith('inv'): #cargo
continue
listI[row[0]] = [ row[0], row[1], row[4], "", 0 ]
count += 1
i = 0
count = 0
with open(sys.argv[2]) as csvfile: # salarios
spamreader = csv.reader(csvfile, delimiter=';')
for row in spamreader:
if row[2] in listI:
if not row[5] or re.search(r'^\s*[0-9\.\,]+\s*$', row[5]) is None:
listI[row[2]][4] = -1
else:
listI[row[2]][4] = float(row[5].replace(",", "."))
count += 1
i += 1
listValues = listI.values()
listI = list(listValues)
random.shuffle(listI)
listI = listI[:maxCount]
for item in listI:
item[3] = gerarFone()
camposVariaveis = truncarCamposVariaveis(item[1], item[2])
item[1] = camposVariaveis[0]
item[2] = camposVariaveis[1]
i = 0
for item in listI:
if i >= Null1:
break
i += 1
item[1] = ""
random.shuffle(listI)
i = 0
for item in listI:
if i >= Null2:
break
i += 1
item[2] = ""
random.shuffle(listI)
i = 0
for item in listI:
if i >= Null3:
break
i += 1
item[3] = ""
random.shuffle(listI)
i = 0
for item in listI:
if i >= Null4:
break
i += 1
item[4] = -1
random.shuffle(listI)
listI.insert(0, ['idServidor', 'nome', 'cargo', 'telefone', 'salario'])
if len(sys.argv) != 4:
print(listI)
sys.exit()
# == TURMA A
for item in listI:
nome = item[1]
cargo = item[2]
telefone = item[3]
salario = item[4]
item[1] = salario
item[2] = telefone
item[3] = nome
item[4] = cargo
with open(sys.argv[3] + "A.csv", 'w') as csvfile: # salvar
spamwriter = csv.writer(csvfile, delimiter=csvDel, quotechar='', escapechar='\\', quoting=csv.QUOTE_NONE)
spamwriter.writerows(listI)
# == TURMA B
for item in listI:
nome = item[3]
cargo = item[4]
telefone = item[2]
salario = item[1]
item[1] = telefone
item[2] = salario
item[3] = cargo
item[4] = nome
with open(sys.argv[3] + "B.csv", 'w') as csvfile: # salvar
spamwriter = csv.writer(csvfile, delimiter=csvDel, quotechar='', escapechar='\\', quoting=csv.QUOTE_NONE)
spamwriter.writerows(listI)
<file_sep>#include <stdlib.h>
#include <string.h>
#include <unordered_map>
#include <iostream>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
int main(int argc, char **argv) {
int N, i, k, val;
int counter[6];
unordered_map<int, int> possibleValues = {
{4, 0},
{8, 1},
{15, 2},
{16, 3},
{23, 4},
{42, 5}
};
cin >> N;
memset(counter, 0, sizeof(int) * 6);
for(k = 0; k < N; k++) {
cin >> val;
i = possibleValues[val];
if(i == 0) {
counter[i]++;
} else if(counter[i - 1] > 0) {
counter[i - 1]--;
counter[i]++;
}
}
val = counter[5] * 6;
cout << (N - val) << endl;
return EXIT_SUCCESS;
}
<file_sep>import sys
import csv
#
# ~ Contador de Feedback Ganesh ~
# Este programa vai fazer a contagem dos feedbacks recebidos do Ganesh e calcular
# a percentagem.
# Ele recebe como entrada o arquivo *.CSV da tabela dos feedbacks separado
# por COMMA.
#
# <NAME> (017)
# Secretário (2018.2)
# <EMAIL>
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
COMMA = ',' # Delimitador de coluna do *.CSV
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Este programa calcula o Feedback para as atividades do Ganesh com base na tabela disponível no Google Drive gerada pelo formulário.")
print("É necessário baixar essa tabela e utilizar a COMMA como separador.")
print("Uso do programa:")
print("\tpython3 " + sys.argv[0] + " CAMINHO_CSV [HEADER]")
print("Onde:")
print("\tCAMINHO_CSV -> caminho para o arquivo *.CSV da tabela com colunas separadas por COMMA")
print("\t[HEADER] -> opcional: se for igual a 1, a primeira linha da tabela será ignorada")
sys.exit(0);
with open(sys.argv[1], mode='r') as fStream:
lines = csv.reader(fStream, delimiter=COMMA)
lines = list(lines)
data = { }
if len(sys.argv) == 3:
if sys.argv[2] == '1':
del lines[0]
for response in lines:
if not response[1] in data:
data[response[1]] = [0, {}, {}, {}, [], []]
data[response[1]][0] += 1
if response[2] in data[response[1]][1]:
data[response[1]][1][response[2]] += 1
else:
data[response[1]][1][response[2]] = 1
if response[3] in data[response[1]][2]:
data[response[1]][2][response[3]] += 1
else:
data[response[1]][2][response[3]] = 1
if response[4] in data[response[1]][3]:
data[response[1]][3][response[4]] += 1
else:
data[response[1]][3][response[4]] = 1
if response[5]:
data[response[1]][4].append(response[5])
if response[6]:
data[response[1]][5].append(response[6])
for dataKey in data:
print("== " + dataKey + ": " + str(data[dataKey][0]) + " feedbacks recebidos ==")
print("Gostou do tema da atividade?")
for liked in sorted(data[dataKey][1]):
print("\t- " + liked + ": " + str(data[dataKey][1][liked]) + " (" + str(round(data[dataKey][1][liked]*100/data[dataKey][0], 2)) + "%)")
print("O quanto você entendeu do assunto?")
for score in sorted(data[dataKey][2]):
print("\t- " + score + "/5: " + str(data[dataKey][2][score]) + " (" + str(round(data[dataKey][2][score]*100/data[dataKey][0], 2)) + "%)")
print("Vale a pena revisar o assunto em reuniões futuras?")
for review in sorted(data[dataKey][3]):
print("\t- " + review + ": " + str(data[dataKey][3][review]) + " (" + str(round(data[dataKey][3][review]*100/data[dataKey][0], 2)) + "%)")
print("Algum assunto que gostaria para próximas atividades ou reuniões?")
if len(data[dataKey][4]) < 1:
print("\t(nada)")
for subject in data[dataKey][4]:
print("\t```\"" + subject + "\"```")
print("Alguma observação ou sugestão de mudança?")
if len(data[dataKey][5]) < 1:
print("\t(nada)")
for suggestion in data[dataKey][5]:
print("\t```\"" + suggestion + "\"```")
print()
<file_sep>#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Main {
private: vector<int> Data;
void print(bool reverse){
if(!reverse){
vector<int>::iterator data_search;
for(data_search = Data.begin(); data_search != Data.end(); data_search++){
printf("%d\n", *data_search);
}
}else{
vector<int>::reverse_iterator data_search;
for(data_search = Data.rbegin(); data_search != Data.rend(); data_search++){
printf("%d\n", *data_search);
}
}
}
void print(){
print(false);
}
public: Main(){
int Aux;
while(scanf("%d", &Aux) > 0){
Data.push_back(Aux);
}
//vector<int>::iterator data_search;
sort(Data.begin(), Data.end());
print();
printf("\n");
print(true);
}
};
int main(){
Main a;
return 0;
}<file_sep>#include <stdlib.h>
#include <iostream>
#include <vector>
#define PRIME_TABLE_MAXSIZE 3001
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
vector<ll> gen_primes_table() {
bool isPrime;
ll i, j;
vector<ll> primeList = vector<ll>();
primeList.push_back(2);
for(i = 3; i <= PRIME_TABLE_MAXSIZE; i += 2) {
isPrime = true;
for(auto prime = primeList.begin(); prime != primeList.end(); prime++) {
if(i % *prime != 0) {
continue;
}
isPrime = false;
break;
}
if(isPrime) {
primeList.push_back(i);
}
}
return primeList;
}
void testCase() {
ll i, N, countOfPrimes, countOfAlmostPrimes;
cin >> N;
countOfAlmostPrimes = 0;
vector<ll> primeList = gen_primes_table();
for(i = 1; i <= N; i++) {
countOfPrimes = 0;
for(auto prime = primeList.begin(); prime != primeList.end(); prime++) {
if(*prime > i) {
break;
}
if(i % *prime != 0) {
continue;
}
countOfPrimes++;
}
if(countOfPrimes == 2) {
countOfAlmostPrimes++;
}
}
cout << countOfAlmostPrimes << endl;
}
int main(int argc, char **argv) {
ll T;
T = 1;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep># Objeto
Objeto obtido do website [free3d](https://free3d.com/pt/3d-model/beretta-pistol-459996.html): licença para uso pessoal.
<file_sep>
#
# ~ Sliding Puzzle ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -Wall
objects/main.o: main.c objects/SlidingPuzzle.o headers/SlidingPuzzle.h
gcc -c -o objects/main.o main.c -Wall -I headers
objects/SlidingPuzzle.o: lib/SlidingPuzzle.c
gcc -c -o objects/SlidingPuzzle.o lib/SlidingPuzzle.c -Wall
run: Prog
./Prog
clean:
rm Prog objects/*.o<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int i;
char str[2000];
fgets(str,sizeof(str),stdin);
for(i=0;i<strlen(str);i++){
if((str[i]>=97) && (str[i]<=122)){
str[i]=str[i]-32;
}
}
printf("%s",str);
return EXIT_SUCCESS;
}<file_sep># Objeto
Objeto de domínio público. Textura obtida do website BlenderSwap (https://www.blendswap.com/blend/3213): licença CC-0.
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "fornecido.h"
#include "consts.h"
#include "register.h"
#include "register2.h"
#include "index.h"
#include "object-to-int.h"
#include "deque.h"
typedef struct __CAMPO_BUSCA {
char nomeCampo[100];
char valorCampo[100];
struct __CAMPO_BUSCA *next;
} CAMPO_BUSCA;
typedef struct __GRAFO_ID {
int idPessoa;
char nomePessoa[100];
} GRAFO_ID;
int busca_match(REG_DATA *reg, CAMPO_BUSCA *campo) {
while(campo != NULL) {
if(reg->removed == R_REMOVIDO && strcmp(campo->nomeCampo, "RRN") != 0) {
campo = campo->next;
continue;
}
if(strcmp(campo->nomeCampo, "idPessoa") == 0) {
if(atoi(campo->valorCampo) == reg->idPessoa) {
return 1;
}
} else if(strcmp(campo->nomeCampo, "nomePessoa") == 0) {
if(strcmp(campo->valorCampo, reg->nomePessoa) == 0) {
return 1;
}
} else if(strcmp(campo->nomeCampo, "idadePessoa") == 0) {
if(campo->valorCampo[0] == '\0' && reg->idadePessoa < 0) {
return 1;
} else if(campo->valorCampo[0] != '\0' && atoi(campo->valorCampo) == reg->idadePessoa) {
return 1;
}
} else if(strcmp(campo->nomeCampo, "twitterPessoa") == 0) {
if(strcmp(campo->valorCampo, reg->twitterPessoa) == 0) {
return 1;
}
} else if(strcmp(campo->nomeCampo, "RRN") == 0) {
if(atoi(campo->valorCampo) == reg->RRN) {
return 1;
}
} else if(strcmp(campo->nomeCampo, "removido") == 0) {
if(reg->removed == R_REMOVIDO) {
return 1;
}
} else if(strcmp(campo->nomeCampo, "true") == 0) {
return 1;
}
campo = campo->next;
}
return 0;
}
int busca_replace(REG_DATA *reg, CAMPO_BUSCA *campo) {
while(campo != NULL) {
if(reg->removed == R_REMOVIDO) {
campo = campo->next;
continue;
}
if(strcmp(campo->nomeCampo, "idPessoa") == 0) {
reg->idPessoa = atoi(campo->valorCampo);
} else if(strcmp(campo->nomeCampo, "nomePessoa") == 0) {
strcpy(reg->nomePessoa, campo->valorCampo);
} else if(strcmp(campo->nomeCampo, "idadePessoa") == 0) {
if(campo->valorCampo[0] == '\0') {
reg->idadePessoa = -1;
} else {
reg->idadePessoa = atoi(campo->valorCampo);
}
} else if(strcmp(campo->nomeCampo, "twitterPessoa") == 0) {
strcpy(reg->twitterPessoa, campo->valorCampo);
} else if(strcmp(campo->nomeCampo, "removido") == 0) {
reg->removed = R_REMOVIDO;
}
campo = campo->next;
}
}
int ordena_comparador(REG2_DATA *A, REG2_DATA *B) {
if(A->idPessoaQueSegue != B->idPessoaQueSegue) {
return A->idPessoaQueSegue - B->idPessoaQueSegue;
}
if(A->idPessoaQueESeguida != B->idPessoaQueESeguida) {
return A->idPessoaQueESeguida - B->idPessoaQueESeguida;
}
if(strcmp(A->dataInicioQueSegue, B->dataInicioQueSegue) != 0) {
return strcmp(A->dataInicioQueSegue, B->dataInicioQueSegue);
}
return strcmp(A->dataFimQueSegue, B->dataFimQueSegue);
}
int grafo_comparador(GRAFO_ID *A, GRAFO_ID *B) {
return A->idPessoa - B->idPessoa;
}
void f1_readCsv(char *csvPath, char *dataPath, char *indexPath) {
FILE *csvStream, *fStream;
REG_HEADER header;
REG_DATA reg;
IND_T *index;
char aux[50];
if((csvStream = fopen(csvPath, "r")) == NULL) {
printf("Falha no carregamento do arquivo.\n");
return;
}
if((fStream = fopen(dataPath, "wb")) == NULL) {
printf("Falha no carregamento do arquivo.\n");
fclose(csvStream);
return;
}
if((index = I_init(NULL)) == NULL) {
printf("Falha no carregamento do arquivo.\n");
fclose(csvStream);
fclose(fStream);
return;
}
header.status = STATUS_INCONSISTENTE;
header.quantidadePessoas = 0;
R_writeH(&header, fStream);
fscanf(csvStream, "%*[^\r\n]"); /* Pular primeira linha. */
while(fscanf(csvStream, "%d%*c", ®.idPessoa) == 1) {
if(fscanf(csvStream, "%[^,]", reg.nomePessoa) != 1) {
reg.nomePessoa[0] = '\0';
}
if(fscanf(csvStream, "%*c%[^,]", aux) == 1) {
reg.idadePessoa = atoi(aux);
} else {
reg.idadePessoa = -1;
}
fscanf(csvStream, "%*c%s", reg.twitterPessoa);
R_write(®, fStream);
I_push(®, index);
header.quantidadePessoas++;
}
header.status = STATUS_CONSISTENTE;
R_writeH(&header, fStream);
fclose(csvStream);
fclose(fStream);
if(I_write(index, indexPath) == 0) {
printf("Falha no carregamento do arquivo.\n");
} else {
binarioNaTela1(dataPath, indexPath);
}
I_destroy(index);
}
void f2_listAll(char *dataPath) {
REG_HEADER header;
FILE *fStream;
REG_DATA reg;
char found;
if((fStream = fopen(dataPath, "rb")) == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
if(R_readH(&header, fStream) == 0 || header.status == STATUS_INCONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
fclose(fStream);
return;
}
found = 0;
while(R_read(®, fStream) == 1) {
if(reg.removed == R_REMOVIDO) {
continue;
}
R_print(®);
found = 1;
}
if(found == 0) {
printf("Registro inexistente.\n");
}
fclose(fStream);
}
void f3_search(char *dataPath, char *indexPath) {
CAMPO_BUSCA criterio;
REG_HEADER header;
FILE *fStream;
IND_DATA *RRN;
REG_DATA reg;
IND_T *index;
char found;
if((fStream = fopen(dataPath, "rb")) == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
if(R_readH(&header, fStream) == 0 || header.status == STATUS_INCONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
fclose(fStream);
return;
}
if((index = I_init(indexPath)) == NULL) {
printf("Falha no processamento do arquivo.\n");
fclose(fStream);
return;
}
criterio.next = NULL;
scanf("%s", criterio.nomeCampo);
scan_quote_string(criterio.valorCampo);
if(strcmp(criterio.nomeCampo, "idPessoa") == 0) { /* Caso especial: usar índice primário. */
if((RRN = I_find(atoi(criterio.valorCampo), index)) == NULL) {
printf("Registro inexistente.\n");
I_destroy(index);
fclose(fStream);
return;
}
if(fseek(fStream, 64 + 64 * RRN->RRN, SEEK_SET) != 0 || R_read(®, fStream) != 1 || reg.removed == R_REMOVIDO) {
printf("Registro inexistente.\n");
I_destroy(index);
fclose(fStream);
return;
}
R_print(®);
I_destroy(index);
fclose(fStream);
return;
}
I_destroy(index);
found = 0;
while(R_read(®, fStream) == 1) {
if(reg.removed == R_REMOVIDO || busca_match(®, &criterio) == 0) {
continue;
}
R_print(®);
found = 1;
}
if(found == 0) {
printf("Registro inexistente.\n");
}
fclose(fStream);
}
void f4_insert(char *dataPath, char *indexPath) {
REG_HEADER header;
FILE *fStream;
REG_DATA reg;
IND_T *index;
char aux[50];
int i, N;
if((fStream = fopen(dataPath, "rb+")) == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
if(R_readH(&header, fStream) == 0 || header.status == STATUS_INCONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
fclose(fStream);
return;
}
if((index = I_init(indexPath)) == NULL) {
printf("Falha no processamento do arquivo.\n");
fclose(fStream);
return;
}
/* Torna inconsistente */
header.status = STATUS_INCONSISTENTE;
R_writeH(&header, fStream);
scanf("%d", &N);
fseek(fStream, 0, SEEK_END);
for(i = 0; i < N; i++) {
scanf("%d", ®.idPessoa);
scan_quote_string(reg.nomePessoa);
scan_quote_string(aux);
if(aux[0] == '\0') {
reg.idadePessoa = -1;
} else {
reg.idadePessoa = atoi(aux);
}
scan_quote_string(reg.twitterPessoa);
R_write(®, fStream);
I_push(®, index);
header.quantidadePessoas++;
}
/* Torna consistente */
header.status = STATUS_CONSISTENTE;
R_writeH(&header, fStream);
I_rewrite(index);
I_destroy(index);
fclose(fStream);
binarioNaTela1(dataPath, indexPath);
}
void f5_update(char *dataPath, char *indexPath) {
CAMPO_BUSCA *criterios, **substituicoes;
REG_HEADER header;
int i, j, N, M;
FILE *fStream;
REG_DATA reg;
IND_T *index;
char found;
if((fStream = fopen(dataPath, "rb+")) == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
if(R_readH(&header, fStream) == 0 || header.status == STATUS_INCONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
fclose(fStream);
return;
}
if((index = I_init(indexPath)) == NULL) {
printf("Falha no processamento do arquivo.\n");
fclose(fStream);
return;
}
I_destroy(index);
if((index = I_init(NULL)) == NULL) {
printf("Falha no processamento do arquivo.\n");
fclose(fStream);
return;
}
scanf("%d", &N);
criterios = (CAMPO_BUSCA *) malloc(sizeof(CAMPO_BUSCA) * N);
substituicoes = (CAMPO_BUSCA **) malloc(sizeof(CAMPO_BUSCA *) * N);
for(i = 0; i < N; i++) {
scanf("%s", criterios[i].nomeCampo);
scan_quote_string(criterios[i].valorCampo);
scanf("%d", &M);
criterios[i].next = NULL;
if(M < 1) {
substituicoes[i] = NULL;
continue;
}
substituicoes[i] = (CAMPO_BUSCA *) malloc(sizeof(CAMPO_BUSCA) * M);
for(j = 0; j < M; j++) {
scanf("%s", substituicoes[i][j].nomeCampo);
scan_quote_string(substituicoes[i][j].valorCampo);
}
for(j = 0; j < M - 1; j++) {
substituicoes[i][j].next = &substituicoes[i][j + 1];
}
substituicoes[i][M - 1].next = NULL;
}
/* Torna inconsistente */
header.status = STATUS_INCONSISTENTE;
R_writeH(&header, fStream);
header.quantidadePessoas = 0;
while(R_read(®, fStream) == 1) {
if(reg.removed == R_REMOVIDO) {
continue;
}
found = 0;
for(i = 0; i < N; i++) {
if(busca_match(®, &criterios[i]) == 1) {
found = 1;
busca_replace(®, substituicoes[i]);
}
}
if(found == 1) {
R_rewrite(®, fStream);
}
if(reg.removed == R_REMOVIDO) {
continue;
}
I_push(®, index);
header.quantidadePessoas++;
}
for(i = 0; i < N; i++) {
free(substituicoes[i]);
}
free(substituicoes);
free(criterios);
/* Torna consistente */
header.status = STATUS_CONSISTENTE;
R_writeH(&header, fStream);
I_write(index, indexPath);
I_destroy(index);
fclose(fStream);
binarioNaTela1(dataPath, indexPath);
}
void f6_readCsv(char *csvPath, char *dataPath) {
FILE *csvStream, *fStream;
REG2_HEADER header;
REG2_DATA reg;
if((csvStream = fopen(csvPath, "r")) == NULL) {
printf("Falha no carregamento do arquivo.\n");
return;
}
if((fStream = fopen(dataPath, "wb")) == NULL) {
printf("Falha no carregamento do arquivo.\n");
fclose(csvStream);
return;
}
header.status = STATUS_INCONSISTENTE;
header.quantidadeSeguidores = 0;
R2_writeH(&header, fStream);
fscanf(csvStream, "%*[^\r\n]"); /* Pular primeira linha. */
while(fscanf(csvStream, "%d%*c%d%*c%[^,]%*c%[^,]%*c%s", ®.idPessoaQueSegue, ®.idPessoaQueESeguida, reg.grauAmizade, reg.dataInicioQueSegue, reg.dataFimQueSegue) == 5) {
R2_write(®, fStream);
header.quantidadeSeguidores++;
}
header.status = STATUS_CONSISTENTE;
R2_writeH(&header, fStream);
fclose(csvStream);
fclose(fStream);
binarioNaTela2(dataPath);
}
void f7_sort(char *dataPath, char *sortedDataPath) {
FILE *fStream, *sortedStream;
REG2_HEADER header;
REG2_DATA *reg;
int i;
if((fStream = fopen(dataPath, "rb")) == NULL) {
printf("Falha no carregamento do arquivo.\n");
return;
}
if(R2_readH(&header, fStream) == 0 || header.status == STATUS_INCONSISTENTE) {
printf("Falha no carregamento do arquivo.\n");
fclose(fStream);
return;
}
reg = NULL;
if((header.quantidadeSeguidores > 0) && (reg = (REG2_DATA *) malloc(sizeof(REG2_DATA) * header.quantidadeSeguidores)) == NULL) {
printf("Falha no carregamento do arquivo.\n");
fclose(fStream);
return;
}
if((sortedStream = fopen(sortedDataPath, "wb")) == NULL) {
printf("Falha no carregamento do arquivo.\n");
fclose(fStream);
return;
}
header.status = STATUS_INCONSISTENTE;
R2_writeH(&header, sortedStream);
fseek(fStream, 32, SEEK_SET);
for(i = 0; R2_read(®[i], fStream) == 1; ) {
if(reg[i].removed == R_NAO_REMOVIDO) {
i += 1;
}
}
fclose(fStream);
qsort(reg, header.quantidadeSeguidores, sizeof(REG2_DATA), (int (*)(const void *, const void *)) ordena_comparador);
fseek(sortedStream, 32, SEEK_SET);
for(i = 0; i < header.quantidadeSeguidores; i++) {
R2_write(®[i], sortedStream);
}
header.status = STATUS_CONSISTENTE;
R2_writeH(&header, sortedStream);
fclose(sortedStream);
binarioNaTela2(sortedDataPath);
}
void f8_listMatch(char *f1Path, char *f1IndPath, char *f2Path, char *key) {
FILE *f1Stream, *f2Stream;
IND_DATA *indFound1;
REG2_HEADER h2;
REG_HEADER h1;
REG2_DATA aux;
REG_DATA reg;
IND_T *ind1;
if((f1Stream = fopen(f1Path, "rb")) == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
if(R_readH(&h1, f1Stream) == 0 || h1.status == STATUS_INCONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
fclose(f1Stream);
return;
}
if((f2Stream = fopen(f2Path, "rb")) == NULL) {
printf("Falha no processamento do arquivo.\n");
fclose(f1Stream);
return;
}
if(R2_readH(&h2, f2Stream) == 0 || h2.status == STATUS_INCONSISTENTE) {
printf("Falha no processamento do arquivo.\n");
fclose(f1Stream);
fclose(f2Stream);
return;
}
if((ind1 = I_init(f1IndPath)) == NULL) {
printf("Falha no processamento do arquivo.\n");
fclose(f1Stream);
fclose(f2Stream);
return;
}
if((indFound1 = I_find(atoi(key), ind1)) == NULL || fseek(f1Stream, 64 + 64 * indFound1->RRN, SEEK_SET) != 0 || R_read(®, f1Stream) != 1 || reg.removed == R_REMOVIDO) {
printf("Registro inexistente.\n");
fclose(f1Stream);
fclose(f2Stream);
I_destroy(ind1);
return;
}
R_print(®);
while(R2_read(&aux, f2Stream) == 1) {
if(aux.removed == R_REMOVIDO || aux.idPessoaQueSegue != reg.idPessoa) {
continue;
}
R2_print(&aux);
}
fclose(f1Stream);
fclose(f2Stream);
I_destroy(ind1);
}
void f9_graph(char *f1Path, char *f1IndPath, char *f2Path) {
FILE *f1Stream, *f2Stream;
OBJTOINT *O, *aux;
GRAFO_ID grafoId;
REG2_HEADER h2;
REG_HEADER h1;
REG2_DATA reg2;
REG_DATA reg1;
IND_T *index1;
char **grafo;
int i, j;
if((index1 = I_init(f1IndPath)) == NULL) {
printf("Falha na execução da funcionalidade.\n");
return;
}
I_destroy(index1);
if((f1Stream = fopen(f1Path, "rb")) == NULL) {
printf("Falha na execução da funcionalidade.\n");
return;
}
if(R_readH(&h1, f1Stream) == 0 || h1.status == STATUS_INCONSISTENTE) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
return;
}
if((f2Stream = fopen(f2Path, "rb")) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
return;
}
if(R2_readH(&h2, f2Stream) == 0 || h2.status == STATUS_INCONSISTENTE) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
fclose(f2Stream);
return;
}
if((O = OBJ_Init(sizeof(char) * 100, (int (*)(const void *, const void *)) strcmp)) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
fclose(f2Stream);
return;
}
if((aux = OBJ_Init(sizeof(GRAFO_ID), (int (*)(const void *, const void *)) grafo_comparador)) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
fclose(f2Stream);
OBJ_Destroy(O);
return;
}
while(R_read(®1, f1Stream) == 1) {
if(reg1.removed == R_REMOVIDO || reg1.nomePessoa[0] == '\0') {
continue;
}
strcpy(grafoId.nomePessoa, reg1.nomePessoa);
grafoId.idPessoa = reg1.idPessoa;
OBJ_Push(&grafoId, aux);
OBJ_Push(reg1.nomePessoa, O);
}
grafo = (char **) malloc(sizeof(char *) * OBJ_Count(O));
for(i = 0; i < OBJ_Count(O); i++) {
grafo[i] = (char *) malloc(sizeof(char) * OBJ_Count(O));
memset(grafo[i], 0, sizeof(char) * OBJ_Count(O));
}
OBJ_BuildVector(O);
OBJ_BuildVector(aux);
while(R2_read(®2, f2Stream) == 1) {
if(reg2.removed == R_REMOVIDO) {
continue;
}
grafoId.idPessoa = reg2.idPessoaQueSegue;
i = OBJ_IndexFor(&grafoId, aux);
OBJ_ObjectFor(i, &grafoId, aux);
i = OBJ_IndexFor(grafoId.nomePessoa, O);
grafoId.idPessoa = reg2.idPessoaQueESeguida;
j = OBJ_IndexFor(&grafoId, aux);
OBJ_ObjectFor(j, &grafoId, aux);
j = OBJ_IndexFor(grafoId.nomePessoa, O);
grafo[i][j] = 1;
}
fclose(f1Stream);
fclose(f2Stream);
OBJ_Destroy(aux);
for(i = 0; i < OBJ_Count(O); i++) {
OBJ_ObjectFor(i, grafoId.nomePessoa, O);
printf("%s", grafoId.nomePessoa);
for(j = 0; j < OBJ_Count(O); j++) {
if(grafo[i][j] != 1) {
continue;
}
OBJ_ObjectFor(j, grafoId.nomePessoa, O);
printf(", %s", grafoId.nomePessoa);
}
printf("\n");
}
OBJ_Destroy(O);
}
void f10_graphInverted(char *f1Path, char *f1IndPath, char *f2Path) {
FILE *f1Stream, *f2Stream;
OBJTOINT *O, *aux;
GRAFO_ID grafoId;
REG2_HEADER h2;
REG_HEADER h1;
REG2_DATA reg2;
REG_DATA reg1;
IND_T *index1;
char **grafo;
int i, j;
if((index1 = I_init(f1IndPath)) == NULL) {
printf("Falha na execução da funcionalidade.\n");
return;
}
I_destroy(index1);
if((f1Stream = fopen(f1Path, "rb")) == NULL) {
printf("Falha na execução da funcionalidade.\n");
return;
}
if(R_readH(&h1, f1Stream) == 0 || h1.status == STATUS_INCONSISTENTE) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
return;
}
if((f2Stream = fopen(f2Path, "rb")) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
return;
}
if(R2_readH(&h2, f2Stream) == 0 || h2.status == STATUS_INCONSISTENTE) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
fclose(f2Stream);
return;
}
if((O = OBJ_Init(sizeof(char) * 100, (int (*)(const void *, const void *)) strcmp)) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
fclose(f2Stream);
return;
}
if((aux = OBJ_Init(sizeof(GRAFO_ID), (int (*)(const void *, const void *)) grafo_comparador)) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
fclose(f2Stream);
OBJ_Destroy(O);
return;
}
while(R_read(®1, f1Stream) == 1) {
if(reg1.removed == R_REMOVIDO || reg1.nomePessoa[0] == '\0') {
continue;
}
strcpy(grafoId.nomePessoa, reg1.nomePessoa);
grafoId.idPessoa = reg1.idPessoa;
OBJ_Push(&grafoId, aux);
OBJ_Push(reg1.nomePessoa, O);
}
grafo = (char **) malloc(sizeof(char *) * OBJ_Count(O));
for(i = 0; i < OBJ_Count(O); i++) {
grafo[i] = (char *) malloc(sizeof(char) * OBJ_Count(O));
memset(grafo[i], 0, sizeof(char) * OBJ_Count(O));
}
OBJ_BuildVector(O);
OBJ_BuildVector(aux);
while(R2_read(®2, f2Stream) == 1) {
if(reg2.removed == R_REMOVIDO) {
continue;
}
grafoId.idPessoa = reg2.idPessoaQueSegue;
i = OBJ_IndexFor(&grafoId, aux);
OBJ_ObjectFor(i, &grafoId, aux);
i = OBJ_IndexFor(grafoId.nomePessoa, O);
grafoId.idPessoa = reg2.idPessoaQueESeguida;
j = OBJ_IndexFor(&grafoId, aux);
OBJ_ObjectFor(j, &grafoId, aux);
j = OBJ_IndexFor(grafoId.nomePessoa, O);
grafo[j][i] = 1;
}
fclose(f1Stream);
fclose(f2Stream);
OBJ_Destroy(aux);
for(i = 0; i < OBJ_Count(O); i++) {
OBJ_ObjectFor(i, grafoId.nomePessoa, O);
printf("%s", grafoId.nomePessoa);
for(j = 0; j < OBJ_Count(O); j++) {
if(grafo[i][j] != 1) {
continue;
}
OBJ_ObjectFor(j, grafoId.nomePessoa, O);
printf(", %s", grafoId.nomePessoa);
}
printf("\n");
}
OBJ_Destroy(O);
}
void f11_bfs(char *f1Path, char *f1IndPath, char *f2Path, char *key) {
FILE *f1Stream, *f2Stream;
OBJTOINT *O, *aux;
GRAFO_ID grafoId;
REG2_HEADER h2;
REG_HEADER h1;
REG2_DATA reg2;
REG_DATA reg1;
IND_T *index1;
char **grafo;
DEQUE *d;
int *ant;
int i, j;
if((index1 = I_init(f1IndPath)) == NULL) {
printf("Falha na execução da funcionalidade.\n");
return;
}
I_destroy(index1);
if((f1Stream = fopen(f1Path, "rb")) == NULL) {
printf("Falha na execução da funcionalidade.\n");
return;
}
if(R_readH(&h1, f1Stream) == 0 || h1.status == STATUS_INCONSISTENTE) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
return;
}
if((f2Stream = fopen(f2Path, "rb")) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
return;
}
if(R2_readH(&h2, f2Stream) == 0 || h2.status == STATUS_INCONSISTENTE) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
fclose(f2Stream);
return;
}
if((O = OBJ_Init(sizeof(char) * 100, (int (*)(const void *, const void *)) strcmp)) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
fclose(f2Stream);
return;
}
if((aux = OBJ_Init(sizeof(GRAFO_ID), (int (*)(const void *, const void *)) grafo_comparador)) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
fclose(f2Stream);
OBJ_Destroy(O);
return;
}
while(R_read(®1, f1Stream) == 1) {
if(reg1.removed == R_REMOVIDO || reg1.nomePessoa[0] == '\0') {
continue;
}
strcpy(grafoId.nomePessoa, reg1.nomePessoa);
grafoId.idPessoa = reg1.idPessoa;
OBJ_Push(&grafoId, aux);
OBJ_Push(reg1.nomePessoa, O);
}
grafo = (char **) malloc(sizeof(char *) * OBJ_Count(O));
ant = (int *) malloc(sizeof(int) * OBJ_Count(O));
for(i = 0; i < OBJ_Count(O); i++) {
grafo[i] = (char *) malloc(sizeof(char) * OBJ_Count(O));
memset(grafo[i], 0, sizeof(char) * OBJ_Count(O));
}
memset(ant, -1, sizeof(int) * OBJ_Count(O));
OBJ_BuildVector(O);
OBJ_BuildVector(aux);
while(R2_read(®2, f2Stream) == 1) {
if(reg2.removed == R_REMOVIDO) {
continue;
}
grafoId.idPessoa = reg2.idPessoaQueSegue;
i = OBJ_IndexFor(&grafoId, aux);
OBJ_ObjectFor(i, &grafoId, aux);
i = OBJ_IndexFor(grafoId.nomePessoa, O);
grafoId.idPessoa = reg2.idPessoaQueESeguida;
j = OBJ_IndexFor(&grafoId, aux);
OBJ_ObjectFor(j, &grafoId, aux);
j = OBJ_IndexFor(grafoId.nomePessoa, O);
grafo[j][i] = 1;
}
fclose(f1Stream);
fclose(f2Stream);
OBJ_Destroy(aux);
if((d = DQ_New(sizeof(int))) == NULL) {
printf("Falha na execução da funcionalidade.\n");
OBJ_Destroy(O);
return;
}
i = OBJ_IndexFor(key, O);
if(i < 0) {
printf("Falha na execução da funcionalidade.\n");
OBJ_Destroy(O);
DQ_Destroy(d);
return;
}
DQ_PushBack(&i, d);
while(DQ_Size(d) > 0) {
DQ_ShiftFront(&i, d);
for(j = 0; j < OBJ_Count(O); j++) {
if(grafo[i][j] == 1 && ant[j] < 0) {
ant[j] = i;
DQ_PushBack(&j, d);
}
}
}
for(i = 0; i < OBJ_Count(O); i++) {
if(i == OBJ_IndexFor(key, O)) {
continue;
}
OBJ_ObjectFor(i, grafoId.nomePessoa, O);
printf("%s", grafoId.nomePessoa);
if(ant[i] < 0) {
printf(", NAO SEGUE A CELEBRIDADE");
} else {
for(j = ant[i]; j >= 0 && j != OBJ_IndexFor(key, O); j = ant[j]) {
OBJ_ObjectFor(j, grafoId.nomePessoa, O);
printf(", %s", grafoId.nomePessoa);
}
printf(", %s", key);
}
printf("\n");
}
OBJ_Destroy(O);
DQ_Destroy(d);
}
void f12_dfsCycle(char *f1Path, char *f1IndPath, char *f2Path, char *key) {
FILE *f1Stream, *f2Stream;
OBJTOINT *O, *aux;
GRAFO_ID grafoId;
REG2_HEADER h2;
REG_HEADER h1;
REG2_DATA reg2;
REG_DATA reg1;
IND_T *index1;
char **grafo;
DEQUE *d;
int *ant;
int i, j;
if((index1 = I_init(f1IndPath)) == NULL) {
printf("Falha na execução da funcionalidade.\n");
return;
}
I_destroy(index1);
if((f1Stream = fopen(f1Path, "rb")) == NULL) {
printf("Falha na execução da funcionalidade.\n");
return;
}
if(R_readH(&h1, f1Stream) == 0 || h1.status == STATUS_INCONSISTENTE) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
return;
}
if((f2Stream = fopen(f2Path, "rb")) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
return;
}
if(R2_readH(&h2, f2Stream) == 0 || h2.status == STATUS_INCONSISTENTE) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
fclose(f2Stream);
return;
}
if((O = OBJ_Init(sizeof(char) * 100, (int (*)(const void *, const void *)) strcmp)) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
fclose(f2Stream);
return;
}
if((aux = OBJ_Init(sizeof(GRAFO_ID), (int (*)(const void *, const void *)) grafo_comparador)) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(f1Stream);
fclose(f2Stream);
OBJ_Destroy(O);
return;
}
while(R_read(®1, f1Stream) == 1) {
if(reg1.removed == R_REMOVIDO || reg1.nomePessoa[0] == '\0') {
continue;
}
strcpy(grafoId.nomePessoa, reg1.nomePessoa);
grafoId.idPessoa = reg1.idPessoa;
OBJ_Push(&grafoId, aux);
OBJ_Push(reg1.nomePessoa, O);
}
grafo = (char **) malloc(sizeof(char *) * OBJ_Count(O));
ant = (int *) malloc(sizeof(int) * OBJ_Count(O));
for(i = 0; i < OBJ_Count(O); i++) {
grafo[i] = (char *) malloc(sizeof(char) * OBJ_Count(O));
memset(grafo[i], 0, sizeof(char) * OBJ_Count(O));
}
memset(ant, -1, sizeof(int) * OBJ_Count(O));
OBJ_BuildVector(O);
OBJ_BuildVector(aux);
while(R2_read(®2, f2Stream) == 1) {
if(reg2.removed == R_REMOVIDO) {
continue;
}
grafoId.idPessoa = reg2.idPessoaQueSegue;
i = OBJ_IndexFor(&grafoId, aux);
OBJ_ObjectFor(i, &grafoId, aux);
i = OBJ_IndexFor(grafoId.nomePessoa, O);
grafoId.idPessoa = reg2.idPessoaQueESeguida;
j = OBJ_IndexFor(&grafoId, aux);
OBJ_ObjectFor(j, &grafoId, aux);
j = OBJ_IndexFor(grafoId.nomePessoa, O);
grafo[j][i] = 1;
}
fclose(f1Stream);
fclose(f2Stream);
OBJ_Destroy(aux);
if((d = DQ_New(sizeof(int))) == NULL) {
printf("Falha na execução da funcionalidade.\n");
OBJ_Destroy(O);
return;
}
i = OBJ_IndexFor(key, O);
if(i < 0) {
printf("Falha na execução da funcionalidade.\n");
OBJ_Destroy(O);
DQ_Destroy(d);
return;
}
DQ_PushBack(&i, d);
while(DQ_Size(d) > 0) {
DQ_ShiftBack(&i, d);
for(j = OBJ_Count(O) - 1; j >= 0; j--) {
if(grafo[i][j] == 1 && ant[j] < 0) {
ant[j] = i;
DQ_PushBack(&j, d);
}
}
}
DQ_Destroy(d);
i = OBJ_IndexFor(key, O);
if(ant[i] < 0) {
printf("A FOFOCA NAO RETORNOU\n");
} else {
for(i = ant[i], j = 1; i != OBJ_IndexFor(key, O) && ant[i] >= 0; j++) {
i = ant[i];
}
printf("%d\n", j);
}
OBJ_Destroy(O);
}
void fx_invalidadeStatus(char *filePath) {
FILE *fStream;
char aux;
if((fStream = fopen(filePath, "rb+")) == NULL) {
printf("Falha no processamento do arquivo.\n");
return;
}
aux = STATUS_INCONSISTENTE;
if(fwrite(&aux, sizeof(char), 1, fStream) != 1) {
printf("Falha no processamento do arquivo.\n");
} else {
printf("Invalidado com sucesso!\n");
}
fclose(fStream);
}
void fx_compressFile2(char *file2Path) {
FILE *fStream, *newFStream;
REG2_HEADER h2;
REG2_DATA reg2;
char buff[512];
long n;
if((newFStream = tmpfile()) == NULL) {
printf("Falha na execução da funcionalidade.\n");
return;
}
if((fStream = fopen(file2Path, "rb")) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(newFStream);
return;
}
if(R2_readH(&h2, fStream) == 0 || h2.status == STATUS_INCONSISTENTE) {
printf("Falha na execução da funcionalidade.\n");
fclose(fStream);
fclose(newFStream);
return;
}
R2_writeH(&h2, newFStream);
while(R2_read(®2, fStream) == 1) {
if(reg2.removed == R_REMOVIDO) {
continue;
}
R2_write(®2, newFStream);
}
fclose(fStream);
fseek(newFStream, 0, SEEK_SET);
if((fStream = fopen(file2Path, "wb")) == NULL) {
printf("Falha na execução da funcionalidade.\n");
fclose(newFStream);
return;
}
while((n = fread(buff, sizeof(char), 512, newFStream)) > 0) {
fwrite(buff, sizeof(char), n, fStream);
}
fclose(fStream);
fclose(newFStream);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int i,j,k,R;
int Dim[2][2]={{0,0},{0,0}};
scanf("%d %d",&Dim[0][0],&Dim[0][1]);
int **MatA=(int **)malloc(sizeof(int *)*Dim[0][0]);
for(i=0;i<Dim[0][0];i++){
MatA[i]=(int *)malloc(sizeof(int)*Dim[0][1]);
for(j=0;j<Dim[0][1];j++){
scanf("%d",&MatA[i][j]);
}
}
scanf("%d %d",&Dim[1][0],&Dim[1][1]);
int **MatB=(int **)malloc(sizeof(int *)*Dim[1][0]);
for(i=0;i<Dim[1][0];i++){
MatB[i]=(int *)malloc(sizeof(int)*Dim[1][1]);
for(j=0;j<Dim[1][1];j++){
scanf("%d",&MatB[i][j]);
}
}
for(i=0;i<Dim[0][0];i++){
for(j=0;j<Dim[1][1];j++){
for(R=0,k=0;k<Dim[1][0];k++){
R+=MatA[i][k]*MatB[k][j];
}
if(j){
printf(" %d",R);
}else{
printf("%d",R);
}
}
printf("\n");
}
for(i=0;i<Dim[0][0];i++){
free(MatA[i]);
}
for(i=0;i<Dim[1][0];i++){
free(MatB[i]);
}
free(MatA);
free(MatB);
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <limits.h>
#include <string.h>
typedef struct __graph_node_t {
int dest;
int weight;
char *additionalInfo;
struct __graph_node_t *next;
} GRAPH_NODE_T;
typedef struct __graph_t {
GRAPH_NODE_T **edges;
int nVertex;
int nEdge;
} GRAPH_T;
GRAPH_T *G_new(int nVertex) {
GRAPH_T *aux;
int i;
if(nVertex < 1) {
return NULL;
}
aux = (GRAPH_T *) malloc(sizeof(GRAPH_T));
if(aux == NULL) {
return NULL;
}
aux->edges = (GRAPH_NODE_T **) calloc(1, nVertex * sizeof(GRAPH_NODE_T *));
/*aux->edges = (GRAPH_NODE_T **) malloc(nVertex * sizeof(GRAPH_NODE_T *));
for(i = 0; i < nVertex; i++) {
aux->edges[i] = NULL;
}*/
if(aux->edges == NULL) {
free(aux);
return NULL;
}
aux->nVertex = nVertex;
aux->nEdge = 0;
return aux;
}
int G_addEdgeInfo(int source, int destination, int weight, char *additionalInformation, GRAPH_T *g) {
GRAPH_NODE_T **link, *aux;
size_t strN;
if(g == NULL || source < 0 || source >= g->nVertex || destination < 0 || destination >= g->nVertex) {
return 0;
}
link = &g->edges[source];
aux = NULL;
while(*link != NULL && (*link)->dest <= destination) {
link = &(*link)->next;
}
if(*link != NULL) {
aux = *link;
}
*link = (GRAPH_NODE_T *) malloc(sizeof(GRAPH_NODE_T));
if(*link == NULL) {
return 0;
}
if(additionalInformation != NULL) {
strN = strlen(additionalInformation);
(*link)->additionalInfo = (char *) malloc((strN + 1) * sizeof(char));
if((*link)->additionalInfo == NULL) {
free(*link);
return 0;
}
strcpy((*link)->additionalInfo, additionalInformation);
} else {
(*link)->additionalInfo = NULL;
}
(*link)->dest = destination;
(*link)->weight = weight;
(*link)->next = aux;
g->nEdge++;
return 1;
}
int G_addEdge(int source, int destination, int weight, GRAPH_T *g) {
return G_addEdgeInfo(source, destination, weight, NULL, g);
}
int G_resetEdges(GRAPH_T *g) {
GRAPH_NODE_T *link, *aux;
int i;
if(g == NULL) {
return 0;
}
for(i = 0; i < g->nVertex; i++) {
link = g->edges[i];
while(link != NULL) {
aux = link;
link = link->next;
free(aux);
}
g->edges[i] = NULL;
}
g->nEdge = 0;
return 1;
}
char *G_getInfo(int source, int destination, GRAPH_T *g) {
GRAPH_NODE_T *link;
if(g == NULL || g->nEdge < 1 || source < 0 || source >= g->nVertex || destination < 0 || destination >= g->nVertex) {
return NULL;
}
link = g->edges[source];
while(link != NULL) {
if(link->dest == destination) {
return link->additionalInfo;
}
link = link->next;
}
return NULL;
}
int G_dijkstra(int source, int **preV, int **disV, int *nVertex, GRAPH_T *g) {
int i, j, u, v, *pre, *dis, aux; // Vector pi (predecessors), distance and queue.
char *visitedStatus; // Vector visited
GRAPH_NODE_T *link;
if(g == NULL || g->nEdge < 1) {
return 0;
}
pre = (int *) malloc(g->nVertex * sizeof(int));
dis = (int *) malloc(g->nVertex * sizeof(int));
visitedStatus = (char *) malloc(g->nVertex * sizeof(char));
if(pre == NULL || dis == NULL || visitedStatus == NULL) {
free(pre);
free(dis);
free(visitedStatus);
return 0;
}
for(i = 0; i < g->nVertex; i++) {
visitedStatus[i] = 0;
dis[i] = INT_MAX;
pre[i] = -1;
}
dis[source] = 0;
pre[source] = source;
for(i = 1; i < g->nVertex; i++) {
aux = INT_MAX;
u = 0;
for(j = 0; j < g->nVertex; j++) {
if(visitedStatus[j] == 0 && dis[j] < aux) {
aux = dis[j];
u = j;
}
}
visitedStatus[u] = 1;
link = g->edges[u];
while(link != NULL) {
v = link->dest;
if(visitedStatus[v] == 0 && dis[u] != INT_MAX && dis[u] + link->weight < dis[v]) {
dis[v] = dis[u] + link->weight;
pre[v] = u;
}
link = link->next;
}
}
if(preV != NULL) {
*preV = pre;
} else {
free(pre);
}
if(disV != NULL) {
*disV = dis;
} else {
free(dis);
}
if(nVertex != NULL) {
*nVertex = g->nVertex;
}
free(visitedStatus);
return 1;
}
int G_prim(int source, int **preV, int **keyV, int *nVertex, GRAPH_T *g) {
int i, j, u, v, *pre, *dis, aux; // Vector pi (predecessors), distance and queue.
char *visitedStatus; // Vector visited
GRAPH_NODE_T *link;
if(g == NULL || g->nEdge < 1) {
return 0;
}
pre = (int *) malloc(g->nVertex * sizeof(int));
dis = (int *) malloc(g->nVertex * sizeof(int));
visitedStatus = (char *) malloc(g->nVertex * sizeof(char));
if(pre == NULL || dis == NULL || visitedStatus == NULL) {
free(pre);
free(dis);
free(visitedStatus);
return 0;
}
for(i = 0; i < g->nVertex; i++) {
visitedStatus[i] = 0;
dis[i] = INT_MAX;
pre[i] = -1;
}
dis[source] = 0;
// pre[source] = source;
for(i = 1; i < g->nVertex; i++) {
aux = INT_MAX;
u = 0;
for(j = 0; j < g->nVertex; j++) {
if(visitedStatus[j] == 0 && dis[j] < aux) {
aux = dis[j];
u = j;
}
}
visitedStatus[u] = 1;
link = g->edges[u];
while(link != NULL) {
v = link->dest;
if(visitedStatus[v] == 0 && link->weight < dis[v]) {
dis[v] = link->weight;
pre[v] = u;
}
link = link->next;
}
}
if(preV != NULL) {
*preV = pre;
} else {
free(pre);
}
if(keyV != NULL) {
*keyV = dis;
} else {
free(dis);
}
if(nVertex != NULL) {
*nVertex = g->nVertex;
}
free(visitedStatus);
return 1;
}
void G_printEdgesFor(int vertex, void *(printEdgeFunction)(int vertex, int distance, char *additionalInformation, void *ptr), void *ptr, GRAPH_T *g) {
GRAPH_NODE_T *link;
int u;
if(g == NULL || printEdgeFunction == NULL || vertex < 0 || vertex >= g->nVertex) {
return;
}
link = g->edges[vertex];
while(link != NULL) {
u = link->dest;
printEdgeFunction(u, link->weight, link->additionalInfo, ptr);
link = link->next;
}
}
void G_destroy(GRAPH_T *g) {
GRAPH_NODE_T *link, *aux;
int i;
if(g == NULL) {
return;
}
for(i = 0; i < g->nVertex; i++) {
link = g->edges[i];
while(link != NULL) {
aux = link;
link = link->next;
free(aux);
}
g->edges[i] = NULL;
}
free(g->edges);
free(g);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <funcionalidades.h>
#include <consts.h>
#include <escreverTela.h>
#include <vector_builder.h>
int icmp(int *a, int *b) {
return *b - *a;
}
int ircmp(int *a, int *b) {
return *a - *b;
}
int main(int argc, char **argv) {
char aux1[5000], aux2[5000], aux3[5000];
int Op, aux4;
scanf("%d", &Op);
switch(Op) {
case 1: // CSV -> Bin
scanf("%s", aux1);
if(f1_csvBuild(BINARY_DISK_FILE, aux1)) {
binarioNaTela2(BINARY_DISK_FILE);
//fprintf(stdout, "%s", BINARY_DISK_FILE);
}
break;
case 2: // imprimir tudo tela
scanf("%s", aux1);
f2_list(aux1);
break;
case 3: // busca por determinado campo
scanf("%s %s %[^\r\n]", aux1, aux2, aux3);
f3_search(aux1, aux2, aux3);
break;
case 4: // remoção
scanf("%s %d", aux1, &aux4);
if(f4_removeRegs(aux1, aux4, stdin)) {
binarioNaTela2(aux1);
}
break;
case 5: // inserção
scanf("%s %d", aux1, &aux4);
if(f5_addRegs(aux1, aux4, stdin)) {
binarioNaTela2(aux1);
}
break;
case 6: // atualização
scanf("%s %d", aux1, &aux4);
if(f6_updateRegs(aux1, aux4, stdin)) {
binarioNaTela2(aux1);
}
break;
case 7: // ordenar
scanf("%s %s", aux1, aux2);
if(f7_sort(aux1, aux2)) {
binarioNaTela2(aux2);
}
break;
case 8: // merge
scanf("%s %s %s", aux1, aux2, aux3);
if(f8_merge(aux1, aux2, aux3)) {
binarioNaTela2(aux3);
}
break;
case 9: // match
scanf("%s %s %s", aux1, aux2, aux3);
if(f9_match(aux1, aux2, aux3)) {
binarioNaTela2(aux3);
}
break;
case 10: // criar index
scanf("%s %s", aux1, aux2);
if(f10_index(aux1, aux2)) {
binarioNaTela2(aux2);
}
break;
case 11: // busca por nomeServidor no index
scanf("%s %s %*s %[^\r\n]", aux1, aux2, aux3);
f11_searchKey(aux1, aux2, aux3);
break;
case 12: // remove por nomeServidor no index
scanf("%s %s %d", aux1, aux2, &aux4);
if(f12_removeRegsKey(aux1, aux2, aux4, stdin) == 1) {
binarioNaTela2(aux2);
}
break;
case 13: // adiciona regitros, usando o index
scanf("%s %s %d", aux1, aux2, &aux4);
if(f13_addRegsKey(aux1, aux2, aux4, stdin) == 1) {
binarioNaTela2(aux2);
}
break;
case 14: // busca por nomeServidor no index, gerando estatisticas
scanf("%s %s %*s %[^\r\n]", aux1, aux2, aux3);
f14_searchKeyStats(aux1, aux2, aux3);
break;
case 15: // criar btree
scanf("%s %s", aux1, aux2);
if(f15_indexB(aux1, aux2)) {
binarioNaTela2(aux2);
}
break;
case 16: // busca por idServidor na btree
scanf("%s %s %*s %[^\r\n]", aux1, aux2, aux3);
f16_searchKeyB(aux1, aux2, aux3);
break;
/* Funcionalidades p/ criação de casos de teste */
case 98: // Invalidar arquivo binário (status = '0')
scanf("%s", aux1);
fx_invalidate(aux1);
break;
case 99: // Imprimir arquivo binário (binarioNaTela)
scanf("%s", aux1);
binarioNaTela2(aux1);
break;
case 100: // Imprimir lista de itens removidos de arquivo binário de dados
scanf("%s", aux1);
fx_listRemoved(aux1);
break;
default:
printf("Funcionalidade inválida.\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int i,j,N,Rl=0,Rc,Rd1,Rd2;
scanf("%d",&N);
int Mat[N][N];
for(i=0;i<N;i++){
for(j=0;j<N;j++){
scanf("%d",&Mat[i][j]);
}
}
Rd1=0;
Rd2=0;
for(i=0;i<N;i++){
Rd1+=Mat[i][i];
Rd2+=Mat[N-(i+1)][N-(i+1)];
}
if(Rd1!=Rd2){
printf("NAO\n");
return EXIT_SUCCESS;
}
for(i=0;i<N;i++){
Rl=0;
Rc=0;
for(j=0;j<N;j++){
Rl+=Mat[i][j];
Rc+=Mat[j][i];
}
if((Rl!=Rc) || (Rl!=Rd1)){
printf("NAO\n");
return EXIT_SUCCESS;
}
}
printf("SIM\n");
return EXIT_SUCCESS;
}
<file_sep>
CCF = -I headers -lm
run:
./prog
all: prog
prog: bin/main.o bin/funcionalidades.o bin/register.o bin/escreverTela.o bin/indiceCidades.o bin/graph.o bin/buscaCampos.o
gcc bin/*.o -o prog $(CCF)
bin/main.o: src/main.c headers/funcionalidades.h headers/consts.h
gcc -c src/main.c -o bin/main.o $(CCF)
bin/funcionalidades.o: src/funcionalidades.c headers/funcionalidades.h headers/escreverTela.h headers/register.h headers/indiceCidades.h headers/graph.h headers/buscaCampos.h headers/consts.h
gcc -c src/funcionalidades.c -o bin/funcionalidades.o $(CCF)
bin/buscaCampos.o: src/buscaCampos.c headers/buscaCampos.h headers/register.h headers/consts.h
gcc -c src/buscaCampos.c -o bin/buscaCampos.o $(CCF)
bin/register.o: src/register.c headers/register.h headers/consts.h
gcc -c src/register.c -o bin/register.o $(CCF)
bin/indiceCidades.o: src/indiceCidades.c headers/indiceCidades.h headers/consts.h
gcc -c src/indiceCidades.c -o bin/indiceCidades.o $(CCF)
bin/graph.o: src/graph.c headers/graph.h headers/consts.h
gcc -c src/graph.c -o bin/graph.o $(CCF)
bin/escreverTela.o: src/escreverTela.c headers/escreverTela.h
gcc -c src/escreverTela.c -o bin/escreverTela.o $(CCF)
gerar:
./prog < gerardados.in
clean:
rm bin/*.o prog
<file_sep>
#ifndef INDEX_H_
#define INDEX_H_
#include "register.h"
typedef struct {
int key;
int RRN;
} IND_DATA;
typedef struct {
char status;
int nItems;
IND_DATA *data;
char path[5000];
} IND_T;
#define IND_DATA_SIZE 128
IND_T *I_init(char *path);
int I_read(IND_T *index, char *path);
int I_rewrite(IND_T *index);
int I_write(IND_T *index, char *path);
void I_destroy(IND_T *index);
int I_push(REG_DATA *reg, IND_T *index);
int I_pop(REG_DATA *reg, IND_T *index);
int I_update(REG_DATA *reg, IND_T *index);
IND_DATA *I_find(int key, IND_T *index);
#endif<file_sep>#include <vectorutils.h>
void bubblesort(void *vector, int size, int (*cmp)(void *,void *), int n, int *CmpN, int *MovN) {
int i, j, C = 0, M = 0;
for (j = 1; j < n; j++) {
for (i = 0; i < n-j; i++) {
C++;
if (cmp(vector+i*size,vector+(i+1)*size)<0) {
M+=3;
gswap(vector+i*size, vector+(i+1)*size, size);
}
}
}
*CmpN = C;
*MovN = M;
}
<file_sep>import numpy as np
#import imageio
import random
import math
import sys
#
# ~ Trabalho 1: Gerador de Imagens ~
#
# <NAME>
# <EMAIL>
# Nº USP 10369014
# Processamento de Imagens: SCC-0251 2018.1
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
# == DEFINIÇÃO DE FUNÇÕES ==
def NPMax(Arr):
"Esta função calcula o máximo valor de uma matriz numpy."
Max = sys.float_info.min # Começa com FLOAT_MIN
N = len(Arr)
for x in range(0, N):
for y in range(0, N): # Percorrer matriz achando maior valor
if Arr[x, y] > Max:
Max = Arr[x, y]
return Max
def NPMin(Arr):
"Esta função calcula o mínimo valor de uma matriz numpy."
Min = sys.float_info.max # Começa com FLOAT_MAX
N = len(Arr)
for x in range(0, N):
for y in range(0, N): # Percorrer matriz achando menor valor
if Arr[x, y] < Min:
Min = Arr[x, y]
return Min
def NPMaxIn(Arr, i, j, d):
"Esta função calcula o máximo valor dentro de uma submatriz de uma matriz numpy maior."
#if d <= 1: # Caso em que não há submatriz
#return Arr[i, j]
Max = sys.float_info.min # Começa com FLOAT_MIN
xstart = i*d
xend = xstart + d
ystart = j*d
yend = ystart + d
for x in range(xstart, xend):
for y in range(ystart, yend): # Percorrer submatriz da matriz principal 'Arr', encontrando maior valor
if Arr[x, y] > Max:
Max = Arr[x, y]
return Max
def Func1(C):
"f(x, y) = x + y"
Arr = np.empty([C, C], dtype=np.float) # Alocar matriz
for x in range(0, C):
for y in range(0, C):
Arr[x, y] = np.float(x + y)
return Arr
def Func2(C, Q):
"f(x, y) = | sin(x/Q) + sin(y/Q) |"
Arr = np.empty([C, C], dtype=np.float) # Alocar matriz
for x in range(0, C):
for y in range(0, C):
Arr[x, y] = np.float(math.fabs(math.sin(x/Q) + math.sin(y/Q)))
return Arr
def Func3(C, Q):
"f(x, y) = [ x/Q - sqrt(y/Q) ]"
Arr = np.empty([C, C], dtype=np.float) # Alocar matriz
Q = np.float(Q)
for x in range(0, C):
for y in range(0, C):
Arr[x, y] = np.float((x/Q) - math.sqrt(y/Q))
return Arr
def Func4(C, S):
"f(x, y) = random [0.0, 1.0]"
Arr = np.empty([C, C], dtype=np.float) # Alocar matriz
random.seed(S)
for x in range(0, C):
for y in range(0, C):
Arr[x, y] = np.float(random.uniform(0, 1))
return Arr
def Func5(C, S):
"f(x, y) = random_walk"
Arr = np.zeros([C, C], dtype=np.float) # Alocar matriz zerada
counter = int(1 + (C*C)/2) # Contador de passos
random.seed(S)
x = y = 0
Arr[x, y] = np.float(1)
while counter >= 0:
x = (x + random.randrange(-1, 2)) % C # Soma +1 ou -1 a x
Arr[x, y] = np.float(1)
y = (y + random.randrange(-1, 2)) % C # Soma +1 ou -1 a y
Arr[x, y] = np.float(1)
counter = counter - 1
return Arr
# == MAIN ==
# Leitura dos dados da entrada padrão
file_name = str(input()).rstrip()
C = int(input())
f = int(input())
Q = int(input())
N = int(input())
B = int(input())
S = int(input())
# Variável 'd' de relação entre os tamanhos da Imagem Cena e da Imagem Digital
d = int(C/N)
# Processar funções e gerar matriz Cena 'Shot'
if f == 1:
Shot = Func1(C) # f(x,y) = x + y
elif f == 2:
Shot = Func2(C, Q) # f(x, y) = | sin(x/Q) + sin(y/Q) |
elif f == 3:
Shot = Func3(C, Q) # f(x, y) = [ (x/Q) - sqrt(y/Q) ]
elif f == 4:
Shot = Func4(C, S) # f(x, y) = random [0.0, 1.0]
else:
Shot = Func5(C, S) # f(x, y) = random_walk
# Achar valores máximo e mínimo presentes na matriz
Min = NPMin(Shot)
Max = NPMax(Shot)
# Normalizar valores entre 0 e 65535
Razao = np.float(65535 / (Max - Min))
for x in range(0, C):
for y in range(0, C):
Shot[x, y] = np.float((Shot[x, y] - Min) * Razao)
# Gerar imagem digital g 'Digital'
Digital = np.empty([N, N], dtype=np.float)
for x in range(0, N):
for y in range(0, N):
Digital[x, y] = NPMaxIn(Shot, x, y, d)
# Normalizar valores entre 0 e 255
Min = NPMin(Digital)
Max = NPMax(Digital)
Ratio = np.float(255 / (Max - Min))
for x in range(0, N):
for y in range(0, N):
Digital[x, y] = np.float((Digital[x, y] - Min) * Ratio)
# Converter de float para uint8
Digital = Digital.astype(dtype=np.uint8)
# Considerar apenas os primeiros B bits menos significativos
NBits = 8 - B
for x in range(0, N):
for y in range(0, N):
Digital[x, y] = np.uint8(Digital[x, y] >> NBits)
# Carregar imagem do disco e converter para tipo uint8
LoadedImg = np.load(file_name)
LoadedImg = LoadedImg.astype(np.uint8)
# Calcular RMSE
RMSE = float(0)
for x in range(0, N):
for y in range(0, N):
RMSE += math.pow(float(Digital[x, y]) - float(LoadedImg[x, y]), 2)
RMSE = math.sqrt(RMSE / (N*N))
# Imprimir resultado do RMSE com 4 casas decimais
print("%.4f" % round(RMSE, 4))
# == DEBUGGING ==
# Imprimir minha imagem gerada e imagem lida do disco para comparação
#imageio.imwrite("c/out_expected.png", LoadedImg)
#imageio.imwrite("c/out_generated.png", Digital)
#print("")
#print(Digital)
#print("")
#print(LoadedImg)
#print("")
<file_sep>#include <stdlib.h>
#include <string.h>
/*
* ~ Deque ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
struct __deque_node_t {
void *value;
struct __deque_node_t *prev, *next;
};
struct __deque_t {
struct __deque_node_t *first, *last;
unsigned long nitems;
size_t memsize;
};
struct __deque_t *DQ_New(size_t memsize){
struct __deque_t *Aux;
if(memsize < 1) return NULL;
Aux = (struct __deque_t *) malloc(sizeof(struct __deque_t));
Aux->first = Aux->last = NULL;
Aux->memsize = memsize;
Aux->nitems = 0;
return Aux;
}
long DQ_Size(struct __deque_t *DQ){
if(DQ == NULL) return -1;
return DQ->nitems;
}
int DQ_PushFront(void *X, struct __deque_t *DQ){
struct __deque_node_t *Aux;
if(DQ == NULL || X == NULL) return 0;
Aux = (struct __deque_node_t *) malloc(sizeof(struct __deque_node_t));
Aux->value = (void *) malloc(DQ->memsize);
Aux->prev = NULL;
Aux->next = DQ->first;
memcpy(Aux->value, X, DQ->memsize);
if(DQ->nitems > 0)
DQ->first->prev = Aux;
else
DQ->last = Aux;
DQ->first = Aux;
DQ->nitems++;
return 1;
}
int DQ_PushBack(void *X, struct __deque_t *DQ){
struct __deque_node_t *Aux;
if(DQ == NULL || X == NULL) return 0;
Aux = (struct __deque_node_t *) malloc(sizeof(struct __deque_node_t));
Aux->value = (void *) malloc(DQ->memsize);
Aux->prev = DQ->last;
Aux->next = NULL;
memcpy(Aux->value, X, DQ->memsize);
if(DQ->nitems > 0)
DQ->last->next = Aux;
else
DQ->first = Aux;
DQ->last = Aux;
DQ->nitems++;
return 1;
}
int DQ_Front(void *X, struct __deque_t *DQ){
if(DQ == NULL || X == NULL) return 0;
if(DQ->nitems < 1) return 0;
memcpy(X, DQ->first->value, DQ->memsize);
return 1;
}
int DQ_Back(void *X, struct __deque_t *DQ){
if(DQ == NULL || X == NULL) return 0;
if(DQ->nitems < 1) return 0;
memcpy(X, DQ->last->value, DQ->memsize);
return 1;
}
int DQ_ShiftFront(void *X, struct __deque_t *DQ){
struct __deque_node_t *Aux;
if(DQ == NULL) return 0;
if(DQ->nitems < 1) return 0;
if(X != NULL)
memcpy(X, DQ->first->value, DQ->memsize);
Aux = DQ->first;
DQ->first = DQ->first->next;
DQ->nitems--;
if(DQ->nitems < 1)
DQ->last = NULL;
free(Aux->value);
free(Aux);
return 1;
}
int DQ_ShiftBack(void *X, struct __deque_t *DQ){
struct __deque_node_t *Aux;
if(DQ == NULL) return 0;
if(DQ->nitems < 1) return 0;
if(X != NULL)
memcpy(X, DQ->last->value, DQ->memsize);
Aux = DQ->last;
DQ->last = DQ->last->prev;
DQ->nitems--;
if(DQ->nitems < 1)
DQ->first = NULL;
free(Aux->value);
free(Aux);
return 1;
}
void DQ_Destroy(struct __deque_t *DQ){
struct __deque_node_t *P, *Aux;
if(DQ == NULL) return;
P = DQ->first;
while(P != NULL) {
Aux = P;
P = P->next;
free(Aux->value);
free(Aux);
}
free(DQ);
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <super_string.h>
/*
* ~ SOCCER ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
struct __soccer_game_t { // Estrutura de cada jogo.
int TeamA,TeamB;
int PointsA,PointsB;
};
struct __soccer_team_t { // Estrutura de cada equipe.
char Name[50];
int Points,VictoryCount,DrawCount,DefeatCount,GoalCount,ReceivedGoalCount;
};
struct __soccer_tour_t { // Estrutura de um torneio.
char Name[150];
int TeamCount,GameCount;
struct __soccer_team_t *Teams;
struct __soccer_game_t *Games;
};
struct __soccer_tour_t *S_NewFrom(FILE *FStream){
/*
* Esta função cria um novo torneio a partir de 'FStream'.
*/
struct __soccer_tour_t *Aux=(struct __soccer_tour_t *)malloc(sizeof(struct __soccer_tour_t));
char Str[200];
int i,j;
SS_ReadAllWhites(FStream);
SS_ReadUntil(Aux->Name,'\n',FStream);
scanf("%d",&Aux->TeamCount);
Aux->Teams=(struct __soccer_team_t *)malloc(sizeof(struct __soccer_team_t)*Aux->TeamCount);
for(i=0;i<Aux->TeamCount;i++){
SS_ReadAllWhites(FStream);
SS_ReadUntil(Aux->Teams[i].Name,'\n',FStream);
Aux->Teams[i].Points=Aux->Teams[i].VictoryCount=Aux->Teams[i].DrawCount=Aux->Teams[i].DefeatCount=Aux->Teams[i].GoalCount=Aux->Teams[i].ReceivedGoalCount=0;
}
scanf("%d",&Aux->GameCount);
Aux->Games=(struct __soccer_game_t *)malloc(sizeof(struct __soccer_game_t)*Aux->GameCount);
for(i=0;i<Aux->GameCount;i++){
SS_ReadAllWhites(FStream);
SS_ReadUntil(Str,'#',FStream);
for(j=0;j<Aux->TeamCount;j++)
if(strcmp(Aux->Teams[j].Name,Str)==0){
Aux->Games[i].TeamA=j;
break;
}
scanf("%*c%d%*c%d%*c",&Aux->Games[i].PointsA,&Aux->Games[i].PointsB);
SS_ReadUntil(Str,'\n',FStream);
for(j=0;j<Aux->TeamCount;j++)
if(strcmp(Aux->Teams[j].Name,Str)==0){
Aux->Games[i].TeamB=j;
break;
}
}
return Aux;
}
char S_Calc(struct __soccer_tour_t *Soc){
/*
* Esta função calcula todos os gols de 'Soc' e salva o resultado de cada equipe.
*
* Ela retorna 1 em caso de sucesso, e 0 em caso de erros.
*/
if(Soc==NULL) return 0;
int i;
for(i=0;i<Soc->GameCount;i++){ // Para cada jogo...
Soc->Teams[Soc->Games[i].TeamA].GoalCount+=Soc->Games[i].PointsA; // Calcular pontuação das equipes participantes.
Soc->Teams[Soc->Games[i].TeamB].GoalCount+=Soc->Games[i].PointsB;
Soc->Teams[Soc->Games[i].TeamA].ReceivedGoalCount+=Soc->Games[i].PointsB;
Soc->Teams[Soc->Games[i].TeamB].ReceivedGoalCount+=Soc->Games[i].PointsA;
if(Soc->Games[i].PointsA>Soc->Games[i].PointsB){ // A venceu B...
Soc->Teams[Soc->Games[i].TeamA].Points+=3; // Mais 3 pontos para A.
Soc->Teams[Soc->Games[i].TeamA].VictoryCount++;
Soc->Teams[Soc->Games[i].TeamB].DefeatCount++;
}else if(Soc->Games[i].PointsA<Soc->Games[i].PointsB){ // B venceu A...
Soc->Teams[Soc->Games[i].TeamB].Points+=3; // Mais 3 pontos para B.
Soc->Teams[Soc->Games[i].TeamB].VictoryCount++;
Soc->Teams[Soc->Games[i].TeamA].DefeatCount++;
}else{ // Empate...
Soc->Teams[Soc->Games[i].TeamA].Points+=1; // Mais 1 ponto para A.
Soc->Teams[Soc->Games[i].TeamB].Points+=1; // Mais 1 ponto para B.
Soc->Teams[Soc->Games[i].TeamA].DrawCount++;
Soc->Teams[Soc->Games[i].TeamB].DrawCount++;
}
}
return 1;
}
char S_Sort(struct __soccer_tour_t *Soc){
/*
* Esta função ordena as equipes de 'Soc' com base nos requisitos.
*
* Ela retorna 1 em caso de sucesso, e 0 em caso de erros.
*/
if(Soc==NULL) return 0;
struct __soccer_team_t R;
int i,j,k;
k=Soc->TeamCount/2;
// Shell Sort
while(k>0){
for(j=k;j<Soc->TeamCount;j++){
R=Soc->Teams[j];
i=j;
while( i>=k && ( Soc->Teams[i-k].Points<R.Points
|| (Soc->Teams[i-k].Points==R.Points && Soc->Teams[i-k].VictoryCount<R.VictoryCount)
|| (Soc->Teams[i-k].Points==R.Points && Soc->Teams[i-k].VictoryCount==R.VictoryCount && Soc->Teams[i-k].GoalCount-Soc->Teams[i-k].ReceivedGoalCount<R.GoalCount-R.ReceivedGoalCount)
|| (Soc->Teams[i-k].Points==R.Points && Soc->Teams[i-k].VictoryCount==R.VictoryCount && Soc->Teams[i-k].GoalCount-Soc->Teams[i-k].ReceivedGoalCount==R.GoalCount-R.ReceivedGoalCount && Soc->Teams[i-k].GoalCount<R.GoalCount)
|| (Soc->Teams[i-k].Points==R.Points && Soc->Teams[i-k].VictoryCount==R.VictoryCount && Soc->Teams[i-k].GoalCount-Soc->Teams[i-k].ReceivedGoalCount==R.GoalCount-R.ReceivedGoalCount && Soc->Teams[i-k].GoalCount==R.GoalCount && Soc->Teams[i-k].VictoryCount+Soc->Teams[i-k].DrawCount+Soc->Teams[i-k].DefeatCount>R.VictoryCount+R.DrawCount+R.DefeatCount)
|| (Soc->Teams[i-k].Points==R.Points && Soc->Teams[i-k].VictoryCount==R.VictoryCount && Soc->Teams[i-k].GoalCount-Soc->Teams[i-k].ReceivedGoalCount==R.GoalCount-R.ReceivedGoalCount && Soc->Teams[i-k].GoalCount==R.GoalCount && Soc->Teams[i-k].VictoryCount+Soc->Teams[i-k].DrawCount+Soc->Teams[i-k].DefeatCount==R.VictoryCount+R.DrawCount+R.DefeatCount && SS_InsensitiveCmp(Soc->Teams[i-k].Name,R.Name)>0) ) ){
Soc->Teams[i]=Soc->Teams[i-k];
i-=k;
}
Soc->Teams[i]=R;
}
k/=2;
}
return 1;
}
char S_Print(struct __soccer_tour_t *Soc,FILE *FStream){
/*
* Esta função imprime as equipes de 'Soc' e seus resultados em 'FStream'.
*
* Ela retorna 1 em caso de sucesso, e 0 em caso de erros.
*/
if(Soc==NULL) return 0;
int i;
fprintf(FStream,"%s\n",Soc->Name);
for(i=0;i<Soc->TeamCount;i++){
fprintf(FStream,"%d) %s %dp, %dj (%d-%d-%d), %dsg (%d-%d)\n",i+1,Soc->Teams[i].Name,Soc->Teams[i].Points,Soc->Teams[i].VictoryCount+Soc->Teams[i].DrawCount+Soc->Teams[i].DefeatCount,Soc->Teams[i].VictoryCount,Soc->Teams[i].DrawCount,Soc->Teams[i].DefeatCount,Soc->Teams[i].GoalCount-Soc->Teams[i].ReceivedGoalCount,Soc->Teams[i].GoalCount,Soc->Teams[i].ReceivedGoalCount);
}
return 1;
}
char S_Destroy(struct __soccer_tour_t *Soc){
/*
* Esta função limpa 'Soc' da memória.
*
* Ela retorna 1 em caso de sucesso, e 0 em caso de erros.
*/
if(Soc==NULL) return 0;
free(Soc->Teams);
free(Soc->Games);
free(Soc);
return 1;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
<NAME>
<EMAIL>
*/
int main(){
unsigned int i,j,n;
char is_prime;
scanf("%d",&n);
for(i=2;i<=n;i++){
is_prime=1;
for(j=2;j<=sqrt(n);j++){
if(i!=j && !(i%j)){
is_prime=0;
break;
}
}
if(is_prime){
if(i!=2){
printf(" %d",i);
}else{
printf("%d",i);
}
}
}
printf("\n");
return EXIT_SUCCESS;
}<file_sep><?php
/* Estes são os dados do servidor MySQL */
$dbServer = "HOSTNAME_BD";
$dbUsername = "USUARIO_BD";
$dbPassword = "<PASSWORD>";
$dbName = "NOME_BD";
/* Senha de acesso ao painel de administrador que mostra os dados capturados pela extensão */
$accessPassword = "<PASSWORD>";
$sleep = false;
if(file_get_contents("sleep.txt") == "true") {
$sleep = true;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int a,b,div=0;
scanf("%d",&a);
scanf("%d",&b);
while(a>=b){
div++;
a-=b;
}
printf("%d\n",div);
printf("%d",a);
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
<NAME>
<EMAIL>
*/
int main(){
unsigned int Nc=0,i;
int Ni[10000],Nr; // REVER O TAMANHO DA ARRAY!
double Mean=0,T=0;
while(1){
scanf("%d",&Nr);
if(Nr){
Ni[Nc]=Nr;
Mean+=Nr;
Nc++;
}else{
break;
}
}
Mean=Mean/(double)Nc;
for(i=0;i<Nc-2;i++){
T=pow(Ni[i+1],2)/(double)(Mean*((Ni[i]+Ni[i+1]+Ni[i+2])/3.0));
printf("%.4lf\n",T);
}
return EXIT_SUCCESS;
}<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <consts.h>
#include <buffer.h>
#include <register.h>
#include <bindex.h>
BTR_T *BT_init(char *path) {
char buff[BTREE_PAGE_SIZE];
BTR_T *aux;
aux = (BTR_T *) malloc(sizeof(BTR_T));
aux->stream = fopen(path, "rb+");
if(aux->stream == NULL) {
free(aux);
return NULL;
}
if(fread(buff, sizeof(char), BTREE_PAGE_SIZE, aux->stream) != BTREE_PAGE_SIZE) {
fclose(aux->stream);
free(aux);
return NULL;
}
memcpy(&aux->header.status, buff, sizeof(char));
memcpy(&aux->header.root, &buff[1], sizeof(int));
if(aux->header.status != STATUS_CONSISTENTE) {
fclose(aux->stream);
free(aux);
return NULL;
}
aux->header.status = STATUS_INCONSISTENTE;
if(fseek(aux->stream, 0, SEEK_SET) != 0 || fwrite(&aux->header.status, sizeof(char), 1, aux->stream) != 1) {
fclose(aux->stream);
free(aux);
return NULL;
}
aux->levelCount = 0;
return aux;
}
BTR_T *BT_new(char *path) {
char buff[BTREE_PAGE_SIZE];
BTR_T *aux;
aux = (BTR_T *) malloc(sizeof(BTR_T));
aux->stream = fopen(path, "wb+");
if(aux->stream == NULL) {
free(aux);
return NULL;
}
aux->header.status = STATUS_INCONSISTENTE;
aux->header.root = L_NIL;
aux->levelCount = 0;
memset(buff, LIXO, sizeof(char) * BTREE_PAGE_SIZE);
memcpy(buff, &aux->header.status, sizeof(char));
memcpy(&buff[1], &aux->header.root, sizeof(int));
if(fwrite(buff, sizeof(char), BTREE_PAGE_SIZE, aux->stream) != BTREE_PAGE_SIZE) {
fclose(aux->stream);
free(aux);
return NULL;
}
return aux;
}
long BT_count(BTR_T *index) {
return index->levelCount;
}
void BT_resetCount(BTR_T *index) {
index->levelCount = 0;
}
BTR_NODE BT_read_node(int RRN, BTR_T *index) {
char aux[BTREE_PAGE_SIZE], *R;
BTR_NODE auxN;
int i;
/* skip header, jump to node position and read a single node */
if(fseek(index->stream, BTREE_PAGE_SIZE + RRN * BTREE_PAGE_SIZE, SEEK_SET) != 0 || fread(aux, sizeof(char), BTREE_PAGE_SIZE, index->stream) != BTREE_PAGE_SIZE) {
fprintf(stderr, "Error reading BTREE page %d.\n", RRN);
exit(1);
}
auxN.nodeRRN = RRN;
R = aux;
memcpy(&auxN.leave, R, sizeof(char));
R += sizeof(char);
memcpy(&auxN.nItems, R, sizeof(int));
R += sizeof(int);
/* copy all pointers and keys */
for(i = 0; i < BTR_M - 1; i++) {
memcpy(&auxN.pointers[i], R, sizeof(int));
R += sizeof(int);
memcpy(&auxN.key[i], R, sizeof(int));
R += sizeof(int);
memcpy(&auxN.byteOffset[i], R, sizeof(long));
R += sizeof(long);
}
memcpy(&auxN.pointers[i], R, sizeof(int));
return auxN;
}
void BT_rewrite_node(BTR_NODE root, BTR_T *index) {
char aux[BTREE_PAGE_SIZE], *R;
int i;
memset(aux, BTR_TRASH, sizeof(char) * BTREE_PAGE_SIZE);
R = aux;
memcpy(R, &root.leave, sizeof(char));
R += sizeof(char);
memcpy(R, &root.nItems, sizeof(int));
R += sizeof(int);
/* copy all pointers and keys */
for(i = 0; i < root.nItems; i++) {
memcpy(R, &root.pointers[i], sizeof(int));
R += sizeof(int);
memcpy(R, &root.key[i], sizeof(int));
R += sizeof(int);
memcpy(R, &root.byteOffset[i], sizeof(long));
R += sizeof(long);
}
memcpy(R, &root.pointers[i], sizeof(int));
/* skip header, jump to node position and write a single node */
if(fseek(index->stream, BTREE_PAGE_SIZE + root.nodeRRN * BTREE_PAGE_SIZE, SEEK_SET) != 0 || fwrite(aux, sizeof(char), BTREE_PAGE_SIZE, index->stream) != BTREE_PAGE_SIZE) {
fprintf(stderr, "Error writing BTREE page %d.\n", root.nodeRRN);
exit(1);
}
}
int BT_write_node(BTR_NODE root, BTR_T *index) {
long pos;
/* skip to the end of the file */
if(fseek(index->stream, 0, SEEK_END) != 0) {
fprintf(stderr, "Error seeking new BTREE page.\n");
exit(1);
}
/* get file stream pointer position and calculate RRN */
if((pos = ftell(index->stream)) < 0) {
fprintf(stderr, "Error calculating new BTREE page RRN.\n");
exit(1);
}
root.nodeRRN = (pos - BTREE_PAGE_SIZE) / BTREE_PAGE_SIZE;
/* write a single new node */
BT_rewrite_node(root, index);
return root.nodeRRN;
}
long BT_search_node(BTR_NODE root, int key, BTR_T *index) {
int i;
index->levelCount++;
for(i = 0; i < root.nItems; i++) {
if(root.key[i] >= key) {
break;
}
}
if(i >= root.nItems) {
if(root.pointers[root.nItems] < 0) {
return -1;
}
return BT_search_node(BT_read_node(root.pointers[root.nItems], index), key, index);
}
if(key == root.key[i]) {
return root.byteOffset[i];
}
if(root.pointers[i] < 0) {
return -1;
}
return BT_search_node(BT_read_node(root.pointers[i], index), key, index);
}
long BT_search(int key, BTR_T *index) {
int i, j, aux;
if(index->header.root < 0) {
return -1;
}
return BT_search_node(BT_read_node(index->header.root, index), key, index);
}
int BT_push_node(REG_DATA *reg, int *keySplit, long *offsetSplit, BTR_NODE root, BTR_T *index) {
int i, key, pointer;
long keyOffset;
BTR_NODE newNode;
index->levelCount++;
key = reg->idServidor;
keyOffset = reg->byteOffset;
pointer = BTR_TRASH;
for(i = 0; i < root.nItems; i++) {
/*if(root.key[i] >= key) {
break;
}*/
if(root.key[i] > key) {
break;
}
}
/*if(i < root.nItems && key == root.key[i]) { // not inserting, but actually updating instead
if(keyOffset != root.byteOffset[i]) {
root.byteOffset[i] = keyOffset;
BT_rewrite_node(root, index);
}
return -2; // updated
}*/
if(root.pointers[i] >= 0 && (pointer = BT_push_node(reg, &key, &keyOffset, BT_read_node(root.pointers[i], index), index)) < 0) {
/* not leave node, so the algorithm must iterate down */
return -1;
}
if(root.nItems < BTR_M - 1) { /* Cabe nesse nó: só adiciona */
memmove(&root.key[i + 1], &root.key[i], sizeof(int) * (BTR_M - 2 - i));
memmove(&root.byteOffset[i + 1], &root.byteOffset[i], sizeof(long) * (BTR_M - 2 - i));
memmove(&root.pointers[i + 2], &root.pointers[i + 1], sizeof(int) * (BTR_M - 2 - i));
root.key[i] = key;
root.byteOffset[i] = keyOffset;
root.pointers[i + 1] = pointer;
root.nItems++;
BT_rewrite_node(root, index);
return -1;
}
memset(&newNode, BTR_TRASH, sizeof(BTR_NODE));
newNode.nItems = (BTR_M - 1) / 2;
newNode.leave = root.leave;
root.nItems = BTR_M / 2;
if(i > BTR_M / 2) { /* A chave a ser adicionada está no segundo (novo) nó. */
*keySplit = root.key[BTR_M / 2];
*offsetSplit = root.byteOffset[BTR_M / 2];
memcpy(newNode.key, &root.key[BTR_M / 2 + 1], sizeof(int) * (i - BTR_M / 2 - 1));
memcpy(newNode.byteOffset, &root.byteOffset[BTR_M / 2 + 1], sizeof(long) * (i - BTR_M / 2 - 1));
memcpy(newNode.pointers, &root.pointers[BTR_M / 2 + 1], sizeof(int) * (i - BTR_M / 2));
memcpy(&newNode.key[i - BTR_M / 2], &root.key[i], sizeof(int) * (BTR_M - 1 - i));
memcpy(&newNode.byteOffset[i - BTR_M / 2], &root.byteOffset[i], sizeof(long) * (BTR_M - 1 - i));
memcpy(&newNode.pointers[i - BTR_M / 2 + 1], &root.pointers[i + 1], sizeof(int) * (BTR_M - 1 - i));
newNode.key[i - BTR_M / 2 - 1] = key;
newNode.byteOffset[i - BTR_M / 2 - 1] = keyOffset;
newNode.pointers[i - BTR_M / 2] = pointer;
} else if(i < BTR_M / 2) { /* A chave a ser adicionada está no primeiro nó. */
*keySplit = root.key[BTR_M / 2 - 1];
*offsetSplit = root.byteOffset[BTR_M / 2 - 1];
memcpy(newNode.key, &root.key[BTR_M / 2], sizeof(int) * (BTR_M - BTR_M / 2 - 1));
memcpy(newNode.byteOffset, &root.byteOffset[BTR_M / 2], sizeof(long) * (BTR_M - BTR_M / 2 - 1));
memcpy(newNode.pointers, &root.pointers[BTR_M / 2], sizeof(int) * (BTR_M - BTR_M / 2));
memmove(&root.key[i + 1], &root.key[i], sizeof(int) * (BTR_M / 2 - 1 - i));
memmove(&root.byteOffset[i + 1], &root.byteOffset[i], sizeof(long) * (BTR_M / 2 - 1 - i));
memmove(&root.pointers[i + 2], &root.pointers[i + 1], sizeof(int) * (BTR_M / 2 - 1 - i));
root.key[i] = key;
root.byteOffset[i] = keyOffset;
root.pointers[i + 1] = pointer;
} else { /* A chave a ser promovida está exatamente no centro. */
*keySplit = key;
*offsetSplit = keyOffset;
memcpy(newNode.key, &root.key[BTR_M / 2], sizeof(int) * (BTR_M - BTR_M / 2 - 1));
memcpy(newNode.byteOffset, &root.byteOffset[BTR_M / 2], sizeof(long) * (BTR_M - BTR_M / 2 - 1));
memcpy(&newNode.pointers[1], &root.pointers[BTR_M / 2 + 1], sizeof(int) * (BTR_M - BTR_M / 2 - 1));
newNode.pointers[0] = pointer;
}
BT_rewrite_node(root, index);
return BT_write_node(newNode, index);
}
int BT_push(REG_DATA *reg, BTR_T *index) {
int key, pointer;
long keyOffset;
BTR_NODE root;
/* no root yet */
if(index->header.root < 0) {
root.nItems = 1;
root.key[0] = reg->idServidor;
root.byteOffset[0] = reg->byteOffset;
root.leave = BTR_IS_LEAVE;
root.pointers[0] = root.pointers[1] = -1;
index->header.root = BT_write_node(root, index);
return 3;
}
if((pointer=BT_push_node(reg, &key, &keyOffset, BT_read_node(index->header.root, index), index)) >= 0) {
/* Caso em que é necessário alocar uma nova raiz (chave promovida abaixo) */
memset(&root, BTR_TRASH, sizeof(BTR_NODE));
root.leave = BTR_IS_NOT_LEAVE;
root.nItems = 1;
root.key[0] = key;
root.byteOffset[0] = keyOffset;
root.pointers[0] = index->header.root;
root.pointers[1] = pointer;
index->header.root = BT_write_node(root, index);
return 2;
}
return 1;
}
int BT_flush(BTR_T *index) {
if(index == NULL) {
return 0;
}
fflush(index->stream);
return 1;
}
int BT_close(BTR_T *index) {
char aux[BTREE_PAGE_SIZE];
if(index == NULL) {
return 0;
}
memset(aux, LIXO, sizeof(char) * BTREE_PAGE_SIZE);
aux[0] = STATUS_CONSISTENTE;
memcpy(&aux[1], &index->header.root, sizeof(int));
if(fseek(index->stream, 0, SEEK_SET) != 0 || fwrite(aux, sizeof(char), BTREE_PAGE_SIZE, index->stream) != BTREE_PAGE_SIZE) {
return 0;
}
fclose(index->stream);
free(index);
return 1;
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <unordered_map>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
void testCase() {
string s, t;
char lastCh;
ll i, j;
bool ok;
cin >> s >> t;
if(s[0] != t[0]) {
cout << "NO" << endl;
return;
}
lastCh = t[0];
i = 1;
for(j = 1; j < s.size(); j++) {
ok = false;
for(; i < t.size(); i++) {
if(s[j] == t[i]) {
lastCh = t[i];
ok = true;
i++;
break;
}
if(t[i] != lastCh) {
cout << "NO" << endl;
return;
}
}
if(!ok) {
cout << "NO" << endl;
return;
}
}
for(; i < t.size(); i++) {
if(t[i] != lastCh) {
cout << "NO" << endl;
return;
}
}
cout << "YES" << endl;
}
int main(int argc, char **argv) {
ll T;
cin >> T;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <cabecalho.h>
/*
* ~ Trabalho Prático: Parte 2 ~
*
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
/* == Definições de pré-compilação == */
#define TAMANHO_PAGINA 116
#define PAGINA_NULO -1
#define ORDEM 10
/* == Declaração da estrutura de uma página == */
typedef struct {
int N,
P[ORDEM],
C[ORDEM - 1],
PR[ORDEM - 1];
int noP;
char
changed,
secondChance;
} PAGINA_NO;
/* Buffer-pool com 4 posições + uma posição reservada para nó raiz */
PAGINA_NO Buffer[4];
PAGINA_NO BufferRaiz;
/* Contadores de "page fault" e "page hit" */
int PageFault,
PageHit;
/* Funções usadas pela árvore-B */
void iniciarBufferPool();
void finalizarBufferPool(char *, FILE *);
int FIFOShift(FILE *);
PAGINA_NO lerPagina(int, FILE *);
void escreverPagina(PAGINA_NO, FILE *);
int inserirChaveRecursao(int, int, int, int *, int *, PAGINA_NO, FILE *);
int removerChaveRecursao(int, int *, int, int, int *, int *, int, int *, int *, int *, int *, PAGINA_NO, FILE *);
/* Implementação da Árvore-B */
int buscaRRN(int chave, FILE *arquivoIndices) {
/*
* Esta função retorna o RRN (do arquivo de dados) para uma chave de busca 'chave'.
* Em caso de chave não encontrada, retorna -1.
*/
PAGINA_NO Aux;
int i, altura;
/*Aux = lerPagina(cabIndice.noRaiz, arquivoIndices);*/
i = 0;
Aux.P[0] = cabIndice.noRaiz;
altura = cabIndice.altura;
do { /* Enquanto tiver filhos... */
Aux = lerPagina(Aux.P[i], arquivoIndices);
for(i = 0; i < Aux.N; i++) { /* Percorrer cada chave no nó */
if(Aux.C[i] > chave) { /* Verificar onde se posiciona a chave (busca dentro do nó) */
break;
} else if(Aux.C[i] == chave){
return Aux.PR[i]; /* Encontrou */
}
}
altura--;
} while(altura >= 0);
return -1; /* Não encontrou a chave na árvore-B */
}
void inserirChave(int chave, int RRN, FILE *arquivoIndices) {
/*
* Esta função insere a chave de busca 'chave', junto com o RRN 'RRN' na árvore-B.
*/
int P, C, PR;
PAGINA_NO Aux;
if(cabIndice.altura < 1) {
/* Caso em que não há raiz criada ainda */
memset(&Aux, PAGINA_NULO, sizeof(PAGINA_NO));
Aux.noP = 0;
Aux.N = 1;
Aux.C[0] = chave;
Aux.PR[0] = RRN;
cabIndice.altura = 1;
cabIndice.noRaiz = cabIndice.ultimoRRN = 0;
escreverPagina(Aux, arquivoIndices);
} else if((P = inserirChaveRecursao(chave, RRN, cabIndice.altura - 1, &C, &PR, lerPagina(cabIndice.noRaiz, arquivoIndices), arquivoIndices)) >= 0) {
/* Caso em que é necessário alocar uma nova raiz (chave promovida abaixo) */
memset(&Aux, PAGINA_NULO, sizeof(PAGINA_NO));
Aux.noP = ++cabIndice.ultimoRRN;
Aux.N = 1;
Aux.C[0] = C;
Aux.PR[0] = PR;
Aux.P[0] = cabIndice.noRaiz;
Aux.P[1] = P;
cabIndice.altura++;
cabIndice.noRaiz = Aux.noP;
escreverPagina(Aux, arquivoIndices);
}
}
int removerChave(int chave, FILE *arquivoIndices) {
/*
* Esta função remove a chave de busca 'chave' da árvore-B.
*
* Ela retorna o RRN da chave que acaba de ser removida.
*/
PAGINA_NO raiz;
int i, j = 97, Aux;
if(cabIndice.altura < 1)
return -1;
raiz = lerPagina(cabIndice.noRaiz, arquivoIndices);
for(i = 0; i < raiz.N; i++) { /* Percorrer cada chave no nó */
if(raiz.C[i] >= chave) /* Verificar onde se posiciona a chave (busca dentro do nó) */
break;
}
if(cabIndice.altura < 2 && i < raiz.N && raiz.C[i] == chave) {
/* Caso em que só há uma página (raiz) e a chave está nela */
Aux = 3;
j = raiz.PR[i];
}else if(cabIndice.altura < 2 && (i >= raiz.N || raiz.C[i] != chave)) {
/* Caso em que só há uma página (raiz) e a chave não está nela */
Aux = j = -1;
} else if(i < raiz.N && raiz.C[i] == chave) {
/* Caso em que há mais de uma página, mas a chave se encontra na raiz */
Aux = removerChaveRecursao(chave, &j, cabIndice.altura - 1, (i > 0) ? raiz.P[i - 1] : -1, (i > 0) ? &raiz.C[i - 1] : NULL, (i > 0) ? &raiz.PR[i - 1] : NULL, raiz.P[i + 1], &raiz.C[i], &raiz.PR[i], &raiz.C[i], &raiz.PR[i], lerPagina(raiz.P[i], arquivoIndices), arquivoIndices);
if(Aux == 0)
escreverPagina(raiz, arquivoIndices);
} else if(i < raiz.N) {
/* Caso em que há mais de uma página, e a chave não se encontra na raiz */
Aux = removerChaveRecursao(chave, &j, cabIndice.altura - 1, (i > 0) ? raiz.P[i - 1] : -1, (i > 0) ? &raiz.C[i - 1] : NULL, (i > 0) ? &raiz.PR[i - 1] : NULL, raiz.P[i + 1], &raiz.C[i], &raiz.PR[i], NULL, NULL, lerPagina(raiz.P[i], arquivoIndices), arquivoIndices);
} else {
/* Caso em que há mais de uma página, e a chave não se encontra na raiz (maior filho) */
Aux = removerChaveRecursao(chave, &j, cabIndice.altura - 1, raiz.P[i - 1], &raiz.C[i - 1], &raiz.PR[i - 1], -1, NULL, NULL, NULL, NULL, lerPagina(raiz.P[i], arquivoIndices), arquivoIndices);
}
if(Aux == 0 || Aux == -1) {
return j;
} else if(Aux == 1) {
escreverPagina(raiz, arquivoIndices);
return j;
} else if(Aux == 2) {
i--;
}
if(raiz.N < 2) {
/* Caso em que a altura da árvore diminui porque houve concatenação na raiz */
cabIndice.noRaiz = raiz.P[i + 1];
cabIndice.altura--;
lerPagina(cabIndice.noRaiz, arquivoIndices); /* Apenas para forçar colocação da página raiz no buffer-pool */
return j;
}
/* Caso em que houve concatenação na raiz sem diminuir a altura da árvore */
memmove(&raiz.C[i], &raiz.C[i + 1], sizeof(int) * (ORDEM - 2 - i));
memmove(&raiz.PR[i], &raiz.PR[i + 1], sizeof(int) * (ORDEM - 2 - i));
memmove(&raiz.P[i], &raiz.P[i + 1], sizeof(int) * (ORDEM - 1 - i));
raiz.N--;
escreverPagina(raiz, arquivoIndices);
return j;
}
/* Implementação das funções usadas pela árvore-B */
void iniciarBufferPool() {
/*
* Esta função inicia o buffer-pool, colocando todas as páginas lá presentes como nulas.
*/
memset(&Buffer, -1, sizeof(PAGINA_NO) * 4);
memset(&BufferRaiz, -1, sizeof(PAGINA_NO));
PageFault = PageHit = 0;
}
void finalizarBufferPool(char *nomeArquivoContadorPageFaultHit, FILE *arquivoIndices) {
/*
* Esta função finaliza o buffer-pool.
* Se existirem páginas que precisam ser escritas em disco, estas são escritas.
* Ela também escreve no arquivo de texto o número de "page fault" e "page hit".
*/
FILE *contadorPageFaultHit;
char aux[TAMANHO_PAGINA];
int i, j;
/* Escrever possíveis páginas que estavam modificadas no buffer no disco */
for(i = 0; i < 4; i++) {
if(Buffer[i].noP < 0 || Buffer[i].changed == 0)
continue;
memcpy(aux, &Buffer[i].N, sizeof(int));
for(j = 0; j < ORDEM - 1; j++) {
memcpy(aux + sizeof(int) * (j * 3 + 1), &Buffer[i].P[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 2), &Buffer[i].C[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 3), &Buffer[i].PR[j], sizeof(int));
}
memcpy(aux + sizeof(int) * (j * 3 + 1), &Buffer[i].P[j], sizeof(int));
if(fseek(arquivoIndices, TAMANHO_CABECALHO_INDICE + TAMANHO_PAGINA * Buffer[i].noP, SEEK_SET) == 0)
fwrite(aux, TAMANHO_PAGINA, 1, arquivoIndices);
}
/* Escrever nó raiz, se for o caso */
if(BufferRaiz.noP >= 0 && BufferRaiz.changed) {
memcpy(aux, &BufferRaiz.N, sizeof(int));
for(j = 0; j < ORDEM - 1; j++) {
memcpy(aux + sizeof(int) * (j * 3 + 1), &BufferRaiz.P[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 2), &BufferRaiz.C[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 3), &BufferRaiz.PR[j], sizeof(int));
}
memcpy(aux + sizeof(int) * (j * 3 + 1), &BufferRaiz.P[j], sizeof(int));
if(fseek(arquivoIndices, TAMANHO_CABECALHO_INDICE + TAMANHO_PAGINA * BufferRaiz.noP, SEEK_SET) == 0)
fwrite(aux, TAMANHO_PAGINA, 1, arquivoIndices);
}
/* Acrescentar contagem de "page fault" e "page hit" */
contadorPageFaultHit = fopen(nomeArquivoContadorPageFaultHit, "a");
if(contadorPageFaultHit == NULL)
return;
fprintf(contadorPageFaultHit, "Page fault: %d; Page hit: %d.\n", PageFault, PageHit);
fclose(contadorPageFaultHit);
}
int FIFOShift(FILE *arquivoIndices) {
/*
* Esta função cuida do Shifting da FIFO e lida com o Second-chance Algorithm.
*/
char aux[TAMANHO_PAGINA];
int i, j;
for(i = 0; i < 4; i++)
if(Buffer[i].noP < 0) /* Caso em que o Buffer ainda tem espaço sobrando */
return i;
for(i = 0; i < 4; i++) { /* Caso em que o Buffer está cheio e é necessário aplicar a política de substituição: SCA */
if(Buffer[i].secondChance) {
if(Buffer[i].changed) {
memcpy(aux, &Buffer[i].N, sizeof(int));
for(j = 0; j < ORDEM - 1; j++) {
memcpy(aux + sizeof(int) * (j * 3 + 1), &Buffer[i].P[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 2), &Buffer[i].C[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 3), &Buffer[i].PR[j], sizeof(int));
}
memcpy(aux + sizeof(int) * (j * 3 + 1), &Buffer[i].P[j], sizeof(int));
if(fseek(arquivoIndices, TAMANHO_CABECALHO_INDICE + TAMANHO_PAGINA * Buffer[i].noP, SEEK_SET) == 0)
fwrite(aux, TAMANHO_PAGINA, 1, arquivoIndices);
}
memmove(&Buffer[i], &Buffer[i + 1], sizeof(PAGINA_NO) * (3 - i));
return 3;
} else {
Buffer[i].secondChance = 1;
}
}
i = 0;
if(Buffer[i].changed) { /* Caso em que percorreu todos: volta para o início da fila */
memcpy(aux, &Buffer[i].N, sizeof(int));
for(j = 0; j < ORDEM - 1; j++) {
memcpy(aux + sizeof(int) * (j * 3 + 1), &Buffer[i].P[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 2), &Buffer[i].C[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 3), &Buffer[i].PR[j], sizeof(int));
}
memcpy(aux + sizeof(int) * (j * 3 + 1), &Buffer[i].P[j], sizeof(int));
if(fseek(arquivoIndices, TAMANHO_CABECALHO_INDICE + TAMANHO_PAGINA * Buffer[i].noP, SEEK_SET) == 0)
fwrite(aux, TAMANHO_PAGINA, 1, arquivoIndices);
}
memmove(&Buffer[i], &Buffer[i + 1], sizeof(PAGINA_NO) * (3 - i));
return 3;
}
PAGINA_NO lerPagina(int P, FILE *arquivoIndices) {
/*
* Esta função retorna uma página de índice relativo 'P' da árvore-B.
*
* Se a página já estiver no buffer-pool, não há acessos a disco.
* Caso contrário, a página entra para o buffer-pool (substituindo outra, se for o caso, de acordo
* com a política de substituição), fazendo acessos a disco.
*/
char aux[TAMANHO_PAGINA];
PAGINA_NO destino;
int i, j;
memset(&destino, PAGINA_NULO, sizeof(PAGINA_NO));
if(P < 0)
return destino;
if(BufferRaiz.noP == P) { /* Foi pedido o nó raiz. Ele está no Buffer? */
PageHit++;
return BufferRaiz;
}
for(i = 0; i < 4; i++) { /* Este nó está no Buffer? */
if(Buffer[i].noP == P) {
PageHit++;
Buffer[i].secondChance = 0;
return Buffer[i];
}
}
/* Não está no Buffer: carregar do disco */
if(fseek(arquivoIndices, TAMANHO_CABECALHO_INDICE + TAMANHO_PAGINA * P, SEEK_SET) != 0)
return destino;
if(fread(aux, TAMANHO_PAGINA, 1, arquivoIndices) != 1)
return destino;
PageFault++;
destino.noP = P;
destino.changed = 0;
destino.secondChance = 1;
memcpy(&destino.N, aux, sizeof(int));
for(i = 0; i < ORDEM - 1; i++) {
memcpy(&destino.P[i], aux + sizeof(int) * (i * 3 + 1), sizeof(int));
memcpy(&destino.C[i], aux + sizeof(int) * (i * 3 + 2), sizeof(int));
memcpy(&destino.PR[i], aux + sizeof(int) * (i * 3 + 3), sizeof(int));
}
memcpy(&destino.P[i], aux + sizeof(int) * (i * 3 + 1), sizeof(int));
if(cabIndice.noRaiz == P) { /* Se for um novo nó raiz */
if(BufferRaiz.noP >=0 && BufferRaiz.changed) { /* Salvar? */
memcpy(aux, &BufferRaiz.N, sizeof(int));
for(j = 0; j < ORDEM - 1; j++) {
memcpy(aux + sizeof(int) * (j * 3 + 1), &BufferRaiz.P[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 2), &BufferRaiz.C[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 3), &BufferRaiz.PR[j], sizeof(int));
}
memcpy(aux + sizeof(int) * (j * 3 + 1), &BufferRaiz.P[j], sizeof(int));
if(fseek(arquivoIndices, TAMANHO_CABECALHO_INDICE + TAMANHO_PAGINA * BufferRaiz.noP, SEEK_SET) == 0)
fwrite(aux, TAMANHO_PAGINA, 1, arquivoIndices);
}
memcpy(&BufferRaiz, &destino, sizeof(PAGINA_NO));
return destino;
}
memcpy(&Buffer[FIFOShift(arquivoIndices)], &destino, sizeof(PAGINA_NO));
return destino;
}
void escreverPagina(PAGINA_NO origem, FILE *arquivoIndices) {
/*
* Esta função salva uma página na árvore-B.
*
* Se a página já estiver no buffer-pool, não há acessos a disco.
* Caso contrário, a página entra para o buffer-pool (substituindo outra, se for o caso, de acordo
* com a política de substituição), fazendo acessos a disco.
*/
char aux[TAMANHO_PAGINA];
int i, j;
if(origem.noP < 0)
return;
origem.changed = 1;
origem.secondChance = 1;
if(BufferRaiz.noP == origem.noP) { /* Foi modificado o nó raiz. Ele está no Buffer? */
PageHit++;
memcpy(&BufferRaiz, &origem, sizeof(PAGINA_NO));
return;
}
for(i = 0; i < 4; i++) { /* Este nó está no Buffer? */
if(Buffer[i].noP == origem.noP) {
PageHit++;
memcpy(&Buffer[i], &origem, sizeof(PAGINA_NO));
Buffer[i].secondChance = 0;
return;
}
}
/* Não está no Buffer: colocar para salvar posteriormente, ou criar imediatamente em disco */
PageFault++;
if(origem.noP == cabIndice.ultimoRRN) { /* Página recém-criada: é necessário gravar em disco */
memcpy(aux, &origem.N, sizeof(int));
for(j = 0; j < ORDEM - 1; j++) {
memcpy(aux + sizeof(int) * (j * 3 + 1), &origem.P[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 2), &origem.C[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 3), &origem.PR[j], sizeof(int));
}
memcpy(aux + sizeof(int) * (j * 3 + 1), &origem.P[j], sizeof(int));
if(fseek(arquivoIndices, TAMANHO_CABECALHO_INDICE + TAMANHO_PAGINA * origem.noP, SEEK_SET) == 0)
fwrite(aux, TAMANHO_PAGINA, 1, arquivoIndices);
origem.changed = 0;
}
if(cabIndice.noRaiz == origem.noP) { /* Se for um novo nó raiz */
if(BufferRaiz.noP >=0 && BufferRaiz.changed) { /* Salvar? */
memcpy(aux, &BufferRaiz.N, sizeof(int));
for(j = 0; j < ORDEM - 1; j++) {
memcpy(aux + sizeof(int) * (j * 3 + 1), &BufferRaiz.P[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 2), &BufferRaiz.C[j], sizeof(int));
memcpy(aux + sizeof(int) * (j * 3 + 3), &BufferRaiz.PR[j], sizeof(int));
}
memcpy(aux + sizeof(int) * (j * 3 + 1), &BufferRaiz.P[j], sizeof(int));
if(fseek(arquivoIndices, TAMANHO_CABECALHO_INDICE + TAMANHO_PAGINA * BufferRaiz.noP, SEEK_SET) == 0)
fwrite(aux, TAMANHO_PAGINA, 1, arquivoIndices);
}
memcpy(&BufferRaiz, &origem, sizeof(PAGINA_NO));
return;
}
memcpy(&Buffer[FIFOShift(arquivoIndices)], &origem, sizeof(PAGINA_NO));
}
int inserirChaveRecursao(int chave, int RRN, int altura, int *CSplit, int *PRSplit, PAGINA_NO raiz, FILE *arquivoIndices) {
/*
* Esta é a recursão que faz a inserção de uma chave na árvore-B.
* Ela já lida com Split quando necessário, e preza pelo menor número de acessos
* a disco que puder.
*/
int i, P, C, PR;
PAGINA_NO Aux;
C = chave;
PR = RRN;
P = PAGINA_NULO;
for(i = 0; i < raiz.N; i++) { /* Percorrer cada chave no nó */
if(raiz.C[i] > chave) /* Verificar onde se posiciona a chave (busca dentro do nó) */
break;
}
/* Chamar recursão (se não for nó folha), e verificar se houve chave promovida. */
if(altura > 0 && (P=inserirChaveRecursao(chave, RRN, altura - 1, &C, &PR, lerPagina(raiz.P[i], arquivoIndices), arquivoIndices)) < 0) {
return -1;
}
/* Aparentemente chegou uma chave para ser adicionada nesse nó. */
if(raiz.N < ORDEM - 1) {
/* Tem espaço pra ela nesse nó. Perfeito, só adiciona. */
memmove(&raiz.C[i + 1], &raiz.C[i], sizeof(int) * (ORDEM - 2 - i));
memmove(&raiz.PR[i + 1], &raiz.PR[i], sizeof(int) * (ORDEM - 2 - i));
memmove(&raiz.P[i + 2], &raiz.P[i + 1], sizeof(int) * (ORDEM - 2 - i));
raiz.C[i] = C;
raiz.PR[i] = PR;
raiz.P[i + 1] = P;
raiz.N++;
escreverPagina(raiz, arquivoIndices);
return -1;
}
/* Eita! Não tem espaço pra essa chave aqui. Vamos ter que fazer Split e promover alguém. */
memset(&Aux, PAGINA_NULO, sizeof(PAGINA_NO));
Aux.noP = ++cabIndice.ultimoRRN;
Aux.N = (ORDEM - 1) / 2;
raiz.N = ORDEM / 2;
if(i > ORDEM/2) { /* Caso em que a chave promovida anteriormente está no primeiro nó */
*CSplit = raiz.C[ORDEM/2];
*PRSplit = raiz.PR[ORDEM/2];
memcpy(&Aux.C, &raiz.C[ORDEM/2 + 1], sizeof(int) * (i - ORDEM/2 - 1));
memcpy(&Aux.PR, &raiz.PR[ORDEM/2 + 1], sizeof(int) * (i - ORDEM/2 - 1));
memcpy(&Aux.P, &raiz.P[ORDEM/2 + 1], sizeof(int) * (i - ORDEM/2));
memcpy(&Aux.C[i - ORDEM/2], &raiz.C[i], sizeof(int) * (ORDEM - 1 - i));
memcpy(&Aux.PR[i - ORDEM/2], &raiz.PR[i], sizeof(int) * (ORDEM - 1 - i));
memcpy(&Aux.P[i - ORDEM/2 + 1], &raiz.P[i + 1], sizeof(int) * (ORDEM - 1 - i));
Aux.C[i - ORDEM/2 - 1] = C;
Aux.PR[i - ORDEM/2 - 1] = PR;
Aux.P[i - ORDEM/2] = P;
} else if(i < ORDEM/2) { /* Caso em que a chave promovida anteriormente está no segundo nó */
*CSplit = raiz.C[ORDEM/2 - 1];
*PRSplit = raiz.PR[ORDEM/2 - 1];
memcpy(&Aux.C, &raiz.C[ORDEM/2], sizeof(int) * (ORDEM - ORDEM/2 - 1));
memcpy(&Aux.PR, &raiz.PR[ORDEM/2], sizeof(int) * (ORDEM - ORDEM/2 - 1));
memcpy(&Aux.P, &raiz.P[ORDEM/2], sizeof(int) * (ORDEM - ORDEM/2));
memmove(&raiz.C[i + 1], &raiz.C[i], sizeof(int) * (ORDEM/2 - 1 - i));
memmove(&raiz.PR[i + 1], &raiz.PR[i], sizeof(int) * (ORDEM/2 - 1 - i));
memmove(&raiz.P[i + 2], &raiz.P[i + 1], sizeof(int) * (ORDEM/2 - 1 - i));
raiz.C[i] = C;
raiz.PR[i] = PR;
raiz.P[i + 1] = P;
} else { /* Caso em que a chave promovida anteriormente está no centro */
*CSplit = C;
*PRSplit = PR;
memcpy(&Aux.C, &raiz.C[ORDEM/2], sizeof(int) * (ORDEM - ORDEM/2 - 1));
memcpy(&Aux.PR, &raiz.PR[ORDEM/2], sizeof(int) * (ORDEM - ORDEM/2 - 1));
memcpy(&Aux.P[1], &raiz.P[ORDEM/2 + 1], sizeof(int) * (ORDEM - ORDEM/2 - 1));
Aux.P[0] = P;
}
memset(&raiz.C[ORDEM/2], PAGINA_NULO, sizeof(int) * (ORDEM - ORDEM/2 - 1));
memset(&raiz.PR[ORDEM/2], PAGINA_NULO, sizeof(int) * (ORDEM - ORDEM/2 - 1));
memset(&raiz.P[ORDEM/2 + 1], PAGINA_NULO, sizeof(int) * (ORDEM - ORDEM/2 - 1));
escreverPagina(Aux, arquivoIndices);
escreverPagina(raiz, arquivoIndices);
return Aux.noP;
}
int removerChaveRecursao(int chave, int *RRN, int altura, int PEsq, int *CEsqConcat, int *PREsqConcat, int PDir, int *CDirConcat, int *PRDirConcat, int *trocaC, int *trocaPR, PAGINA_NO raiz, FILE *arquivoIndices) {
/*
* Esta é a recursão que faz a remoção de uma chave na árvore-B.
* Ela já lida com Concatenação quando necessário, e preza pelo menor número de acessos
* a disco que puder.
*/
PAGINA_NO AuxL, AuxR;
int i, j, Aux;
for(i = 0; i < raiz.N; i++) { /* Percorrer cada chave no nó */
if(raiz.C[i] >= chave) /* Verificar onde se posiciona a chave (busca dentro do nó) */
break;
}
if(altura > 1) {
/* Caso em que a recursão não está em nó-folha */
if(i < raiz.N && raiz.C[i] == chave) {
Aux = removerChaveRecursao(chave, RRN, altura - 1, (i > 0) ? raiz.P[i - 1] : -1, (i > 0) ? &raiz.C[i - 1] : NULL, (i > 0) ? &raiz.PR[i - 1] : NULL, raiz.P[i + 1], &raiz.C[i], &raiz.PR[i], &raiz.C[i], &raiz.PR[i], lerPagina(raiz.P[i], arquivoIndices), arquivoIndices);
if(Aux == 0)
escreverPagina(raiz, arquivoIndices);
} else if(i < raiz.N) {
Aux = removerChaveRecursao(chave, RRN, altura - 1, (i > 0) ? raiz.P[i - 1] : -1, (i > 0) ? &raiz.C[i - 1] : NULL, (i > 0) ? &raiz.PR[i - 1] : NULL, raiz.P[i + 1], &raiz.C[i], &raiz.PR[i], trocaC, trocaPR, lerPagina(raiz.P[i], arquivoIndices), arquivoIndices);
} else {
Aux = removerChaveRecursao(chave, RRN, altura - 1, raiz.P[i - 1], &raiz.C[i - 1], &raiz.PR[i - 1], -1, NULL, NULL, trocaC, trocaPR, lerPagina(raiz.P[i], arquivoIndices), arquivoIndices);
}
if(Aux == 0 || Aux == -1) {
return Aux;
} else if(Aux == 1) {
escreverPagina(raiz, arquivoIndices);
return 0;
} else if(Aux == 2) {
i--;
}
}else if(trocaC != NULL) {
/* Caso em que a chave não está em nó-folha */
i = raiz.N - 1;
Aux = *trocaC;
*trocaC = raiz.C[i];
raiz.C[i] = Aux;
Aux = *trocaPR;
*trocaPR = raiz.PR[i];
*RRN = raiz.PR[i] = Aux;
} else if(i >= raiz.N || raiz.C[i]!= chave) {
/* Caso "chave não encontrada" */
*RRN = -1;
return -1;
} else {
/* Salvar o RRN */
*RRN = raiz.PR[i];
}
/* Vamos remover a chave em i */
memmove(&raiz.C[i], &raiz.C[i + 1], sizeof(int) * (ORDEM - 2 - i));
memmove(&raiz.PR[i], &raiz.PR[i + 1], sizeof(int) * (ORDEM - 2 - i));
memmove(&raiz.P[i], &raiz.P[i + 1], sizeof(int) * (ORDEM - 1 - i));
raiz.N--;
if(raiz.N >= ORDEM / 2 - 1) {
/* Caso em que não houve underflow: perfeito! */
escreverPagina(raiz, arquivoIndices);
return 0;
}
/* Houve underflow. Precisamos tratar isso... */
if(PEsq >= 0 && (AuxL = lerPagina(PEsq, arquivoIndices)).N >= ORDEM/2) {
/* 1) Tentar redistribuir com o irmão da esquerda */
j = (AuxL.N + raiz.N + 1) / 2;
memmove(&raiz.C[AuxL.N - j], raiz.C, sizeof(int) * (ORDEM / 2 - 2));
memmove(&raiz.PR[AuxL.N - j], raiz.PR, sizeof(int) * (ORDEM / 2 - 2));
memmove(&raiz.P[AuxL.N - j], raiz.P, sizeof(int) * (ORDEM / 2 - 1));
memcpy(&raiz.C[AuxL.N - j - 1], CEsqConcat, sizeof(int));
memcpy(&raiz.PR[AuxL.N - j - 1], PREsqConcat, sizeof(int));
memcpy(raiz.C, &AuxL.C[j + 1], sizeof(int) * (AuxL.N - j - 1));
memcpy(raiz.PR, &AuxL.PR[j + 1], sizeof(int) * (AuxL.N - j - 1));
memcpy(raiz.P, &AuxL.P[j], sizeof(int) * (AuxL.N - j));
*CEsqConcat = AuxL.C[j];
*PREsqConcat = AuxL.PR[j];
raiz.N += AuxL.N - j;
AuxL.N = j;
escreverPagina(AuxL, arquivoIndices);
escreverPagina(raiz, arquivoIndices);
return 1;
}else if(PDir >= 0 && (AuxR = lerPagina(PDir, arquivoIndices)).N >= ORDEM/2) {
/* Não deu: 2) Tentar redistribuir com o irmão da direita */
j = (AuxR.N + raiz.N + 1) / 2 - raiz.N - 1;
memcpy(&raiz.C[ORDEM / 2 - 2], CDirConcat, sizeof(int));
memcpy(&raiz.PR[ORDEM / 2 - 2], PRDirConcat, sizeof(int));
memcpy(&raiz.C[ORDEM / 2 - 1], AuxR.C, sizeof(int) * j);
memcpy(&raiz.PR[ORDEM / 2 - 1], AuxR.PR, sizeof(int) * j);
memcpy(&raiz.P[ORDEM / 2 - 1], &AuxR.P, sizeof(int) * (j + 1));
*CDirConcat = AuxR.C[j];
*PRDirConcat = AuxR.PR[j];
memmove(AuxR.C, &AuxR.C[j + 1], sizeof(int) * (ORDEM - 2 - j));
memmove(AuxR.PR, &AuxR.PR[j + 1], sizeof(int) * (ORDEM - 2 - j));
memmove(AuxR.P, &AuxR.P[j + 1], sizeof(int) * (ORDEM - 1 - j));
AuxR.N -= j + 1;
raiz.N += j + 1;
escreverPagina(AuxR, arquivoIndices);
escreverPagina(raiz, arquivoIndices);
return 1;
}
/* Não deu, somos obrigados a concatenar: 3) Tentar concatenar com o irmão da esquerda */
if(PEsq >= 0) {
memmove(&raiz.C[AuxL.N + 1], raiz.C, sizeof(int) * raiz.N);
memmove(&raiz.PR[AuxL.N + 1], raiz.PR, sizeof(int) * raiz.N);
memmove(&raiz.P[AuxL.N + 1], raiz.P, sizeof(int) * (raiz.N + 1));
memcpy(&raiz.C[AuxL.N], CEsqConcat, sizeof(int));
memcpy(&raiz.PR[AuxL.N], PREsqConcat, sizeof(int));
memcpy(raiz.C, AuxL.C, sizeof(int) * AuxL.N);
memcpy(raiz.PR, AuxL.PR, sizeof(int) * AuxL.N);
memcpy(raiz.P, AuxL.P, sizeof(int) * (AuxL.N + 1));
raiz.N += AuxL.N + 1;
escreverPagina(raiz, arquivoIndices);
return 2;
}
/* Não deu: 4) Concatenar com o irmão da direita */
memmove(&AuxR.C[raiz.N + 1], AuxR.C, sizeof(int) * AuxR.N);
memmove(&AuxR.PR[raiz.N + 1], AuxR.PR, sizeof(int) * AuxR.N);
memmove(&AuxR.P[raiz.N + 1], AuxR.P, sizeof(int) * (AuxR.N + 1));
memcpy(&AuxR.C[raiz.N], CDirConcat, sizeof(int));
memcpy(&AuxR.PR[raiz.N], PRDirConcat, sizeof(int));
memcpy(AuxR.C, raiz.C, sizeof(int) * raiz.N);
memcpy(AuxR.PR, raiz.PR, sizeof(int) * raiz.N);
memcpy(AuxR.P, raiz.P, sizeof(int) * (raiz.N + 1));
AuxR.N += raiz.N + 1;
escreverPagina(AuxR, arquivoIndices);
return 3;
}
<file_sep>#include <stdlib.h>
#include <string.h>
typedef struct __VECTOR_NODE_T {
void *item;
struct __VECTOR_NODE_T *next;
} VECTOR_NODE_T;
typedef struct __VECTOR_T {
VECTOR_NODE_T *first;
unsigned long n;
size_t memsize;
} VECTOR_T;
VECTOR_T *V_new(size_t memsize) {
VECTOR_T *aux;
if(memsize < 1) {
return NULL;
}
aux = (VECTOR_T *) malloc(sizeof(VECTOR_T));
aux->memsize = memsize;
aux->first = NULL;
aux->n = 0;
return aux;
}
int V_pushback(void *item, VECTOR_T *v) {
VECTOR_NODE_T *aux;
if(item == NULL || v == NULL) {
return 0;
}
aux = (VECTOR_NODE_T *) malloc(sizeof(VECTOR_NODE_T));
aux->item = (void *) malloc(v->memsize);
aux->next = v->first;
v->first = aux;
v->n++;
memcpy(aux->item, item, v->memsize);
return 1;
}
unsigned long V_size(VECTOR_T *v) {
return v->n;
}
unsigned long V_copy(void *dest, VECTOR_T *v) {
VECTOR_NODE_T *n;
void *p;
if(v == NULL || v->n < 1) {
return 0;
}
p = dest + (v->n - 1) * v->memsize;
n = v->first;
while(n != NULL) {
memcpy(p, n->item, v->memsize);
p -= v->memsize;
n = n->next;
}
return v->n;
}
unsigned long V_build(void *dest, VECTOR_T *v) {
VECTOR_NODE_T *n;
void *aux, *p;
if(v == NULL || v->n < 1) {
aux = NULL;
memcpy(dest, &aux, sizeof(void *));
return 0;
}
aux = (void *) malloc(v->memsize * v->n);
p = aux + (v->n - 1) * v->memsize;
n = v->first;
while(n != NULL) {
memcpy(p, n->item, v->memsize);
p -= v->memsize;
n = n->next;
}
memcpy(dest, &aux, sizeof(void *));
return v->n;
}
int V_clear(VECTOR_T *v) {
VECTOR_NODE_T *n, *aux;
if(v == NULL) {
return 0;
}
n = v->first;
while(n != NULL) {
aux = n;
n = n->next;
free(aux->item);
free(aux);
}
v->first = NULL;
v->n = 0;
return 1;
}
void V_destroy(VECTOR_T *v) {
VECTOR_NODE_T *n, *aux;
if(v == NULL) {
return;
}
n = v->first;
while(n != NULL) {
aux = n;
n = n->next;
free(aux->item);
free(aux);
}
free(v);
}
<file_sep># Trabalho 1 de Introdução a Redes Neurais
Neste repositório encontram-se os arquivos do Trabalho 1 de Introdução à Redes Neurais de 2019.1.
# Grupo
- <NAME> (Nº 10349540)
- <NAME> (Nº 10369014)
- <NAME> (Nº 9081453)
# Descrição do repositório
No arquivo [Codigo.py](Codigo.py) encontra-se o código do programa da rede neural implementada (em Python 3), enquanto que no arquivo [semeion.data](semeion.data) encontra-se o conjunto de dados que foi usado para treinamento e testagem da rede. O arquivo [semeion.names](semeion.names) fornece uma descrição para este conjunto de dados utilizado.
<file_sep>import numpy as np
import imageio
#
# ~ Trabalho 5: Inpainting usando FFTs ~
#
# <NAME>
# <EMAIL>
# Nº USP 10369014
# Processamento de Imagens: SCC-0251 2018.1
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
# == DEFINIÇÃO DE FUNÇÕES ==
def Normalize(Arr):
"Esta função normaliza a imagem Arr entre 0-255."
Res = np.copy(Arr) # Criar cópia da array que será normalizada
Res -= np.min(Res) # Alinhar em 0
Res *= 255 / np.max(Res) # Agora o máximo é 255
return Res
def Apply_Filter_Frequency(Arr, Mask):
"Aplica um filtro Mask sob uma imagem Arr no domínio das frequências."
Res = np.zeros(Arr.shape, dtype=np.float)
Res[: Mask.shape[0], : Mask.shape[1]] += Mask # Filtro do tamanho da imagem
Res = np.fft.fft2(Res) # FFT do filtro estendido
Res = np.multiply(Arr, Res) # Multiplicar ponto a ponto
return Res
def Apply_GerchbergPapoulis(Arr, Mask, T):
"Aplica o algoritmo Gerchberg-Papoulis na imagem Arr usando uma máscara Mask e T interações."
Convolution_Mask = np.ones([7, 7], dtype=np.float) / (7 * 7) # Criar filtro de média
M = np.fft.fft2(Mask) # Máscara no domínio das frequências
Mask = Mask.astype(np.float) / 255 # É esperado que seja 0 ou 1
Last = Arr # Começa com a imagem original
for _ in range(T): # T interações
G = np.fft.fft2(Last) # Faz a transformada
G = np.where(M < 0.01 * np.max(G), G, 0) # Filtro "passa-alta" (ii)
G = np.where(M < 0.9 * np.max(M), G, 0) # Filtro "passa-baixa" (i)
G = Apply_Filter_Frequency(G, Convolution_Mask) # Aplicar o filtro de média 7x7
G = np.real(np.fft.ifft2(G)) # Transformada inversa
G = Normalize(G) # [0 - 255]
G = np.multiply(1 - Mask, Arr) + np.multiply(Mask, G) # Estimativa k
Last = G
return Last
# == MAIN ==
# Leitura dos dados da entrada padrão
filename_i = str(input()).rstrip()
filename_g = str(input()).rstrip()
filename_m = str(input()).rstrip()
T = int(input())
# Carregamento das imagens
i = imageio.imread(filename_i) # Carregar imagem original
g = imageio.imread(filename_g) # Carregar imagem que precisa ser restaurada
m = imageio.imread(filename_m) # Carregar máscara para restauração
# Executar o algorítmo
g = Apply_GerchbergPapoulis(g, m, T)
# Converter para o tipo inteiro de 8 bits
g = np.uint8(g)
# Calcular RMSE
RMSE = np.sqrt(np.sum(np.power(i - g, 2)) / i.size)
# Imprimir resultado do RMSE com 5 casas decimais
print("%.5f" % round(RMSE, 5))
# == DEBUGGING ==
#imageio.imwrite("out_expected.png", i)
#imageio.imwrite("out_generated.png", g)
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include "labyrinth.h"
/*
* ~ Labirinto com Tesouro ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv){
LABYRINTH *Lab;
Lab=ReadLab(stdin); // Ler labirinto da entrada padrão.
FindSolutionsWithoutTreasure(Lab); // Achar soluções sem passar pela câmara de tesouro.
FindSolutionsWithTreasure(Lab); // Achar soluções passando pela câmara de tesouro.
SortSolutions(Lab); // Ordenar as soluções encontradas.
PrintSolutions(Lab,stdout); // Imprimir as soluções na saída de texto.
DestroyLab(Lab); // Limpar memória usada.
return EXIT_SUCCESS;
}
<file_sep>import numpy as np
import imageio
import math
#
# ~ Trabalho 2: Realce e Superresolução ~
#
# <NAME>
# Nº USP: 10369014
# <EMAIL>
# Processamento de Imagens: SCC-0251 2018.1
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
# == DEFINIÇÃO DE FUNÇÕES ==
def Histogram(Arr):
"Calcula o histograma acumulado da imagem 'Arr'"
Sum = np.zeros(256, dtype=np.float) # Alocar matriz do histograma zerada
for x in range(0, Arr.shape[0]): # Somar valores
for y in range(0, Arr.shape[1]):
Sum[int(Arr[x, y])] += 1
for i in range(1, 256): # Fazer cumulativo
Sum[i] += Sum[i - 1]
return Sum
def HistogramList(ArrList):
"Calcula o histograma acumulado das imagens em 'ArrList'"
Sum = np.zeros(256, dtype=np.float) # Alocar matriz do histograma zerada
for i in range(0, len(ArrList)): # Para cada imagem na lista...
for x in range(0, ArrList[i].shape[0]): # Somar valores
for y in range(0, ArrList[i].shape[1]):
Sum[int(ArrList[i][x, y])] += 1
for i in range(1, 256): # Fazer cumulativo
Sum[i] += Sum[i - 1]
return Sum
def Equalise(Arr, Histogram, Count):
"Realiza a equalização do histograma 'Histogram' (feito a partir de 'Count' imagens) na imagem 'Arr', retornando uma imagem resultado."
NewArr = np.empty(Arr.shape, dtype=np.float) # Aloca a imagem resultado
Ratio = float(255/(NewArr.shape[0] * NewArr.shape[1] * Count))
for x in range(0, NewArr.shape[0]): # Equalizar
for y in range(0, NewArr.shape[1]):
NewArr[x, y] = np.float(Ratio * Histogram[int(Arr[x, y])])
return NewArr
def Gamma(Arr, Param):
"Aplica a correção de Gamma na imagem 'Arr' de acordo com o parâmetro 'Param', retornando uma imagem resultado"
NewArr = np.empty(Arr.shape, dtype=np.float) # Aloca a imagem resultado
Power = float(1/Param)
for x in range(0, NewArr.shape[0]): # Aplicar correção de Gamma
for y in range(0, NewArr.shape[1]):
NewArr[x, y] = np.float(math.floor(255 * pow(Arr[x, y]/255.0, Power)))
return NewArr
# == MAIN ==
# Leitura dos dados da entrada padrão
imglow = str(input()).rstrip()
imghigh = str(input()).rstrip()
method = int(input())
param = float(input())
# Carregamento das imagens
Images = [ imageio.imread(imglow + "1.png"),
imageio.imread(imglow + "2.png"),
imageio.imread(imglow + "3.png"),
imageio.imread(imglow + "4.png")]
# Processar realce
if method == 1:
for i in range(0, 4):
HistogramSum = Histogram(Images[i])
Images[i] = Equalise(Images[i], HistogramSum, 1)
elif method == 2:
HistogramSum = HistogramList(Images)
for i in range(0, 4):
Images[i] = Equalise(Images[i], HistogramSum, 4)
elif method == 3:
for i in range(0, 4):
Images[i] = Gamma(Images[i], param)
# Alocar imagem de alta resolução
HighResImage = np.empty([Images[0].shape[0]*2, Images[0].shape[1]*2], dtype=np.float)
# Gerar imagem de alta resolução
for x in range(0, Images[0].shape[0]):
for y in range(0, Images[0].shape[1]): # Carregar a matriz 2x2 a partir das 4 imagens originais
HighResImage[x*2, y*2] = np.float(Images[0][x, y])
HighResImage[x*2, y*2 + 1] = np.float(Images[1][x, y])
HighResImage[x*2 + 1, y*2] = np.float(Images[2][x, y])
HighResImage[x*2 + 1, y*2 + 1] = np.float(Images[3][x, y])
# Agora não precisamos mais das imagens de menor resolução. Permitir que o Garbage Collector libere elas
del Images
# Converter para o tipo uint8
HighResImage = HighResImage.astype(np.uint8)
# Carregar imagem original do disco e converter para tipo uint8
LoadedImg = imageio.imread(imghigh + ".png")
LoadedImg = LoadedImg.astype(np.uint8)
# Calcular RMSE
RMSE = float(0)
for x in range(0, LoadedImg.shape[0]):
for y in range(0, LoadedImg.shape[1]):
RMSE += math.pow(float(HighResImage[x, y]) - float(LoadedImg[x, y]), 2)
RMSE = math.sqrt(RMSE / (LoadedImg.shape[0]*LoadedImg.shape[1]))
# Imprimir resultado do RMSE com 4 casas decimais
print("%.4f" % round(RMSE, 4))
# == DEBUGGING ==
# Salvar minhas imagens geradas e imagem lida do disco para comparação
#imageio.imwrite("out_expected.png", LoadedImg)
#imageio.imwrite("out_generated0.png", HighResImage)
#imageio.imwrite("out_generated1.png", Images[0].astype(dtype=np.uint8))
#imageio.imwrite("out_generated2.png", Images[1].astype(dtype=np.uint8))
#imageio.imwrite("out_generated3.png", Images[2].astype(dtype=np.uint8))
#imageio.imwrite("out_generated4.png", Images[3].astype(dtype=np.uint8))
<file_sep>from sklearn.cluster import KMeans
import numpy as np
import re
#
# ~ Trabalho 2: Implementação de uma rede RBF ~
#
# Grupo:
# <NAME> (N 10349540)
# <NAME> (N 10369014)
# <NAME> (N 9081453)
#
# Introdução à Redes Neurais: SCC-0570 2019.1
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
# Constantes do programa
N_CLUSTER_CENTERS = 60 # Número de neurônios na camada oculta (cluster centers)
ERROR_THRESHOLD = 0.5 # Erro máximo pra ser considerado teste incorreto (recomendado: algo entre 0.1 e 0.5)
# Configuração inicial dos pesos w de cada neurônio da camada de saída e dos cluster centers:
weights = None
centroids = None
sigma = None
learned = 0
# Função que lê o arquivo de entrada.
def readData(filePath):
v = [ ]
try:
with open(filePath, "r") as fStream:
lines = fStream.readlines()
for line in lines:
aux = line.strip()
if aux == '':
print("Linha vazia encontrada no arquivo. Ignorando linha...")
continue
items = re.split(r'\s+', aux)
if(len(items) != 266):
print("Linha em formato inválido encontrada no arquivo. Ignorando linha...")
continue
v.append([ items[:256], items[256:266] ])
for i in range(len(v)):
for j in range(256):
v[i][0][j] = float(v[i][0][j])
for j in range(10):
v[i][1][j] = float(v[i][1][j])
except:
return None
return v
# Função de ativação (gaussiana)
def gauss(value, center):
global sigma
return np.exp(np.power(np.linalg.norm(value - center), 2)/np.power(5 * sigma, 2) * -1)
# Função que realiza o aprendizado a partir de um dataset de entrada (256 bits das N imagens).
def learn(dataset, activationFunction):
global learned, centroids, weights, sigma
values = np.array(dataset, copy=True)
inputs = np.empty([values.shape[0], 256], dtype=np.float)
classes = np.empty([values.shape[0], 10], dtype=np.float)
distances = np.empty([values.shape[0], N_CLUSTER_CENTERS], dtype=np.float)
for i in range(values.shape[0]):
inputs[i] = values[i][0]
classes[i] = values[i][1]
# K-mean
KMi = KMeans(n_clusters=N_CLUSTER_CENTERS, max_iter=100)
KMi.fit(inputs)
centroids = KMi.cluster_centers_
# Calcular sigma
distances = np.empty([N_CLUSTER_CENTERS, N_CLUSTER_CENTERS], dtype=np.float)
for i in range(N_CLUSTER_CENTERS):
for j in range(N_CLUSTER_CENTERS):
distances[i][j] = np.linalg.norm(centroids[i] - centroids[j])
sigma = np.amax(distances) / np.sqrt(N_CLUSTER_CENTERS)
# Ajustar pesos
distances = np.empty([values.shape[0], N_CLUSTER_CENTERS], dtype=np.float)
for i in range(values.shape[0]):
for j in range(N_CLUSTER_CENTERS):
distances[i][j] = activationFunction(inputs[i], centroids[j])
wFac = np.dot(np.linalg.inv(np.dot(distances.T, distances)), distances.T)
weights = np.dot(wFac, classes).T
learned += values.shape[0]
# Função que testa uma única entrada na rede neural.
def test(inputValues, activationFunction):
global weights, centroids
values = np.array(inputValues, copy=True)
distance = np.empty([N_CLUSTER_CENTERS])
for i in range(N_CLUSTER_CENTERS):
distance[i] = activationFunction(np.array(values[0], dtype=np.float), centroids[i])
result = np.empty(10, dtype=np.float)
for i in range(10):
result[i] = np.sum(np.multiply(weights[i], distance))
#result = np.dot(distance, weights)
return [ np.abs(np.array(values[1], dtype=np.float) - result), result ]
# Função que divide o conjunto de dados em k partes.
def splitData(inputData, k):
list = [ ]
groupSize = int(len(inputData) / k)
for i in range(k):
list.append(inputData[i * groupSize:i * groupSize + groupSize])
return list
# Implementação do menu principal
print("Bem-vinde à nossa rede neural artificial, implementada através de uma rede RBF.")
while True:
print()
print("== Opções ==")
print("1. Treinar com conjunto de dados")
if learned > 0:
print("2. Testar com conjunto de dados")
print("3. Treinar e testar com conjunto de dados (k-fold)")
if learned > 0:
print("4. Testar com conjunto de dados (com detalhes)")
print("5. Listar pesos da camada de saída")
print("6. Informações da Rede")
print("0. Sair")
print()
option = 0
option = int(input("Escolha uma opção (0-6) > "))
if option == 1: # treinar com um arquivo de dados
data = readData(input("Entre com um arquivo com o conjunto de dados (imagens) > ").strip())
if data == None:
print("Erro: o arquivo de dados não pode ser lido (não existe, sem permissões, ...) ou não está no formato adequado.")
continue
#n = int(input("Entre com o número de iterações para aprendizado (n: 1-inf) > "))
n = 1
if n < 1:
print("Erro: n deve ser maior ou igual à 1.")
continue
print()
for it in range(n):
print("\r%6.2lf%% processado... (não pressione nenhuma tecla ainda)" % (float(100 * it/n)), end='')
np.random.shuffle(data)
learn(data, gauss)
print("\r%6.2lf%% processado... (não pressione nenhuma tecla ainda)" % (float(100)), end='')
print()
print("# A rede aprendeu com o conjunto de dados submetido! Pesos atualizados.")
elif learned > 0 and option == 2: # testar com um arquivo de dados
data = readData(input("Entre com um arquivo com o conjunto de dados (imagens) > ").strip())
if data == None:
print("Erro: o arquivo de dados não pode ser lido (não existe, sem permissões, ...) ou não está no formato adequado.")
continue
errorTotal = 0
corrects = 0
total = 0
for item in data:
itemStats = test(item, gauss)
correct = True
for error in itemStats[0]:
errorTotal += error
if error >= ERROR_THRESHOLD:
correct = False
if correct:
corrects += 1
total += 1
print()
print("# Teste terminou.")
print("Acertos: %d de %d (%.2lf%%)." % (corrects, total, 100 * corrects/total))
print("Erro: total de %.2lf e médio de %.2lf." % (errorTotal, errorTotal/total))
elif option == 3: # k-fold através de um arquivo de dados
data = readData(input("Entre com um arquivo com o conjunto de dados (imagens) > ").strip())
if data == None:
print("Erro: o arquivo de dados não pode ser lido (não existe, sem permissões, ...) ou não está no formato adequado.")
continue
#n = int(input("Entre com o número de iterações para aprendizado (n) > "))
n = 1
if n < 1:
print("Erro: n deve ser maior ou igual à 1.")
continue
k = int(input("Entre com o número de blocos usados k (k) > "))
if k < 2 or k > len(data):
print("Erro: k deve ser maior ou igual à 2 e deve ser menor ou igual ao número de exemplos no arquivo (" + str(len(data)) + ").")
continue
np.random.shuffle(data)
errorTotal = 0
corrects = 0
total = 0
groupsOfData = splitData(data, k)
print()
for kt in range(k):
testData = groupsOfData[kt]
learnData = [ ]
for it in range(kt):
learnData += groupsOfData[it]
for it in range(kt + 1, k):
learnData += groupsOfData[it]
for it in range(n):
print("\r%6.2lf%% processado... (não pressione nenhuma tecla ainda)" % (float(100 * (kt * n + it)/(k * n))), end='')
learn(learnData, gauss)
errorKt = 0
correctsKt = 0
totalKt = 0
for item in testData:
itemStats = test(item, gauss)
correct = True
for error in itemStats[0]:
errorKt += error
if error >= ERROR_THRESHOLD:
correct = False
if correct:
correctsKt += 1
totalKt += 1
errorTotal += errorKt
corrects += correctsKt
total += totalKt
print("\r# A execução para a iteração k = " + str(kt + 1) + " do " + str(k) + "-fold foi completa.")
print("Acertos: %d de %d (%.2lf%%)." % (correctsKt, totalKt, 100 * correctsKt/totalKt))
print("Erro: total de %.2lf e médio de %.2lf." % (errorKt, errorKt/totalKt))
print("\r%6.2lf%% processado... (não pressione nenhuma tecla ainda)" % (float(100)), end='')
print()
print("# A rede aprendeu com o conjunto de dados submetido! Pesos atualizados. Além disso também foi testada.")
print("Acertos: %d de %d (%.2lf%%)." % (corrects, total, 100 * corrects/total))
print("Erro: total de %.2lf e médio de %.2lf." % (errorTotal, errorTotal/total))
elif learned > 0 and option == 4: # testar com um arquivo de dados (detalhes)
data = readData(input("Entre com um arquivo com o conjunto de dados (imagens) > ").strip())
if data == None:
print("Erro: o arquivo de dados não pode ser lido (não existe, sem permissões, ...) ou não está no formato adequado.")
continue
errorTotal = 0
corrects = 0
total = 0
print()
print("[saída esperada] -> [saída produzida] (acerto/erro)")
for item in data:
itemStats = test(item, gauss)
correct = True
errorItem = 0
for error in itemStats[0]:
errorItem += error
if error >= ERROR_THRESHOLD:
correct = False
if correct:
print("%s -> %s (acerto: com erro total de %.2lf)" % (str(np.array(item[1], dtype=np.float)), str(itemStats[1]), errorItem))
corrects += 1
else:
print("%s -> %s (erro: de %.2lf)" % (str(np.array(item[1], dtype=np.float)), str(itemStats[1]), errorItem))
total += 1
errorTotal += errorItem
print()
print("# Teste terminou.")
print("Acertos: %d de %d (%.2lf%%)." % (corrects, total, 100 * corrects/total))
print("Erro: total de %.2lf e médio de %.2lf." % (errorTotal, errorTotal/total))
elif learned > 0 and option == 5: # pesos de um neurônio da camada de saída
i = int(input("Entre com o neurônio da camada de saída a qual deseja obter os pesos (i: 1-10) > "))
i -= 1
if i < 0 or i >= n:
print("Erro: neurônio " + str(i + 1) + " não existe na camada de saída.")
continue
print()
print("# Pesos do neurônio " + str(i + 1) + " da camada de saída:")
print(weights[i])
elif option == 6: # informações da rede neural
print()
print("# Informações da rede:")
if learned > 0:
print("Já foi treinada? Sim. Foi treinada usando um total de " + str(learned) + " exemplos.")
else:
print("Já foi treinada? Não.")
print("Entrada: 256 inteiros ou floats")
print("Saída esperada e produzida: 10 floats")
print("Estrutura: 2 camadas, 1 escondida/s e 1 de saída")
print("Número de neurônios na camada escondida (centros de clusters): " + str(N_CLUSTER_CENTERS))
print("Número de neurônios na camada de saída: 10")
else: # sair
print()
print("# Saindo do programa...")
break
<file_sep>#include <stdlib.h>
#include <string.h>
#include <vectorutils.h>
void merge(void *vector, int size, int (*cmp)(void *,void *), int start, int middle, int end, int *CmpN, int *MovN) {
int i, j, k;
void *left, *right;
int nleft, nright;
nleft = middle - start + 1;
nright = end - middle;
left = (void *) malloc(size * nleft);
right = (void *) malloc(size * nright);
memcpy(left,vector+start*size,nleft*size);
memcpy(right,vector+(middle+1)*size,nright*size);
i = j = 0;
for (k = start; k <= end; k++) {
if (j>=nright || (i<nleft && ++(*CmpN) && cmp(left+i*size,right+j*size)>=0)) {
(*MovN)+=3;
gswap(vector+k*size,left+(i++)*size,size);
} else if(j<nright) {
(*MovN)+=3;
gswap(vector+k*size,right+(j++)*size,size);
}
}
free(left);
free(right);
}
void mergesort_(void *vector, int size, int (*cmp)(void *,void *), int start, int end, int *CmpN, int *MovN) {
if (start < end) {
int middle = (start+end) / 2;
mergesort_(vector, size, cmp, start, middle, CmpN, MovN);
mergesort_(vector, size, cmp, middle+1, end, CmpN, MovN);
merge(vector, size, cmp, start, middle, end, CmpN, MovN);
}
}
void mergesort(void *vector, int size, int (*cmp)(void *,void *), int n, int *CmpN, int *MovN){
int C = 0, M = 0;
mergesort_(vector,size,cmp,0,n-1, &C, &M);
*CmpN = C;
*MovN = M;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <unordered_map>
#include <cstdint>
#define SIZE 25
/*
* == Jan-Ken-Puzzle PD ==
*
* Nomes:
* <NAME> (Nº 10262631)
* <NAME> (Nº 10295242)
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
/* == STRUCTURE DEFINITION == */
/* This structure represents any possible solution. */
typedef struct solution_t{
int i,j;
int piece;
} solution_t;
typedef std::unordered_map<uint_fast64_t, int_fast64_t> boardmap_t;
typedef struct data {
solution_t* solvedArray;
int_fast64_t ways;
int solutions;
int depth;
} data;
typedef struct stBoard {
char board[SIZE/2][SIZE/2];
int row, col;
int counter;
} stBoard;
typedef struct move {
int b[2];
int e[2];
} move;
/* == DATA DEFINITION == */
boardmap_t boardMap;
long long int runBoardtimes, islandstimes,findWaystimes;
/* == FUNCTION DEFINITION == */
int valid(int, int);
uint_fast64_t mat2int64(stBoard);
int_fast64_t findWays(uint_fast64_t);
int floodBoard(char board[SIZE/2][SIZE/2], int, int);
bool islandsBoard(stBoard, int, int);
int_fast64_t runBoard(data *, stBoard, move);
void sortSolutions(solution_t *, int);
/* == MAIN == */
int main(int argc, char **argv) {
int i, j, read;
stBoard b;
move m;
data d;
d.ways = 0;
d.depth = 0;
d.solutions = 0;
b.counter = 0;
d.solvedArray = (solution_t *) malloc((SIZE * 3) * sizeof(solution_t));
for (i = 0; i < SIZE/2; ++i) {
for (j = 0; j < SIZE/2; ++j) {
b.board[i][j] = 0;
}
}
for (i = 0; i < SIZE*3; ++i) {
d.solvedArray[i].i = 0;
d.solvedArray[i].j = 0;
d.solvedArray[i].piece = 0;
}
/* Reads from stdin the initial state of the board */
scanf("%d %d", &b.row, &b.col);
for (i = 0; i < b.row; ++i) {
for (j = 0; j < b.col; ++j) {
scanf(" %d", &read);
b.board[i][j] = (char) read;
if(b.board[i][j] > 0) {
b.counter++;
m.e[0]=i;
m.e[1]=j;
}
}
}
m.b[0]= -1;
/* Calls recursive algorithm */
runBoard(&d, b, m);
/* Sorts set of solutions */
sortSolutions(d.solvedArray, d.solutions);
/* Prints set of solutions (result) */
printf("%ld\n", d.ways);
printf("%d\n", d.solutions);
for (i = 0; i < d.solutions; ++i) {
printf("%d %d %d\n", d.solvedArray[i].i+1, d.solvedArray[i].j+1, d.solvedArray[i].piece);
}
free(d.solvedArray);
return EXIT_SUCCESS;
}
/* == FUNCTION IMPLEMENTATION == */
/* This functions checks weather a move is valid or not */
int valid(int b, int e) {
/* It returns true if valid, false otherwise */
if((b==1 && e==2)
|| (b==2 && e==3)
|| (b==3 && e==1))
return 1;
else
return 0;
}
/* This function converts 'nxn matrix' to 'uint_fast64_t', under base 4 */
uint_fast64_t mat2int64(stBoard b) {
uint_fast64_t base4, matrix64;
int i, j;
base4 = 1;
matrix64 = 0;
for (i = 0; i < b.row ; ++i) {
for (j = 0; j < b.col; ++j) {
/* Adds 0-3 no. in mat mult. by power of 4 */
matrix64 += b.board[i][j] * base4;
base4 *= 4;
}
}
return matrix64;
}
/* This function finds the board value in unordered map.
If found, it returns number of solutions;
if not found, it returns -1 */
int_fast64_t findWays(uint_fast64_t board_id) {
boardmap_t::const_iterator got;
findWaystimes++;
got = boardMap.find(board_id);
if(got == boardMap.end())
return -1;
else
return got->second;
}
/* This function returns the number of conected cells */
int floodBoard(char board[SIZE/2][SIZE/2], int p, int q) {
int floodCount;
floodCount = 1;
board[p][q]=0;
if(p>0 && board[p-1][q]>0)
floodCount += floodBoard(board,p-1,q);
if(q>0 && board[p][q-1]>0)
floodCount += floodBoard(board,p,q-1);
if(p<SIZE/2-1 && board[p+1][q]>0)
floodCount += floodBoard(board,p+1,q);
if(q<SIZE/2-1 && board[p][q+1]>0)
floodCount += floodBoard(board,p,q+1);
return floodCount;
}
/* this function returns true if there are islands on the board,
false otherwise. */
bool islandsBoard(stBoard b, int p, int q) {
stBoard copy;
islandstimes++;
copy = b;
if(floodBoard(copy.board,p,q) != b.counter)
return true;
else
return false;
}
/* This function iterates over the board looking for a valid movement.
If any valid movement is found, the algorithm is recursively executed */
int_fast64_t runBoard(data *d, stBoard b, move m) {
uint_fast64_t board_id;
int_fast64_t waysFound;
int i, j, count, last;
/* If valid, moves m */
if(m.b[0] != -1) {
b.board[m.e[0]][m.e[1]] = b.board[m.b[0]][m.b[1]];
b.board[m.b[0]][m.b[1]] = 0;
b.counter--;
}
/* If board is already solved, increases the value of nways
and returns the nways found */
board_id = mat2int64(b);
waysFound = findWays(board_id);
if(waysFound >= 0){
d->ways += waysFound;
return waysFound;
}
/* if any islands is found, returns 0 */
if(islandsBoard(b, m.e[0], m.e[1])){
boardMap.insert ({board_id, 0});
return 0;
}
/* Until there are no valid moves anymore:
mark the movement and recursively call algorithm;
find the next valid moves */
count = 0;
waysFound = 0;
last = 0;
for (i = 0; i < b.row; ++i) {
for (j = 0; j < b.col; ++j) {
/* Checks l, r, u and d */
if(b.board[i][j] != 0) {
count ++;
last = b.board[i][j];
/* Left (l) */
if(j!=0) {
if(valid(b.board[i][j], b.board[i][j-1])) {
m.b[0] = i;
m.b[1] = j;
m.e[0] = i;
m.e[1] = j-1;
waysFound += runBoard(d, b, m);
}
}
/* Right (r) */
if(j!= b.col-1) {
if(valid(b.board[i][j], b.board[i][j+1])) {
m.b[0] = i;
m.b[1] = j;
m.e[0] = i;
m.e[1] = j+1;
waysFound += runBoard(d, b, m);
}
}
/* Up (u) */
if(i!=0) {
if(valid(b.board[i][j], b.board[i-1][j])) {
m.b[0] = i;
m.b[1] = j;
m.e[0] = i-1;
m.e[1] = j;
waysFound += runBoard(d, b, m);
}
}
/* Down (d) */
if(i!= b.row-1) {
if(valid(b.board[i][j], b.board[i+1][j])) {
m.b[0] = i;
m.b[1] = j;
m.e[0] = i+1;
m.e[1] = j;
waysFound += runBoard(d, b, m); }
}
}
}
if(count == b.counter)
break;
}
/* If there is only one piece on the board, then the algorithm has finished its execution */
if(count == 1) {
/* Adds this solution to the set of solutions */
d->solvedArray[d->solutions].i = m.e[0];
d->solvedArray[d->solutions].j = m.e[1];
d->solvedArray[d->solutions].piece = last;
d->solutions++;
d->ways++;
waysFound = 1;
}
/* Adds solved board to map */
boardMap.insert({board_id, waysFound});
return waysFound;
}
/* This function sorts the set of solutions */
void sortSolutions(solution_t *s, int numSols) {
solution_t aux;
int i, j;
for (i = 1; i < numSols; ++i) {
aux = s[i];
for (j = i-1; j >= 0; --j) {
if(s[j].i < aux.i) {
break;
} else if (s[j].i == aux.i) {
if(s[j].j < aux.j) {
break;
} else if (s[j].j == aux.j) {
if(s[j].piece < aux.piece) {
break;
}
}
}
s[j+1] = s[j];
}
s[j+1] = aux;
}
}
<file_sep>#ifndef STACK_H_
#define STACK_H_
//#include <stdlib.h>
typedef struct __stack_t STACK;
struct __stack_t *S_New(size_t);
int S_Push(void *, struct __stack_t *);
int S_Get(void *, struct __stack_t *);
int S_Pop(void *, struct __stack_t *);
void S_Destroy(struct __stack_t *);
#endif<file_sep>#include <stdlib.h>
#include <string.h>
/*
* ~ Pilha ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
struct __stack_node_t {
void *value;
struct __stack_node_t *below;
};
struct __stack_t {
struct __stack_node_t *topper, *bottom;
unsigned long nitems;
size_t memsize;
};
struct __stack_t *S_New(size_t memsize){
struct __stack_t *Aux;
if(memsize < 1) return NULL;
Aux = (struct __stack_t *) malloc(sizeof(struct __stack_t));
Aux->topper = Aux->bottom = NULL;
Aux->memsize = memsize;
Aux->nitems = 0;
return Aux;
}
long S_Size(struct __stack_t *S){
if(S == NULL) return -1;
return S->nitems;
}
int S_Push(void *X, struct __stack_t *S){
struct __stack_node_t *Aux;
if(X == NULL || S == NULL) return 0;
Aux = (struct __stack_node_t *) malloc(sizeof(struct __stack_node_t));
Aux->value = (void *) malloc(S->memsize);
Aux->below = S->topper;
memcpy(Aux->value, X, S->memsize);
S->topper = Aux;
if(S->nitems < 1)
S->bottom = Aux;
S->nitems++;
return 1;
}
int S_Top(void *X, struct __stack_t *S){
if(X == NULL || S == NULL) return 0;
if(S->nitems < 1) return 0;
memcpy(X, S->topper->value, S->memsize);
return 1;
}
int S_Bottom(void *X, struct __stack_t *S){
if(X == NULL || S == NULL) return 0;
if(S->nitems < 1) return 0;
memcpy(X, S->bottom->value, S->memsize);
return 1;
}
int S_Pop(void *X, struct __stack_t *S){
struct __stack_node_t *Aux;
if(S == NULL) return 0;
if(S->nitems < 1) return 0;
if(X != NULL)
memcpy(X, S->topper->value, S->memsize);
Aux = S->topper;
S->topper = S->topper->below;
S->nitems--;
if(S->nitems < 1)
S->bottom = NULL;
free(Aux->value);
free(Aux);
return 1;
}
void S_Destroy(struct __stack_t *S){
struct __stack_node_t *P, *Aux;
if(S == NULL) return;
P = S->topper;
while(P != NULL) {
Aux = P;
P = P->below;
free(Aux->value);
free(Aux);
}
free(S);
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
/*
<NAME>
<EMAIL>
*/
int main(){
char TabelaVelha[3][3]={{-1,-1,-1},{-1,-1,-1},{-1,-1,-1}}, vencedor=-1;
int i=0,X,Y;
while(scanf("%d %d",&X,&Y)>0){
TabelaVelha[X][Y]=(i++)%2;
}
if(TabelaVelha[0][0]!=' ' && TabelaVelha[0][0]==TabelaVelha[1][1] && TabelaVelha[1][1]==TabelaVelha[2][2]){ // Venceu por diagonal?
vencedor=TabelaVelha[0][0];
}else if(TabelaVelha[0][2]!=' ' && TabelaVelha[0][2]==TabelaVelha[1][1] && TabelaVelha[1][1]==TabelaVelha[2][0] ){ // Venceu por diagonal?
vencedor=TabelaVelha[0][2];
}else if(TabelaVelha[0][0]!=' ' && TabelaVelha[0][0]==TabelaVelha[0][1] && TabelaVelha[0][1]==TabelaVelha[0][2]){ // Venceu na 1ª linha
vencedor=TabelaVelha[0][0];
}else if(TabelaVelha[1][0]!=' ' && TabelaVelha[1][0]==TabelaVelha[1][1] && TabelaVelha[1][1]==TabelaVelha[1][2]){ // Venceu na 2ª linha
vencedor=TabelaVelha[1][0];
}else if(TabelaVelha[2][0]!=' ' && TabelaVelha[2][0]==TabelaVelha[2][1] && TabelaVelha[2][1]==TabelaVelha[2][2]){ // Venceu na 3ª linha
vencedor=TabelaVelha[2][0];
}else if(TabelaVelha[0][0]!=' ' && TabelaVelha[0][0]==TabelaVelha[1][0] && TabelaVelha[1][0]==TabelaVelha[2][0]){ // Venceu na 1ª coluna
vencedor=TabelaVelha[0][0];
}else if(TabelaVelha[0][1]!=' ' && TabelaVelha[0][1]==TabelaVelha[1][1] && TabelaVelha[1][1]==TabelaVelha[2][1]){ // Venceu na 2ª coluna
vencedor=TabelaVelha[0][1];
}else if(TabelaVelha[0][2]!=' ' && TabelaVelha[0][2]==TabelaVelha[1][2] && TabelaVelha[1][2]==TabelaVelha[2][2]){ // Venceu na 3ª coluna
vencedor=TabelaVelha[0][2];
}
if(vencedor==-1){
printf("empate");
}else{
printf("%d",(int)vencedor);
}
return EXIT_SUCCESS;
}
<file_sep>#ifndef H_ESCREVERNATELA_
#define H_ESCREVERNATELA_
#include <stdio.h>
void binarioNaTela1(char *nomeArquivoBinario);
void trim(char *str);
void scan_quote_string(char *str);
#endif<file_sep># Simulador MIPS
Trabalho 2 de Organização de Computadores
## Integrantes
* <NAME>
* <NAME>
* <NAME>
* <NAME>
<file_sep>
#
# ~ <NAME> ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -ansi -pedantic -Wall
objects/main.o: main.c objects/redblacktree.o headers/redblacktree.h
gcc -c -o objects/main.o main.c -ansi -pedantic -Wall -I headers
objects/redblacktree.o: lib/redblacktree.c headers/redblacktree.h
gcc -c -o objects/redblacktree.o lib/redblacktree.c -ansi -pedantic -Wall -I headers
run: Prog
./Prog
clean:
rm Prog objects/*.o
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int N;
float s=0;
scanf("%d",&N);
for(N=N;N>0;N--){
if(N%2){
s+=1/(float)N;
}else{
s-=1/(float)N;
}
}
printf("%.4f",s);
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int N;
FILE *Stream;
char FileName[100];
scanf("%s",FileName);
FileName[99]='\0';
Stream=fopen(FileName,"r");
fseek(Stream,0,SEEK_END);
N=ftell(Stream);
fclose(Stream);
printf("%d",N);
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
<NAME>
<EMAIL>
*/
unsigned long math_factorial(unsigned char n){
unsigned long factorial;
for(factorial=1;n>1;n--){
factorial=factorial*n;
}
return factorial;
}
int main(){
int i=32,div=3;
float a;
double s;
scanf(" %f",&a);
s=a;
for(i=i;i>0;i--){
if(i%2){
s+=pow(a,div)/(double)math_factorial(div);
}else{
s-=pow(a,div)/(double)math_factorial(div);
}
div+=2;
}
printf("%.6f",(float)s);
return EXIT_SUCCESS;
}
<file_sep>import glfw
from OpenGL.GL import *
import OpenGL.GL.shaders
import numpy as np
import random as rand
import math
#
# ~ Projeto 1: Mola 2D ~
#
# <NAME> (Nº USP 9875952)
# <NAME> (Nº USP 10369014)
#
# Computação Gráfica: SCC-0250 2020.1
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
# Inicializar janela
glfw.init()
glfw.window_hint(glfw.VISIBLE, glfw.FALSE);
window = glfw.create_window(800, 800, "Trabalho Pratico 1", None, None)
glfw.make_context_current(window)
# Programa Vertex Shader
vertex_code = """
attribute vec2 position;
uniform mat4 mat;
void main(){
gl_Position = mat * vec4(position, 0.0, 1.0);
}
"""
# Programa Fragment Shader
fragment_code = """
void main(){
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
}
"""
# Requisitar slotes do Fragment Shader e Vertex Shader para a GPU
program = glCreateProgram()
vertex = glCreateShader(GL_VERTEX_SHADER)
fragment = glCreateShader(GL_FRAGMENT_SHADER)
# Associar código-fonte aos slotes requisitados
glShaderSource(vertex, vertex_code)
glShaderSource(fragment, fragment_code)
# Compilar Vertex Shader
glCompileShader(vertex)
if not glGetShaderiv(vertex, GL_COMPILE_STATUS):
error = glGetShaderInfoLog(vertex).decode()
print(error)
raise RuntimeError("Erro de compilação do Vertex Shader!")
# Compilar Fragment Shader
glCompileShader(fragment)
if not glGetShaderiv(fragment, GL_COMPILE_STATUS):
error = glGetShaderInfoLog(fragment).decode()
print(error)
raise RuntimeError("Erro de compilação do Fragment Shader!")
# Associar programas compilados ao programa principal
glAttachShader(program, vertex)
glAttachShader(program, fragment)
# Linkagem dos programas
glLinkProgram(program)
if not glGetProgramiv(program, GL_LINK_STATUS):
print(glGetProgramInfoLog(program))
raise RuntimeError("Erro de linkagem dos programas!")
glUseProgram(program)
# == MODELANDO A MOLA ==
# Variáveis editáveis da mola
num_vertices = 200 # Define a "qualidade" dos circulo da mola
radius = 0.1 # Raio da mola
loop = 5 # Número de círculos na mola
y_scale = 0.02 # Escala na variável y
vertices = np.zeros(num_vertices, [("position", np.float32, 2)])
pi = math.pi
counter = 0
angle = 0.0
for counter in range(num_vertices):
angle += loop*2*pi/num_vertices
x = math.sin(angle)*radius
y = angle*y_scale/loop
vertices[counter]['position'] = [x,y]
# Requisitar slot para enviar dados para GPU
buffer = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, buffer)
# Enviar pontos gerados da mola
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_DYNAMIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, buffer)
# Associar variáveis do GLSL (Vertex Shaders) com os nossos dados enviados
stride = vertices.strides[0]
offset = ctypes.c_void_p(0)
loc = glGetAttribLocation(program, "position")
glEnableVertexAttribArray(loc)
glVertexAttribPointer(loc, 2, GL_FLOAT, False, stride, offset)
# = CAPTURAR ENTRADAS DO TECLADO =
space_pressed = False
def key_event(window,key,scancode,action,mods):
global space_pressed
if key == 32 and action == 1: # Apertou a tecla de espaço.
space_pressed = True
elif key == 32 and action == 0: # Soltou a tecla de espaço.
space_pressed = False
glfw.set_key_callback(window,key_event)
# Exibir janela
glfw.show_window(window)
# == DDEFINIÇÃO DE FUNÇÕES IMPORTANTES ==
# Essa função multiplica duas matrizes (a e b), retornando o resultado da multiplicação.
def multiplica_matriz(a,b):
m_a = a.reshape(4,4)
m_b = b.reshape(4,4)
m_c = np.dot(m_a,m_b)
c = m_c.reshape(1,16)
return c
# Essa função desenha na tela a mola com as devidas transformações.
def desenhar(translation_x = 0.0, translation_y = 0.0, scale_x = 1.0, scale_y = 1.0, rotation = 0.0):
global glfw, vertices, y_start
sin_rotation = math.sin(rotation)
cos_rotation = math.cos(rotation)
translation_y += y_start
glfw.poll_events()
glClear(GL_COLOR_BUFFER_BIT)
glClearColor(1.0, 1.0, 1.0, 1.0)
mat_scale = np.array([ scale_x, 0.0, 0.0, 0.0,
0.0, scale_y, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0], np.float32)
mat_rotation = np.array([ cos_rotation, -sin_rotation, 0.0, 0.0,
sin_rotation, cos_rotation, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0], np.float32)
mat_translation = np.array([ 1.0, 0.0, 0.0, translation_x,
0.0, 1.0, 0.0, translation_y,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0], np.float32)
mat_transform = multiplica_matriz(mat_scale, mat_rotation)
mat_transform = multiplica_matriz(mat_translation, mat_transform)
loc = glGetUniformLocation(program, "mat")
glUniformMatrix4fv(loc, 1, GL_TRUE, mat_transform)
glDrawArrays(GL_LINE_STRIP, 0, len(vertices))
glfw.swap_buffers(window)
# == CONSTANTES DE ANIMAÇÃO DA MOLA ==
compress_rate = 0.005 # Velocidade de compressão da mola quando [ESPAÇO] é pressionado.
compress_min = 0.1 # Compressão mínima permitida na mola - se não chegar nisso, ela não pula.
compress_max = 0.75 # Compressão máxima permitida na mola - se chegar nisso, ela para o mais longe possível.
bounce_random_probability = 0.5 # 0.0 = só pula pra esquerda, 1.0 = só pula pra direita, 0.5 = random com chances iguais
bounce_rate = 0.005 # Velocidade de pulo da mola.
bounce_min_x_distance = 0.2 # Distância mínima (eixo x) que a mola para após o pulo.
bounce_min_y_distance = 0.2 # Distância mínima (eixo y) que a mola para após o pulo.
bounce_max_x_distance = 0.85 # Distância máxima (eixo x) que a mola para após o pulo.
bounce_max_y_distance = 1.4 # Distância máxima (eixo y) que a mola para após o pulo.
restart_wait = 60 # Tempo que o programa espera depois que a mola pousou antes de retomar sua posição inicial.
y_start = -0.8 # Posição de "spawn" da mola no eixo y
# == LOOP PRINCIPAL DA JANELA ==
while not glfw.window_should_close(window):
if(space_pressed == False): # Enquanto não apertar [ESPAÇO], só desenha a mola normal parada.
desenhar()
continue
current_compression = 0.0
while space_pressed == True: # Apertou [ESPAÇO], então começar a compressionar a mola
if current_compression < compress_max:
current_compression += compress_rate
desenhar(scale_y = 1.0 - current_compression)
if current_compression < compress_min:
continue # Não compressionou a mola o bastante! Sem forças para pular.
# Colocou forças o bastante na compressão! Definir agora se vai pular para esquerda ou direita.
direction = rand.uniform(0.0, 1.0)
if(direction > bounce_random_probability):
direction = -1.0 # Vai pular para esquerda
else:
direction = 1.0 # Vai pular para direita
compression_normalized = (current_compression - compress_min) / (compress_max - compress_min) # Normaliza entre 0..1.
posx = 0.0 # Posição começa em 0.
posx_max = bounce_min_x_distance + compression_normalized * (bounce_max_x_distance - bounce_min_x_distance) # A força de compressão decide a posição x máxima.
posy_max = bounce_min_y_distance + compression_normalized * (bounce_max_y_distance - bounce_min_y_distance) # A força de compressão decide a posição y máxima.
posy_factor = posy_max / math.pow(posx_max / 2.0, 2) # Isso é apenas para fazer um efeito de força gravidade no eixo y.
while posx < posx_max: # Loop que faz o pulo efetivamente.
posx += bounce_rate # Aumenta a posição no eixo x.
posy = -posy_factor * math.pow(posx - posx_max / 2, 2) + posy_max # Calcula a posição no eixo y.
normalized_x = max(0.0, min(1.0, posx / posx_max)) * 2.0 - 1.0 # Normaliza posição x entre -1..1
angle = math.acos(normalized_x) # Calcula o ângulo.
desenhar(translation_x = direction * posx, translation_y = posy, rotation = direction * angle)
c = 0.0
while c < current_compression: # Animação de quando bate no chão - parte 1 (compressionando)
desenhar(translation_x = direction * posx, scale_y = 1.0 - c)
c += 10 * compress_rate
while c > 0.0: # Animação de quando bate no chão - parte 2 (retornando ao estado normal)
desenhar(translation_x = direction * posx, scale_y = 1.0 - c)
c -= 10 * compress_rate
time = 0
while time < restart_wait: # Espera um pouco antes de retornar a mola para a posição original.
time += 1
desenhar(translation_x = direction * posx)
space_pressed = False # Força que o usuário pressiona o [ESPAÇO] novamente, caso queira uma nova animação.
glfw.terminate()
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
int int_cmp(const int *a, const int *b) {
return *a - *b;
}
void testCase() {
int left, right, middle, count, aux;
int i, j, n, m, *M;
char found;
cin >> n >> m;
M = (int *) malloc(sizeof(int) * m);
for(i = 0; i < m; i++) {
cin >> M[i];
M[i] *= 2;
}
qsort(M, m, sizeof(int), (int (*)(const void *, const void *)) int_cmp); // Sort houses by street number.
left = 0;
right = (M[m - 1] - M[0]) / 2;
while(left <= right) {
middle = (left + right) / 2;
count = 1;
found = 1;
aux = M[0] + middle;
for(i = 0; i < m; i++) {
if(abs(aux - M[i]) > middle) {
count++;
if(count > n) {
found = 0;
break;
}
aux = M[i] + middle;
}
}
if(found == 1) {
right = middle - 1;
} else {
left = middle + 1;
}
}
printf("%.1lf", (right + 1) / (double) 2.0);
cout << endl;
}
int main(int argc, char **argv) {
int T;
cin >> T;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>
/*
* ~ Trabalho Prático: Parte 2 ~
*
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef ARVOREB_H_
#define ARVOREB_H_
#include <stdio.h>
void iniciarBufferPool();
void finalizarBufferPool(char *, FILE *);
int buscaRRN(int, FILE *);
void inserirChave(int, int, FILE *);
int removerChave(int, FILE *);
#endif
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <unordered_map>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
void testCase() {
ll N, i, aux, sum;
cin >> N;
unordered_map<ll, ll> count = unordered_map<ll, ll>();
for(i = 0; i < N; i++) {
cin >> aux;
count[aux]++;
}
sum = 0;
for(auto it = count.begin(); it != count.end(); it++) {
if(it->first > it->second) {
sum += it->second;
continue;
}
sum += it->second - it->first;
}
cout << sum << endl;
}
int main(int argc, char **argv) {
ll T;
T = 1;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>
#ifndef INDICECIDADES_H_
#define INDICECIDADES_H_
typedef struct __INDEX_T INDEX_T;
INDEX_T *I_new();
INDEX_T *I_newFrom(char *filename);
int I_insert(char *key, INDEX_T *ind);
int I_insertCount(char *key, unsigned long count, INDEX_T *ind);
int I_remove(char *key, INDEX_T *ind);
int I_removeCount(char *key, unsigned long count, INDEX_T *ind);
long I_keyCount(INDEX_T *ind);
int I_fillRestOfKey(char *key, INDEX_T *ind);
long I_getIndexFor(char *key, INDEX_T *ind);
char *I_getKeyFor(long index, INDEX_T *ind);
int I_saveTo(char *filename, INDEX_T *ind);
int I_loadFrom(char *filename, INDEX_T *ind);
void I_destroy(INDEX_T *ind);
#endif<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int i,iinserted,entradas[6]={0,0,0,0,0,0},maior_frequencia=0;
while(scanf("%d",&iinserted)!=EOF){
if(iinserted>=1 && iinserted<=6){
entradas[iinserted-1]++;
if(entradas[iinserted-1]>maior_frequencia){
maior_frequencia=entradas[iinserted-1];
}
}
}
for(i=0;i<6;i++){
if(entradas[i]==maior_frequencia){
printf("%d\n",i+1);
}
}
printf("%d",maior_frequencia);
return EXIT_SUCCESS;
}<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <consts.h>
typedef struct __INDEX_NODE_T {
char key[INDEX_KEY_MAX_LEN + 1];
unsigned long value;
unsigned long index;
struct __INDEX_NODE_T *next;
} INDEX_NODE_T;
typedef struct __INDEX_T {
INDEX_NODE_T **hashTable;
INDEX_NODE_T **vector;
unsigned long keyCount;
char vectorReady; // bool
} INDEX_T;
int I_loadFrom(char *, INDEX_T *);
void I_destroy(INDEX_T *);
INDEX_T *I_new() {
INDEX_T *aux;
aux = (INDEX_T *) malloc(sizeof(INDEX_T));
if(aux == NULL) {
return NULL;
}
aux->hashTable = (INDEX_NODE_T **) malloc(sizeof(INDEX_NODE_T *) * INDEX_HASHTABLE_LEN);
if(aux->hashTable == NULL) {
free(aux);
return NULL;
}
memset(aux->hashTable, 0 /* NULL */, sizeof(INDEX_NODE_T *) * INDEX_HASHTABLE_LEN);
aux->keyCount = 0;
aux->vector = NULL;
aux->vectorReady = 0;
return aux;
}
INDEX_T *I_newFrom(char *filename) {
INDEX_T *aux;
if(filename == NULL) {
return NULL;
}
aux = I_new();
if(aux == NULL) {
return NULL;
}
if(I_loadFrom(filename, aux) != 1) {
I_destroy(aux);
return NULL;
}
}
unsigned long I_hashKey(char *key, unsigned long *length) {
unsigned long i, count;
for(i = count = 0; key[i] != '\0'; i++) {
count += key[i];
}
if(length != NULL) {
*length = i;
}
count = count % INDEX_HASHTABLE_LEN;
return count;
}
int I_insertCount(char *key, unsigned long count, INDEX_T *ind) {
INDEX_NODE_T **nodeI, *aux;
long len, pos;
if(key == NULL || ind == NULL) {
return 0;
}
pos = I_hashKey(key, &len);
if(len > INDEX_KEY_MAX_LEN) {
return 0;
}
nodeI = &ind->hashTable[pos];
while(*nodeI != NULL) {
if(strcmp((*nodeI)->key, key) == 0) {
if((*nodeI)->value < 1) {
ind->keyCount++;
}
(*nodeI)->value += count;
ind->vectorReady = 0;
return 1;
}
nodeI = &(*nodeI)->next;
}
aux = (INDEX_NODE_T *) malloc(sizeof(INDEX_NODE_T));
if(aux == NULL) {
return 0;
}
aux->value = count;
aux->next = NULL;
strcpy(aux->key, key);
*nodeI = aux;
ind->keyCount++;
ind->vectorReady = 0;
return 1;
}
int I_insert(char *key, INDEX_T *ind) {
return I_insertCount(key, 1, ind);
}
int I_removeCount(char *key, unsigned long count, INDEX_T *ind) {
INDEX_NODE_T **nodeI, *aux;
long len, pos;
if(key == NULL || ind == NULL) {
return 0;
}
pos = I_hashKey(key, &len);
if(len > INDEX_KEY_MAX_LEN) {
return 0;
}
nodeI = &ind->hashTable[pos];
while(*nodeI != NULL) {
if(strcmp((*nodeI)->key, key) == 0) {
if((*nodeI)->value < 1) {
return 0;
}
if(count >= (*nodeI)->value) {
(*nodeI)->value = 0;
} else {
(*nodeI)->value -= count;
}
ind->vectorReady = 0;
if((*nodeI)->value < 1) {
ind->keyCount--;
}
return 1;
}
nodeI = &(*nodeI)->next;
}
return 0;
}
int I_remove(char *key, INDEX_T *ind) {
return I_removeCount(key, 1, ind);
}
int I_sortCmp(INDEX_NODE_T **a, INDEX_NODE_T **b) {
return strcmp((*a)->key, (*b)->key);
}
int I_sort(INDEX_T *ind) {
INDEX_NODE_T **nodeI;
unsigned long i, j;
if(ind == NULL) {
return 0;
}
if(ind->vectorReady) {
return 1;
}
if(ind->keyCount < 1) {
ind->vector = NULL;
return 1;
}
if(ind->vector != NULL) {
free(ind->vector);
}
ind->vector = (INDEX_NODE_T **) malloc(sizeof(INDEX_NODE_T *) * ind->keyCount);
if(ind->vector == NULL) {
return 0;
}
for(i = j = 0; i < INDEX_HASHTABLE_LEN; i++) {
nodeI = &ind->hashTable[i];
while(*nodeI != NULL) {
if((*nodeI)->value > 0) {
ind->vector[j] = *nodeI;
j++;
}
nodeI = &(*nodeI)->next;
}
}
qsort(ind->vector, ind->keyCount, sizeof(INDEX_NODE_T *), (int (*)(const void *, const void *)) I_sortCmp);
for(j = 0; j < ind->keyCount; j++) {
ind->vector[j]->index = j;
}
ind->vectorReady = 1;
return 1;
}
int I_fillRestOfKey(char *key, INDEX_T *ind) {
INDEX_NODE_T *aux;
long len, pos;
if(key == NULL || ind == NULL || I_sort(ind) != 1) {
return -1;
}
for(pos = 0; pos < INDEX_HASHTABLE_LEN; pos++) {
aux = ind->hashTable[pos];
while(aux != NULL) {
if(strncmp(aux->key, key, strlen(key)) == 0) {
strcpy(key, aux->key);
return 1;
}
aux = aux->next;
}
}
return 0;
}
long I_getIndexFor(char *key, INDEX_T *ind) {
INDEX_NODE_T *aux;
long len, pos;
if(key == NULL || ind == NULL || I_sort(ind) != 1) {
return -1;
}
pos = I_hashKey(key, &len);
if(len > INDEX_KEY_MAX_LEN) {
return -1;
}
aux = ind->hashTable[pos];
while(aux != NULL) {
if(strcmp(aux->key, key) == 0) {
return aux->index;
}
aux = aux->next;
}
return -2;
}
char *I_getKeyFor(long index, INDEX_T *ind) {
INDEX_NODE_T *aux;
if(ind == NULL || I_sort(ind) != 1 || index < 0 || index >= ind->keyCount) {
return NULL;
}
aux = ind->vector[index];
return aux->key;
}
long I_keyCount(INDEX_T *ind) {
if(ind == NULL) {
return -1;
}
return ind->keyCount;
}
int I_loadFrom(char *filename, INDEX_T *ind) {
char buff[INDEX_KEY_MAX_LEN + sizeof(int)], status, key[INDEX_KEY_MAX_LEN + 1];
FILE *stream;
int value;
if(filename == NULL || ind == NULL || (stream = fopen(filename, "rb")) == NULL) {
return 0;
}
if(fread(&status, sizeof(char), 1, stream) != 1) {
fclose(stream);
return 0;
}
if(status != R_TRUE) {
fclose(stream);
return 0;
}
while(fread(buff, INDEX_KEY_MAX_LEN + sizeof(int), 1, stream) == 1) {
key[INDEX_KEY_MAX_LEN] = '\0';
strncpy(key, buff, INDEX_KEY_MAX_LEN);
memcpy(&value, &buff[INDEX_KEY_MAX_LEN], sizeof(int));
I_insertCount(key, value, ind);
}
fclose(stream);
return 1;
}
int I_saveTo(char *filename, INDEX_T *ind) {
char buff[INDEX_KEY_MAX_LEN + sizeof(int)], status, saved;
unsigned long i, aux;
FILE *stream;
int value;
if(filename == NULL || ind == NULL || I_sort(ind) != 1 || (stream = fopen(filename, "wb")) == NULL) {
return 0;
}
status = R_TRUE;
if(fwrite(&status, sizeof(char), 1, stream) != 1) {
fclose(stream);
return 0;
}
saved = 1;
for(i = 0; i < ind->keyCount; i++) {
memset(buff, R_LIXO, sizeof(char) * (INDEX_KEY_MAX_LEN + sizeof(int)));
strcpy(buff, ind->vector[i]->key);
memcpy(&aux, &ind->vector[i]->value, sizeof(unsigned long));
value = (int) aux;
memcpy(&buff[INDEX_KEY_MAX_LEN], &value, sizeof(int));
if(fwrite(buff, INDEX_KEY_MAX_LEN + sizeof(int), 1, stream) != 1) {
saved = 0;
}
}
fclose(stream);
if(saved != 1) {
saved = 0;
}
return saved;
}
void I_destroy(INDEX_T *ind) {
INDEX_NODE_T *nodeI, *aux;
unsigned long i, j;
if(ind == NULL) {
return;
}
if(ind->vector != NULL) {
free(ind->vector);
}
for(i = 0; i < INDEX_HASHTABLE_LEN; i++) {
nodeI = ind->hashTable[i];
while(nodeI != NULL) {
aux = nodeI;
nodeI = nodeI->next;
free(aux);
}
}
free(ind);
}<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "ATM.h"
/*
* ~ Relatório Fluxo ATM ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
// Número de "caixas automáticos".
#define ATM_COUNT 4
// Tamanho fixo da HashTable.
#define MAX_SIZE 2048
// Lucro por cada operação (3 reais).
#define PROFIT 3
int main(int argc, char **argv){
int i, Aux, ATM, Limit, Bank1, Bank2, ErrorATMs[ATM_COUNT][4], ErrorTotal[4];
double ProfitATMs[ATM_COUNT], ProfitTotal = 0, Money;
HASHTABLE *Operations, *ATMs[ATM_COUNT], *Total;
char Command;
// Zerar variáveis e inicializar HashTables
Operations=New_HashTable(sizeof(OPERATION), NULL, MAX_SIZE);
Total=New_HashTable(sizeof(BANK), NULL, MAX_SIZE);
memset(ErrorTotal, 0, sizeof(ErrorTotal));
memset(ErrorATMs, 0, sizeof(ErrorATMs));
memset(ProfitATMs, 0, sizeof(ProfitATMs));
for(i=0;i<ATM_COUNT;i++)
ATMs[i]=New_HashTable(sizeof(BANK), NULL, MAX_SIZE);
while( (Aux=ReadOperation(&Command, &ATM, &Limit, &Bank1, &Bank2, &Money))>0 ){ // Ler operação.
if(Command < 0) break;
switch(Command){
case 'S': // Saque.
if(Aux == 3){ // Erro.
ErrorATMs[ATM][0]++;
ErrorTotal[0]++;
continue;
}
Withdraw(Money, Bank1, ATMs[ATM]);
Withdraw(Money, Bank1, Total);
AddAudit(ATM, audit_withdraw, Bank1, -1, Money, Operations);
break;
case 'D': // Depósito.
if(Aux == 3){ // Erro.
ErrorATMs[ATM][1]++;
ErrorTotal[1]++;
continue;
}
Deposit(Money, Bank1, ATMs[ATM]);
Deposit(Money, Bank1, Total);
AddAudit(ATM, audit_deposit, Bank1, -1, Money, Operations);
break;
case 'U': // Transferência bancos diferentes.
if(Aux == 3){ // Erro.
ErrorATMs[ATM][2]++;
ErrorTotal[2]++;
continue;
}
TransferFrom(Money, Bank1, ATMs[ATM]);
TransferTo(Money, Bank2, ATMs[ATM]);
TransferFrom(Money, Bank1, Total);
TransferTo(Money, Bank2, Total);
AddAudit(ATM, audit_transfer, Bank1, Bank2, Money, Operations);
break;
case 'T': // Transferência mesmo banco.
if(Aux == 3){ // Erro.
ErrorATMs[ATM][2]++;
ErrorTotal[2]++;
continue;
}
AddAudit(ATM, audit_transfer, Bank1, Bank1, Money, Operations);
break;
default: // Consulta.
if(Aux == 3){ // Erro.
ErrorATMs[ATM][3]++;
ErrorTotal[3]++;
continue;
}
break;
}
ProfitATMs[ATM]+=PROFIT;
ProfitTotal+=PROFIT;
if(Aux == 2) break; // Fim da entrada.
}
for(i=0;i<ATM_COUNT;i++){ // Imprimir informações processadas de cada terminal.
printf("===TERMINAL %d===\n", i+1);
PrintATM(ATMs[i]);
Destroy_HashTable(ATMs[i]);
printf("Lucro obtido: %.2lf\n", ProfitATMs[i]);
if(ErrorATMs[i][0] > 0) printf("Erros de saque: %d\n", ErrorATMs[i][0]);
if(ErrorATMs[i][1] > 0) printf("Erros de deposito: %d\n", ErrorATMs[i][1]);
if(ErrorATMs[i][3] > 0) printf("Erros de consulta: %d\n", ErrorATMs[i][3]);
if(ErrorATMs[i][2] > 0) printf("Erros de transferencia: %d\n", ErrorATMs[i][2]);
if(ErrorATMs[i][0]+ErrorATMs[i][1]+ErrorATMs[i][2]+ErrorATMs[i][3] > 0) printf("Total de erros: %d\n", ErrorATMs[i][0]+ErrorATMs[i][1]+ErrorATMs[i][2]+ErrorATMs[i][3]);
}
// Imprimir total de informações processadas.
printf("===TOTAL===\n");
PrintATM(Total);
Destroy_HashTable(Total);
printf("Lucro obtido: %.2lf\n", ProfitTotal);
if(ErrorTotal[0] > 0) printf("Erros de saque: %d\n", ErrorTotal[0]);
if(ErrorTotal[1] > 0) printf("Erros de deposito: %d\n", ErrorTotal[1]);
if(ErrorTotal[3] > 0) printf("Erros de consulta: %d\n", ErrorTotal[3]);
if(ErrorTotal[2] > 0) printf("Erros de transferencia: %d\n", ErrorTotal[2]);
if(ErrorTotal[0]+ErrorTotal[1]+ErrorTotal[2]+ErrorTotal[3] > 0) printf("Total de erros: %d\n", ErrorTotal[0]+ErrorTotal[1]+ErrorTotal[2]+ErrorTotal[3]);
if(Command < 0){ // Auditoria.
printf("===AUDITORIA===\n");
do {
Command*=-1;
switch(Command){
case 'S': // Saque.
printf("===SAQUE TERMINAL %d===\n", ATM+1);
PrintAudit(ATM, audit_withdraw, Limit, Operations);
break;
case 'D': // Depósito.
printf("===DEPOSITO TERMINAL %d===\n", ATM+1);
PrintAudit(ATM, audit_deposit, Limit, Operations);
break;
case 'U': // Transferência mesmo banco.
case 'T': // Transferência bancos diferentes.
printf("===TRANSFERENCIA TERMINAL %d===\n", ATM+1);
PrintAudit(ATM, audit_transfer, Limit, Operations);
break;
default:
break;
}
if(Aux == 2) break; // Fim da entrada.
} while( (Aux=ReadOperation(&Command, &ATM, &Limit, &Bank1, &Bank2, &Money))>0 ); // Ler mais pedidos de auditoria, se tiver.
}
Destroy_HashTable(Operations);
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <iostream>
#include <vector>
#include <queue>
#include <tuple>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
void find_and_print(int source, vector< vector< pair<int, int> > > G) {
int i, N, u, v, w, *distances, *visited;
bool *inQ;
N = G.size();
queue<int> Q = queue<int>();
distances = (int *) malloc(sizeof(int) * N);
visited = (int *) malloc(sizeof(int) * N);
inQ = (bool *) malloc(sizeof(bool) * N);
memset(visited, 0, sizeof(int) * N);
for(i = 0; i < N; i++) {
distances[i] = INT_MIN;
inQ[i] = false;
}
distances[source] = 0;
Q.push(source);
while(Q.size() > 0) {
u = Q.front();
Q.pop();
inQ[u] = false;
visited[u]++;
if(visited[u] > N) {
cout << "Unlimited!" << endl;
return;
}
for(i = 0; i < G[u].size(); i++) {
v = G[u][i].first;
w = G[u][i].second;
if(distances[u] + w <= distances[v]) {
continue;
}
distances[v] = distances[u] + w;
if(inQ[v] == false) {
inQ[v] = true;
Q.push(v);
}
}
}
w = INT_MIN;
for(i = 0; i < N; i++) {
if(distances[i] > w) {
w = distances[i];
}
}
cout << w << endl;
free(distances);
free(visited);
free(inQ);
}
void testCase(int N, int M) {
int i, aux1, aux2, aux3;
vector< vector< pair<int, int> > > G = vector< vector< pair<int, int> > >();
for(i = 0; i < N; i++) {
G.push_back( vector< pair<int, int> >() );
}
for(i = 0; i < M; i++) {
cin >> aux1 >> aux2 >> aux3;
aux1--;
aux2--;
G[aux1].push_back( make_pair(aux2, aux3) );
}
find_and_print(0, G);
}
int main(int argc, char **argv) {
int N, M;
cin >> N >> M;
while(N > 0 && M > 0) {
testCase(N, M);
cin >> N >> M;
}
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/*
<NAME>
<EMAIL>
*/
typedef struct {
char key[100];
int value;
} array;
void Sort(array *, int);
void strfix(char *);
int main(int argc, char **argv){
int i,N;
char R[100],FileName[100];
FILE *FStream;
array *Words;
scanf("%s %d",FileName,&N);
Words=(array *)malloc(sizeof(array)*N);
for(i=0;i<N;i++){
scanf("%s",Words[i].key);
strfix(Words[i].key);
Words[i].value=0;
}
FStream=fopen(FileName,"r");
if(FStream!=NULL){
while(feof(FStream)==0){
fscanf(FStream,"%s ",R);
strfix(R);
for(i=0;i<N;i++)
if(strcmp(R,Words[i].key)==0)
Words[i].value++;
}
Sort(Words,N);
for(i=0;i<N;i++){
printf("%s %d\n",Words[i].key,Words[i].value);
}
fclose(FStream);
}
free(Words);
return EXIT_SUCCESS;
}
void Sort(array *ArrayVector,int N){
int i,j;
array R;
for(i=0;i<N;i++){
j=i;
while(j>0 && strcmp(ArrayVector[j-1].key,ArrayVector[j].key)>0 ){
R=ArrayVector[j-1];
ArrayVector[j-1]=ArrayVector[j];
ArrayVector[j]=R;
j--;
}
}
}
void strfix(char *String){
int i=0,j;
while( !(String[i]>='A' && String[i]<='Z') && !(String[i]>='a' && String[i]<='z') && String[i]!='\0' ){
j=i;
while(String[j]!='\0'){
String[i+j]=String[i+j+1];
j++;
}
i++;
}
for(i=strlen(String)-1;i>=0;i--){
if( (String[i]>='A' && String[i]<='Z') || (String[i]>='a' && String[i]<='z') ){
break;
}else{
String[i]='\0';
}
}
i=0;
while(String[i]!='\0'){
String[i]=tolower(String[i]);
i++;
}
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <skiplist.h>
/*
* ~ Dicionário ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
int main(int argc, char **argv){
char Operacao[15], Word[51], Meaning[141];
SKIPLIST *Words;
Words=New_Dictionary(time(NULL));
while(scanf("%s",Operacao)==1) /* Enquanto existirem operações para serem executadas... */
if(!strcmp(Operacao,"insercao")){
scanf("%50s %140[^\n^\r]s",Word,Meaning);
if(Insert_Word(Word,Meaning,Words)!=1) printf("OPERACAO INVALIDA\n"); /* Inserir ou retornar mensagem de erro. */
}else if(!strcmp(Operacao,"alteracao")){
scanf("%50s %140[^\n^\r]s",Word,Meaning);
if(Set_Word(Word,Meaning,Words)!=1) printf("OPERACAO INVALIDA\n"); /* Alterar ou retornar mensagem de erro. */
}else if(!strcmp(Operacao,"remocao")){
scanf("%50s",Word);
if(Remove_Word(Word,Words)!=1) printf("OPERACAO INVALIDA\n"); /* Remover ou retornar mensagem de erro. */
}else if(!strcmp(Operacao,"busca")){
scanf("%50s",Word);
if(Print_Word(Word, stdout, Words)!=1) printf("OPERACAO INVALIDA\n"); /* Imprimir definição ou retornar mensagem de erro. */
}else if(!strcmp(Operacao,"impressao")){
scanf("%50s",Word);
if(Print_Words_Starting_With(Word[0],stdout,Words)!=1) printf("NAO HA PALAVRAS INICIADAS POR %c\n", Word[0]); /* Imprimir definições ou retornar mensagem de aviso. */
}else printf("OPERACAO INVALIDA\n");
Destroy_Dictionary(Words);
return EXIT_SUCCESS;
}<file_sep># Busca em Labirinto
### Inteligência Artificial (SCC-0230) - Projeto 1
Neste projeto, foram implementados cinco algoritmos de busca em labirinto. Além do mais, uma análise completa foi feita sob estes algoritmos.
## Integrantes
* <NAME> (Nº USP 8596351)
* <NAME> (Nº USP 10369014)
* <NAME> (Nº USP 10783243)
## Organização do Repositório
O repositório foi organizado da seguinte maneira:
* [Mapas](Mapas): aqui se encontram as entradas usadas para os casos de teste do relatório, além de outros casos de teste opcionais.
* [Especificacao.pdf](Especificacao.pdf): Especificação do projeto fornecida pelo professor.
* [Relatorio.pdf](Relatorio.pdf): Relatório completo do projeto.
* [TrabalhoPratico1.py](TrabalhoPratico1.py): Código em Python. Executado com Python 3; pode-se utilizar os casos de teste disponíveis em [_Mapas_](Mapas).
* [GeradorLabirinto.py](GeradorLabirinto.py): Gerador de labirintos, usado para os casos de teste de tempo de execução.
## Relatório
O relatório completo do projeto encontra-se em [Relatorio](Relatorio.pdf).<file_sep>from datetime import datetime
import random
import string
import names
import time
import sys
import csv
csvDel = ',' # Delimitador do CSV de saída.
maxCount = 150 # Número de itens do arquivo Pessoa.
Null1 = .15 # % de campos NOME nulos.
Null2 = .4 # % de campos IDADE nulos.
Null3 = .95 # % de lista_segue eliminados.
timeRandomVariation = 60*60*24*730 # padrão: 2 anos.
now = int(time.time())
lista = { }
count = 0
def randomPastDate():
start_point = now - timeRandomVariation * 4
start_point += random.uniform(-timeRandomVariation, timeRandomVariation)
return datetime.fromtimestamp(start_point).strftime("%Y-%m-%d")
def randomFutureDate():
start_point = now + timeRandomVariation * 4
start_point += random.uniform(-timeRandomVariation, timeRandomVariation)
return datetime.fromtimestamp(start_point).strftime("%Y-%m-%d")
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Passe como argumento o nome do arquivo CSV a ser salvo e, opcionalmente, o nome do arquivo de seguidores.")
sys.exit(0)
print("%.2f%% concluído..." % (0.0), end="")
while len(lista) < maxCount:
print("\r%.2f%% concluído..." % (100 * len(lista)/maxCount), end="")
idPessoa = str(count + 1)
nomePessoa = names.get_full_name()
for _ in range(random.randint(0, 4)):
nomePessoa += " " + names.get_last_name()
idadePessoa = str(random.randint(14, 40))
twitterPessoa = nomePessoa.replace(" ", "").strip().lower()
if len(twitterPessoa) > 14:
twitterPessoa = twitterPessoa[:14]
lista[twitterPessoa] = [idPessoa, nomePessoa, idadePessoa, twitterPessoa]
count += 1
print("\r%.2f%% concluído... Pronto." % (100.0))
lista = [lista[k] for k in lista]
# Gerar lista de seguidores.
lista_segue = [ ]
print("%.2f%% concluído..." % (0.0), end="")
for i in range(len(lista)):
print("\r%.2f%% concluído..." % (100 * i/len(lista)), end="")
for pessoa2 in lista:
if lista[i][0] == pessoa2[0]:
continue
lista_segue.append( [lista[i][0], pessoa2[0], "%d" % (random.randint(0, 2)), randomPastDate(), randomFutureDate()] )
print("\r%.2f%% concluído... Pronto." % (100.0))
Null1 = int(Null1 * len(lista))
Null2 = int(Null2 * len(lista))
Null3 = int(Null3 * len(lista_segue))
random.shuffle(lista)
for i in range(Null1):
lista[i][1] = ""
random.shuffle(lista)
for i in range(Null2):
lista[i][2] = "-1"
random.shuffle(lista_segue)
lista_segue = lista_segue[Null3:]
random.shuffle(lista)
random.shuffle(lista_segue)
lista.insert(0, ["idPessoa", "nomePessoa", "idadePessoa", "twitterPessoa"])
lista_segue.insert(0, ["idPessoaQueSegue", "idPessoaQueESeguida", "grauAmizade", "dataInicioQueSegue", "dataFimQueSegue"])
with open(sys.argv[1], 'w') as csvfile: # Salvar.
spamwriter = csv.writer(csvfile, delimiter=csvDel, quotechar='', escapechar='\\', quoting=csv.QUOTE_NONE)
spamwriter.writerows(lista)
if len(sys.argv) == 3:
with open(sys.argv[2], 'w') as csvfile: # Salvar.
spamwriter = csv.writer(csvfile, delimiter=csvDel, quotechar='', escapechar='\\', quoting=csv.QUOTE_NONE)
spamwriter.writerows(lista_segue)
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
<NAME>
<EMAIL>
*/
#define ADDITION_NUMBER 5
#define bool char
#define true 1
#define false 0
bool DentroDe(char *Pattern,char *Str){
int i,j;
for(i=0;i<strlen(Str);i++){
for(j=0;j<strlen(Pattern);j++){
if(Str[i+j]!=Pattern[j]){
break;
}
}
if(j==strlen(Pattern)){
return true;
}
}
return false;
}
int main(){
int N,S=1;
char c,*N1=(char *)malloc(sizeof(char)*S),*N2=(char *)malloc(sizeof(char)*S);
N=0;
do{
c=getchar();
N1[N++]=c;
if(N>=S){
S+=ADDITION_NUMBER;
N1=(char *)realloc(N1,sizeof(char)*S);
}
} while(c>=48 && c<=57);
N1[N-1]='\0';
do{
c=getchar();
} while(!(c>=48 && c<=57));
N2[0]=c;
N=1;
S=1;
do{
c=getchar();
N2[N++]=c;
if(N>=S){
S+=ADDITION_NUMBER;
N2=(char *)realloc(N2,sizeof(char)*S);
}
} while(c>=48 && c<=57);
N2[N-1]='\0';
if(atoi(N1)>=atoi(N2)){
printf("%s %s ",N2,N1);
if(DentroDe(N2,N1)==true){
printf("SIM");
}else{
printf("NAO");
}
}else{
printf("%s %s ",N1,N2);
if(DentroDe(N1,N2)==true){
printf("SIM");
}else{
printf("NAO");
}
}
free(N1);
free(N2);
return EXIT_SUCCESS;
}
<file_sep>#include <stdlib.h>
#include <string.h>
typedef struct __objtoint_node {
void *object;
struct __objtoint_node *next;
} NODE;
typedef struct __objtoint {
int (*compar)(const void *, const void *);
void *vector;
NODE *root;
long count;
size_t size;
} OBJTOINT;
OBJTOINT *OBJ_Init(size_t Size, int (*Compar)(const void *, const void *)) {
OBJTOINT *aux;
if(Size < 1) {
return NULL;
}
aux = (OBJTOINT *) malloc(sizeof(OBJTOINT));
if(aux == NULL) {
return NULL;
}
aux->compar = Compar;
aux->vector = NULL;
aux->root = NULL;
aux->size = Size;
aux->count = 0;
return aux;
}
int OBJ_Push(void *Obj, OBJTOINT *O) {
NODE *aux;
if(Obj == NULL || O == NULL || O->vector != NULL) {
return 0;
}
aux = (NODE *) malloc(sizeof(NODE));
if(aux == NULL) {
return 0;
}
aux->object = (void *) malloc(O->size);
memcpy(aux->object, Obj, O->size);
aux->next = O->root;
O->root = aux;
O->count++;
return 1;
}
int OBJ_BuildVector(OBJTOINT *O) {
NODE *aux, *tmp;
long i;
if(O == NULL || O->count < 1) {
return 0;
}
if(O->vector != NULL) {
return 1;
}
O->vector = (void *) malloc(O->size * O->count);
if(O->vector == NULL) {
return 0;
}
for(i = 0, aux = O->root; aux != NULL; aux = aux->next) {
memcpy(O->vector + O->size * (i++), aux->object, O->size);
}
aux = O->root;
while(aux != NULL) {
tmp = aux;
aux = aux->next;
free(tmp->object);
free(tmp);
}
O->root = NULL;
qsort(O->vector, O->count, O->size, O->compar);
return 1;
}
long OBJ_Count(OBJTOINT *O) {
if(O == NULL) {
return -1;
}
return O->count;
}
long OBJ_IndexFor(void *Obj, OBJTOINT *O) {
long start, end, middle, cmp;
if(O == NULL || Obj == NULL || O->vector == NULL) {
return -2;
}
for(start = 0, end = O->count - 1; start <= end;) {
middle = (start + end) / 2;
cmp = O->compar(O->vector + middle * O->size, Obj);
if(cmp < 0) {
start = middle + 1;
} else if(cmp > 0) {
end = middle - 1;
} else {
return middle;
}
}
return -1;
}
int OBJ_ObjectFor(long index, void *ret, OBJTOINT *O) {
if(O == NULL || O->vector == NULL || index < 0 || index >= O->count) {
return 0;
}
if(ret != NULL) {
memcpy(ret, O->vector + index * O->size, O->size);
}
return 1;
}
void OBJ_Destroy(OBJTOINT *O) {
NODE *aux, *tmp;
if(O == NULL) {
return;
}
aux = O->root;
while(aux != NULL) {
tmp = aux;
aux = aux->next;
free(tmp->object);
free(tmp);
}
if(O->vector != NULL) {
free(O->vector);
}
free(O);
}
<file_sep>
#
# ~ MATRIOSKA ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -Wall
objects/main.o: main.c objects/matrioska.o headers/matrioska.h
gcc -c -o objects/main.o main.c -Wall -I headers
objects/matrioska.o: lib/matrioska.c objects/stack.o headers/stack.h
gcc -c -o objects/matrioska.o lib/matrioska.c -Wall -I headers
objects/stack.o: lib/stack.c headers/stack.h
gcc -c -o objects/stack.o lib/stack.c -Wall -I headers
run: Prog
./Prog
clean:
rm Prog objects/*.o
<file_sep>#include <stdlib.h>
#include <string.h>
#include <iostream>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
void testCase() {
ll N, M, i, aux1, aux2, *count;
cin >> N >> M;
count = (ll *) malloc(sizeof(ll) * N);
memset(count, 0, sizeof(ll) * N);
for(i = 0; i < M; i++) {
cin >> aux1 >> aux2;
aux1--;
aux2--;
count[aux1]++;
count[aux2]++;
}
for(i = 0; i < N; i++) {
cout << count[i] << endl;
}
}
int main(int argc, char **argv) {
ll T;
T = 1;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>package score;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.JOptionPane;
public class ScoreDAO {
@SuppressWarnings("resource")
public static List<Score> getAll() {
List<Score> scores = new ArrayList<Score>();
try {
String path = new File("score.csv").getAbsolutePath();
BufferedReader br = null;
String line = "";
br = new BufferedReader(new FileReader(path));
while ((line = br.readLine()) != null) {
String[] s = line.split(",");
Score score = new Score(s[0]);
score.setScore(Long.parseLong(s[1].trim()));
score.setDuration(Long.parseLong(s[2].trim()));
scores.add(score);
}
} catch (FileNotFoundException e) {
//e.printStackTrace();
System.out.println("No scores file");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Could not get scores");
}
Collections.sort(scores, new Comparator<Score>() {
@Override
public int compare(Score s0, Score s1) {
if (s0.getScore() > s1.getScore()) return -1;
if (s0.getScore() < s1.getScore()) return 1;
if (s0.getDuration() < s1.getDuration()) return -1;
if (s0.getDuration() > s1.getDuration()) return 1;
return 0;
}
});
return scores;
}
public static void add(Score score) {
File file = new File("score.csv");
try {
FileWriter fw = new FileWriter(file, true);
fw.append(score.getPlayer() + ", " + score.getScore() + ", "
+ score.getDuration() + "\n");
fw.flush();
fw.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Could not save score");
e.printStackTrace();
}
}
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
<NAME>
<EMAIL>
*/
#define N_DIAS_NO_MES 31
int main(){
char Word[300],is_palindrome=1;
int i,Word_len;
fgets(Word,sizeof(Word)-1,stdin);
Word_len=strlen(Word);
Word[Word_len-1]='\0';
Word_len-=1;
for(i=0;i<Word_len;i++){
if(!(Word[i]==Word[Word_len-(i+1)])){
is_palindrome=0;
break;
}
}
if(is_palindrome){
printf("SIM");
}else{
printf("NAO");
}
return EXIT_SUCCESS;
}<file_sep>
/*
* ~ HashTable ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef HASHTABLE_H_
#define HASHTABLE_H_
#include <stdlib.h>
typedef struct __hashtable_t HASHTABLE;
struct __hashtable_t *New_HashTable(size_t, void (*)(void *), unsigned long );
int Insert_Into_HashTable(long, void *, struct __hashtable_t *);
unsigned long Search_From_HashTable(long, void *, struct __hashtable_t *);
int Traverse_HashTable(void (*)(void *), struct __hashtable_t *);
void Destroy_HashTable(struct __hashtable_t *);
#endif<file_sep># Objeto
Objeto obtido do website [free3d](https://free3d.com/3d-model/abandoned-cottage-house-825251.html): licença para uso pessoal.
<file_sep>#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv) {
char aux;
while((aux = getc(stdin)) != EOF && aux != '\r');
if(aux == EOF) {
printf("Não tem barra R.\n");
} else {
printf("Tem barra R.\n");
}
return EXIT_SUCCESS;
}
<file_sep>
/*
* == IMAGENS P&B ==
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __IMAGE_H_
#define __IMAGE_H_
typedef struct __img_t IMG;
struct __img_t *New_Img();
char Read_Img(FILE *,struct __img_t *);
struct __img_t *Join_Img(struct __img_t *,struct __img_t *);
int Count_Img_Filled_Pixels(int,struct __img_t *);
char Destroy_Img(struct __img_t *);
#endif<file_sep>#include <stdlib.h>
#include <assert.h>
#include "linkedlist.h"
#ifndef LINKEDLIST_ELEM
#define LINKEDLIST_ELEM int
#endif
/*
* ~ Lista Enumerada ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
enum __ListItem_Type_t { Elem = 0, List };
union __ListItem_Value_t {
LINKEDLIST_ELEM E;
struct __List_t *L;
};
struct __ListItem_t{
enum __ListItem_Type_t Type;
union __ListItem_Value_t Value;
struct __ListItem_t *N;
};
struct __List_t{
int size;
struct __ListItem_t *start, *end;
};
struct __List_t *L_New(){
struct __List_t *Aux=(struct __List_t *)malloc(sizeof(struct __List_t)*1);
Aux->size=0;
Aux->start=NULL;
Aux->end=NULL;
return Aux;
}
int L_Size(struct __List_t *L){
if(L==NULL) return -1;
return L->size;
}
char L_Add(LINKEDLIST_ELEM X,struct __List_t *L){
struct __ListItem_t *Aux;
if(L==NULL) return 0;
if(L->size==0){
L->end=(struct __ListItem_t *)malloc(sizeof(struct __ListItem_t)*1);
L->end->Type=Elem;
L->end->Value.E=X;
L->end->N=NULL;
L->size++;
L->start=L->end;
return 2;
}
Aux=L->end;
Aux->N=(struct __ListItem_t *)malloc(sizeof(struct __ListItem_t)*1);
Aux->N->Type=Elem;
Aux->N->Value.E=X;
Aux->N->N=NULL;
L->end=Aux->N;
L->size++;
return 1;
}
char L_AddSubList(struct __List_t *X,struct __List_t *L){
struct __ListItem_t *Aux;
if(L==NULL) return 0;
if(L->size==0){
L->end=(struct __ListItem_t *)malloc(sizeof(struct __ListItem_t)*1);
L->end->Type=List;
L->end->Value.L=X;
L->end->N=NULL;
L->size++;
L->start=L->end;
return 2;
}
Aux=L->end;
Aux->N=(struct __ListItem_t *)malloc(sizeof(struct __ListItem_t)*1);
Aux->N->Type=List;
Aux->N->Value.L=X;
Aux->N->N=NULL;
L->end=Aux->N;
L->size++;
return 1;
}
char L_AddAt(LINKEDLIST_ELEM X,int i,struct __List_t *L){
struct __ListItem_t *Aux,*NewAux;
int p;
if(L==NULL) return -1;
if(i<0 || i>L->size) return 0;
Aux=L->start;
NewAux=(struct __ListItem_t *)malloc(sizeof(struct __ListItem_t)*1);
if(L->size==0){
NewAux->N=NULL;
L->start=L->end=NewAux;
}else if(i==L->size){
NewAux->N=NULL;
L->end->N=NewAux;
L->end=NewAux;
}else if(i==L->size-1){
NewAux->N=L->end->N;
L->end->N=NewAux;
L->end=NewAux;
}else if(i==0){
NewAux->N=L->start;
L->start=NewAux;
}else{
p=0;
while(p<i-1){
Aux=Aux->N;
p++;
}
NewAux->N=Aux->N->N;
Aux->N=NewAux;
}
NewAux->Type=Elem;
NewAux->Value.E=X;
L->size++;
return 1;
}
char L_AddSubListAt(struct __List_t *X,int i,struct __List_t *L){
struct __ListItem_t *Aux,*NewAux;
int p;
if(L==NULL) return -1;
if(i<0 || i>L->size) return 0;
Aux=L->start;
NewAux=(struct __ListItem_t *)malloc(sizeof(struct __ListItem_t)*1);
if(L->size==0){
NewAux->N=NULL;
L->start=L->end=NewAux;
}else if(i==L->size){
NewAux->N=NULL;
L->end->N=NewAux;
L->end=NewAux;
}else if(i==L->size-1){
NewAux->N=L->end->N;
L->end->N=NewAux;
L->end=NewAux;
}else if(i==0){
NewAux->N=L->start;
L->start=NewAux;
}else{
p=0;
while(p<i-1){
Aux=Aux->N;
p++;
}
NewAux->N=Aux->N->N;
Aux->N=NewAux;
}
NewAux->Type=List;
NewAux->Value.L=X;
L->size++;
return 1;
}
char L_Destroy(struct __List_t *);
char L_Remove(struct __List_t *L){
struct __ListItem_t *Aux;
if(L==NULL) return -1;
if(L->size<=0) return 0;
Aux=L->start;
while(Aux->N!=L->end && Aux->N!=NULL){
Aux=Aux->N;
}
Aux->N=NULL;
if(L->end->Type==List) L_Destroy(L->end->Value.L);
free(L->end);
L->end=Aux;
L->size--;
if(L->size<=0){
L->end=L->start=NULL;
}
return 1;
}
char L_RemoveAt(int i,struct __List_t *L){
struct __ListItem_t *Aux,*R;
int p;
if(L==NULL) return -1;
if(i<0 || i>=L->size) return 0;
Aux=L->start;
if(L->size==1){
if(Aux->Type==List) L_Destroy(Aux->Value.L);
free(Aux);
L->start=NULL;
L->end=NULL;
}else if(i==0){
R=Aux->N;
if(Aux->Type==List) L_Destroy(Aux->Value.L);
free(Aux);
L->start=R;
}else{
for(p=0;p<i-1;p++)
Aux=Aux->N;
R=Aux->N;
Aux->N=Aux->N->N;
if(i==L->size-1){
L->end=Aux;
}
if(R->Type==List) L_Destroy(R->Value.L);
free(R);
}
L->size--;
return 1;
}
char L_IsSubList(struct __List_t *L){
if(L==NULL) return -2;
if(L->size<=0) return -1;
return (L->end->Type==List) ? 1 : 0;
}
char L_IsSubListAt(int i,struct __List_t *L){
struct __ListItem_t *Aux;
int p;
if(L==NULL) return -2;
if(i<0 || i>=L->size) return -1;
if(i==L->size-1){
Aux=L->end;
return (Aux->Type==List) ? 1 : 0;
}
Aux=L->start;
for(p=0;p<i;p++)
Aux=Aux->N;
return (Aux->Type==List) ? 1 : 0;
}
LINKEDLIST_ELEM L_Get(struct __List_t *L){
if(L==NULL) assert(0);
if(L->size<=0) assert(0);
return L->end->Value.E;
}
LINKEDLIST_ELEM L_GetAt(int i,struct __List_t *L){
struct __ListItem_t *Aux;
int p;
if(L==NULL) assert(0);
if(i<0 || i>=L->size) assert(0);
if(i==L->size-1){
Aux=L->end;
return Aux->Value.E;
}
Aux=L->start;
for(p=0;p<i;p++)
Aux=Aux->N;
return Aux->Value.E;
}
struct __List_t *L_GetSubList(struct __List_t *L){
if(L==NULL) assert(0);
if(L->size<=0) assert(0);
return L->end->Value.L;
}
struct __List_t *L_GetSubListAt(int i,struct __List_t *L){
struct __ListItem_t *Aux;
int p;
if(L==NULL) assert(0);
if(i<0 || i>=L->size) assert(0);
if(i==L->size-1){
Aux=L->end;
return Aux->Value.L;
}
Aux=L->start;
for(p=0;p<i;p++)
Aux=Aux->N;
return Aux->Value.L;
}
char L_Set(LINKEDLIST_ELEM X,struct __List_t *L){
if(L==NULL) return -1;
if(L->size<=0) return 0;
if(L->end->Type==List) L_Destroy(L->end->Value.L);
L->end->Type=Elem;
L->end->Value.E=X;
return 1;
}
char L_SetAt(LINKEDLIST_ELEM X,int i,struct __List_t *L){
struct __ListItem_t *Aux;
int p;
if(L==NULL) return -1;
if(i<0 || i>=L->size) return 0;
Aux=L->start;
for(p=0;p<i;p++)
Aux=Aux->N;
if(Aux->Type==List) L_Destroy(Aux->Value.L);
Aux->Type=Elem;
Aux->Value.E=X;
return 1;
}
char L_SetSubList(struct __List_t *X,struct __List_t *L){
if(L==NULL) return -1;
if(L->size<=0) return 0;
if(L->end->Type==List) L_Destroy(L->end->Value.L);
L->end->Type=List;
L->end->Value.L=X;
return 1;
}
char L_SetSubListAt(struct __List_t *X,int i,struct __List_t *L){
struct __ListItem_t *Aux;
int p;
if(L==NULL) return -1;
if(i<0 || i>=L->size) return 0;
Aux=L->start;
for(p=0;p<i;p++)
Aux=Aux->N;
if(Aux->Type==List) L_Destroy(Aux->Value.L);
Aux->Type=List;
Aux->Value.L=X;
return 1;
}
char L_Destroy(struct __List_t *L){
struct __ListItem_t *Aux,*R;
if(L==NULL) return 0;
if(L->size>0){
Aux=L->start;
while(Aux!=NULL){
R=Aux->N;
if(Aux->Type==List) L_Destroy(Aux->Value.L);
free(Aux);
Aux=R;
}
}
free(L);
return 1;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
<NAME>
<EMAIL>
*/
int main(){
unsigned int i,j,N,n,nc;
char is_prime;
scanf("%d",&N);
n=N;
for(i=2;i<=N;i++){
nc=0;
is_prime=1;
for(j=2;j<=sqrt(N);j++){
if(i!=j && !(i%j)){
is_prime=0;
break;
}
}
if(is_prime){
while(!(n%i)){
n=n/i;
nc++;
}
if(nc>0){
printf("%d %d \n",i,nc);
}
}
}
return EXIT_SUCCESS;
}<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/*
<NAME>
<EMAIL>
*/
int Contar(char *str,char chpatt){
int i,count=0;
for(i=0;i<strlen(str);i++){
if(str[i]==chpatt){
count++;
}
}
return count;
}
int main(){
char Str[1000],ChPatt;
fgets(Str,sizeof(Str),stdin);
scanf(" %c",&ChPatt);
printf("%d",Contar(Str,ChPatt));
return EXIT_SUCCESS;
}
<file_sep># Objeto
Objeto obtido do website [free3d](https://free3d.com/3d-model/freddy-krueger-72575.html): licença para uso pessoal.
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stack.h>
/*
* ~ LABYRINTH ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
enum __bool_t { false=0, true }; // Pseudo-booleano.
struct __point_t { // Cada ponto do labirinto, independente se é câmara, túnel de segmento ou beco sem saída, é representado por esta estrutura.
float x, y; // Posição.
enum __bool_t exit,visited; // Se o ponto for câmara, indica se é uma saída do labirinto ou se já passamos por aqui, na hora de encontrar soluções.
int links_to[8]; // O ponto pode ter túneis que o liga até 8 outros pontos.
};
struct __treasure_invert_action_t { // Essa estrutura é utilizada para indicar as ações que a câmara de tesouro solicita.
int A,B;
};
struct __solution_path_t { // Cada caminho de solução é dado por esta estrutura.
enum __bool_t Treasure; // Indica se o caminho passa pela câmara de tesouro.
float GeoSum,Points; // Soma Geodésica e Pontuação do caminho.
STACK *Path; // Pilha que representa o caminho.
};
struct __lab_t { // O labirinto como um todo é representado por esta estrutura.
int Cs,Ct,NP,SolutionCount,T,TCount;
struct __treasure_invert_action_t *TActions;
struct __point_t *Points;
struct __solution_path_t *Solutions;
};
struct __lab_t *ReadLab(FILE *FStream){
/*
* Esta função vai ler as entradas necessárias para formar um labirinto de 'FStream'.
*
* Ela retorna o labirinto formado.
*/
struct __lab_t *Aux=(struct __lab_t *)malloc(sizeof(struct __lab_t));
int i,j,R,S,T,U;
Aux->SolutionCount=Aux->TCount=0;
Aux->Solutions=NULL;
Aux->TActions=NULL;
scanf("%d",&Aux->NP); // Número de pontos.
Aux->Points=(struct __point_t *)malloc(sizeof(struct __point_t)*Aux->NP);
for(i=0;i<Aux->NP;i++){ // Para cada ponto...
scanf("%f %f",&Aux->Points[i].x,&Aux->Points[i].y); // Obter sua posição.
Aux->Points[i].exit=Aux->Points[i].visited=false;
for(j=0;j<8;j++) Aux->Points[i].links_to[j]=0;
}
scanf("%d",&R); // Número de câmaras.
for(i=0;i<R;i++){ // Para cada câmara...
scanf("%d %d",&S,&T);
if(T!=0 && S>0 && S <=Aux->NP) Aux->Points[S-1].exit=true; // Se a câmara for de saída, marcar isso no ponto que representa ela.
}
scanf("%d",&R); // Número de segmentos.
for(i=0;i<R;i++){ // Para cada segmento...
scanf("%d %d",&S,&T); // Conectar os pontos correspondentes.
if(S<0 || T<0) U=-1;
else U=1;
R=abs(R);
S=abs(S);
if(S>0 && S<=Aux->NP && T>0 && T<=Aux->NP){
j=0;
while(abs(Aux->Points[S-1].links_to[j])!=0) j++;
Aux->Points[S-1].links_to[j]=T*U;
j=0;
while(abs(Aux->Points[T-1].links_to[j])!=0) j++;
Aux->Points[T-1].links_to[j]=S*U;
}
}
scanf("%d %d %d",&Aux->Ct,&Aux->T,&R); // Câmara do tesouro, Pontuação do tesouro e Número de ações.
if(Aux->Ct<=0 || Aux->Ct>Aux->NP){ // Verificação de integridade da câmara de tesouro.
Aux->Ct=0; // Câmara não é válida! Não existe tesouro nesse labirinto mais.
Aux->T=0;
for(i=0;i<R;i++) scanf("%*d %*d");
}else{
for(i=0;i<R;i++){ // Para cada ação do tesouro...
scanf("%d %d",&S,&T); // Registrar essa ação para uso apenas quando passar pela câmara de tesouro.
if(S<0 || T<0) U=-1;
else U=1;
S=abs(S);
T=abs(T);
if(S>0 && S<=Aux->NP && T>0 && T<=Aux->NP){
Aux->TActions=(struct __treasure_invert_action_t *)realloc(Aux->TActions,sizeof(struct __treasure_invert_action_t)*(++Aux->TCount));
Aux->TActions[Aux->TCount-1].A=S*U;
Aux->TActions[Aux->TCount-1].B=T*U;
}
}
}
scanf("%d",&Aux->Cs); // Câmara inicial.
return Aux;
}
char FindSolutionsWithoutTreasure(struct __lab_t *Lab){
/*
* Esta função vai procurar por todas as soluções possíveis para o labirinto já formado 'Lab', SEM PASSAR PELO TESOURO.
*
* Ela retorna 2 em caso de sucesso, 1 caso não tenha encontrado nenhum caminho (caso Cs=Ct), e 0 em caso de erros.
*/
if(Lab==NULL) return 0;
if(Lab->Cs==Lab->Ct) return 1; // Se a Câmara de tesouro e a Câmara inicial forem a mesma, ignorar essa função.
STACK *Path=S_New(); // Criar uma pilha para representar o caminho.
int i,Last=0;
S_Push(Lab->Cs,Path); // Começa na câmara inicial "Cs".
while(S_Size(Path)>0){ // Procurar por saídas sem passar pela câmara de tesouro.
if(Lab->Points[S_Get(Path)-1].visited==false && Lab->Points[S_Get(Path)-1].exit==true && S_Get(Path)!=Lab->Cs){ // É saída?
Lab->Solutions=(struct __solution_path_t *)realloc(Lab->Solutions,sizeof(struct __solution_path_t)*(++Lab->SolutionCount)); // SIM! Salvar caminho percorrido até aqui.
Lab->Solutions[Lab->SolutionCount-1].Path=S_NewFrom(Path); // Copia esse caminho para o vetor de soluções.
Lab->Solutions[Lab->SolutionCount-1].Treasure=false;
}
Lab->Points[S_Get(Path)-1].visited=true; // Marcar que estamos passando por aqui.
for(i=0;i<8;i++) if(Lab->Points[S_Get(Path)-1].links_to[i]==Last) break; // Estamos vindo de onde?
if(i>=8 || Last==0) i=0; // Lugar nenhum porque chegamos aqui agora.
else i++; // Já passamos aqui e estamos voltando para pegar um portal diferente dessa vez.
while(i<8){
if(Lab->Points[S_Get(Path)-1].links_to[i]>0 && Lab->Points[S_Get(Path)-1].links_to[i]!=Lab->Ct && Lab->Points[Lab->Points[S_Get(Path)-1].links_to[i]-1].visited==false ){ // O portal tá trancado por algum motivo OU é um beco sem saída?
Last=0; // Não. Vamos lá.
S_Push(Lab->Points[S_Get(Path)-1].links_to[i],Path);
break;
}
i++;
}
if(i>=8){ // Passamos por todos os portais?
Lab->Points[S_Get(Path)-1].visited=false; // Sim. Vamos voltar pra trás então.
Last=S_Pop(Path);
}
}
S_Push(Lab->Cs,Path);
Lab->Solutions=(struct __solution_path_t *)realloc(Lab->Solutions,sizeof(struct __solution_path_t)*(++Lab->SolutionCount)); // Colocar a solução trivial no vetor de soluções.
Lab->Solutions[Lab->SolutionCount-1].Path=S_NewFrom(Path);
Lab->Solutions[Lab->SolutionCount-1].Treasure=false;
S_Destroy(Path);
return 2;
}
char FindSolutionsWithTreasure(struct __lab_t *Lab){
/*
* Esta função vai procurar por todas as soluções possíveis para o labirinto já formado 'Lab', PASSANDO PELO TESOURO.
* Vale lembrar que ela vai modificar o labirinto, realizando as ações solicitadas pela câmara do tesouro.
*
* Ela retorna 1 se for executada, e 0 em caso de erros.
*/
if(Lab==NULL) return 0;
STACK *Path=S_New(),**Paths=NULL; // Criar uma pilha para representar o caminho atual, e um vetor de pilhas para representar todos os caminhos possíveis até a câmara do tesouro.
int i,j,Last=0,PathsCount=0;
S_Push(Lab->Cs,Path); // Começa na câmara inicial "Cs".
while(S_Size(Path)>0){ // Procurar por caminhos até a câmara do tesouro.
if(Lab->Points[S_Get(Path)-1].visited==false && S_Get(Path)==Lab->Ct && S_Get(Path)!=Lab->Cs){ // É a câmara do tesouro?
Paths=(STACK **)realloc(Paths,sizeof(STACK *)*(++PathsCount)); // SIM! Salvar caminho percorrido até aqui.
Paths[PathsCount-1]=S_NewFrom(Path); // Copia esse caminho para o vetor de pilhas.
}
Lab->Points[S_Get(Path)-1].visited=true; // Marcar que estamos passando por aqui.
for(i=0;i<8;i++) if(Lab->Points[S_Get(Path)-1].links_to[i]==Last) break; // Estamos vindo de onde?
if(i>=8 || Last==0) i=0; // Lugar nenhum porque chegamos aqui agora.
else i++; // Já passamos aqui e estamos voltando para pegar um portal diferente dessa vez.
while(i<8){
if(Lab->Points[S_Get(Path)-1].links_to[i]>0 && Lab->Points[Lab->Points[S_Get(Path)-1].links_to[i]-1].visited==false){ // O portal tá trancado por algum motivo OU é um beco sem saída?
Last=0; // Não. Vamos lá.
S_Push(Lab->Points[S_Get(Path)-1].links_to[i],Path);
break;
}
i++;
}
if(i>=8){ // Passamos por todos os portais?
Lab->Points[S_Get(Path)-1].visited=false; // Sim. Vamos voltar pra trás então.
Last=S_Pop(Path);
}
}
for(j=0;j<Lab->TCount;j++){ // Para cada Ação do tesouro, realizar.
for(i=0;i<8;i++) if(Lab->Points[abs(Lab->TActions[j].A)-1].links_to[i]==0 || abs(Lab->Points[abs(Lab->TActions[j].A)-1].links_to[i])==abs(Lab->TActions[j].B)) break;
if(i<8) Lab->Points[abs(Lab->TActions[j].A)-1].links_to[i]=Lab->TActions[j].B;
for(i=0;i<8;i++) if(Lab->Points[abs(Lab->TActions[j].B)-1].links_to[i]==0 || abs(Lab->Points[abs(Lab->TActions[j].B)-1].links_to[i])==abs(Lab->TActions[j].A)) break;
if(i<8) Lab->Points[abs(Lab->TActions[j].B)-1].links_to[i]=Lab->TActions[j].A;
}
if(Lab->Cs==Lab->Ct){ // Se a Câmara inicial e a Câmara de tesouro forem a mesma...
Paths=(STACK **)realloc(Paths,sizeof(STACK *)*(++PathsCount)); // Então vamos sempre começar da própria Câmara de tesouro.
Paths[PathsCount-1]=S_New();
S_Push(Lab->Ct,Paths[PathsCount-1]);
}
for(j=0;j<PathsCount;j++){ // Há soluções DISTINTAS para CADA caminho que temos até a Câmara de tesouro. Vamos salvar TODAS que encontrarmos.
S_Push(S_Get(Paths[j]),Path); // Agora vamos achar o caminho normalmente, mas o início será no último elemento da pilha (a própria Câmara de tesouro).
Last=0;
while(S_Size(Path)>0){ // Procurar por caminhos até a saída.
if(Lab->Points[S_Get(Path)-1].visited==false && Lab->Points[S_Get(Path)-1].exit==true && S_Get(Path)!=Lab->Ct){ // É uma saída?
Lab->Solutions=(struct __solution_path_t *)realloc(Lab->Solutions,sizeof(struct __solution_path_t)*(++Lab->SolutionCount)); // SIM! Salvar caminho percorrido até aqui, incluindo o caminho até a Câmara de tesouro.
Lab->Solutions[Lab->SolutionCount-1].Path=S_NewFrom(Paths[j]); // Copia o caminho até a Câmara de tesouro para a solução.
for(i=1;i<S_Size(Path);i++) S_Push(S_GetAt(i,Path),Lab->Solutions[Lab->SolutionCount-1].Path); // Completa com o resto do caminho até a saída.
Lab->Solutions[Lab->SolutionCount-1].Treasure=true;
}
Lab->Points[S_Get(Path)-1].visited=true; // Marcar que estamos passando por aqui.
for(i=0;i<8;i++) if(abs(Lab->Points[S_Get(Path)-1].links_to[i])==Last) break; // Estamos vindo de onde?
if(i>=8 || Last==0) i=0; // Lugar nenhum porque chegamos aqui agora.
else i++; // Já passamos aqui e estamos voltando para pegar um portal diferente dessa vez.
while(i<8){
if(Lab->Points[S_Get(Path)-1].links_to[i]>0 && Lab->Points[Lab->Points[S_Get(Path)-1].links_to[i]-1].visited==false){ // O portal tá trancado por algum motivo OU é um beco sem saída?
Last=0; // Não. Vamos lá.
S_Push(abs(Lab->Points[S_Get(Path)-1].links_to[i]),Path);
break;
}
i++;
}
if(i>=8){ // Passamos por todos os portais?
Lab->Points[S_Get(Path)-1].visited=false; // Sim. Vamos voltar pra trás então.
Last=S_Pop(Path);
}
}
if(Lab->Points[Lab->Ct-1].exit==true){ // Se a Câmara de tesouro for uma saída também, colocar a solução trivial no vetor de soluções.
Lab->Solutions=(struct __solution_path_t *)realloc(Lab->Solutions,sizeof(struct __solution_path_t)*(++Lab->SolutionCount));
Lab->Solutions[Lab->SolutionCount-1].Path=S_NewFrom(Paths[j]);
Lab->Solutions[Lab->SolutionCount-1].Treasure=true;
}
S_Destroy(Paths[j]);
}
free(Paths);
S_Destroy(Path);
return 1;
}
char SortSolutions(struct __lab_t *Lab){
/*
* Esta função vai calcular a soma geodésica e a pontuação dos caminhos soluções e ordenar de acordo com os requisitos solicitados.
*
* Ela retorna 1 se for executada, e 0 em caso de erros.
*/
if(Lab==NULL) return 0;
struct __solution_path_t R;
int i,j,k;
float GeoSum;
// Primeiramente vamos calcular a soma geodésica e a pontuação.
for(i=0;i<Lab->SolutionCount;i++){ // Para cada caminho solução...
GeoSum=0; // Calcular a soma geodésica...
for(j=1;j<S_Size(Lab->Solutions[i].Path);j++){
GeoSum+=sqrt(pow(Lab->Points[S_GetAt(j,Lab->Solutions[i].Path)-1].x-Lab->Points[S_GetAt(j-1,Lab->Solutions[i].Path)-1].x,2)+pow(Lab->Points[S_GetAt(j,Lab->Solutions[i].Path)-1].y-Lab->Points[S_GetAt(j-1,Lab->Solutions[i].Path)-1].y,2));
}
Lab->Solutions[i].GeoSum=GeoSum;
if(Lab->Solutions[i].Treasure==true) Lab->Solutions[i].Points=Lab->T;
else Lab->Solutions[i].Points=0;
Lab->Solutions[i].Points-=GeoSum; // e a pontuação.
}
// Agora vamos ordenar (Shell Sort).
k=Lab->SolutionCount/2;
while(k>0){
for(j=k;j<Lab->SolutionCount;j++){
R=Lab->Solutions[j];
i=j;
while( i>=k && ( Lab->Solutions[i-k].Points<R.Points || (Lab->Solutions[i-k].Points==R.Points && Lab->Solutions[i-k].GeoSum<R.GeoSum) || (Lab->Solutions[i-k].Points==R.Points && Lab->Solutions[i-k].GeoSum==R.GeoSum && S_Size(Lab->Solutions[i-k].Path)>S_Size(R.Path)) || (Lab->Solutions[i-k].Points==R.Points && Lab->Solutions[i-k].GeoSum==R.GeoSum && S_Size(Lab->Solutions[i-k].Path)==S_Size(R.Path) && S_Cmp(Lab->Solutions[i-k].Path,R.Path)<0) ) ){
Lab->Solutions[i]=Lab->Solutions[i-k];
i-=k;
}
Lab->Solutions[i]=R;
}
k/=2;
}
return 1;
}
char PrintSolutions(struct __lab_t *Lab,FILE *FStream){
/*
* Esta função vai imprimir todas as soluções encontradas para o labirinto 'Lab' de forma organizada em 'FStream'.
*
* Ela retorna 1 se for executada, e 0 em caso de erros.
*/
if(Lab==NULL) return 0;
int i,j;
printf("%d %d\n",Lab->Ct,Lab->T);
for(i=0;i<Lab->SolutionCount;i++){
fprintf(FStream,"%d",S_Size(Lab->Solutions[i].Path));
for(j=0;j<S_Size(Lab->Solutions[i].Path);j++){
fprintf(FStream," %d",S_GetAt(j,Lab->Solutions[i].Path));
}
fprintf(FStream," %d %d\n",(int)round(Lab->Solutions[i].GeoSum),(int)round(Lab->Solutions[i].Points));
}
return 1;
}
char DestroyLab(struct __lab_t *Lab){
/*
* Esta função vai limpar da memória todo o labirinto 'Lab'.
*
* Ela retorna 1 se for executada, e 0 em caso de erros.
*/
if(Lab==NULL) return 0;
int i;
for(i=0;i<Lab->SolutionCount;i++) S_Destroy(Lab->Solutions[i].Path);
free(Lab->TActions);
free(Lab->Points);
free(Lab->Solutions);
free(Lab);
return 1;
}
<file_sep># Objeto
Objeto obtido do website [blendswap](https://www.blendswap.com/blend/9504): licença CC-0.
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <stack.h>
#include <queue.h>
#include <heap.h>
int compare_integer(void *PA, void *PB){
int *A=PA, *B=PB;
return (*B)-(*A);
}
int main(int argc, char **argv){
STACK *Data_S;
QUEUE *Data_Q;
HEAP *Data_H;
int i,N,Action,Element,Aux;
char WhatIsIt;
scanf("%d", &N);
while(N!=0){
Data_S=S_New(sizeof(int));
Data_Q=Q_New(sizeof(int));
Data_H=H_New(sizeof(int), compare_integer);
WhatIsIt=7;
for(i=0;i<N;i++){
scanf("%d %d", &Action,&Element);
if(Action==1){ // Adicionar
if(WhatIsIt&1) S_Push(&Element,Data_S);
if(WhatIsIt&2) Q_Add(&Element,Data_Q);
if(WhatIsIt&4) H_Add(&Element,Data_H);
}else{ // Remover
if(WhatIsIt&1){
S_Pop(&Aux,Data_S);
if(Aux!=Element) WhatIsIt=WhatIsIt&(~1);
}
if(WhatIsIt&2){
Q_Shift(&Aux,Data_Q);
if(Aux!=Element) WhatIsIt=WhatIsIt&(~2);
}
if(WhatIsIt&4){
H_Shift(&Aux,Data_H);
if(Aux!=Element) WhatIsIt=WhatIsIt&(~4);
}
}
}
if(WhatIsIt==0){
printf("impossivel\n");
}else if((WhatIsIt|1)==1){
printf("pilha\n");
}else if((WhatIsIt|2)==2){
printf("fila\n");
}else if((WhatIsIt|4)==4){
printf("fila de prioridade\n");
}else{
printf("incerto\n");
}
S_Destroy(Data_S);
Q_Destroy(Data_Q);
H_Destroy(Data_H);
scanf("%d",&N);
}
return EXIT_SUCCESS;
}<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
int main(){
int N,i,P=1,M=0;
float s=0;
scanf("%d",&N);
for(i=1;i<=N;i++){
s+=P/(float)(N-M);
P+=2;
M++;
}
printf("%.4f",s);
return EXIT_SUCCESS;
}
<file_sep>from utils import Config, DBConnection
from threading import Thread, Lock
from consts import TA_THREAD_SLEEP_TIMEOUT
import time
import kafka
class TaskManager:
_THREAD = None
_MUTEX = None
_STOP = None
_KAFKA_PRODUCER = None
@staticmethod
def Init():
if TaskManager._STOP != None:
return
TaskManager._THREAD = Thread(target=TaskManager._Run)
TaskManager._MUTEX = Lock()
TaskManager._KAFKA_PRODUCER = kafka.KafkaProducer(bootstrap_servers=Config.KAFKA, value_serializer=lambda x: str(x).encode('utf-8'))
TaskManager._THREAD.start()
TaskManager._STOP = False
@staticmethod
def _Run():
while True:
TaskManager._MUTEX.acquire(timeout = TA_THREAD_SLEEP_TIMEOUT)
if TaskManager._STOP == True: # Stop thread?
con.close()
return
con = DBConnection()
waiting_analytics = con.fetchOne('SELECT `id` FROM `analysis` WHERE `ready` = false')
con.close()
if waiting_analytics is None: # Any analytics waiting to be processed?
continue
TaskManager._KAFKA_PRODUCER.send('ta_analysis_jobs', waiting_analytics[0])
@staticmethod
def WakeUp():
if TaskManager._STOP != False:
return
TaskManager._MUTEX.release()
@staticmethod
def Stop():
if TaskManager._STOP != False:
return
TaskManager._STOP = True
TaskManager._THREAD.join()
TaskManager._THREAD = None
TaskManager._MUTEX = None
TaskManager._STOP = None
@staticmethod
def WaitStop():
if TaskManager._STOP != False:
return
TaskManager._THREAD.join()
class TaskNode:
_THREAD = None
_STOP = None
_KAFKA_CONSUMER = None
@staticmethod
def Init():
if TaskNode._STOP != None:
return
TaskNode._THREAD = Thread(target=TaskNode._Run)
TaskNode._KAFKA_CONSUMER = kafka.KafkaConsumer('ta_analysis_jobs', bootstrap_servers=Config.KAFKA)
TaskNode._THREAD.start()
TaskNode._STOP = False
@staticmethod
def _Run():
for job in TaskNode._KAFKA_CONSUMER:
con = DBConnection()
analysis = con.fetchOne('SELECT `id`, `db_id` FROM `analysis` WHERE `ready` = false AND `id` = %s', (int(job.value), ))
if analysis is None:
con.close()
continue
analysis = {'id': analysis[0], 'db_id': analysis[1]}
fewinteractions = con.fetchOne('SELECT COUNT(DISTINCT `user_id`) FROM `tweets` WHERE `db_id` = %s AND `favoritecount`+`retweetcount` <= %s', (analysis['db_id'], 5, ))[0] # 5 Interactions
usercount = con.fetchOne('SELECT COUNT(DISTINCT `user_id`) FROM `tweets` WHERE `db_id` = %s', (analysis['db_id'], ))[0]
recentusercount = con.fetchOne('SELECT COUNT(DISTINCT `user_id`) FROM `tweets` WHERE `db_id` = %s AND `user_createdat` >= %s', (analysis['db_id'], time.time() - 365*24*60*60, ))[0] # 1 year.
defaultprofilecount = con.fetchOne('SELECT COUNT(DISTINCT `user_id`) FROM `tweets` WHERE `db_id` = %s AND `user_defaultprofile` = true', (analysis['db_id'], ))[0]
defaultpicturecount = con.fetchOne('SELECT COUNT(DISTINCT `user_id`) FROM `tweets` WHERE `db_id` = %s AND `user_defaultpicture` = true', (analysis['db_id'], ))[0]
fewfollowings = con.fetchOne('SELECT COUNT(DISTINCT `user_id`) FROM `tweets` WHERE `db_id` = %s AND `user_following` <= %s', (analysis['db_id'], 100, ))[0] # 100 Following
fewfollowers = con.fetchOne('SELECT COUNT(DISTINCT `user_id`) FROM `tweets` WHERE `db_id` = %s AND `user_followers` <= %s', (analysis['db_id'], 30, ))[0] # 30 Followers
fewstatus = con.fetchOne('SELECT COUNT(DISTINCT `user_id`) FROM `tweets` WHERE `db_id` = %s AND `user_statuscount` <= %s', (analysis['db_id'], 50, ))[0] # 50 Status
fewfavorites = con.fetchOne('SELECT COUNT(DISTINCT `user_id`) FROM `tweets` WHERE `db_id` = %s AND `user_favoritescount` <= %s', (analysis['db_id'], 50, ))[0] # 50 Favorites
results = (fewinteractions, usercount, recentusercount, defaultprofilecount, defaultpicturecount, fewfollowings, fewfollowers, fewstatus, fewfavorites)
# Save results.
con.execute('UPDATE `analysis` SET `ready` = true, `results_fewinteractions` = %s, `results_usercount` = %s, `results_recentusercount` = %s, `results_defaultprofilecount` = %s, `results_defaultpicturecount` = %s, `results_fewfollowings` = %s, `results_fewfollowers` = %s, `results_fewstatus` = %s, `results_fewfavorites` = %s WHERE `id` = %s', results + (analysis['id'], ))
con.close()
@staticmethod
def Stop():
if TaskNode._STOP != False:
return
TaskNode._STOP = True
TaskNode._THREAD.join()
TaskNode._THREAD = None
TaskNode._STOP = None
@staticmethod
def WaitStop():
if TaskNode._STOP != False:
return
TaskNode._THREAD.join()
if __name__ == '__main__':
print('Running data_worker.py as main...')
Config.Init()
TaskManager.Init()
TaskNode.Init()
TaskManager.WaitStop()
TaskNode.WaitStop()
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <HashTree.h>
/*
* ~ Tabela Hash ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#define MAX_M 100
int main(int argc, char **argv){
HASHTREE *BigTable=HTree_New(MAX_M);
char Operation[10];
int Aux;
scanf("%5s", Operation);
while(Operation[0]!='f'){
switch(Operation[0]){
case 'i':
scanf("%d", &Aux);
HTree_Insert(Aux, BigTable);
break;
case 'b':
scanf("%d", &Aux);
if(HTree_Count(Aux, BigTable) > 0) printf("encontrado\n");
else printf("nao encontrado\n");
break;
case 'r':
scanf("%d", &Aux);
HTree_Remove(Aux, BigTable);
break;
default:
HTree_Traverse(stdout, BigTable);
}
scanf("%5s", Operation);
}
HTree_Destroy(BigTable);
return EXIT_SUCCESS;
}
<file_sep>
/*
* ~ Lista Enumerada ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __LIST_H_
#define __LIST_H_
#define LINKEDLIST_ELEM double
typedef struct __List_t LIST;
struct __List_t *L_New();
int L_Size(struct __List_t *);
char L_IsSubList(struct __List_t *);
char L_IsSubListAt(int,struct __List_t *);
char L_Add(LINKEDLIST_ELEM,struct __List_t *);
char L_AddSubList(struct __List_t *,struct __List_t *);
char L_AddAt(LINKEDLIST_ELEM,int,struct __List_t *);
char L_AddSubListAt(struct __List_t *,int,struct __List_t *);
char L_Remove(struct __List_t *);
char L_RemoveAt(int,struct __List_t *);
LINKEDLIST_ELEM L_Get(struct __List_t *);
struct __List_t *L_GetSubList(struct __List_t *);
LINKEDLIST_ELEM L_GetAt(int,struct __List_t *);
struct __List_t *L_GetSubListAt(int,struct __List_t *);
char L_Set(LINKEDLIST_ELEM,struct __List_t *);
char L_SetSubList(struct __List_t *,struct __List_t *);
char L_SetAt(LINKEDLIST_ELEM,int,struct __List_t *);
char L_SetSubListAt(struct __List_t *,int,struct __List_t *);
char L_Destroy(struct __List_t *L);
#endif
<file_sep>
/*
* ~ SUPER FILE ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
#ifndef __SUPER_FILE_H_
#define __SUPER_FILE_H_
char SF_PreviewChar(FILE *);
int SF_ReadWhites(FILE *);
int SF_ReadUntil(char,FILE *);
char *SF_ReadString(FILE *);
char *SF_ReadFormattedString(FILE *);
#endif
<file_sep>#include <stdlib.h>
#include <string.h>
//#include <vectorutils.h>
void insertionsort(void *vector, int size, int (*cmp)(void *,void *), int n, int *CmpN, int *MovN) {
int i, j, C = 0, M = 0;
void *key = (void *) malloc(size);
for (i = 1; i < n; i++) {
j = i;
M++;
memcpy(key,vector+j*size,size);
while (j > 0 && ++C && cmp(key,vector+(j-1)*size)>0) {
M++;
memcpy(vector+j*size,vector+(j-1)*size,size);
j--;
}
M++;
memcpy(vector+j*size,key,size);
}
*CmpN = C;
*MovN = M;
free(key);
}
<file_sep>
#ifndef GRAPH_H_
#define GRAPH_H_
typedef struct __graph_t GRAPH_T;
GRAPH_T *G_new(int nVertex);
int G_addEdgeInfo(int source, int destination, int weight, char *additionalInformation, GRAPH_T *g);
int G_addEdge(int source, int destination, int weight, GRAPH_T *g);
char *G_getInfo(int source, int destination, GRAPH_T *g);
int G_resetEdges(GRAPH_T *g);
void G_destroy(GRAPH_T *g);
void G_printEdgesFor(int vertex, void *(printEdgeFunction)(int vertex, int distance, char *additionalInformation, void *ptr), void *ptr, GRAPH_T *g);
int G_dijkstra(int source, int **preV, int **disV, int *nVertex, GRAPH_T *g);
int G_prim(int source, int **preV, int **keyV, int *nVertex, GRAPH_T *g);
#endif<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "cabecalho.h"
/*
* ~ Trabalho Prático: Parte 2 ~
*
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
void lerCabecalho(FILE *arquivoDAT) {
/*
* Esta função lê para 'cab' o cabeçalho contido no arquivo 'arquivoDAT'.
*/
char aux[TAMANHO_CABECALHO];
fseek(arquivoDAT, 0, SEEK_SET);
fread(aux, TAMANHO_CABECALHO, 1, arquivoDAT);
memcpy(&cab.status, aux, sizeof(char));
memcpy(&cab.topoPilha, aux + sizeof(char), sizeof(int));
}
void escreverCabecalho(FILE *arquivoDAT) {
/*
* Esta função escreve o cabeçalho 'cab' no arquivo 'arquivoDAT'.
*/
char aux[TAMANHO_CABECALHO];
fseek(arquivoDAT, 0, SEEK_SET);
memcpy(aux, &cab.status, sizeof(char));
memcpy(aux + sizeof(char), &cab.topoPilha, sizeof(int));
fwrite(aux, TAMANHO_CABECALHO, 1, arquivoDAT);
}
void lerCabecalhoIndice(FILE *arquivoIndice) {
/*
* Esta função lê para 'cabIndice' o cabeçalho de índice contido no arquivo 'arquivoIndice'.
*/
char aux[TAMANHO_CABECALHO_INDICE];
fseek(arquivoIndice, 0, SEEK_SET);
fread(aux, TAMANHO_CABECALHO_INDICE, 1, arquivoIndice);
memcpy(&cabIndice.status, aux, sizeof(char));
memcpy(&cabIndice.noRaiz, aux + sizeof(char), sizeof(int));
memcpy(&cabIndice.altura, aux + sizeof(char) + sizeof(int), sizeof(int));
memcpy(&cabIndice.ultimoRRN, aux + sizeof(char) + sizeof(int) * 2, sizeof(int));
}
void escreverCabecalhoIndice(FILE *arquivoIndice) {
/*
* Esta função escreve o cabeçalho de índice 'cabIndice' no arquivo 'arquivoIndice'.
*/
char aux[TAMANHO_CABECALHO_INDICE];
fseek(arquivoIndice, 0, SEEK_SET);
memcpy(aux, &cabIndice.status, sizeof(char));
memcpy(aux + sizeof(char), &cabIndice.noRaiz, sizeof(int));
memcpy(aux + sizeof(char) + sizeof(int), &cabIndice.altura, sizeof(int));
memcpy(aux + sizeof(char) + sizeof(int) * 2, &cabIndice.ultimoRRN, sizeof(int));
fwrite(aux, TAMANHO_CABECALHO_INDICE, 1, arquivoIndice);
}
<file_sep>#ifndef BUBBLESORT_H_
#define BUBBLESORT_H_
void bubblesort(void *, int, int (*)(void *,void *), int, int *, int *);
#endif
<file_sep>#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
<EMAIL>
*/
int positionof(float number, float *numbers, int numbers_count){
int i;
for(i=0;i<numbers_count;i++){
if(numbers[i]==number){
return i;
}
}
return -1;
}
int main(){
int i,j,R,N,n=0;
float S;
scanf("%d",&N);
float Number_Array[N];
int Count_Array[N];
for(i=0;i<N;i++){
Count_Array[i]=0;
scanf("%f",&Number_Array[n]);
R=positionof(Number_Array[n],Number_Array,N);
if(R==n){
Count_Array[n++]++;
}else{
Count_Array[R]++;
}
}
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(Number_Array[i]>Number_Array[j]){
S=Number_Array[i];
Number_Array[i]=Number_Array[j];
Number_Array[j]=S;
R=Count_Array[i];
Count_Array[i]=Count_Array[j];
Count_Array[j]=R;
}
}
printf("%.1f %d\n",Number_Array[i],Count_Array[i]);
}
return EXIT_SUCCESS;
}
<file_sep>import glfw
from OpenGL.GL import *
import OpenGL.GL.shaders
import numpy as np
import glm
import math
from PIL import Image
import threading
import random
from time import sleep
#
# ~ Projeto 2: Cenário 3D ~
#
# <NAME> (Nº USP 9875952)
# <NAME> (Nº USP 10369014)
#
# Computação Gráfica: SCC-0250 2020.1
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
OBJ_FILE_PATH_PATTERN = "objects/%s/vertex.obj" # Onde ficarão os arquivos *.obj dos objetos que serão desenhados na tela (%s = id do objeto).
TEXTURE_FILE_PATH_PATTERN = "objects/%s/texture_%s.png" # Onde ficarão os arquivos de textura dos objetos que serão desenhados na tela (%s = id do objeto, %s = qualidade da textura).
TEXTURE_QUALITY = "med" # Qualidade das texturas carregadas, que pode ser "high", "med" ou "low".
WINDOW_WIDTH = 800 # Largura da janela.
WINDOW_HEIGHT = 800 # Altura da janela.
WINDOW_MIN_SIZE = 300 # Tamanho mínimo da janela permitido.
WINDOW_MAX_SIZE = 50000 # Tamanho máximo da janela permitido.
WINDOW_TITLE = "Projeto 2 - Cenário 3D" # Nome da janela.
glfw.init()
glfw.window_hint(glfw.VISIBLE, glfw.FALSE)
window = glfw.create_window(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE, None, None)
glfw.make_context_current(window)
winWidth = WINDOW_WIDTH
winHeight = WINDOW_HEIGHT
glfw.set_window_size_limits(window, WINDOW_MIN_SIZE, WINDOW_MIN_SIZE, WINDOW_MAX_SIZE, WINDOW_MAX_SIZE)
### Vertex Shader ###
vertex_code = """
attribute vec3 position;
attribute vec2 texture_coord;
varying vec2 out_texture;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main(){
gl_Position = projection * view * model * vec4(position,1.0);
out_texture = vec2(texture_coord);
}
"""
### Fragment Shader ###
fragment_code = """
uniform vec4 color;
varying vec2 out_texture;
uniform sampler2D samplerTexture;
void main(){
vec4 texture = texture2D(samplerTexture, out_texture);
gl_FragColor = texture;
}
"""
# Request a program and shader slots from GPU.
program = glCreateProgram()
vertex = glCreateShader(GL_VERTEX_SHADER)
fragment = glCreateShader(GL_FRAGMENT_SHADER)
# Set shaders source.
glShaderSource(vertex, vertex_code)
glShaderSource(fragment, fragment_code)
# Compile Vertex Shaders.
glCompileShader(vertex)
if not glGetShaderiv(vertex, GL_COMPILE_STATUS):
error = glGetShaderInfoLog(vertex).decode()
print(error)
raise RuntimeError("Erro de compilacao do Vertex Shader")
# Compile Vertex Shaders.
glCompileShader(fragment)
if not glGetShaderiv(fragment, GL_COMPILE_STATUS):
error = glGetShaderInfoLog(fragment).decode()
print(error)
raise RuntimeError("Erro de compilacao do Fragment Shader")
# Attach shader objects to the program.
glAttachShader(program, vertex)
glAttachShader(program, fragment)
# Build program.
glLinkProgram(program)
if not glGetProgramiv(program, GL_LINK_STATUS):
print(glGetProgramInfoLog(program))
raise RuntimeError('Linking error')
# Make program the default program.
glUseProgram(program)
class SceneObject:
_currentTextureIndex = 0 # Indica o id da textura atual (a cada objeto SceneObject criado, isso incrementa).
_points = None # Armazena todos os pontos de todos os vértices dos objetos SceneObject criados, para serem enviados para a GPU.
_textures = None # Armazena todos os pontos de todas as texturas de SceneObject criados, para serem enviados para a GPU.
def __init__(self, objName = None, x = 0.0, y = 0.0, z = 0.0, sx = 1.0, sy = 1.0, sz = 1.0, rx = 0.0, ry = 0.0, rz = 0.0, visible = True):
### Construtor de um objeto 3D que será desenhado na tela. ###
self._thread = None # Inicialmente, não é necessário criar uma thread por objeto (a não ser que ele vá se mover depois).
self._threadStop = False
# Definir posição inicial do objeto no mundo.
self.x = x
self.y = y
self.z = z
# Definir escala inicial do objeto.
self.sx = sx
self.sy = sy
self.sz = sz
# Definir rotação inicial do objeto (em radianos).
self.rx = rx
self.ry = ry
self.rz = rz
# Definir objeto como visível.
self.visible = visible
# Definição do índice de textura desse objeto, início dos vértices e término.
self._textureIndex = None
self._vertexIndex = None
self._vertexLength = None
if objName is not None:
print("Construindo objeto '%s'... Carregando pontos... " % (objName), end = "")
self.setVertex(OBJ_FILE_PATH_PATTERN % (objName))
print("Carregando textura... ", end = "")
self.setTexture(TEXTURE_FILE_PATH_PATTERN % (objName, "high"))
print("Pronto!")
def setVertex(self, filePath):
### Essa função vai definir os vértices deste objeto no mundo usando um arquivo *.obj em disco. ###
if self._vertexIndex is not None or self._vertexLength is not None:
raise Exception("Não é possível definir os vértices do objeto porque eles já foram definidos! Crie um novo objeto se quer definir novos vértices.")
vertices = [ ]
texture_coords = [ ]
faces = [ ]
material = None
# Abre o arquivo *.obj para leitura.
with open(filePath, "r") as fp:
for line in fp: # Para cada linha do arquivo *.obj...
if line.startswith('#'):
continue # Ignora comentarios.
values = line.split() # Quebra a linha por espaço.
if not values:
continue
if values[0] == 'v': # A linha representa um vértice.
vertices.append(values[1:4])
elif values[0] == 'vt': # A linha representa coordenadas de textura.
texture_coords.append(values[1:3])
elif values[0] in ('usemtl', 'usemat'): # A linha representa como serão determinadas as faces.
material = values[1]
elif values[0] == 'f' and material is not None: # A linha representa uma face.
face = []
face_texture = []
for v in values[1:]:
w = v.split('/')
face.append(int(w[0]))
if len(w) >= 2 and len(w[1]) > 0:
face_texture.append(int(w[1]))
else:
face_texture.append(0)
faces.append((face, face_texture, material))
model = { }
model['vertices'] = vertices
model['texture'] = texture_coords
model['faces'] = faces
if SceneObject._points is None or SceneObject._textures is None: # Primeiro devemos preparar a GPU para receber os dados (executado apenas na criação do primeiro objeto).
glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_LINE_SMOOTH)
glEnable(GL_TEXTURE_2D)
SceneObject._points = [ ]
SceneObject._textures = [ ]
self._vertexIndex = len(SceneObject._points)
for face in model['faces']:
for vertice_id in face[0]:
SceneObject._points.append(model['vertices'][vertice_id - 1])
for texture_id in face[1]:
SceneObject._textures.append(model['texture'][texture_id - 1])
self._vertexLength = len(SceneObject._points) - self._vertexIndex
def setTexture(self, filePath):
### Essa função vai definir a textura deste objeto no mundo usando um arquivo em disco. ###
if self._textureIndex is None:
self._textureIndex = SceneObject._currentTextureIndex
SceneObject._currentTextureIndex += 1
img = Image.open(filePath)
img_width = img.size[0]
img_height = img.size[1]
image_data = img.convert("RGBA").tobytes("raw", "RGBA", 0, -1)
#image_data = img.tobytes("raw", "RGB", 0, -1)
#image_data = np.array(list(img.getdata()), np.uint8)
glBindTexture(GL_TEXTURE_2D, self._textureIndex)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img_width, img_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data)
@staticmethod
def syncGPU():
### Essa função sincroniza os dados dos vértices e coordenadas de textura com a GPU. Basicamente, ela envia os dados pra GPU. ###
# Ela deve ser chamada apenas após criação de todos os objetos que serão desenhados.
if SceneObject._points is None or SceneObject._textures is None:
raise Exception("Nenhum objeto foi definido para ser desenhado na tela. Por favor, faça isso!")
buffer = glGenBuffers(2) # Requisitar slots de buffer pra GPU.
# Definir vértices.
vertices = np.zeros(len(SceneObject._points), [("position", np.float32, 3)])
vertices['position'] = SceneObject._points
# Carregar vértices.
glBindBuffer(GL_ARRAY_BUFFER, buffer[0])
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
stride = vertices.strides[0]
offset = ctypes.c_void_p(0)
loc_vertices = glGetAttribLocation(program, "position")
glEnableVertexAttribArray(loc_vertices)
glVertexAttribPointer(loc_vertices, 3, GL_FLOAT, False, stride, offset)
# Definir coordenadas de texturas.
textures = np.zeros(len(SceneObject._textures), [("position", np.float32, 2)]) # Duas coordenadas.
textures['position'] = SceneObject._textures
# Carregar coordenadas de texturas.
glBindBuffer(GL_ARRAY_BUFFER, buffer[1])
glBufferData(GL_ARRAY_BUFFER, textures.nbytes, textures, GL_STATIC_DRAW)
stride = textures.strides[0]
offset = ctypes.c_void_p(0)
loc_texture_coord = glGetAttribLocation(program, "texture_coord")
glEnableVertexAttribArray(loc_texture_coord)
glVertexAttribPointer(loc_texture_coord, 2, GL_FLOAT, False, stride, offset)
def draw(self):
### Essa função vai desenhar este objeto no mundo (usando a matriz model). ###
if self._textureIndex is None or self._vertexIndex is None or self._vertexLength is None:
raise Exception("Você precisa primeiro definir o arquivo *.obj e de textura antes de desenhar o objeto na tela!")
if not self.visible: # Se objeto não estiver visível, não precisa desenhar.
return
matrix_transform = glm.mat4(1.0) # Instanciando uma matriz identidade.
# Aplicando translação em X, Y e Z.
matrix_transform = glm.translate(matrix_transform, glm.vec3(self.x, self.y, self.z))
# Aplicando rotação no eixo X.
matrix_transform = glm.rotate(matrix_transform, self.rx, glm.vec3(1.0, 0.0, 0.0))
# Aplicando rotação no eixo Y.
matrix_transform = glm.rotate(matrix_transform, self.ry, glm.vec3(0.0, 1.0, 0.0))
# Aplicando rotação no eixo Z.
matrix_transform = glm.rotate(matrix_transform, self.rz, glm.vec3(0.0, 0.0, 1.0))
# Aplicando escala em X, Y e Z.
matrix_transform = glm.scale(matrix_transform, glm.vec3(self.sx, self.sy, self.sz))
matrix_transform = np.array(matrix_transform).T # Pegando a transposta da matriz (glm trabalha com ela invertida).
loc_model = glGetUniformLocation(program, "model")
glUniformMatrix4fv(loc_model, 1, GL_TRUE, matrix_transform)
# Define o id da textura do modelo.
glBindTexture(GL_TEXTURE_2D, self._textureIndex)
# Desenha o modelo.
glDrawArrays(GL_TRIANGLES, self._vertexIndex, self._vertexLength) # Rendeniza na tela.
def _alive():
### Essa função faz as tarefas do objeto vivo. Por exemplo, se ele se mover, será feito esse movimento nessa função. Se ele não for um objeto vivo, ela nunca é chamada. ###
pass # Ela deve ser sobescrita por classes filhas, de forma que o código das tarefas a serem feitas pelo objeto fica aqui.
def spawn(self):
### Essa função só serve para objetos que tem vida própria (vão se mover na tela por exemplo). Ela basicamente dá vida ao objeto e ele começa a se mexer. ###
if self._thread is not None:
raise Exception("Esse objeto já está vivo! Para ele nascer de novo, primeiro mate ele.")
self._thread = threading.Thread(target = self.__threadLoop)
self._threadStop = False
self._thread.start()
return self
def kill(self):
### Essa função só serve para objetos que tem vida própria (vão se mover na tela por exemplo). Ela basicamente tira a vida de um objeto (para de se mexer). ###
if self._thread is None:
raise Exception("Esse objeto não está vivo! Para ele morrer, primeiro faça ele nascer.")
self._threadStop = True
self._thread.join()
self._thread = None
def __threadLoop(self):
### Essa função faz o loop da thread do objeto (se ele tiver vida). Se o objeto não tiver vida, ela nunca é chamada. ###
# Observe que essa função é interna e não deve ser modificada por classes filhas.
while(not self._threadStop):
self._alive()
CAMERA_SPEED = 0.2 # Velocidade de locomoção da câmera.
CAMERA_Y = 0.7 # Posição da câmera quando bloqueada no cenário.
CAMERA_FOVY = glm.radians(60.0) # Campo de visão (field-of-view) da câmera.
CAMERA_NEAR = 0.01 # Mínimo do campo de visão da câmera.
CAMERA_FAR = 1000 # Máximo do campo de visão da câmera.
CAMERA_X_MIN = -16
CAMERA_X_MAX = 16
CAMERA_Z_MIN = -16
CAMERA_Z_MAX = 16
polygonal_mode = False # Modo polígono ativado?
free_camera = False # Modo câmera livre ativado?
paused = False # Jogo pausado?
W_pressed = False
S_pressed = False
A_pressed = False
D_pressed = False
cameraUp = glm.vec3(0.0, 1.0, 0.0)
cameraFront = glm.vec3(0.0, 0.0, -1.0)
cameraPos = glm.vec3(5.0, CAMERA_Y, 6.0)
yaw = 0.0
pitch = 0.0
lastX = winWidth / 2
lastY = winHeight / 2
class Camera(SceneObject):
def _alive(self):
global cameraPos, cameraFront, cameraUp, paused, CAMERA_SPEED
### A câmera se move usando uma thread separada. Esse objeto não desenha nada na tela, é usado apenas por conta da thread mesmo. ###
# O motivo de usar uma thread separada é porque assim a câmera terá um movimento mais suave, além de que é possível apertar várias teclas ao mesmo tempo.
if paused: # O jogo está pausado. Dorme o processo pra economizar recursos do processador.
sleep(1.0)
return
if free_camera: # No modo de câmera livre, a velocidade é maior
camera_speed = 4 * CAMERA_SPEED
else:
camera_speed = CAMERA_SPEED
if W_pressed:
cameraPos += cameraFront * camera_speed
if S_pressed:
cameraPos -= cameraFront * camera_speed
if A_pressed:
cameraPos -= glm.normalize(glm.cross(cameraFront, cameraUp)) * camera_speed
if D_pressed:
cameraPos += glm.normalize(glm.cross(cameraFront, cameraUp)) * camera_speed
if not free_camera: # A câmera não está em modo livre, então vamos limitar o jogador aos limites do cenário.
cameraPos[1] = CAMERA_Y
cameraPos[0] = max(CAMERA_X_MIN, min(CAMERA_X_MAX, cameraPos[0]))
cameraPos[2] = max(CAMERA_Z_MIN, min(CAMERA_Z_MAX, cameraPos[2]))
sleep(0.05)
def key_event(window,key,scancode,action,mods): # Tecla pressionada.
global polygonal_mode, paused, free_camera, W_pressed, S_pressed, A_pressed, D_pressed, lastX, lastY
cameraSpeed = 0.2
if key == 87: # Tecla W.
W_pressed = False if (action == 0) else True
elif key == 83: # Tecla S.
S_pressed = False if (action == 0) else True
elif key == 65: # Tecla A.
A_pressed = False if (action == 0) else True
elif key == 68: # Tecla D.
D_pressed = False if (action == 0) else True
elif key == 80 and action == 0: # Botão P (modo polígono).
polygonal_mode = not polygonal_mode
elif key == 67 and action == 0: # Botão C (modo de câmera: bloqueado ou livre).
free_camera = not free_camera
elif (key == 257 or key == 256) and action == 0: # Botão ENTER ou ESC (câmera lock).
paused = not paused
glfw.set_cursor_pos(window, lastX, lastY)
glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_NORMAL if paused else glfw.CURSOR_HIDDEN)
#print("Tecla '%s' apertada com scancode = '%s' (action = %s)." % (key, scancode, action))
def mouse_event(window, xpos, ypos): # Mouse movimentado
global paused, firstMouse, cameraFront, yaw, pitch, lastX, lastY
if paused: # Jogo está pausado, não mudar nada na câmera.
return
xoffset = xpos - lastX
yoffset = lastY - ypos
sensitivity = 0.3
xoffset *= sensitivity
yoffset *= sensitivity
yaw += xoffset
pitch += yoffset
if pitch >= 80.0: pitch = 80.0
if pitch <= -80.0: pitch = -80.0
front = glm.vec3()
front.x = math.cos(glm.radians(yaw)) * math.cos(glm.radians(pitch))
front.y = math.sin(glm.radians(pitch))
front.z = math.sin(glm.radians(yaw)) * math.cos(glm.radians(pitch))
cameraFront = glm.normalize(front)
glfw.set_cursor_pos(window, lastX, lastY) # Dúvida: isso gera uma recursão infinita? Não há informações o suficiente na internet, e meus testes indicam que não.
def window_event(window, width, height): # A janela foi redimensionada, então ajustar parâmetros.
global winWidth, winHeight, lastX, lastY
winWidth = width
winHeight = height
lastX = winWidth / 2
lastY = winHeight / 2
glViewport(0, 0, winWidth, winHeight)
camera = Camera()
glfw.set_key_callback(window,key_event)
glfw.set_cursor_pos_callback(window, mouse_event)
glfw.set_window_size_callback(window, window_event)
glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_HIDDEN)
def view():
global cameraPos, cameraFront, cameraUp
mat_view = glm.lookAt(cameraPos, cameraPos + cameraFront, cameraUp)
mat_view = np.array(mat_view)
return mat_view
def projection():
global winHeight, winWidth, CAMERA_FOVY, CAMERA_NEAR, CAMERA_FAR
mat_projection = glm.perspective(CAMERA_FOVY, winWidth/winHeight, CAMERA_NEAR, CAMERA_FAR)
mat_projection = np.array(mat_projection)
return mat_projection
loadingScreen = SceneObject(objName = "loadingScreen", rx = math.pi / 2) # Criar tela de carregamento.
SceneObject.syncGPU() # Enviar tela de carregamento para GPU.
glfw.show_window(window) # Mostrar janela.
glEnable(GL_DEPTH_TEST) # Importante para rendenização 3D.
for _ in range(30): # Força redesenho (por conta de ser double-buffered).
glfw.poll_events()
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glClearColor(1.0, 1.0, 1.0, 1.0) # Fundo branco.
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL) # Desativar modo polígono.
loadingScreen.draw() # Desenhar tela de pause.
mat_view = np.array(glm.lookAt(glm.vec3(3.0, 0.0, 0.0), glm.vec3(0.0, 0.0, 0.0), glm.vec3(0.0, 1.0, 0.0))) # View.
loc_view = glGetUniformLocation(program, "view")
glUniformMatrix4fv(loc_view, 1, GL_FALSE, mat_view)
mat_projection = projection() # Projection.
loc_projection = glGetUniformLocation(program, "projection")
glUniformMatrix4fv(loc_projection, 1, GL_FALSE, mat_projection)
glfw.swap_buffers(window)
staticObjects = [ ]
staticObjects.append( SceneObject(objName = "ground", y = -0.9, sx = 20.0, sz = 20.0) ) # Chão de grama.
staticObjects.append( SceneObject(objName = "mountains", x = 18.0, ry = math.pi/2) ) # Montanhas 1.
staticObjects.append( SceneObject(objName = "mountains", x = -18.0, ry = math.pi/2) ) # Montanhas 2.
staticObjects.append( SceneObject(objName = "mountains", z = 18.0) ) # Montanhas 3.
staticObjects.append( SceneObject(objName = "mountains", z = -18.0) ) # Montanhas 4.
staticObjects.append( SceneObject(objName = "oldHouse", y = 0.11, sx = 1.5, sz = 1.5, sy = 1.5) ) # Casa antiga (1).
staticObjects.append( SceneObject(objName = "abandonedHouse", y = 0.01, x = 8, sx = 0.1, sz = 0.1, sy = 0.1) ) # Casa abandonada isolada (2).
staticObjects.append( SceneObject(objName = "abandonedHouseFloor", y = -0.89, x = 7.75, z = -0.01,sx = 1.51, sz = 0.80) ) # Piso da casa abandonada (2).
staticObjects.append( SceneObject(objName = "table", y = 0.25, x = 8, sx = 0.003, sz = 0.003, sy = 0.003) ) # Mesa de madeira (2).
staticObjects.append( SceneObject(objName = "skull", y = 0.40, x = 8.12, z = 0.25, ry = -math.pi/2.0, sx = 0.012, sz = 0.012, sy = 0.012) ) # Crânio de um esqueleto (2).
staticObjects.append( SceneObject(objName = "street", y = -0.89, x = 5, z = 6, sx = 0.75, sz = 8) ) # Piso da casa abandonada (2).
staticObjects.append( SceneObject(objName = "streetLamp", y = 1, x = 5.8, z = 2, sx = 0.08, ry = math.pi/2, sy = 0.08, sz = 0.08) ) # Piso da casa abandonada (2).
pausedScreen = SceneObject(objName = "pauseScreen", rx = math.pi / 2) # Tela de pause.
dynamicObjects = [ ]
class Gun(SceneObject): # A arma que fica dentro da casa fica girando.
def _alive(self):
self.ry = (self.ry + 0.1) % (2 * math.pi)
sleep(0.1)
class Moon(SceneObject): # A lua vai nascendo e se pondo no horizonte aos poucos.
def _alive(self):
self.y += 0.02
if self.y > 100.0:
self.y = -20
sleep(0.1)
class Sky(SceneObject): # As nuvens no céu vão se movendo lentamente.
def _alive(self):
self.ry = (self.ry + 0.001) % (2 * math.pi)
sleep(0.1)
class Freddy(SceneObject): # O Fantasma do Freddy Sem Cabeça pode se locomover e voar pelo mapa.
MOVEMENTS = ["walk", "fly", "dissapear"]
FLOOR_Y = 0.1
def __init__(self, objName = None):
self.mov = None
self.pos = None
self.speed = None
self.start = None
self.end = None
super(Freddy, self).__init__(objName = objName, sx = 0.06, sy = 0.06, sz = 0.06, visible = False)
def _alive(self):
if self.mov == None: # Determinar o que ele vai fazer: andar pelo cenário, voar pelo mapa ou desaparecer
self.mov = random.choice(Freddy.MOVEMENTS)
self.speed = random.uniform(0.001, 0.01)
self.pos = 0.0
self.start = [random.uniform(-16, 16), random.uniform(10, 20), random.uniform(-16, 16)]
self.end = [random.uniform(-16, 16), random.uniform(10, 20), random.uniform(-16, 16)]
self.ry = math.atan2((self.end[0] - self.start[0]), (self.end[2] - self.start[2]))
if self.mov == "walk": # Ele está andando pelo cenário...
self.x = self.start[0] + self.pos * (self.end[0] - self.start[0])
self.y = Freddy.FLOOR_Y
self.z = self.start[2] + self.pos * (self.end[2] - self.start[2])
self.visible = True
elif self.mov == "fly": # Ele está voando pelo mapa...
self.x = self.start[0] + self.pos * (self.end[0] - self.start[0])
self.y = self.start[1] + self.pos * (self.end[1] - self.start[1])
self.z = self.start[2] + self.pos * (self.end[2] - self.start[2])
self.visible = True
else: # Ele está invisível (desapareceu)...
self.pos += self.speed
self.visible = False
self.pos += self.speed
if self.pos > 1.0: # A animação acabou. Restaurar para determinar a próxima animação.
self.mov = None
sleep(0.1)
dynamicObjects.append( Gun(objName = "gun", x = 8, y = 0.6, sx = 0.015, sy = 0.015, sz = 0.015) )
dynamicObjects.append( Sky(objName = "sky", sx = 90.0, sy = 90.0, sz = 90.0) )
dynamicObjects.append( Moon(objName = "moon", x = 45, y = 50, z = 45, sx = 10.0, sy = 10.0, sz = 10.0) )
dynamicObjects.append( Freddy(objName = "freddyGhost") )
SceneObject.syncGPU()
#glfw.show_window(window)
glfw.set_cursor_pos(window, lastX, lastY)
#glEnable(GL_DEPTH_TEST) # Importante para rendenização 3D.
for obj in dynamicObjects: # Dar vida aos objetos dinâmicos.
obj.spawn()
camera.spawn() # Iniciar thread da câmera.
while not glfw.window_should_close(window):
glfw.poll_events()
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glClearColor(0.0, 0.0, 0.0, 1.0) # Fundo preto.
if paused: # O jogo está pausado?
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL) # Desativar modo polígono.
pausedScreen.draw() # Desenhar tela de pause.
mat_view = np.array(glm.lookAt(glm.vec3(3.0, 0.0, 0.0), glm.vec3(0.0, 0.0, 0.0), glm.vec3(0.0, 1.0, 0.0))) # View.
loc_view = glGetUniformLocation(program, "view")
glUniformMatrix4fv(loc_view, 1, GL_FALSE, mat_view)
mat_projection = projection() # Projection.
loc_projection = glGetUniformLocation(program, "projection")
glUniformMatrix4fv(loc_projection, 1, GL_FALSE, mat_projection)
glfw.swap_buffers(window)
continue
if polygonal_mode == True: # Modo polígono está ativado?
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
else:
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
for obj in staticObjects: # Desenhar objetos estáticos.
obj.draw()
for obj in dynamicObjects: # Desenhar objetos dinâmicos.
obj.draw()
mat_view = view() # View.
loc_view = glGetUniformLocation(program, "view")
glUniformMatrix4fv(loc_view, 1, GL_FALSE, mat_view)
mat_projection = projection() # Projection.
loc_projection = glGetUniformLocation(program, "projection")
glUniformMatrix4fv(loc_projection, 1, GL_FALSE, mat_projection)
glfw.swap_buffers(window)
for obj in dynamicObjects: # Tirar vida dos objetos dinâmicos.
obj.kill()
camera.kill() # Matar thread da câmera.
glfw.terminate() # Fechar janela.
<file_sep>#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
ll recursive_count_max(ll position, ll top, map<pair<ll, ll>, ll> &pd, vector<ll> &missiles) {
ll counter1, counter2;
if(position < 0 || position >= missiles.size()) {
return 0;
}
if(pd.count(make_pair(position, top)) > 0) {
return pd[make_pair(position, top)];
}
counter1 = recursive_count_max(position + 1, top, pd, missiles);
counter2 = -1;
if(missiles[position] <= top) {
counter2 = recursive_count_max(position + 1, missiles[position], pd, missiles) + 1;
}
if(counter1 >= counter2) {
pd[make_pair(position, top)] = counter1;
return counter1;
}
pd[make_pair(position, top)] = counter2;
return counter2;
}
ll testCase() {
ll i, aux;
vector<ll> missiles = vector<ll>();
map<pair<ll, ll>, ll> pd = map< pair<ll, ll>, ll >();
cin >> aux;
while(aux >= 0) {
missiles.push_back(aux);
cin >> aux;
}
if(missiles.size() < 1) {
return -1;
}
return recursive_count_max(0, INT_MAX, pd, missiles);
}
int main(int argc, char **argv) {
ll intercepted, counter;
counter = 1;
while((intercepted = testCase()) >= 0) {
if(counter > 1) {
cout << endl;
}
cout << "Test #" << counter << ":" << endl;
cout << " maximum possible interceptions: " << intercepted << endl;
counter++;
}
return EXIT_SUCCESS;
}
<file_sep># Trabalho Prático de Redes de Computadores - 2019.1
Trabalho prático de Redes de Computadores.
# Sala Inteligente
## Membros do Grupo
- <NAME> (Nº 10284542)
- <NAME> (Nº 10258876)
- <NAME> (Nº 10369014)
- <NAME> (Nº 9005961)
## Como executar
Para executar o trabalho, você vai precisar executar vários programas Java.
- Em alguns sistemas operacionais, basta clicar duas vezes no arquivo _X.jar_.
- Em outros sistemas operacionais, é possível executar no terminal (bash) através do comando `java -jar X.jar`.
Siga os passos abaixo para que a execução ocorra com sucesso:
- Inicie o [gerenciador](Gerenciador.jar). Ele será apenas um servidor, então ele vai solicitar uma porta para servir. Lembre-se de definir uma porta que não esteja já em uso em seu computador.
- Inicie todos os alimentadores: [iluminação](SistemaIluminacao.jar), [ar-condicionado](AlimentadorAr.jar) e [projetor](AlimentadorProjetor.jar). Cada um desses funciona como servidor e cliente para o gerenciador. Isso significa que eles vão solicitar uma porta para servir, e essa porta também deve ser única para cada um desses. Eles também vão solicitar o endereço de host e porta do gerenciador (iniciado anteriormente) no formato adequado. Você pode usar "localhost:PORTA" no caso de estar executando tudo em uma mesma máquina.
- Inicie todos os sensores: [presença](SensorPresenca.jar), [leitor de cartão](LeitorCartao.jar) e [chave do projetor](ChaveProjetor.jar). Estes funcionam apenas como cliente para o gerenciador. Sendo assim, vão solicitar o endereço de host e porta do gerenciador (iniciado no primeiro passo). Você pode usar "localhost:PORTA" no caso de estar executando tudo em uma mesma máquina.
- Inicie a [interface gráfica do professor](UI.jar). Ela funciona também apenas como cliente, e vai solicitar o endereço de host e porta do gerenciador, do mesmo modo que antes.
## Código-fonte
No diretório [Codigo-fonte](Codigo-fonte) encontram-se todos os projetos do trabalho prático e sua implementação em Java.
<file_sep>#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <iostream>
/*
* == AlgAvançados ==
*
* <NAME> (Nº 10369014)
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
using namespace std;
typedef long long ll;
bool solutionValid(ll solution, ll N, ll K, ll *candyBoxes) {
ll i, sum;
sum = 0;
for(i = 0; i < N; i++) {
sum += candyBoxes[i] / solution;
}
if(sum >= K) {
return true;
}
return false;
}
void testCase() {
ll N, K, i, start, end, middle, max, *candyBoxes;
cin >> N >> K;
candyBoxes = (ll *) malloc(sizeof(ll) * N);
start = 1;
end = 1e9;
max = LLONG_MIN;
for(i = 0; i < N; i++) {
cin >> candyBoxes[i];
}
while(start <= end) {
middle = (start + end) / 2;
if(solutionValid(middle, N, K, candyBoxes)) {
if(middle > max) {
max = middle;
}
start = middle + 1;
} else {
end = middle - 1;
}
}
if(max == LLONG_MIN) {
cout << 0 << endl;
return;
}
cout << max << endl;
}
int main(int argc, char **argv) {
ll T;
cin >> T;
for(; T > 0; T--) {
testCase();
}
return EXIT_SUCCESS;
}
<file_sep>
#
# ~ Tabela Hash ~
#
# <NAME>
# <EMAIL>
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
## make all -> Apenas compilar
## make noobj -> Compilar e remover arquivos *.o gerados
## make run -> Executar programa compilado
## make clean -> Remover arquivos *.o gerados e o próprio executável do programa
all: Prog
noobj: Prog
rm objects/*.o
Prog: objects/main.o
gcc -o Prog objects/*.o -Wall
objects/main.o: main.c objects/HashTree.o headers/HashTree.h
gcc -c -o objects/main.o main.c -Wall -I headers
objects/HashTree.o: lib/HashTree.c
gcc -c -o objects/HashTree.o lib/HashTree.c -Wall
run: Prog
./Prog
clean:
rm Prog objects/*.o<file_sep># Imagens e Atribuição
As imagens nesse diretório e utilizadas em nosso trabalho foram retiradas do website Flickr.
Todas possuem a licensa Creative Commons.
Abaixo se encontram os links destas:
* Krefeld.jpg: https://flic.kr/p/anum58
* Ocean.jpg: https://flic.kr/p/YRcPxM
* Street.jpg: https://flic.kr/p/5WZ6aq
* Boats.jpg: https://flic.kr/p/daSX8K
* Swan.jpg: https://flic.kr/p/Y25jbm
* Yosemite.jpg: https://flic.kr/p/oiWgeV
As imagens originais estão em [Original](Original).
<file_sep># Trabalho Prático de POO
- <NAME>
- <NAME>
- <NAME>
<file_sep># Inpainting de Objetos Largos
### Processamento de Imagens (SCC0251) - Projeto Final
Neste projeto, foi implementado um algoritmo avançado de Inpainting, capaz de remover objetos de grande dimensão e formato de uma imagem colorida, reconstruíndo-a. O domínio de espaço por trás deste objeto foi reconstruído através de outras regiões da imagem próximas ao objeto removido ou de semelhança com as extremidades deste, arranjando os blocos remendados de uma forma visualmente aceitável.
## Integrantes
* <NAME> (Nº USP 9896250)
* <NAME> (Nº USP 10369014)
## Organização do Repositório
O repositório foi organizado da seguinte maneira:
* [ImagesAndAttribution](ImagesAndAttribution): aqui se encontram as imagens que foram usadas como teste no projeto. O underscore (\_) determina diferentes variações de uma mesma imagem, como diferentes resoluções por exemplo.
* [FirstsResults](FirstsResults): aqui se encontram os resultados iniciais (parciais) obtidos nas primeiras versões do algoritmo. Para o relatório final do trabalho, desconsiderar tal diretório.
* [Results](Results): aqui se encontram os resultados obtidos nos casos de teste construídos.
* [TestCases](TestCases): casos de teste usados para executar o algoritmo.
* [InpaintingLargeObjects.py](InpaintingLargeObjects.py): Código em Python. Executado com Python 3; pode-se utilizar os casos de teste disponíveis em [_TestCases_](TestCases).
* [ProjectReport.ipynb](ProjectReport.ipynb): Relatório final do projeto.
## Relatório Final
O relatório final do projeto encontra-se em [ProjectReport](ProjectReport.ipynb).
<file_sep># SCC-0504 Programação Orientada a Objetos - 2018.1
Aqui estão todos os trabalhos que implementei em POO.
<file_sep># Objeto
Objeto de domínio público (cubo). Textura de domínio público.
<file_sep>#include <iostream>
#include <vector>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>
using namespace std;
typedef struct {
char Q[8];
char O[8];
int M;
} Game;
bool check(Game *G){
int i, j;
int DiagA, DiagB;
for(i = 0; i < 8; i++){
DiagA = G->Q[i] - i;
DiagB = G->Q[i] + i;
for(j = 0; j < i; j++){
if(G->Q[j] == G->Q[i]) return false;
if(G->Q[j] == G->Q[j]+DiagA) return false;
if(G->Q[j] == (-1*G->Q[j])+DiagB) return false;
}
for(j = i+1; j < 8; j++){
if(G->Q[j] == G->Q[i]) return false;
if(G->Q[j] == G->Q[j]+DiagA) return false;
if(G->Q[j] == (-1*G->Q[j])+DiagB) return false;
}
}
return true;
}
int combine(Game *G, int pos){
long i, min = INT_MAX, aux;
if(pos >= 7){
if(check(G)){
return 0;
}
return min;
}
for(i = 0; i < 8; i++){
G->Q[pos] = i;
aux = abs(G->O[pos] - G->Q[pos]);
aux = 1;
aux += combine(G, pos+1);
if(aux < min) min = aux;
//G->Q[pos] = G->O[pos];
}
return min;
}
int main(int argc, char **argv){
unsigned int i, n = 1;
int Q[8];
Game Aux;
while(scanf("%d %d %d %d %d %d %d %d", &Q[0], &Q[1], &Q[2], &Q[3], &Q[4], &Q[5], &Q[6], &Q[7]) == 8){
memset(&Aux, 0, sizeof(Game));
for(i = 0; i < 8; i++)
Aux.O[i] = Q[i] - 1;
cout << "Case " << n++ << ": " << combine(&Aux, 0) << "\n";
}
}<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
/*
* ~ SUPER STRING ~
*
* <NAME>
* <EMAIL>
* _______ _______ _______
* | | | \
* | | | \ |___|
* | | \ | |
* |_______ _______|___|
*
*/
// Esta biblioteca está em fase de desenvolvimento.
char *SS_ReadUntil(char *String,char Ch,FILE *FStream){
/*
* Esta função lê de 'FStream' uma string até chegar em um caractere 'Ch'. Ela não inclui 'Ch' na string gerada, mas inclui o caracter NULL "\0".
* - Se 'String' for igual a NULL, a função vai alocar na memória uma string e retornar o endereço para tal.
* - Se 'String' for diferente de NULL, a função vai modificar a própria 'String'.
* CUIDADO: Nesse caso, a função pode e vai sobrescrever indefinidamente 'String', podendo inclusive ultrapassar os limites de tal, ocasionando um erro de segmentação (Out of Bounds).
*
* Ela retorna um ponteiro para a string alocada ou modificada.
*/
int n=0;
char R,*Aux=String;
if(Aux==NULL){
Aux=malloc(sizeof(char)*1);
while( (R=getc(FStream))!=EOF && R!=Ch){
Aux=(char *)realloc(Aux,sizeof(char)*n+2);
Aux[n++]=R;
}
}else
while( (R=getc(FStream))!=EOF && R!=Ch) Aux[n++]=R;
Aux[n]='\0';
if(R!=EOF) fseek(FStream,-1,SEEK_CUR);
return Aux;
}
int SS_ReadAllWhites(FILE *FStream){
/*
* Esta função avança o ponteiro de 'FStream' até um ponto em que não existam mais caracteres considerados "white-space".
*
* Ela retorna o número de caracteres pulados para chegar até tal, ou -1 em caso de erros.
*/
char R;
int n=0;
while( (R=getc(FStream))!=EOF && isspace(R) ) n++;
if(R==EOF) return -1;
fseek(FStream,-1,SEEK_CUR);
return n;
}
char SS_InsensitiveCmp(char *A,char *B){
/*
* Esta função compara 'A' com 'B' em formato "case-insensitive", ou seja, sem levar em consideração a diferença entre maiúsculos e minúsculos.
*
* Ela retorna -1 para 'A' maior que 'B', 0 se forem iguais, e 1 para 'B' maior que 'A'.
*/
int i,NA=strlen(A),NB=strlen(B);
char *StrA=(char *)malloc(sizeof(char)*NA),*StrB=(char *)malloc(sizeof(char)*NB);
for(i=0;i<NA;i++) StrA[i]=tolower(A[i]);
for(i=0;i<NB;i++) StrB[i]=tolower(B[i]);
i=strcmp(StrA,StrB);
free(StrA);
free(StrB);
if(i>0) return 1;
else if(i<0) return -1;
else return 0;
}
<file_sep>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <consts.h>
#include <buffer.h>
#include <register.h>
#include <index.h>
IND_T *I_init(char *path) {
IND_T *aux;
aux = (IND_T *) malloc(sizeof(IND_T));
aux->header.status = STATUS_CONSISTENTE;
aux->header.nItems = 0;
aux->accessCount = 0;
aux->data = NULL;
aux->path[0] = '\0';
if(path != NULL) {
if(I_read(aux, path) != 1) {
I_destroy(aux);
return NULL;
}
}
return aux;
}
int I_read(IND_T *index, char *path) {
char aux[PAGE_SIZE];
FILE *stream;
int i;
stream = fopen(path, "rb");
if(stream == NULL) {
return 0;
}
if(fread(aux, sizeof(char), PAGE_SIZE, stream) != PAGE_SIZE) {
fclose(stream);
return 0;
}
if(aux[0] != STATUS_CONSISTENTE) {
fclose(stream);
return 0;
}
index->header.status = STATUS_CONSISTENTE;
memcpy(&index->header.nItems, &aux[1], sizeof(int));
strcpy(index->path, path);
if(index->data != NULL) {
free(index->data);
}
index->data = (IND_DATA *) malloc(sizeof(IND_DATA) * index->header.nItems);
for(i = 0; i < index->header.nItems; i++) {
index->data[i].RRN = i;
if(fread(aux, sizeof(char), IND_DATA_SIZE, stream) != IND_DATA_SIZE) {
fclose(stream);
return 0;
}
strcpy(index->data[i].key, aux);
memcpy(&index->data[i].byteOffset, &aux[120], sizeof(long));
}
index->accessCount += ftell(stream) / PAGE_SIZE;
if(ftell(stream) % PAGE_SIZE != 0) {
index->accessCount++;
}
fclose(stream);
return 1;
}
int I_rewrite(IND_T *index) {
char aux[PAGE_SIZE];
FILE *stream;
int i;
if(index->path[0] == '\0') {
return 0;
}
stream = fopen(index->path, "wb");
if(stream == NULL) {
return 0;
}
index->header.status = STATUS_INCONSISTENTE;
memset(aux, LIXO, PAGE_SIZE);
memcpy(aux, &index->header.status, sizeof(char));
memcpy(&aux[1], &index->header.nItems, sizeof(int));
if(fwrite(aux, sizeof(char), PAGE_SIZE, stream) != PAGE_SIZE) {
fclose(stream);
return 0;
}
memset(aux, LIXO, PAGE_SIZE);
for(i = 0; i < index->header.nItems; i++) {
memset(aux, LIXO, IND_DATA_SIZE);
strcpy(aux, index->data[i].key);
memcpy(&aux[120], &index->data[i].byteOffset, sizeof(long));
if(fwrite(aux, sizeof(char), IND_DATA_SIZE, stream) != IND_DATA_SIZE) {
fclose(stream);
return 0;
}
}
index->header.status = STATUS_CONSISTENTE;
memset(aux, LIXO, PAGE_SIZE);
memcpy(aux, &index->header.status, sizeof(char));
memcpy(&aux[1], &index->header.nItems, sizeof(int));
fseek(stream, 0, SEEK_SET);
if(fwrite(aux, sizeof(char), PAGE_SIZE, stream) != PAGE_SIZE) {
fclose(stream);
return 0;
}
index->accessCount += ftell(stream) / PAGE_SIZE;
if(ftell(stream) % PAGE_SIZE != 0) {
index->accessCount++;
}
fclose(stream);
return 1;
}
int I_write(IND_T *index, char *path) {
strcpy(index->path, path);
return I_rewrite(index);
}
long I_count(IND_T *index) {
return index->accessCount;
}
void I_resetCount(IND_T *index) {
index->accessCount = 0;
}
int I_push(REG_DATA *reg, IND_T *index) {
int i, aux;
for(i = 0; i < index->header.nItems; i++) {
aux = strncmp(reg->nomeServidor, index->data[i].key, 120);
if(aux < 0 || (aux == 0 && reg->byteOffset < index->data[i].byteOffset)) {
break;
}
}
index->data = (IND_DATA *) realloc(index->data, sizeof(IND_DATA) * (index->header.nItems + 1));
memmove(&index->data[i + 1], &index->data[i], sizeof(IND_DATA) * (index->header.nItems - i));
index->data[i].byteOffset = reg->byteOffset;
strcpy(index->data[i].key, reg->nomeServidor);
index->header.nItems++;
for(i = 0; i < index->header.nItems; i++) {
index->data[i].RRN = i;
}
return 1;
}
int I_pop(REG_DATA *reg, IND_T *index) {
int i, aux;
for(i = 0; i < index->header.nItems; i++) {
if(reg->byteOffset == index->data[i].byteOffset) {
break;
}
}
if(i >= index->header.nItems) {
return 0;
}
memmove(&index->data[i], &index->data[i + 1], sizeof(IND_DATA) * (index->header.nItems - i - 1));
//index->data = (IND_DATA *) realloc(index->data, sizeof(IND_DATA) * (index->header.nItems - 1));
index->header.nItems--;
for(i = 0; i < index->header.nItems; i++) {
index->data[i].RRN = i;
}
return 1;
}
int I_update(REG_DATA *reg, IND_T *index) {
int i, aux;
for(i = 0; i < index->header.nItems; i++) {
if(reg->byteOffset == index->data[i].byteOffset) {
break;
}
}
if(i >= index->header.nItems) {
return 0;
}
memmove(&index->data[i], &index->data[i + 1], sizeof(IND_DATA) * (index->header.nItems - i - 1));
index->header.nItems--;
for(i = 0; i < index->header.nItems; i++) {
aux = strcmp(reg->nomeServidor, index->data[i].key);
if(aux > 0 || (aux == 0 && reg->byteOffset > index->data[i].byteOffset)) {
break;
}
}
memmove(&index->data[i + 1], &index->data[i], sizeof(IND_DATA) * (index->header.nItems - i));
index->data[i].byteOffset = reg->byteOffset;
strcpy(index->data[i].key, reg->nomeServidor);
index->header.nItems++;
for(i = 0; i < index->header.nItems; i++) {
index->data[i].RRN = i;
}
return 1;
}
IND_DATA *I_iterate(int *n, char *key, IND_T *index) {
int i, j, aux;
for(i = 0; i < index->header.nItems; i++) {
aux = strcmp(key, index->data[i].key);
if(aux < 0) {
*n = 0;
return NULL;
} else if(aux == 0) {
break;
}
}
if(i >= index->header.nItems) {
*n = 0;
return NULL;
}
for(j = i; j < index->header.nItems; j++) {
if(strcmp(key, index->data[j].key) != 0) {
break;
}
}
*n = j - i;
return &index->data[i];
}
void I_destroy(IND_T *index) {
if(index == NULL) {
return;
}
free(index->data);
free(index);
}
<file_sep>#!python3
import numpy as np
import heapq
import math
import time
import sys
#
# ~ Trabalho Prático 1: Busca ~
#
# Grupo:
# <NAME> (Nº USP 8596351)
# <NAME> (Nº USP 10369014)
# <NAME> (Nº USP 10783243)
#
# Inteligência Artificial: SCC-0230 2020.2
#
# _______ _______ _______
# | | | \
# | | | \ |___|
# | | \ | |
# |_______ _______|___|
#
#
CHAR_PATH = "@" # Caractere usado para representar um caminho encontrado.
VISUAL_POINTS_MAX = 30 # Tamanho máximo para ser considerado "grande demais" no número de pontos.
VISUAL_ROW_MAX = 30 # Tamanho máximo para ser considerado "grande demais" no número de linhas.
VISUAL_COL_MAX = 30 # Tamanho máximo para ser considerado "grande demais" no número de colunas.
def introducao():
### Essa função introduz o programa ao usuário. ###
print("Bem-vinde ao nosso trabalho!")
print("Funciona da seguinte maneira:")
print("- Você vai passar como entrada um labirinto, da maneira como proposto na especificação do trabalho.")
print("- Em seguida todos os algoritmos irão executar.")
print("- Ao final da execução de cada algoritmo, será retornado os resultados para você. Se um caminho foi encontrado, os pontos do caminho e uma representação gráfica estarão disponíveis.")
print()
def ler_entrada():
### Essa função realiza a leitura dos dados de entrada. ###
dimm = input("Entre com as dimenções do labirinto (valores inteiros >= 1). > ").strip().split() # Obtém uma linha da entrada.
if len(dimm) != 2: # Verifica se passou 2 inteiros.
print()
print("ERRO: você deve passar dois inteiros para o programa para a dimensão do labirinto em uma única linha.")
sys.exit(-1)
lab = np.empty([int(dimm[0]), int(dimm[1])], dtype=np.str) # Aloca array.
print("Agora, entre com o labirinto abaixo. >")
current_i = 0
while current_i < lab.shape[0] * lab.shape[1]: # Lê o labirinto.
line = "".join(input().strip().split())
for char in line:
if char != "*" and char != "-" and char != "$" and char != "#":
continue
lab[int(current_i / lab.shape[1]), int(current_i % lab.shape[1])] = char
current_i += 1
return lab
def imprimir_resultados(algo, labirinto, path, time):
### Essa função imprime os resultados de um algoritmo executado na tela. ###
for point in path: # Para cada ponto no caminho solução encontrado...
labirinto[point[0], point[1]] = CHAR_PATH # Colocar como "@" no labirinto (para representação visual).
print("== %s ==" % (algo)) # Imprimir nome do algoritmo.
print("\tTempo de execução: %.5f segundos" % (time)) # Imprimir tempo de execução.
if len(path) > VISUAL_POINTS_MAX: # Se houver um caminho encontrado mas é muito grande...
print("\tCaminho: encontrado, mas longo demais para exibir os %d pontos aqui." % (len(path)))
if labirinto.shape[0] > VISUAL_ROW_MAX or labirinto.shape[1] > VISUAL_COL_MAX:
print("\t(Labirinto grande demais para exibir representação visual.)")
else:
for line in labirinto: # Imprimir representação visual desse caminho.
print("\t", end = "")
for item in line:
print(item, end = "")
print()
elif len(path) > 1: # Se houver um caminho encontrado...
print("\tCaminho (%d): " % (len(path)), end="")
for point in path:
print("(%d, %d) " % (point[0], point[1]), end="") # Imprimir os pontos desse caminho.
print()
if labirinto.shape[0] > VISUAL_ROW_MAX or labirinto.shape[1] > VISUAL_COL_MAX:
print("\t(Labirinto grande demais para exibir representação visual.)")
else:
for line in labirinto: # Imprimir representação visual desse caminho.
print("\t", end = "")
for item in line:
print(item, end = "")
print()
else:
print("\tNenhum caminho encontrado.")
print()
def is_point_valid(labirinto, x, y):
### Essa função apenas retorna TRUE se um ponto é válido para percorrer em um dado labirinto, e FALSE caso contrário. ###
return x >= 0 and x < labirinto.shape[0] \
and y >= 0 and y < labirinto.shape[1] \
and (labirinto[x, y] == "*" or labirinto[x, y] == "$")
def point_heuristic_distance(x, y, end_point):
### Essa função retorna a distancia de um determinado ponto (x, y) a outro ponto de destino end_point, usada nos algoritmos de busca informada. ###
#return math.sqrt(math.pow(x - end_point[0], 2) + math.pow(y - end_point[1], 2)) # Distância Euclidiana
return abs(x - end_point[0]) + abs(y - end_point[1]) # Distância de Manhattan
def algo_dfs(labirinto):
path = [ ]
start_point = np.argwhere(labirinto == "#")[0].tolist()
start_time = time.time()
# Inicio do algoritmo.
stack = [ start_point ] # Aloca pilha.
antecessor = np.full(labirinto.shape, None, dtype=np.object) # Vetor de antecessores.
while len(stack) > 0: # Enquanto existirem pontos a serem percorridos na pilha...
point = stack.pop() # Retira do fim da pilha (então faz uma busca DFS).
if labirinto[point[0], point[1]] == "$": # Solução encontrada! Gerar vetor com a solução e encerrar algoritmo.
while point[0] != start_point[0] or point[1] != start_point[1]:
path.insert(0, point)
point = antecessor[point[0], point[1]]
path.insert(0, start_point)
break
if is_point_valid(labirinto, point[0] - 1, point[1]) and antecessor[point[0] - 1, point[1]] is None: # Subir.
stack.append([point[0] - 1, point[1]])
antecessor[point[0] - 1, point[1]] = point
if is_point_valid(labirinto, point[0] + 1, point[1]) and antecessor[point[0] + 1, point[1]] is None: # Descer.
stack.append([point[0] + 1, point[1]])
antecessor[point[0] + 1, point[1]] = point
if is_point_valid(labirinto, point[0], point[1] - 1) and antecessor[point[0], point[1] - 1] is None: # Esquerda.
stack.append([point[0], point[1] - 1])
antecessor[point[0], point[1] - 1] = point
if is_point_valid(labirinto, point[0], point[1] + 1) and antecessor[point[0], point[1] + 1] is None: # Direita.
stack.append([point[0], point[1] + 1])
antecessor[point[0], point[1] + 1] = point
# Fim do algoritmo.
end_time = time.time()
imprimir_resultados("Algoritmo de Busca em Profundidade", labirinto, path, end_time - start_time)
def algo_bfs(labirinto):
path = [ ]
start_point = np.argwhere(labirinto == "#")[0].tolist()
start_time = time.time()
# Inicio do algoritmo.
queue = [ start_point ] # Aloca fila.
antecessor = np.full(labirinto.shape, None, dtype=np.object) # Vetor de antecessores.
while len(queue) > 0: # Enquanto existirem pontos a serem percorridos na fila...
point = queue.pop(0) # Retira do começo da fila (então faz uma busca BFS).
if labirinto[point[0], point[1]] == "$": # Solução encontrada! Gerar vetor com a solução e encerrar algoritmo.
while point[0] != start_point[0] or point[1] != start_point[1]:
path.insert(0, point)
point = antecessor[point[0], point[1]]
path.insert(0, start_point)
break
if is_point_valid(labirinto, point[0] - 1, point[1]) and antecessor[point[0] - 1, point[1]] is None: # Subir.
queue.append([point[0] - 1, point[1]])
antecessor[point[0] - 1, point[1]] = point
if is_point_valid(labirinto, point[0] + 1, point[1]) and antecessor[point[0] + 1, point[1]] is None: # Descer.
queue.append([point[0] + 1, point[1]])
antecessor[point[0] + 1, point[1]] = point
if is_point_valid(labirinto, point[0], point[1] - 1) and antecessor[point[0], point[1] - 1] is None: # Esquerda.
queue.append([point[0], point[1] - 1])
antecessor[point[0], point[1] - 1] = point
if is_point_valid(labirinto, point[0], point[1] + 1) and antecessor[point[0], point[1] + 1] is None: # Direita.
queue.append([point[0], point[1] + 1])
antecessor[point[0], point[1] + 1] = point
# Fim do algoritmo.
end_time = time.time()
imprimir_resultados("Algoritmo de Busca em Largura", labirinto, path, end_time - start_time)
def algo_best_first_search(labirinto):
path = [ ]
start_point = np.argwhere(labirinto == "#")[0].tolist()
start_time = time.time()
# Inicio do algoritmo.
end_point = np.argwhere(labirinto == "$")[0].tolist()
priority_queue = [ ] # Aloca fila de prioridade.
antecessor = np.full(labirinto.shape, None, dtype=np.object) # Vetor de antecessores.
heapq.heappush(priority_queue, (point_heuristic_distance(start_point[0], start_point[1], end_point), start_point)) # Adiciona o ponto inicial à fila de prioridade.
while len(priority_queue) > 0: # Enquanto existirem pontos a serem percorridos na fila de prioridade...
point = heapq.heappop(priority_queue)[1] # Retira da fila de prioridades (baseando-se apenas na distancia até o ponto destino, função h(x)).
if labirinto[point[0], point[1]] == "$": # Solução encontrada! Gerar vetor com a solução e encerrar algoritmo.
while point[0] != start_point[0] or point[1] != start_point[1]:
path.insert(0, point)
point = antecessor[point[0], point[1]]
path.insert(0, start_point)
break
if is_point_valid(labirinto, point[0] - 1, point[1]) and antecessor[point[0] - 1, point[1]] is None: # Subir.
heapq.heappush(priority_queue, (point_heuristic_distance(point[0] - 1, point[1], end_point), [point[0] - 1, point[1]]))
antecessor[point[0] - 1, point[1]] = point
if is_point_valid(labirinto, point[0] + 1, point[1]) and antecessor[point[0] + 1, point[1]] is None: # Descer.
heapq.heappush(priority_queue, (point_heuristic_distance(point[0] + 1, point[1], end_point), [point[0] + 1, point[1]]))
antecessor[point[0] + 1, point[1]] = point
if is_point_valid(labirinto, point[0], point[1] - 1) and antecessor[point[0], point[1] - 1] is None: # Esquerda.
heapq.heappush(priority_queue, (point_heuristic_distance(point[0], point[1] - 1, end_point), [point[0], point[1] - 1]))
antecessor[point[0], point[1] - 1] = point
if is_point_valid(labirinto, point[0], point[1] + 1) and antecessor[point[0], point[1] + 1] is None: # Direita.
heapq.heappush(priority_queue, (point_heuristic_distance(point[0], point[1] + 1, end_point), [point[0], point[1] + 1]))
antecessor[point[0], point[1] + 1] = point
# Fim do algoritmo.
end_time = time.time()
imprimir_resultados("Algoritmo de Busca Best-First Search", labirinto, path, end_time - start_time)
def algo_a_star(labirinto):
path = [ ]
start_point = np.argwhere(labirinto == "#")[0].tolist()
start_time = time.time()
# Inicio do algoritmo.
end_point = np.argwhere(labirinto == "$")[0].tolist()
priority_queue = [ ] # Aloca fila de prioridade.
antecessor = np.full(labirinto.shape, None, dtype=np.object) # Vetor de antecessores.
heapq.heappush(priority_queue, (point_heuristic_distance(start_point[0], start_point[1], end_point) + 0, start_point)) # Adiciona o ponto inicial à fila de prioridade.
while len(priority_queue) > 0: # Enquanto existirem pontos a serem percorridos na fila de prioridade...
point_priority = heapq.heappop(priority_queue) # Retira da fila de prioridades. f(x) = g(x) + h(x)
point = point_priority[1] # x.
current_priority = max(point_priority[0] - point_heuristic_distance(point[0], point[1], end_point), 0) + 1 # g(x) = f(x) - h(x).
if labirinto[point[0], point[1]] == "$": # Solução encontrada! Gerar vetor com a solução e encerrar algoritmo.
while point[0] != start_point[0] or point[1] != start_point[1]:
path.insert(0, point)
point = antecessor[point[0], point[1]][1]
path.insert(0, start_point)
break
if is_point_valid(labirinto, point[0] - 1, point[1]) and (antecessor[point[0] - 1, point[1]] is None or antecessor[point[0] - 1, point[1]][0] > current_priority + point_heuristic_distance(point[0] - 1, point[1], end_point)): # Subir.
next_priority = current_priority + point_heuristic_distance(point[0] - 1, point[1], end_point)
heapq.heappush(priority_queue, (next_priority, [point[0] - 1, point[1]]))
antecessor[point[0] - 1, point[1]] = [next_priority, point]
if is_point_valid(labirinto, point[0] + 1, point[1]) and (antecessor[point[0] + 1, point[1]] is None or antecessor[point[0] + 1, point[1]][0] > current_priority + point_heuristic_distance(point[0] + 1, point[1], end_point)): # Descer.
next_priority = current_priority + point_heuristic_distance(point[0] + 1, point[1], end_point)
heapq.heappush(priority_queue, (next_priority, [point[0] + 1, point[1]]))
antecessor[point[0] + 1, point[1]] = [next_priority, point]
if is_point_valid(labirinto, point[0], point[1] - 1) and (antecessor[point[0], point[1] - 1] is None or antecessor[point[0], point[1] - 1][0] > current_priority + point_heuristic_distance(point[0], point[1] - 1, end_point)): # Esquerda.
next_priority = current_priority + point_heuristic_distance(point[0], point[1] - 1, end_point)
heapq.heappush(priority_queue, (next_priority, [point[0], point[1] - 1]))
antecessor[point[0], point[1] - 1] = [next_priority, point]
if is_point_valid(labirinto, point[0], point[1] + 1) and (antecessor[point[0], point[1] + 1] is None or antecessor[point[0], point[1] + 1][0] > current_priority + point_heuristic_distance(point[0], point[1] + 1, end_point)): # Direita.
next_priority = current_priority + point_heuristic_distance(point[0], point[1] + 1, end_point)
heapq.heappush(priority_queue, (next_priority, [point[0], point[1] + 1]))
antecessor[point[0], point[1] + 1] = [next_priority, point]
# Fim do algoritmo.
end_time = time.time()
imprimir_resultados("Algoritmo de Busca A*", labirinto, path, end_time - start_time)
def algo_hill_climbing(labirinto):
path = [ ]
start_point = np.argwhere(labirinto == "#")[0].tolist()
start_time = time.time()
# Inicio do algoritmo.
end_point = np.argwhere(labirinto == "$")[0].tolist()
antecessor = np.full(labirinto.shape, None, dtype=np.object) # Vetor de antecessores.
point = start_point # Começa com ponto inicial.
while True: # As condições de parada do algoritmo já estão determinada abaixo.
if labirinto[point[0], point[1]] == "$": # Solução encontrada! Gerar vetor com a solução e encerrar algoritmo.
while point[0] != start_point[0] or point[1] != start_point[1]:
path.insert(0, point)
point = antecessor[point[0], point[1]]
path.insert(0, start_point)
break
nearest_point = None
nearest_distance = float("inf")
if is_point_valid(labirinto, point[0] - 1, point[1]) and antecessor[point[0] - 1, point[1]] is None: # Subir.
if nearest_distance > point_heuristic_distance(point[0] - 1, point[1], end_point):
nearest_point = [point[0] - 1, point[1]]
nearest_distance = point_heuristic_distance(point[0] - 1, point[1], end_point)
if is_point_valid(labirinto, point[0] + 1, point[1]) and antecessor[point[0] + 1, point[1]] is None: # Descer.
if nearest_distance > point_heuristic_distance(point[0] + 1, point[1], end_point):
nearest_point = [point[0] + 1, point[1]]
nearest_distance = point_heuristic_distance(point[0] + 1, point[1], end_point)
if is_point_valid(labirinto, point[0], point[1] - 1) and antecessor[point[0], point[1] - 1] is None: # Esquerda.
if nearest_distance > point_heuristic_distance(point[0], point[1] - 1, end_point):
nearest_point = [point[0], point[1] - 1]
nearest_distance = point_heuristic_distance(point[0], point[1] - 1, end_point)
if is_point_valid(labirinto, point[0], point[1] + 1) and antecessor[point[0], point[1] + 1] is None: # Direita.
if nearest_distance > point_heuristic_distance(point[0], point[1] + 1, end_point):
nearest_point = [point[0], point[1] + 1]
nearest_distance = point_heuristic_distance(point[0], point[1] + 1, end_point)
if nearest_point == None or nearest_distance > point_heuristic_distance(point[0], point[1], end_point):
break
antecessor[nearest_point[0], nearest_point[1]] = point
point = nearest_point
# Fim do algoritmo.
end_time = time.time()
imprimir_resultados("Algoritmo de Busca Hill Climbing", labirinto, path, end_time - start_time)
### MAIN ###
introducao() # Imprimir texto de introdução.
labirinto = ler_entrada() # Ler o labirinto de entrada.
print("Vamos iniciar a execução dos algoritmos. Por favor, aguarde...")
print()
algo_dfs(np.copy(labirinto)) # Busca em profundidade.
algo_bfs(np.copy(labirinto)) # Busca em largura.
algo_best_first_search(np.copy(labirinto)) # Busca Best-First Search.
algo_a_star(np.copy(labirinto)) # Busca A*.
algo_hill_climbing(np.copy(labirinto)) # Hill Climbing.
|
b4dc6ae1796640da99929d642fccccc4c26e3c82
|
[
"Markdown",
"JavaScript",
"Makefile",
"Dockerfile",
"Java",
"Python",
"Text",
"PHP",
"C",
"C++",
"Shell"
] | 407 |
Makefile
|
mcarvalhor/USP
|
90d8e47bacd4e9a3e3bdea0e29458ffd92350182
|
a729db4068f5c02e57499b0523dc8e1190398cff
|
refs/heads/master
|
<repo_name>silvars/agile<file_sep>/README.md
##FreakTemplate
FreakTemplate is application template for web and mobile using Symfony 2.4.0
###SYSTEM REQUIREMENTS
FreakTemplate requires PHP 5.5.0 or later; We recommend using the latest PHP version whenever possible.
###LICENSE
The files in this archive are released under the MIT license. You can find a copy of this license in LICENSE.txt.
### INSTALLATION
Clone the git repository for your project directory:
```shell
$ cd /path/to/project/
```
You can clone with HTTPS:
```shell
$ git clone https://github.com/FreakRabbit/FreakTemplate.git
```
Or SSH:
```shell
$ git clone https://github.com/FreakRabbit/FreakTemplate.git
```
After cloning project, you need rum [Composr](http://getcomposer.org/) for install and manage dependencies.
```shell
$ php composer.phar install
```
For advanced Apache configuration options, see the official [Apache documentation](http://httpd.apache.org/docs/current/mod/core.html#documentroot). The minimum basics to get your application running under Apache2 are:
```shell
#Virtual Host for FreakTemplate:
<VirtualHost *:80>
ServerName freak.localhost
DocumentRoot /path/to/project/web/
<Directory /path/to/project/web/>
AllowOverride All
Order allow,deny
Allow from All
</Directory>
ErrorLog /var/log/apache2/freak_error.log
CustomLog /var/log/apache2/freak_access.log combined
</VirtualHost>
<code>
```
<file_sep>/application/modules/default/Bootstrap.php
<?php
/**
* @package Default
* @version 0.1
* @see http://www.techforti.com.br
* @copyright
**/
class Default_Bootstrap extends Zend_Application_Module_Bootstrap
{
}<file_sep>/application/modules/default/controllers/ProjectController.php
<?php
/**
* @package Default
*/
class Default_ProjectController extends Zend_Controller_Action
{
/**
* @var Default_Model_Project
*/
private $_model;
/**
* Description here.
*
* @access public
* @return ???
*/
public function init()
{
$this->_model = new Default_Model_Project();
}
/**
* Description here . . .
*
* @access public
* @return array
*/
public function indexAction()
{
if ($this->getRequest()->isPost()) {
try {
die("XX");
$project = new Default_Application_Model_Project();
die(print_r($project->getProjecstByIds($this->getRequest()->getPost())));
// $project->getProjecstByIds($this->getRequest()->getPost());
} catch (Exception $ex) {
echo json_encode(array(
'success' => false,
'message' => $ex->getMessage(),
'code' => $ex->getCode()
));
}
}
$this->view->titles = $this->_model->getProjectTitles();
}
}<file_sep>/application/modules/default/controllers/IndexController.php
<?php
/**
* @package Default
*/
class Default_IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$this->_redirect('project');
}
}<file_sep>/application/modules/default/models/DbTable/Project.php
<?php
/**
* @package Default
*/
class Default_Model_DbTable_Project extends Zend_Db_Table_Abstract
{
protected $_name = 'jiraproject';
protected $_primary = 'ID';
}<file_sep>/application/modules/Bootstrap.php
<?php
/**
* @package Default
**/
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
/**
* Returns the HTML Doctype that will be used in the layout.
*
* @access protected
* @return string
*/
protected function _initDoctype()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->doctype('XHTML1_TRANSITIONAL');
}
}<file_sep>/application/modules/default/models/Project.php
<?php
/**
* @package Default
*/
class Default_Model_Project
{
/**
* Return all project titles.
*
* @access public
* @return array
*/
public function getProjectTitles()
{
try {
$sql = $this->select()
->from('project', array('ID', 'pname'));
return $this->fetchAll($sql);
} catch (Exception $ex) {
echo json_encode(array(
'success' => false,
'message' => $ex->getMessage(),
'code' => $ex->getCode()
));
}
}
/**
* Return all project titles.
*
* @access public
* @return array
*/
public function getProjecstByIds(array $params)
{
try {
$select = $this->select()
->setIntegrityCheck(false)
->from(array('ji' => 'jiraissue'))
->join(array('p' => 'project'),
'ji.PROJECT=p.ID')
->join(array('it' => 'issuetype'),
'ji.issuetype=it.ID')
->order('ji.PROJECT')
->order('ji.issuestatus')
->where('PROJECT IN (?)', $params);
return $select;
} catch (Exception $ex) {
echo json_encode(array(
'success' => false,
'message' => $ex->getMessage(),
'code' => $ex->getCode()
));
}
}
}<file_sep>/application/modules/default/models/Mapper/Project.php
<?php
/**
* @package Default
*/
|
fd24dfcb39d9fae02c1e68baac9113ba0fc37fc3
|
[
"Markdown",
"PHP"
] | 8 |
Markdown
|
silvars/agile
|
7c4cac7e42845ee50ae689b292235a17cd0d6f32
|
e1dfe19b8b9001fa06f030878352b9c34be56dd4
|
refs/heads/master
|
<file_sep>from django.contrib import admin
from website.models import *
# Register your models here.
class FavoriteAdmin(admin.ModelAdmin):
list_display = ("favor_count",)
admin.site.register(Favorite, FavoriteAdmin)
class NewsAdmin(admin.ModelAdmin):
list_display = ('title', 'summary', 'url', 'favor_count', 'reply_count', 'news_type', 'user', 'create_date')
admin.site.register(News, NewsAdmin)
admin.site.register(UserType)
admin.site.register(Admin)
admin.site.register(Chat)
admin.site.register(NewsType)
class ReplyAdmin(admin.ModelAdmin):
list_display = ('content', 'news', 'user', 'create_date')
admin.site.register(Reply, ReplyAdmin)
<file_sep># coding=utf-8
from django.shortcuts import render, render_to_response, redirect
from django.http import HttpResponse
from website.models import *
from django.template import RequestContext
# django built-in serializer
from django.core import serializers
import json
import datetime
from django import forms
class UserRegistForm(forms.Form):
username = forms.CharField(label='username', max_length=50)
password = forms.CharField(label='<PASSWORD>', widget=forms.PasswordInput())
# Ajax请求
# 返回 Json 数据
# 装饰器 - 用户验证
def loginCheck(func):
def wrapper(request):
result = {'status': 0, 'data': '', 'message': ''}
if request.session['isLogin']:
return func(request)
else:
result['message'] = 'You need to login first.'
return HttpResponse(json.dumps(result))
return wrapper # Create your views here.
# Homepage1 of ALL
def index(request):
all_data = News.objects.all()
return render_to_response('index.html', {'data': all_data, 'isLogin': request.session['isLogin']})
# Homepage2 of Old Boy
def old_boy(request):
type = NewsType.objects.all()
all_data = News.objects.filter(news_type__exact=type[1])
return render_to_response('homepage2.html', {'data': all_data, 'isLogin': request.session['isLogin']})
# Homepage3 of IT Zone
def it_zone(request):
type = NewsType.objects.all()
all_data = News.objects.filter(news_type__exact=type[0])
return render_to_response('homepage3.html', {'data': all_data, 'isLogin': request.session['isLogin']})
def login(request):
# POST请求 提交表单的操作
if request.method == 'POST':
urf = UserRegistForm(request.POST)
if urf.is_valid():
username = request.POST.get('username', None)
password = request.POST.get('password', None)
user_count = Admin.objects.filter(username__exact=username, password__exact=<PASSWORD>).count()
print user_count
if user_count == 1:
request.session['current_user_id'] = Admin.objects.get(username=username, password=<PASSWORD>).id
if not request.session.get('isLogin'):
request.session['isLogin'] = True
return redirect('/index/', {'isLogin': True})
else:
id_count = Admin.objects.filter(username__exact=username).count()
if id_count == 1:
return render_to_response('login.html', {'msg': 'password invalid !', 'urf': urf})
else:
return render_to_response('login.html', {'msg': 'username doesn exist !', 'urf': urf})
# GET请求 是第一次登陆界面,或者界面的刷新操作
else:
urf = UserRegistForm()
return render_to_response('login.html', {'urf': urf}, context_instance=RequestContext(request))
# def login(request):
# if request.method == 'POST':
# username = request.POST.get('username')
# password = request.POST.get('<PASSWORD>')
# try:
# currentObj = Admin.objects.get(username=username, password=<PASSWORD>)
# except Exception, e:
# currentObj = None
# if currentObj:
# request.session['current_user_id'] = currentObj.id
# return redirect('/index/')
# else:
# return render_to_response('login.html')
# print 'This is the get method.'
# return render_to_response('login.html')
def logout(request):
try:
request.session['isLogin'] = False
del request.session['current_user_id']
except:
pass
return redirect('/index/')
@loginCheck
def addFavor(request):
result = {'status': 0, 'data': '', 'message': ''}
id = request.POST.get('nid')
obj = News.objects.get(id=id)
temp = obj.favor_count + 1
obj.favor_count = temp
obj.save()
result['status'] = 1
result['data'] = temp
return HttpResponse(json.dumps(result))
# def addFavor(request):
# result = {'status': 0, 'data': '', 'message': ''}
# if request.session['isLogin']:
# try:
# id = request.POST.get('nid')
# obj = News.objects.get(id=id)
# temp = obj.favor_count + 1
# obj.favor_count = temp
# obj.save()
# result['status'] = 1
# result['data'] = temp
# except Exception, e:
# result['message'] = 'Required to login before add favor!'
# result['message'] = 'Required to login before add favor!'
# return HttpResponse(json.dumps(result))
# def addFavor(request):
# print 'addFavor'
# return render_to_response(request, 'login.html')
class myJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, datetime.date):
return obj.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self, obj)
def getReply(request):
id = request.POST.get('nid')
reply_list = Reply.objects.filter(news__id=id).values('id', 'content', 'create_date', 'user__username')
reply_list = list(reply_list)
reply_list = json.dumps(reply_list, cls=myJsonEncoder)
print 'getReply' + str(id)
return HttpResponse(reply_list)
def submitReply(request):
result = {'status': 0, 'data': '', 'message': ''}
try:
id = request.POST.get('nid')
data = request.POST.get('data')
newsObj = News.objects.get(id=id)
user = Admin.objects.get(id=request.session['current_user_id'])
replyObj = Reply.objects.create(content=data, news=newsObj, user=user)
count = Reply.objects.filter(news__id=id).count()
newsObj.reply_count = Reply.objects.filter(news__id=id).count()
newsObj.save()
result['status'] = 1
result['data'] = {'reply_count': count, 'content': replyObj.content, 'user__username': replyObj.user.username,
'create_date': replyObj.create_date.strftime('%Y-%m-%d %H:%M:%S')}
print 'submitReply' + str(id)
except Exception, e:
result['message'] = 'Reuqired to login before sumbit.'
print result['message']
return HttpResponse(json.dumps(result))
def submitChat(request):
result = {'status': 0, 'data': '', 'message': ''}
print 123
try:
chat_content = request.POST.get('data')
userObj = Admin.objects.get(id=request.session['current_user_id'])
chatObj = Chat.objects.create(content=chat_content, user=userObj)
result['status'] = 1
result['data'] = {'username': userObj.username,
'create_date': chatObj.create_date.strftime('%Y-%m-%d %H:%M:%S')}
except Exception, e:
result['message'] = e.message
print 'message is :' + str(result)
return HttpResponse(json.dumps(result))
def updateChatPool(request):
chat_list = Chat.objects.order_by('-id')[0:10].values('user__username', 'content', 'create_date')
chat_list = list(chat_list)
chat_list = json.dumps(chat_list, cls=myJsonEncoder)
return HttpResponse(chat_list)
<file_sep>from django.contrib import admin
from models import *
# Register your models here.
class PublisherAdmin(admin.ModelAdmin):
pass
admin.site.register(Publisher, PublisherAdmin)
class DeviceAdmin(admin.ModelAdmin):
list_display = ("device_id",)
admin.site.register(Device, DeviceAdmin)
class DataAdmin(admin.ModelAdmin):
list_display = ("data_name", "data_value", "device_type")
admin.site.register(Data, DataAdmin)<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-21 05:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('database', '0007_remove_publisher_hobby'),
]
operations = [
migrations.CreateModel(
name='Data',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('data_name', models.CharField(max_length=50)),
('data_value', models.FloatField()),
],
),
migrations.CreateModel(
name='Device',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('device_id', models.CharField(max_length=50)),
],
),
migrations.AddField(
model_name='data',
name='device_type',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='database.Device'),
),
]
|
3f77106a9f8b84a0e3738cd7799a1f939c22f5c1
|
[
"Python"
] | 4 |
Python
|
liujunlovecs/mySite
|
a6d1de7a2ab82805a9c7ea571cd098a41b36d531
|
ea5e558a5c6d14b5c28e82e0d7ffaf4e97443ad8
|
refs/heads/master
|
<repo_name>obalunenko/kafka-dump<file_sep>/scripts/tests.sh
#!/bin/bash
export GO111MODULE=on
go fmt $(go list ./... | grep -v /vendor/)
go test -v -race -coverpkg=./... -covermode=atomic -coverprofile=coverage.out ./...<file_sep>/go.mod
module github.com/obalunenko/kafka-dump
go 1.15
require (
github.com/BurntSushi/toml v0.3.1 // indirect
github.com/Shopify/sarama v1.28.0
github.com/bsm/sarama-cluster v2.1.15+incompatible
github.com/fatih/camelcase v1.0.0 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/golang/snappy v0.0.2 // indirect
github.com/koding/multiconfig v0.0.0-20171124222453-69c27309b2d7
github.com/onsi/ginkgo v1.14.2 // indirect
github.com/onsi/gomega v1.10.3 // indirect
github.com/pierrec/lz4 v2.6.0+incompatible // indirect
github.com/sirupsen/logrus v1.8.1
)
<file_sep>/scripts/version.sh
#!/bin/bash
function require_clean_work_tree () {
# Update the index
git update-index -q --ignore-submodules --refresh
err=0
# Disallow unstaged changes in the working tree
if ! git diff-files --quiet --ignore-submodules --
then
echo >&2 "cannot $1: you have unstaged changes."
git diff-files --name-status -r --ignore-submodules -- >&2
err=1
fi
# Disallow uncommitted changes in the index
if ! git diff-index --cached --quiet HEAD --ignore-submodules --
then
echo >&2 "cannot $1: your index contains uncommitted changes."
git diff-index --cached --name-status -r --ignore-submodules HEAD -- >&2
err=1
fi
if [ $err = 1 ]
then
echo >&2 "Please commit or stash them."
exit 1
fi
}
function menu(){
clear
printf "Select what you want to update: \n"
printf "1 - Major update\n"
printf "2 - Minor update\n"
printf "3 - Patch update\n"
printf "4 - Exit\n"
read -r selection
case "$selection" in
1) printf "Major updates......\n"
NEWVERSION=$(git tag | sed 's/\(.*v\)\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\2;\3;\4;\1/g' | sort -t';' -k 1,1n -k 2,2n -k 3,3n | tail -n 1 | awk -F';' '{printf "%s%d.%d.%d", $4, ($1+1),0,0 }')
;;
2) printf "Run Minor update.........\n"
NEWVERSION=$(git tag | sed 's/\(.*v\)\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\2;\3;\4;\1/g' | sort -t';' -k 1,1n -k 2,2n -k 3,3n | tail -n 1 | awk -F';' '{printf "%s%d.%d.%d", $4, $1,($2+1),0 }')
;;
3) printf "Patch update.........\n"
NEWVERSION=$(git tag | sed 's/\(.*v\)\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\2;\3;\4;\1/g' | sort -t';' -k 1,1n -k 2,2n -k 3,3n | tail -n 1 | awk -F';' '{printf "%s%d.%d.%d", $4, $1,$2,($3 + 1) }')
;;
4) printf "Exit................................\n"
exit 1
;;
*) clear
printf "Incorrect selection. Try again\n"
menu
;;
esac
}
## Check if git is clean
require_clean_work_tree "create new version"
git pull
## Sem ver update menu
menu
if [[ "${NEWVERSION}" = "" ]]; then
NEWVERSION="v1.0.0"
fi
echo ${NEWVERSION}
message="version ${NEWVERSION}"
ADD="version"
read -r -n 1 -p "y?:" userok
echo ""
if [[ "$userok" = "y" ]]; then
read -r -n 1 -p "Update commit message?: y/n" userok
echo ""
if [[ "$userok" = "y" ]]; then
read -r -p "Message: " message
ADD="."
echo ""
fi
echo ${NEWVERSION} > version && git add ${ADD} && git commit -m "$message"&& git tag -a ${NEWVERSION} -m ${NEWVERSION} && git push --tags && git push
fi
echo
<file_sep>/scripts/release.sh
#!/usr/bin/env bash
# Get new tags from the remote
git fetch --tags
# Get the latest tag name
latestTag=$(git describe --tags $(git rev-list --tags --max-count=1))
echo ${latestTag}
curl -sL https://git.io/goreleaser | bash<file_sep>/Makefile
NAME=kafka-dump
# COLORS
GREEN := $(shell tput -Txterm setaf 2)
YELLOW := $(shell tput -Txterm setaf 3)
WHITE := $(shell tput -Txterm setaf 7)
RESET := $(shell tput -Txterm sgr0)
TARGET_MAX_CHAR_NUM=20
define colored
@echo '${GREEN}$1${RESET}'
endef
## Show help
help:
${call colored, help is running...}
@echo ''
@echo 'Usage:'
@echo ' ${YELLOW}make${RESET} ${GREEN}<target>${RESET}'
@echo ''
@echo 'Targets:'
@awk '/^[a-zA-Z\-\_0-9]+:/ { \
helpMessage = match(lastLine, /^## (.*)/); \
if (helpMessage) { \
helpCommand = substr($$1, 0, index($$1, ":")-1); \
helpMessage = substr(lastLine, RSTART + 3, RLENGTH); \
printf " ${YELLOW}%-$(TARGET_MAX_CHAR_NUM)s${RESET} ${GREEN}%s${RESET}\n", helpCommand, helpMessage; \
} \
} \
{ lastLine = $$0 }' $(MAKEFILE_LIST)
## dependensies - fetch all dependencies for sripts
dependencies:
${call colored, dependensies is running...}
./scripts/get-dependencies.sh
## Dev mode - go run
dev:
${call colored, dev is running...}
#docker-compose up&
go run main.go
.PHONY: dev
## Compile binary
compile:
${call colored, compile is running...}
./scripts/compile.sh
.PHONY: compile
## lint project
lint:
${call colored, lint is running...}
./scripts/linters.sh
.PHONY: lint
## Test all packages
test:
${call colored, test is running...}
./scripts/tests.sh
.PHONY: test
## Test coverage
test-cover:
${call colored, test-cover is running...}
go test -race -coverpkg=./... -v -coverprofile .testCoverage.out ./...
gocov convert .testCoverage.out | gocov report
.PHONY: test-cover
new-version: lint test compile
${call colored, new version is running...}
./scripts/version.sh
.PHONY: new-version
## Release
release:
${call colored, release is running...}
./scripts/release.sh
.PHONY: release
.DEFAULT_GOAL := test
|
a0cb5068adf239255373396d4f10b9c957aa64b9
|
[
"Makefile",
"Go Module",
"Shell"
] | 5 |
Shell
|
obalunenko/kafka-dump
|
dee1f8392c6049db8b808cca8d5e6dd439985363
|
b23895b76dc262ad9b66dc2d532bd44ff1ec1612
|
refs/heads/master
|
<file_sep>// Module dependencies
var express = require('express')
var request = require('request')
// initialize a server, listening on default Heroku port or 8080
var server = express()
server.set('port', process.env.PORT || 8080)
server.use(express.static(__dirname))
server.listen(server.get('port'), function () {
console.log('Express server listening on port ' + server.get('port'))
})
// URL string pointing to the BreweryDB API endpoint querying all Vermont breweries
var brewerydbURL =
`https://api.brewerydb.com/v2/locations?region=Vermont&order=name&sort=ASC&key=${process.env.BREWDB_KEY}&format=json`
var untappdURL = 'https://api.untappd.com/v4'
var untappdOAuth = {
client_id: process.env.UNTAPPD_ID,
client_secret: process.env.UNTAPPD_SECRET
}
console.log('Forwarding API requests')
function getAllVtBreweries () {
return new Promise(function (resolve, reject) {
request.get(brewerydbURL, (error, response, body) => {
resolve(body)
})
})
}
server.all('/brewerydb/', function (req, res) {
getAllVtBreweries().then(model => res.send(model))
})
server.all('/untappd/', function (req, res) {
console.log('AJAX request made to Untappd - search for ' + req.query.q)
searchBreweryByName(req.query.q)
.then(id => searchBreweryById(id))
.then(details =>
res.send(details))
})
function searchBreweryByName (query) {
return new Promise(function (resolve, reject) {
request.get(`${untappdURL}/search/brewery?client_id=${untappdOAuth.client_id}&client_secret=${untappdOAuth.client_secret}&q=${query}`, function (error, response, body) {
var data = JSON.parse(body)
if (data.response.brewery.items[0]) {
resolve(data.response.brewery.items[0].brewery.brewery_id)
} else {
reject('No Untappd information available for that brewery')
}
})
})
}
function searchBreweryById (id) {
return new Promise(function (resolve, reject) {
request.get(`${untappdURL}/brewery/info/${id}?client_id=${untappdOAuth.client_id}&client_secret=${untappdOAuth.client_secret}`, function (error, response, body) {
resolve(body)
})
})
}
<file_sep># Vermont Breweries: An Interactive Map
This is a single page application integrating information from Google Maps and two third-party APIs. A list of breweries in the state of Vermont is retrieved from [BreweryDB](http://www.brewerydb.com/), which are then added to a map. A list view and filter are provided. Info windows on the map provide detailed information from [Untappd](https://untappd.com/) on selected breweries.
## Getting Started
### Required Software
Using this app requires [Node.js](https://nodejs.org/en/). We will be running our own local server to serve the page and to make requests to BreweryDB.
### Installation
Clone the repository from Github:
`$ git clone https://github.com/ericjphillips/frontend-nanodegree-neighborhood-map.git`
From the project directory, install the required Node packages:
`$ npm install`
### Starting the Server
To start the server with its default settings:
`$ node index.js`
This will create a local server on port 8080.
### Loading the Application
In your browser's address bar, enter `localhost:8080` to access our local server.
<file_sep>var google, map, ko
var viewModel = {
center:
{
lat: 43.9753,
lng: -72.5623
},
brewery: ko.observableArray([]),
filterby: ko.observable(''),
open2Public: ko.observable(false),
keywords: ko.observable(''),
infowindow: {},
menuButton: document.getElementById('menuButton'),
menuArea: document.getElementById('menuArea'),
toggleMenu: function () {
this.menuButton.classList.toggle('slide')
this.menuButton.classList.toggle('spin')
this.menuArea.classList.toggle('slide')
}
}
var untappdSearch = new XMLHttpRequest()
// method to move the map's infowindow and update its content.
// takes a brewery as an argument
// closes any open infowindow
// makes a call to Untappd for more detailed information
// assembles infowindow content from available information
// uses the infoWindow setOptions method to change its content and position, then open it on the map
viewModel.infoWindowChange = function (brewery) {
viewModel.infowindow.close()
viewModel.infowindow.setOptions(
{
content: 'Loading: ...',
position: brewery.marker.position
}
)
brewery.marker.setAnimation(google.maps.Animation.BOUNCE)
viewModel.infowindow.open(map)
untappdSearch.open('GET', '/untappd/?q=' + brewery.brewery.name, true)
untappdSearch.send()
untappdSearch.onreadystatechange = function () {
brewery.untappd = JSON.parse(untappdSearch.responseText).response.brewery
var content = ''
var bestRated
content += '<img src="' + brewery.untappd.brewery_label + '">'
content += '<h1>' + brewery.untappd.brewery_name + '</h1>'
if (brewery.hasOwnProperty('established')) {
content += '<p> est. ' + brewery.established + '</p>'
}
if (brewery.untappd.hasOwnProperty('brewery_description')) {
content += '<p>' + brewery.untappd.brewery_description + '</p>'
}
content += '<p>'
if (brewery.untappd.contact.url.length > 0) {
content += '<a href="' + brewery.untappd.contact.url + '" target="_blank">' + brewery.untappd.contact.url + '</a> '
}
if (brewery.untappd.contact.facebook.length > 0) {
content += '<a href="' + brewery.untappd.contact.facebook + '" target="_blank">Facebook</a> '
}
if (brewery.untappd.contact.instagram.length > 0) {
content += '<a href="https://www.instagram.com/' + brewery.untappd.contact.instagram + '" target="_blank">Instagram</a> '
}
if (brewery.untappd.contact.twitter.length > 0) {
content += '<a href="https://twitter.com/' + brewery.untappd.contact.twitter + '" target="_blank">Twitter</a>'
}
if (brewery.untappd.beer_list.items.length > 0) {
content += '</p>'
content += '<p>Beer enthusiasts on Untappd really like the '
bestRated = brewery.untappd.beer_list.items.reduce(function (prev, curr) {
return (prev.beer.rating_score > curr.beer.rating_score) ? prev : curr
})
content += '<a href="https://untappd.com/beer/' + bestRated.beer.bid + '" target="_blank">' + bestRated.beer.beer_name + '</a>'
}
viewModel.infowindow.setOptions(
{
content: content
}
)
brewery.marker.setAnimation(null)
}
}
// This utility function doesn't ship with the minified version of Knockout!
// Search a string for a substring, return true if found
// Thank you Google user 'rpn' for defining a similar function
ko.utils.stringContains = function (string, substring) {
'use strict'
string = string || ''
if (substring.length > string.length) {
return false
}
return string.indexOf(substring) > -1
}
// A method to filter the list view
// Looks for user text or checkbox, then filters the array appropriately
viewModel.listView = ko.computed(function () {
'use strict'
var open2Public = viewModel.open2Public()
var keywords = viewModel.keywords().toLowerCase()
var filter = viewModel.filterby()
return ko.utils.arrayFilter(viewModel.brewery(), function (item) {
var check = filter === 'Name' ? item.brewery.name : item.locality
if (ko.utils.stringContains(check.toLowerCase(), keywords) && (!open2Public || item.openToPublic === 'Y')) {
item.marker.setVisible(true)
return true
} else {
item.marker.setVisible(false)
return false
}
})
})
// AJAX request to BreweryDB for all breweries in the state of Vermont
var breweriesRequest = new XMLHttpRequest()
breweriesRequest.open('GET', '/brewerydb/', true)
breweriesRequest.onreadystatechange = function () {
var brewModel = JSON.parse(breweriesRequest.responseText).data
brewModel.forEach(function (brewery) {
var model = brewery
model.marker = new google.maps.Marker(
{
position:
{
lat: model.latitude,
lng: model.longitude
},
map: map,
title: model.brewery.name
}
)
model.marker.addListener('click', function () {
viewModel.infoWindowChange(model)
})
viewModel.brewery.push(model)
if (brewModel.indexOf(brewery) === brewModel.length - 1) {
viewModel.brewery.sort(function (left, right) {
return left.brewery.name === right.brewery.name ? 0 : (left.brewery.name < right.brewery.name ? -1 : 1)
})
}
})
}
// Google Maps callback function
// Executes when async response completes
function initMap () {
map = new google.maps.Map(document.getElementById('map'), {
center: viewModel.center,
zoom: 8
})
viewModel.infowindow = new google.maps.InfoWindow(
{
content: '',
pixelOffset: new google.maps.Size(0, -30)
}
)
breweriesRequest.send()
}
// todo (add more graceful error handling)
function googleError () {
'use strict'
window.alert('Google Maps could not be reached.')
}
// apply bindings
ko.applyBindings(viewModel)
|
d8a6985d235fa780061c4cfc7664ace17bc96087
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
snowcrashdotdev/frontend-nanodegree-neighborhood-map
|
149899ffbd0e1b1d3aa633e7bee3f30bd53ecbc3
|
82eb273e8156f123d61419241c4ada515741064a
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.