language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Markdown | UTF-8 | 1,721 | 2.890625 | 3 | [] | no_license | ### Creating A Buggy App
Wait, why are we creating a buggy app? Well, so we can fix it! This repo has a [CloudFormation](https://aws.amazon.com/cloudformation/) template we can deploy. The template describes the infrastructure of an app, and the CloudFormation service takes that template and provisions the app into your AWS account.
The architecture of this app looks like:

To start, we're going to run a few commands that will use CloudFormation to provision the app:
```
aws cloudformation create-stack --stack-name sss-sns-to-db --template-url https://stackery-demo-assets.s3.amazonaws.com/template.yaml --capabilities CAPABILITY_AUTO_EXPAND CAPABILITY_IAM CAPABILITY_NAMED_IAM
```
This will start provisioning resources into your AWS account. It should take around a minute to deploy. You can monitor the status as it deploys by running the following command until the output says `CREATE_COMPLETE`:
```
aws cloudformation describe-stacks --stack-name sss-sns-to-db --output text --query 'Stacks[0].StackStatus'
```
#### If the stack fails to create...
If the stack fails to create successfully, you can issue the following command to see a log of the events. There will be a message in one of the events explaining why the stack failed to create.
```
aws cloudformation describe-stack-events --stack-name sss-sns-to-db --output text --query 'StackEvents[*].[ResourceType,LogicalResourceId,ResourceStatus,ResourceStatusReason]'
```
Then, run the following command to delete the broken stack so you can retry creating the stack:
```
aws cloudformation delete-stack --stack-name sss-sns-to-db
```
## [Continue To Module 2!](./Module-2.md) |
C++ | UTF-8 | 650 | 3.40625 | 3 | [] | no_license | #include <iostream.h>
#include <conio.h>
int arr[10];
int binarySearch(int s, int e, int tst)
{
static int pos=NULL;
int m=(s+e)/2;
if(pos==m)
return pos;
else if(tst<arr[m]) e=m;
else if(tst>arr[m]) s=m;
else if(e==s+1) return NULL;
else pos=m;
binarySearch(s, e, tst);
}
void main()
{
clrscr();
int n;
cout<<"\nEnter No. of Elements : ";cin>>n;
for(int i=0; i<n; i++)
cin>>arr[i];
int tst;
cout<<"\nEnter the No. you want to Search.";cin>>tst;
int pos=binarySearch(0, n, tst);
if(pos!=NULL)
cout<<"\nElement found at "<<pos+1;
else
cout<<"\nElement not found.";
getch();
}
|
C++ | WINDOWS-1252 | 22,739 | 2.890625 | 3 | [] | no_license | #include <windows.h>
#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <fstream>
#include "GestionTableau.h"
#include "Graphisme.h"
using namespace std;
//Dclaration de la fonction qui affichera un message d'erreur lorsque le nom dpasse 50 caractres
void afficheErreurTailleNom()
{
saisieXY("[ERREUR : LE CHAMP NOM NE PEUT DEPASSER CARACTERES. VEUILEZ REESSAYER!]", 54, 39, 4);
saisieXY(" ",61, 20, 0);
coloration(4);
gotoxy(96, 39);
cout << 50;
}
//Dclaration de la fonction qui affichera un message d'erreur lorsque le code dpasse 70 caractres
void afficheErreurTailleCode()
{
saisieXY("[ERREUR : LE CHAMP CODE NE PEUT DEPASSER CARACTERES. VEUILEZ REESSAYER!]", 54, 39, 4);
saisieXY(" ", 62, 22, 0);
coloration(4);
gotoxy(97, 39);
cout << 70;
}
//Dclaration de la fonction qui affichera un message d'erreur lorsque le PAYS dpasse 30 caractres
void afficheErreurTaillePays()
{
saisieXY("[ERREUR : LE CHAMP PAYS NE PEUT DEPASSER CARACTERES. VEUILEZ REESSAYER!]", 55, 39, 4);
saisieXY(" ", 59, 24, 0);
coloration(4);
gotoxy(97, 39);
cout << 30;
}
//Dclaration de la fonction qui affichera un message d'erreur lorsque le poids est ngatif
void afficheErreurPoids()
{
saisieXY("[ERREUR : CE POIDS N EST PAS VALIDE. VEUILEZ REESSAYER!]", 55, 39, 4);
saisieXY(" ", 129, 24, 0);
}
//Dclaration de la fonction qui affichera un message d'erreur lorsque l'anne est infrieure ou gal 0
void afficheErreurAn()
{
saisieXY("[ERREUR : CETTE ANNEE N EST PAS VALIDE. VEUILEZ REESSAYER!]", 55, 39, 4);
saisieXY(" ", 67, 28, 0);
}
//Dclaration de la fonction qui affichera un message d'erreur lorsque le mois est infrieur 0 ou suprieur 12
void afficheErreurMois()
{
saisieXY("[ERREUR : CE MOIS N EST PAS VALIDE. VEUILEZ REESSAYER!]", 55, 39, 4);
saisieXY(" ",138 , 28, 0);
}
//Dclaration de la fonction qui affichera un message d'erreur lorsque le jour est infrieur 0 ou suprieur 31
void afficheErreurJour()
{
saisieXY("[ERREUR : CE JOUR N EST PAS VALIDE. VEUILEZ REESSAYER!]", 55, 39, 4);
saisieXY(" ", 66, 30, 0);
}
//Dclaration de la fonction qui affichera un message d'erreur lorsque l'heure est infrieur 24
void afficheErreurHeure()
{
saisieXY("[ERREUR : CETTE HEURE N EST PAS VALIDE. VEUILEZ REESSAYER!]", 55, 39, 4);
saisieXY(" ", 139, 30, 0);
}
//Dclaration de la fonction qui va afficher une erreur si le tri index ne peut te effectue
void afficheErreurTri()
{
saisieXY("[ERREUR DE TRI: Le tableau des produits ne contient aucun element. veuillez le charger!]", 40, 39, 4);
resteMenuTableau();
}
//Dclaration de la fonction qui va afficher une erreur si la sauvegarde des produits ne peut tre effectue
void afficheErreurSauvegarde()
{
saisieXY("[ERREUR DE SAUVEGARDE: Le tableau des produits ne contient aucun element. veuillez le charger!]", 40, 39, 4);
resteMenuTableau();
}
//Dclaration de la fonction qui va afficher une erreur si l'affichage est impossible
void afficheErreurAffichage()
{
saisieXY("[ERREUR D AFFICHAGES DES PRODUITS: Le tableau peut etre vide ou non trie!]", 40, 39, 4);
resteMenuTableau();
}
//Dclaration de la fonction qui va controller la taille d'un tableau de caractere
void controleNom(char chaine[50])
{
if(strlen(chaine) > 50)
{
afficheErreurTailleNom();
fflush(stdin);
recupereNomPdrt();
}
}
//Dclaration de la fonction qui va controller la taille d'un tableau de caractere
void controleCode(char chaine[70])
{
if(strlen(chaine) > 70)
{
afficheErreurTailleNom();
fflush(stdin);
recupereCodePdrt();
}
}
//Dclaration de la fonction qui va controller la taille d'un tableau de caractere
void controlePays(char chaine[30])
{
if(strlen(chaine) > 30)
{
afficheErreurTailleNom();
fflush(stdin);
recuperePaysPdrt();
}
}
//Dclaration de la fonction qui va controller le poids des produits
void controlePoids(unsigned int poids)
{
if(poids < 0)
{
afficheErreurPoids();
fflush(stdin);
recuperePoidsPdrt();
}
}
//Dclaration de la fonction qui va controller le poids des produits
void controleAnne(unsigned int Annee)
{
if(Annee < 0)
{
afficheErreurAn();
fflush(stdin);
recupereAnPdrt();
}
}
//Dclaration de la fonction qui va controller le mois des produits
void controleMois(short int Mois)
{
if(Mois > 12)
{
afficheErreurMois();
fflush(stdin);
recupereMoisPdrt();
}
}
//Dclaration de la fonction qui va controller le jour des produits
void controleJour(short int Jour)
{
if(Jour > 32)
{
afficheErreurJour();
fflush(stdin);
recupereJourPdrt();
}
}
//Dclaration de la fonction qui va controller l'heure des produits
void controleHeure(short int Heure)
{
if(Heure > 31)
{
afficheErreurHeure();
fflush(stdin);
recupereHeurePdrt();
}
}
//Dclaration de la fonction qui recupera le nom des produits
char * recupereNomPdrt()
{
char chaineCaractere[50];
saisieXY("[IDENTIFICATION] ",30, 18, 8);
saisieXY("Nom du produit : ",43, 20);
coloration(10);
fflush(stdin);
do
{
gotoxy(61, 20);
cin.getline (chaineCaractere, 49);
controleNom(chaineCaractere);
}while(strlen(chaineCaractere) > 50);
return chaineCaractere;
}
//Dclaration de la fonction qui recupera le pays d'origine des produits
char * recuperePaysPdrt()
{
char chaineCaractere[30];
saisieXY("Pays d origine : ",43, 24);
do
{
coloration(10);
gotoxy(61, 24);
cin.getline (chaineCaractere, 29);
controlePays(chaineCaractere);
}while(strlen(chaineCaractere) > 30);
return chaineCaractere;
}
//Dclaration de la fonction qui recupera le pays d'origine des produits
char * recupereCodePdrt()
{
char chaineCaractere[70];
saisieXY("Code du produit : ",43, 22);
do
{
coloration(10);
gotoxy(62, 22);
cin.getline (chaineCaractere, 69);
controleCode(chaineCaractere);
}while(strlen(chaineCaractere) > 70);
return chaineCaractere;
}
//Dclaration de la fonction qui recupera le poids du produit
unsigned int recuperePoidsPdrt()
{
unsigned int poids;
saisieXY("Poids du produit : ",110, 24);
do
{
coloration(10);
gotoxy(129, 24);
cin >> poids;
controlePoids(poids);
}while(poids < 0);
return poids;
}
//Dclaration de la fonction qui recupera l'anne du produit
unsigned int recupereAnPdrt()
{
unsigned int An;
saisieXY("[DATE]",35, 27, 8);
saisieXY("Annee de fabrication : ",43, 28);
do
{
coloration(10);
gotoxy(67, 28);
cin >> An;
controleAnne(An);
}while(An < 0);
return An;
}
//Dclaration de la fonction qui recupera le mois du produit
short int recupereMoisPdrt()
{
short int Mois;
saisieXY("Moi de fabrication : ", 110, 28);
do
{
coloration(10);
gotoxy(131 , 28);
cin >> Mois;
controleMois(Mois);
}while((Mois > 13));
return Mois;
}
//Dclaration de la fonction qui recupera l'anne du produit
short int recupereJourPdrt()
{
short int jour;
saisieXY("Jour de fabrication : ",43, 30);
do
{
coloration(10);
gotoxy(66, 30);
cin >> jour;
controleJour(jour);
}while(jour > 32) ;
return jour;
}
//Dclaration de la fonction qui recupera l'heure de creation du produit
short int recupereHeurePdrt()
{
short int Heure;
saisieXY("Heure de fabrication : ",110, 30);
do
{
coloration(10);
gotoxy(133, 30);
cin >> Heure;
controleHeure(Heure);
}while(Heure > 25);
return Heure;
}
//Dclaration de la fonction qui va affecter un produit a un autre
void affectationProdt(TProduit &prdt2, TProduit &prdt1)
{
strcpy( prdt2.Nom, prdt1.Nom );
strcpy( prdt2.Code, prdt1.Code);
strcpy(prdt2.Pays_Origine, prdt1.Pays_Origine);
prdt2.Poids = prdt1.Poids;
prdt2.An_Fabric = prdt1.An_Fabric;
prdt2.Mois_Fabric = prdt1.Mois_Fabric;
prdt2.Jour_Fabric = prdt1.Jour_Fabric;
prdt2.Heure_Fabric = prdt1.Heure_Fabric;
}
//Dclaration de la fonction qui va affecter un Index un autre
void affectationIndex(TIndex_Poids &index2, TIndex_Poids &index1)
{
index2.Poids = index1.Poids;
index2.Position = index1.Position;
}
//Dclaratio de la fonction qui va effectuer une permutation de produit
void permutationPrdt(TProduit &prdt1, TProduit &prdt2)
{
TProduit intermediaire;
affectationProdt(intermediaire, prdt1);
affectationProdt(prdt1, prdt2);
affectationProdt(prdt2, intermediaire);
}
//Dclaration de la fonction qui va grer la rcupration des informations d'un tableau de produits
void gestionRecuperationPrdt(TProduit tableau[], int taille)
{
transitionMenus();
for (int i = 0; i < taille; i++)
{
saisieXY("3- Saisie des produits", 70, 6, 9);
saisieXY("PRODUIT :", 33, 15, 13);
gotoxy(41, 15);
cout << i + 1;
strcpy( tableau[i].Nom, recupereNomPdrt() );
strcpy( tableau[i].Code, recupereCodePdrt() );
strcpy(tableau[i].Pays_Origine, recuperePaysPdrt());
tableau[i].Poids = recuperePoidsPdrt();
tableau[i].An_Fabric = recupereAnPdrt();
tableau[i].Mois_Fabric = recupereMoisPdrt();
tableau[i].Jour_Fabric = recupereJourPdrt();
tableau[i].Heure_Fabric = recupereHeurePdrt();
transitionMenus();
}
gestionMenuTableau();
}
//Dclaration de la fonction qui va classer les produits par nom
void TriProduitNom(TProduit tab[], int taille, int pos) //Tri bulle amlior(stable)
{
TProduit inter;
int h;
if (pos < taille - 1)
{
h = taille - 1;
for (int a = taille - 1; a > pos; a--)
{
if (strcmp(tab[a - 1].Nom, tab[a].Nom) > 0)
{
affectationProdt(inter, tab[a]);
affectationProdt(tab[a], tab[a - 1]);
affectationProdt(tab[a - 1], inter);
h = a; //Position de la dernire modification
}
}
TriProduitPays(tab, taille, h);
}
}
//Dclaration de la fonction qui va trier les produits par pays
void TriProduitPays(TProduit tab[], int taille, int pos) //Tri bulle amlior(stable)
{
TProduit inter;
int h;
if (pos < taille - 1)
{
h = taille - 1;
for (int a = taille - 1; a > pos; a--)
{
if (strcmp(tab[a - 1].Pays_Origine, tab[a].Pays_Origine) > 0)
{
affectationProdt(inter, tab[a]);
affectationProdt(tab[a], tab[a - 1]);
affectationProdt(tab[a - 1], inter);
h = a; //Position de la dernire modification
}
}
TriProduitPays(tab, taille, h);
}
}
//Dclaration de la fonction qui va trier par ordre alphabtique
void triAlphabetique(TProduit tab[], int taille, int pos, bool Lu, bool restaure)
{
if ( ( Lu == true) || (restaure == true) )
{
transitionMenus();
TriProduitPays(tab, taille, pos);
TriProduitNom(tab, taille, pos);
progressionChargement("Tri des produits en cour...");
messageFini("Tri effectue avec succes!!!");
}
else
afficheErreurTri();
}
//Dclaration de la fonction qui va recuprer le tableau des Idex
void chargerTableauIndex(TProduit tab[], TIndex_Poids tabIndex[], int taille)
{
for (int i = 0; i < taille; i++)
{
tabIndex[i].Poids = tab[i].Poids;
tabIndex[i].Position = i;
}
}
//Dclaration de la fonction qui va trier le tableau des Index par poids
void triTabIndex(TProduit tabPrdts[], TIndex_Poids tabIndex[], int taille, bool Lu, bool restaure) //Tri par insertion squentiel(stable)
{
if ( ( Lu == true) || (restaure == true) )
{
TIndex_Poids temp;
transitionMenus();
chargerTableauIndex(tabPrdts, tabIndex, taille);
int k;
for (int i = 1; i < taille; i++)
{
affectationIndex(temp, tabIndex[i]);
k = i - 1;
while ( (k >= 0) && (tabIndex[k].Poids > temp.Poids) )
{
tabIndex[k + 1] = tabIndex[k];
k--;
}
affectationIndex(tabIndex[k + 1], temp);
}
progressionChargement("Tri des produits en cour...");
messageFini("[Tri effectue avec succes!!!]");
}
else
afficheErreurTri();
}
//Dclaration de la fonction qui ca classer les produits par mois
void triProduitAnnne(TProduit tab[], int taille) //Tri insertion dichotomique(stable)
{
TProduit inter;
int pos, k, milieu, borneInf, borneSup;
for (pos = 1; pos < taille; pos++)
{
if(tab[pos].An_Fabric < tab[pos - 1].An_Fabric)
{
borneInf = 0;
borneSup = pos - 1;
while (borneInf != borneSup)
{
milieu = (borneInf + borneSup) / 2;
if (tab[pos].An_Fabric >= tab[milieu].An_Fabric)
borneInf = milieu + 1;
else
borneSup = milieu;
}
affectationProdt(inter, tab[pos]);
for (k = pos; k > borneInf; k--)
affectationProdt(tab[k], tab[k - 1]);
affectationProdt(tab[borneInf], inter);
}
}
}
//Dclaration de la fonction qui ca classer les produits par mois
void triProduitMois(TProduit tab[], int taille) //Tri insertion dichotomique(stable)
{
TProduit inter;
int pos, k, milieu, borneInf, borneSup;
for (pos = 1; pos < taille; pos++)
{
if(tab[pos].Mois_Fabric < tab[pos - 1].Mois_Fabric)
{
borneInf = 0;
borneSup = pos - 1;
while (borneInf != borneSup)
{
milieu = (borneInf + borneSup) / 2;
if (tab[pos].Mois_Fabric >= tab[milieu].Mois_Fabric)
borneInf = milieu + 1;
else
borneSup = milieu;
}
affectationProdt(inter, tab[pos]);
for (k = pos; k > borneInf; k--)
affectationProdt(tab[k], tab[k - 1]);
affectationProdt(tab[borneInf], inter);
}
}
}
//Dclaration de la fonction qui vatrier les produits par jours
void triProduitJour(TProduit tab[], int taille) //Tri insertion dichotomique(stable)
{
TProduit inter;
int pos, k, milieu, borneInf, borneSup;
for (pos = 1; pos < taille; pos++)
{
if(tab[pos].Jour_Fabric < tab[pos - 1].Jour_Fabric)
{
borneInf = 0;
borneSup = pos - 1;
while (borneInf != borneSup)
{
milieu = (borneInf + borneSup) / 2;
if (tab[pos].Jour_Fabric >= tab[milieu].Jour_Fabric)
borneInf = milieu + 1;
else
borneSup = milieu;
}
affectationProdt(inter, tab[pos]);
for (k = pos; k > borneInf; k--)
affectationProdt(tab[k], tab[k - 1]);
affectationProdt(tab[borneInf], inter);
}
}
}
//Dclaration de ma fonction qui vatrier les produits par date de fabrication (anne, mois et jour de fabrication)
void triProduitDate(TProduit tab[], int taille, bool Lu, bool restaure)
{
if ( ( Lu == true) || (restaure == true) )
{
transitionMenus();
triProduitJour(tab, taille);
triProduitMois(tab, taille);
triProduitAnnne(tab, taille);
progressionChargement("Tri des produits en cour...");
messageFini("[Tri effectue avec succes!!!]");
}
else
afficheErreurTri();
}
//Dclaration de la fonction qui va rcuprer le nom du fichier
char * recupereFichier()
{
transitionMenus();
char nomFichier[90];
saisieXY("Veuillez entrer le nom du fichier :", 30, 20);
positionneCurseur(68, 20, 10);
cin >> nomFichier;
strcat(nomFichier, ".PRD");
return nomFichier;
}
//Dclaration de la fonction qui va crire les produits dans le fichier
void sauvegarderPrdt(TProduit tab[], int taille, bool Lu, bool restaure)
{
if ( ( Lu == true) || (restaure == true) )
{
transitionMenus();
char nomFichier[90];
strcpy(nomFichier, recupereFichier());
transitionMenus();
ofstream fichier (nomFichier, ios::out|ios::binary|ios::app) ; // ouverture du fichier en en mode binaire (criture et ajout en fin du fichier)
if (!fichier)
{
saisieXY("[ERREUR : CREATION IMPOSSIBLE!]", 54, 39, 4);
}
else
{
for (int i = 0; i < taille; i++)
fichier.write ((char *)&tab[i], sizeof(TProduit) ) ;
}
fichier.close ();
progressionChargement("Sauvegarde des produits en cour...");
messageFini("[Sauvegarde effectuee avec succes!!!]");
}
else
afficheErreurSauvegarde();
}
//Dclatation de la fonction qui va calculer le nombre de produits dans le fichier des produits
int compterElemtFichier(char nomFichier[90])
{
TProduit tab[90];
int i = 0;
ifstream fichier (nomFichier, ios::in|ios::binary) ; // ouverture du fichier en en mode binaire (lecture du fichier)
while(!fichier.eof())
{
fichier.read((char *)&tab[i], sizeof(TProduit) );
i++;
}
fichier.close();
return i - 1;
}
//Dclaration de la fonction qui effectue le travail dans le fichier lors de la restauration d'un tableau de produits
void operationRestauration(TProduit tab[], int taille, char nomFichier[90])
{
transitionMenus();
ifstream fichier (nomFichier, ios::in|ios::binary) ; // ouverture du fichier en en mode binaire (lecture du fichier)
if (!fichier)
{
saisieXY("[ERREUR : ERREUR LORS DE L OUVERTURE DU FCIHIER.!]", 54, 39, 4);
resteMenuTableau();
}
else
{
for (int i = 0; i < taille; i++)
fichier.read((char *)&tab[i], sizeof(TProduit) ) ;
progressionChargement("Restauration des produits en cour...");
}
fichier.close ();
}
//Dclaration de la fonction qui va afficher un message si la restauration est impossible
void afficheErreurRestauration()
{
transitionMenus();
saisieXY("[ERREUR LORS DE LA RESTAURATION DU FICHIER. LE FICHIER PEUT ETRE INEXISTANT", 63, 39, 4);
resteMenuTableau();
}
//Dclaration de la fonction qui va lire les produits dans le fichier
void restaurerPrdt(TProduit tab[], int taille)
{
char nomFichier[90];
strcpy(nomFichier, recupereFichier());
int nombreDansLeFichier = compterElemtFichier(nomFichier);
if (taille < nombreDansLeFichier)
{
operationRestauration(tab, taille, nomFichier);
messageFiniRestauration(taille, nombreDansLeFichier);
}
else if (taille == nombreDansLeFichier)
{
operationRestauration(tab, taille, nomFichier);
messageFini("[Restauration effectue avec succes!!!!!]");
}
else
{
afficheErreurRestauration();
resteMenuTableau();
}
}
//Dclaration de la directive qui affiche les produits
void afficheProduits(TProduit tab[], int taille)
{
tracerCadreDynamique();
saisieXY("*** Affichage de la liste des produits [par lindex] ***",59, 10, 9);
saisieXY("[ NOM ] [ PAYS ] -- [JJ/MM/AAAA a HH (h)] -- [Poids(Kg)] -- [ CODE ]", 31, 14, 10);
for(int i = 0; i < taille; i++)
{
saisieXY(i + 1, 26, 16 + i, 3);
saisieXY(". [ ] [ ] -- [ / / a (h)] -- [ (Kg)] -- [ ]", 29, 16 + i, 3);
saisieXY(tab[i].Nom, 42, 16 + i, 3);
saisieXY(tab[i].Pays_Origine, 68, 16 + i, 3);
saisieXY(tab[i].Jour_Fabric, 86, 16 + i, 3);
saisieXY(tab[i].Mois_Fabric, 89, 16 + i, 3);
saisieXY(tab[i].An_Fabric, 92, 16 + i, 3);
saisieXY(tab[i].Heure_Fabric, 100, 16 + i, 3);
saisieXY(tab[i].Poids, 114, 16 + i, 3);
saisieXY(tab[i].Code, 131, 16 + i, 3);
cout << endl;
}
apresAffichageRetourTableau();
}
//Dclaration de la fonction qui va afficher les produits selon un ordre(alaphabetique, date)
void afficheTableauPrdtsTrie(TProduit tab[], int taille, bool Lu, bool restaure)
{
if ( ( Lu == true) || (restaure == true) )
{
afficheProduits(tab, taille);
}
else
afficheErreurAffichage();
}
//Dclaration de la directive qui va afficher les produits par poids
void affichageIndex (TProduit tabPrdt[], TIndex_Poids tabIndex[], int taille)
{
tracerCadreDynamique();
saisieXY("*** Affichage de la liste des produits [par lindex] ***",59, 10, 9);
saisieXY("[ NOM ] [ PAYS ] -- [JJ/MM/AAAA a HH (h)] -- [Poids(Kg)] -- [ CODE ]", 31, 14, 10);
for(int i = 0; i < taille; i++)
{
unsigned int ind = tabIndex[i].Position;
saisieXY(i + 1, 26, 16 + i, 3);
saisieXY(". [ ] [ ] -- [ / / a (h)] -- [ (Kg)] -- [ ]", 29, 16 + i, 3);
saisieXY(tabPrdt[ind].Nom, 42, 16 + i, 3);
saisieXY(tabPrdt[ind].Pays_Origine, 68, 16 + i, 3);
saisieXY(tabPrdt[ind].Jour_Fabric, 86, 16 + i, 3);
saisieXY(tabPrdt[ind].Mois_Fabric, 89, 16 + i, 3);
saisieXY(tabPrdt[ind].An_Fabric, 92, 16 + i, 3);
saisieXY(tabPrdt[ind].Heure_Fabric, 100, 16 + i, 3);
saisieXY(tabPrdt[ind].Poids, 114, 16 + i, 3);
saisieXY(tabPrdt[ind].Code, 131, 16 + i, 3);
cout << endl;
}
apresAffichageRetourTableau();
}
//Dclaration de la fonction qui va affciher les produits par index(poids)
void affichageTableauIndexTrie (TProduit tabPrdt[], TIndex_Poids tabIndex[], int taille, bool indexTrie)
{
if ( indexTrie == true)
{
affichageIndex(tabPrdt, tabIndex, taille);
apresAffichageRetourTableau();
}
else
afficheErreurAffichage();
}
|
C# | UTF-8 | 5,208 | 2.65625 | 3 | [] | no_license | using System.Reflection;
using AutoFixture.Idioms;
using Bstm.UnitTesting;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace Bstm.DirectoryServices.UnitTests
{
public class SearchFilterTests : TestBase
{
public SearchFilterTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
{
}
[Theory]
[AutoMoqData]
public void PublicInterfaceThrowsExceptionForNullArguments(GuardClauseAssertion assertion)
{
// Fixture setup
// Exercise system and verify outcome
assertion.Verify(typeof(SearchFilter).GetMethods(BindingFlags.Static));
}
[Fact]
public void EqualityCreatesCorrectSearchFilter()
{
// Fixture setup
// Exercise system
var filter = SearchFilter.Equality("displayName", "John Doe");
// Verify outcome
filter.ToString().Should().Be("(displayName=John Doe)");
}
[Fact]
public void NegationCreatesCorrectSearchFilter()
{
// Fixture setup
// Exercise system
var filter = SearchFilter.Negation("displayName", "John Doe");
// Verify outcome
filter.ToString().Should().Be("(!(displayName=John Doe))");
}
[Fact]
public void PresenceCreatesCorrectSearchFilter()
{
// Fixture setup
// Exercise system
var filter = SearchFilter.Presence("displayName");
// Verify outcome
filter.ToString().Should().Be("(displayName=*)");
}
[Fact]
public void AbsenceCreatesCorrectSearchFilter()
{
// Fixture setup
// Exercise system
var filter = SearchFilter.Absence("displayName");
// Verify outcome
filter.ToString().Should().Be("(!(displayName=*))");
}
[Fact]
public void GreaterThanOrEqualCreatesCorrectSearchFilter()
{
// Fixture setup
// Exercise system
var filter = SearchFilter.GreaterThanOrEqual("displayName", "John Doe");
// Verify outcome
filter.ToString().Should().Be("(displayName>=John Doe)");
}
[Fact]
public void LessThanOrEqualCreatesCorrectSearchFilter()
{
// Fixture setup
// Exercise system
var filter = SearchFilter.LessThanOrEqual("displayName", "John Doe");
// Verify outcome
filter.ToString().Should().Be("(displayName<=John Doe)");
}
[Fact]
public void AndCreatesCorrectSearchFilter()
{
// Fixture setup
// Exercise system
var filter = SearchFilter
.Equality("displayName", "John")
.And(SearchFilter.Presence("mail"))
.And(SearchFilter.Negation("sn", "Doe"));
// Verify outcome
filter.ToString().Should().Be("(&(displayName=John)(mail=*)(!(sn=Doe)))");
}
[Fact]
public void OrCreatesCorrectSearchFilter()
{
// Fixture setup
// Exercise system
var filter = SearchFilter
.Equality("displayName", "John")
.Or(SearchFilter.Presence("mail"))
.Or(SearchFilter.Negation("sn", "Doe"));
// Verify outcome
filter.ToString().Should().Be("(|(displayName=John)(mail=*)(!(sn=Doe)))");
}
[Fact]
public void AndWithOrCreatesCorrectSearchFilter()
{
// Fixture setup
// Exercise system
var filter = SearchFilter
.Equality("displayName", "John")
.And(SearchFilter.Presence("mail"))
.Or(SearchFilter.Equality("sn", "Doe"));
// Verify outcome
filter.ToString().Should().Be("(|(&(displayName=John)(mail=*))(sn=Doe))");
}
[Fact]
public void OrWithAndCreatesCorrectSearchFilter()
{
// Fixture setup
// Exercise system
var filter = SearchFilter
.Equality("displayName", "John")
.Or(SearchFilter.Presence("mail"))
.And(SearchFilter.Equality("sn", "Doe"));
// Verify outcome
filter.ToString().Should().Be("(&(|(displayName=John)(mail=*))(sn=Doe))");
}
[Fact]
public void ValueReturnsCorrectSearchFilterRepresentation()
{
// Fixture setup
// Exercise system
var filter = SearchFilter.GreaterThanOrEqual("displayName", "John Doe");
// Verify outcome
filter.Value.Should().Be("(displayName>=John Doe)");
}
[Fact]
public void ImplicitConversionOperatorReturnsCorrectSearchFilterRepresentation()
{
// Fixture setup
// Exercise system
string filter = SearchFilter.GreaterThanOrEqual("displayName", "John Doe");
// Verify outcome
filter.Should().Be("(displayName>=John Doe)");
}
}
} |
SQL | UTF-8 | 3,054 | 3.25 | 3 | [] | no_license | --
-- PostgreSQL database dump
--
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: -
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
SET search_path = public, pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: requests; Type: TABLE; Schema: public; Owner: -; Tablespace:
--
CREATE TABLE requests (
id integer NOT NULL,
trap_id character varying NOT NULL,
remote_ip character varying,
request_method character varying,
scheme character varying,
query_string character varying,
query_params jsonb,
cookies jsonb,
headers jsonb,
raw text,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
--
-- Name: requests_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--
CREATE SEQUENCE requests_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
--
-- Name: requests_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--
ALTER SEQUENCE requests_id_seq OWNED BY requests.id;
--
-- Name: schema_migrations; Type: TABLE; Schema: public; Owner: -; Tablespace:
--
CREATE TABLE schema_migrations (
version character varying NOT NULL
);
--
-- Name: traps; Type: TABLE; Schema: public; Owner: -; Tablespace:
--
CREATE TABLE traps (
id character varying NOT NULL,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: -
--
ALTER TABLE ONLY requests ALTER COLUMN id SET DEFAULT nextval('requests_id_seq'::regclass);
--
-- Name: requests_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--
ALTER TABLE ONLY requests
ADD CONSTRAINT requests_pkey PRIMARY KEY (id);
--
-- Name: traps_pkey; Type: CONSTRAINT; Schema: public; Owner: -; Tablespace:
--
ALTER TABLE ONLY traps
ADD CONSTRAINT traps_pkey PRIMARY KEY (id);
--
-- Name: index_requests_on_trap_id; Type: INDEX; Schema: public; Owner: -; Tablespace:
--
CREATE INDEX index_requests_on_trap_id ON requests USING btree (trap_id);
--
-- Name: unique_schema_migrations; Type: INDEX; Schema: public; Owner: -; Tablespace:
--
CREATE UNIQUE INDEX unique_schema_migrations ON schema_migrations USING btree (version);
--
-- Name: fk_rails_b6a996dabf; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY requests
ADD CONSTRAINT fk_rails_b6a996dabf FOREIGN KEY (trap_id) REFERENCES traps(id);
--
-- PostgreSQL database dump complete
--
SET search_path TO "$user",public;
INSERT INTO schema_migrations (version) VALUES ('20150708104805');
INSERT INTO schema_migrations (version) VALUES ('20150708122458');
|
Python | UTF-8 | 659 | 3.140625 | 3 | [] | no_license | import sys
import time
import logging
logging.basicConfig(format='%(message)s', level=logging.INFO)
PROBLEM = 'Reordering Train Cars'
def solve():
return ''
if __name__ == '__main__':
# Problem header
logging.info('@ '+PROBLEM)
global_time = time.time()
# Number of cases
cases = int(sys.stdin.readline())
# Deal with each case
for case in range(cases):
case_time = time.time()
sol = solve()
print("Case #%d: %s" % (case + 1, sol))
logging.info('@ Case {} time: '.format(time.time() - case_time))
# Total time
logging.info('@ Total time: {}'.format(time.time() - global_time))
|
Java | UTF-8 | 1,881 | 1.851563 | 2 | [] | no_license | package io.linx.prometheus;
import io.linx.prometheus.matchers.CustomMatchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.List;
import static org.cthul.matchers.CthulMatchers.matchesPattern;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
@WebIntegrationTest(randomPort = true)
public class PrometheusEndpointTest {
@Value("${local.server.port}")
int localServerPort;
RestTemplate template = new TestRestTemplate();
@Test
public void testMetricsExportedThroughPrometheusEndpoint() {
ResponseEntity<String> metricsResponse = template.getForEntity(getBaseUrl() + "/prometheus", String.class);
assertEquals(HttpStatus.OK, metricsResponse.getStatusCode());
assertTrue(MediaType.TEXT_PLAIN.isCompatibleWith(metricsResponse.getHeaders().getContentType()));
List<String> responseLines = Arrays.asList(metricsResponse.getBody().split("\n"));
assertThat(responseLines, CustomMatchers.exactlyNItems(1,
matchesPattern("# HELP httpsessions_max httpsessions_max")));
}
private String getBaseUrl() {
return "http://localhost:" + localServerPort;
}
}
|
Java | UTF-8 | 577 | 3.234375 | 3 | [] | no_license | package com.raf.calcul;
/**
* L'interface de notation.
*
* @param <T>
* la notation
* @author RAF
*/
public interface Notation<T> extends Comparable<T> {
/**
* Retourne une nouvelle notation résultant de l'ajout de la note à la notation.
*
* @param note
* la note
* @return la nouvelle notation
*/
T add(T note);
/**
* MRetourne une nouvelle notation résultant de la multiplication de la note à la notation.
*
* @param note
* la note
* @return la nouvelle notation
*/
T multiply(T note);
}
|
Python | UTF-8 | 795 | 3.328125 | 3 | [] | no_license | class LRUCache(object):
def __init__(self, store, size=10):
self.store = store
self.size = size
self.keys = []
self.cache = {}
def access(self, key):
if key in self.cache:
to_remove = self.keys.index(key)
del self.keys[to_remove]
self.keys.append(key)
else:
if len(self.keys) >= self.size:
evicted = self.keys.pop(0) # Evict least recently used
del self.cache[evicted]
self.keys.append(key)
self.cache[key] = self.store.get(key)
return self.cache[key]
store = dict((i, i) for i in xrange(0, 1000))
cache = LRUCache(store)
for i in xrange(0, 100):
print cache.access(i), cache.keys, len(cache.keys), len(cache.cache)
|
C | UTF-8 | 1,046 | 2.828125 | 3 | [] | no_license | #include "interpreter.h"
int evaluate(beat_context* ctx){
int stack_memory[MAX_STACK];
stack s = {stack_memory, 0};
char* cp = ctx->expression;
token t;
int n;
while(1){
//skip whitespace
while(*cp == ' ' || *cp == '\n' || *cp == '\t') cp++;
if(*cp == 0x00) break;
t = get_token(cp);
//HARDCODE: the name of the "number" token
if( strncmp(t.name, "ERROR", 5) == 0){
//if no token matches the current string, skip the character
//and continue from the next one
print(ERROR, "syntax error");
cp++;
} else if(t.name[0] == '$'){
// token is variable
int * var_addr = &ctx->var_1;
cp += 1;
var_addr += (*cp - 'a');
push(&s, *var_addr);
cp += 1;
} else if( strncmp(t.name, "number", 6) == 0 ){
n = parse_hex(cp);
push(&s, n);
//"remove" the number token from the input string
while( (*cp >= '0' && *cp <= '9') || (*cp >= 'A' && *cp <='F') ){
cp++;
}
} else {
t.directive(&s);
//"remove" the token from the input string
cp += strlen(t.name);
}
}
return pop(&s);
}
|
Java | UTF-8 | 1,336 | 2.265625 | 2 | [
"Apache-2.0"
] | permissive | package com.karcompany.productsearch.presenters;
import com.karcompany.productsearch.config.AppConfig;
import com.karcompany.productsearch.models.Result;
import com.karcompany.productsearch.models.productdetailsresponse.ProductDetails;
import com.karcompany.productsearch.views.ProductImagesView;
import com.karcompany.productsearch.views.RecentlyViewedView;
import javax.inject.Inject;
/**
* Created by pvkarthik on 2017-01-26.
*
* Presenter implementation which handles core features (show Recently viewed products).
*/
public class RecentlyViewedPresenterImpl implements RecentlyViewedPresenter {
private RecentlyViewedView mView;
private AppConfig mAppConfig;
@Inject
public RecentlyViewedPresenterImpl(AppConfig appConfig) {
mAppConfig = appConfig;
}
@Override
public void setView(RecentlyViewedView recentlyViewedView) {
mView = recentlyViewedView;
}
@Override
public void onStart() {
loadRecentlyViewed();
}
@Override
public void onResume() {
}
@Override
public void onPause() {
}
@Override
public void onStop() {
}
@Override
public void onDestroy() {
mView = null;
}
private void loadRecentlyViewed() {
Result[] recentProducts = mAppConfig.getRecentProducts();
if(recentProducts != null) {
if(mView != null) {
mView.updateRecentItems(recentProducts);
}
}
}
}
|
Markdown | UTF-8 | 3,251 | 2.96875 | 3 | [
"MIT"
] | permissive | ---
status: "active"
title: "Validating dependencies in your project with depcheck package"
layout: post
author: Wilson Mendes
date: '2021-04-22T09:13:00.419Z'
path: /posts/validating-dependencies-in-your-project-with-depcheck-package/
category: "post"
lang: en
tags: ['frontend', 'javascript', 'frontend', 'tip', 'js', 'tooling', 'architecture', 'dependencies']
---

## Introduction
This will be a quick post! Today I'll be sharing how to validate if your project dependency has beem used in your repository. This is a common issue as your project scales and you need to make sure you're not using, installing or even downloading unnecessary dependencies in your local environment, in your CI/CD pipelines or even deploying these packages in your production environment.
### Checking for unused project dependencies with depcheck
To make this a quick process, we can use a NPM package called [depcheck](https://www.npmjs.com/package/depcheck). This package will validate every dependency of your codebase and check if the dependency if you missing to declare some specific dependencies (in order to avoid imports of packages added as transitient dependencies by another dependency of your project) and if the packages have been used or not in your project folder.
### Creating a project to simulate the problem
To create our project inside a folder called `my-project`. Inside this folder, we can run a command `npm init -y`. This command will start a NPM project to be used as an example.
`gist:willmendesneto/fa5a3771487c6d9d89c1034a38456257`
The `package.json` file generated initially for this project won't have any dependencies, neither dev dependencies. As a next step, we'll install a new dev dependency, a NPM package called [perf-marks](https://www.npmjs.com/package/perf-marks) by using the command `npm install perf-marks --save-dev`.
`gist:willmendesneto/f7e7e1e1c67889ce55461e8da77d06a0`
When the command finishes, you might see a new field called `devDependencies` in your `package.json`.
`gist:willmendesneto/af151eeb8fcc74b5aa07e0d408087f87`
Now if you run the command `npx depcheck` you might see a message like that, listing `perf-marks` as an unused dependency.
`gist:willmendesneto/da7ad7137f22ac97aeb5623fbe84a42a`
And that's it! 🎉
### Ignoring a dependency in depcheck
In case you want to ignore a specific dependency for some reason, you can do it too! Just need to create a file called `.depcheckrc` at the root of your repository.
In this file, you can add `perf-marks` as a package to be ignored by depcheck validation.
`gist:willmendesneto/01f6e15a547e8ef50d5cab0fcbe76518`
So, in the next time you run `npx depcheck` command, the call should not return any error message.
Also, this is a video I recorded showing how to use `depcheck` package in your project. Enjoy 🤘🤘🤘
[](http://www.youtube.com/watch?v=lwnZCsafahM "Video showing how to use depcheck package")
<hr/>
### That’s all for now
I hope you enjoyed this reading as much as I enjoyed writing it. Thank you so much for reading until the end and see you soon!
🚀🚀🚀🚀🚀🚀
<hr />
### Cya 👋
|
C | UTF-8 | 1,908 | 3.65625 | 4 | [
"MIT"
] | permissive | // Satvik Choudhary
// 111601021
// 10.64.1.174
// Serial number c
// Question 4
// Assumption - Answers in the file out.txt. I am just giving the row numbers of queens for each successive columns. To get the answer in terminal just comment the freopen function in main 2nd line.
// Logic - recursive search or backtracking using bitmask.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef long long ll;
ll bit[100];
int k = 0;
ll one = 1;
void queen(ll mask, int size){
int i = 0, j, solve, m, n;
if(size == 8){
solve = 1;
for(i=0; i<64; i++){
if(mask & (one << i)) {
for(j=i+1; j<64; j++){
if(mask & (one << j)){
if(i/8 == j/8) solve = 0;
if(i%8 == j%8) solve = 0;
if(i%8 - i/8 == j%8 - j/8) solve = 0;
if(i%8 + i/8 == j%8 + j/8) solve = 0;
}
}
}
}
if(solve){
bit[k++] = mask;
}
return;
}
//printf("infinite. %lld\n", mask);
for(i = 0; i<8; i++){
solve = 0;
for(j = 0; j<size; j++){
if(mask & (one << (j*8+i))) solve = 1;
}
if(!solve) queen(mask | (one << (size*8 + i)), size+1);
}
}
int main(){
//freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
memset(bit, 0, sizeof(bit));
k = 0;
queen(0, 0);
printf("Total number of solutions is - %d\n", k);
printf("These solutions should be interpreted as row number for each successive column from left to right. And I am using 1 based indexing.\n");
int i = 0;
for(i = 0; i<k; i++){
for(int j = 0; j<64; j++){
if(bit[i] & (one << (j))) {
printf("%d", (j%8+1));
}
}
printf("\n");
}
printf("\n");
int b[8][8];
for(i = 0; i<k; i++){
memset(b, 0, sizeof(b));
for(int j = 0; j<64; j++){
if(bit[i] & (one << j)) b[j/8][j%8] = 1;
}
printf("%d\n", i);
int le, ri;
for(le = 0; le < 8; le++){
for(ri = 0; ri < 8; ri++){
printf("%d", b[le][ri]);
}
printf("\n");
}
printf("\n");
}
return 0;
}
|
Markdown | UTF-8 | 11,836 | 3 | 3 | [] | no_license | # CS_Books/Videos/学习资源 小齐精选
现在计算机书籍很多,单纯的罗列没有意义。
一本好书,或许会改变我们的一生;而一本烂书,可能会把我们带偏。
在这个项目里,我会把我看过的、认可的好书、优质的视频分享出来,并给出推荐理由。
### **先给本仓库点个 Star,让我知道这个对你有帮助,以便督促我继续更新,感谢。**
如果不知道从哪里开始看起、不知道学习路线是怎样的,建议先读读我的这篇学习路线的文章: #TODO
如何系统的自学?https://teachyourselfcs.com/
强烈推荐计算机趣味入门视频:
**Crash Computer Science** [B站链接](https://www.bilibili.com/video/BV1EW411u7th) [Youtube 链接](https://www.youtube.com/watch?v=O5nskjZ_GoI)
书籍目录:
| 类别 | 书名| 推荐理由 | 下载链接 |
| :--------- | :--: | -----------: |----------: |
| 算法 | 谷歌师兄刷题笔记 | 必看,不必多说 |[百度网盘链接](https://pan.baidu.com/s/1MWwkk-cg6fR0Ft0VOF75JQ) 密码: 349g |
| | Leetcode cookbook | 必看,不需多说 |[百度网盘链接](https://pan.baidu.com/s/1hYRK9jbqXebhChrLMKsSBg) 密码: rrr7 |
| | 《算法-第四版》 | 这本书非常适合初学者,强烈推荐。 |[百度网盘链接](https://pan.baidu.com/s/15LlLxj1fWI2lf38HpdPT_Q) 密码: khc7 |
| | 《算法导论》| 装x用的 | [百度网盘链接](https://pan.baidu.com/s/1LKGGIi7OWNR6mLDS3UXW6w) 密码: 9hwl |
| Linux| 《鸟哥私房菜》 | Linux 第一 |[百度网盘链接](https://pan.baidu.com/s/1eSJSuSWYz43KsdEQT5OuWQ) 密码: i9ar |
| 操作系统| 《深入理解计算机系统》CSAPP | 领略整个计算机世界 | |
| |《现代操作系统》|原理 + 算法 |[百度网盘链接](https://pan.baidu.com/s/154WG0FldbSO_cxKaig4TQg) 密码: p7w0 |
||《自己动手写操作系统》|从零开始实现一个操作系统内核|[百度网盘链接](https://pan.baidu.com/s/1ypL__CxDuSF6tLEgqDQKwg) 密码: 7cf0 |
||《操作系统真象还原》|从零开始实现操作系统 | [百度网盘链接](https://pan.baidu.com/s/1Jz80lw9S3B5lqkfaDtFJfw) 密码: 4f3o |
|计算机网络|《计算机网络-自顶向下方法》| 各大高校教材,强悍无须解释 | [百度网盘链接](https://pan.baidu.com/s/1S-u7hqmV5RHXEzeRey83LQ) 密码: cu10 |
||斯坦福大学 CS 144 计算机网络| 配套课程| [B 站链接](https://www.bilibili.com/video/av96841516/) |
|数据库 | 《MySQL 必知必会》|入门级,不讲原理,适合初学者| [百度网盘链接](https://pan.baidu.com/s/1ad4Wcq5MNN3gZES-7hZKgQ) 密码: vhn0 |
||《MySQL 技术内幕:InnoDB 存储引擎》|底层原理 | [百度网盘链接](https://pan.baidu.com/s/1WeK80JBLQ1KVB-HzsQGNWw) 密码: 5bv1 |
||《Redis 设计与实现》|Redis为什么这么快?|[百度网盘链接](https://pan.baidu.com/s/1whz5prBIbHVeYdVM_qlW_g) 密码: de2i |
| Java | 面试必看——JAVA核心知识点整理 | 面试小抄 | [百度网盘链接](https://pan.baidu.com/s/1bKLdoqsZxW8DBVUcDni_yg) 密码: m18b|
||《Java 技术核心 卷I》| 入门 Java 的基础书籍 | [百度网盘链接](https://pan.baidu.com/s/1ieVmgFCoGED-dYM_0o_8dw) 密码: vjiw |
||*Head First Java* | 入门书 | [百度网盘链接](https://pan.baidu.com/s/1wn0Lt8mq10bBJs2gFd_aBg) 密码: hout |
||*Effective Java* | 经典中的经典 | [百度网盘链接](https://pan.baidu.com/s/1d_8KxdBhDvBFQ6C1eezxiw) 密码: 3ku9 |
||《深入理解 Java 虚拟机》| 学习 JVM 必看 | [百度网盘链接](https://pan.baidu.com/s/1XgZAVhJHYjGmNEodu-FxAw) 密码: wpul |
||《Java 并发编程的艺术》|高并发必读 | [百度网盘链接](https://pan.baidu.com/s/1Y_XphroMZTA9HTZj9Mr86w) 密码: hl7d |
| Spring 框架|《Spring 实战》| 项目必须 | [百度网盘链接](https://pan.baidu.com/s/1pvYdr7_LjB9c9aGv7lJ75g) 密码: 6b6w |
| C/C++ | *C++ Primer*| 前几章讲 C,后面 C++ | [百度网盘链接](https://pan.baidu.com/s/1XYgb8fVoOXxv8ZwgyHrL7g) 密码: svw3 |
| |*Effective C++*| 经典中的经典 | [百度网盘链接](https://pan.baidu.com/s/1GWL5hWsd6SjdM0d4mrdsfQ) 密码: 7thh |
||*More Effective C++*| C++ 进阶 | [百度网盘链接](https://pan.baidu.com/s/1-EuYr3MUQBgAGgJXn8V8ZA) 密码: duoh |
所有书籍一键下载:在我的微信公众号【码农田小齐】回复【05】即可。

## 算法
- **谷歌师兄刷题笔记** [介绍](https://zhuanlan.zhihu.com/p/334996379) [百度网盘链接](https://pan.baidu.com/s/1MWwkk-cg6fR0Ft0VOF75JQ) 密码: 349g
- **Leetcode cookbook** [介绍](https://www.zhihu.com/zvideo/1313079117991636992) [百度网盘链接](https://pan.baidu.com/s/1hYRK9jbqXebhChrLMKsSBg) 密码: rrr7
- **《算法-第四版》** [百度网盘链接](https://pan.baidu.com/s/15LlLxj1fWI2lf38HpdPT_Q) 密码: khc7
这本书非常适合初学者,强烈推荐。
- **《算法导论》** [百度网盘链接](https://pan.baidu.com/s/1LKGGIi7OWNR6mLDS3UXW6w) 密码: 9hwl
曾在我的多个视频中提到,但是这本书更偏理论,证明比较多,对找工作可能帮助不大。
## 计算机基础:
### Linux
Linux 界的“圣经”:
- **《鸟哥私房菜》** [百度网盘链接](https://pan.baidu.com/s/1eSJSuSWYz43KsdEQT5OuWQ) 密码: i9ar
蝉联最受欢迎华语 Linux 书籍第一的位置,无人能撼动。
这是一本既能帮助你入门,又能随时备查的工具书。更特别的是鸟哥的写作风格,非常口语化,读起来感觉像是有人在跟你实时互动聊天。
建议想要学习的同学可以收藏一本电子版随时备查。第一次阅读的同学估计会被它的厚度吓到,但其实没有必要去一字一字的全部读完,快速的看完前面十章,你就会对 Linux 有一个初步的认识。以后需要用到哪些命令和知识随时再查就可以了。
### 操作系统
- **《深入理解计算机系统》** *Computer Systems A Programmer's perspective* 即 CSAPP
这本书将会带你领略整个计算机世界:把数字电路基础、二进制与指令集体系、汇编语言、程序设计及优化、存储器体系结构、链接与装载、进程、虚拟内存这一堆来自各不同的计算机学科的核心知识点串在一起。
[CMU 配套课程](http://csapp.cs.cmu.edu/3e/courses.html)
- **《现代操作系统》** [百度网盘链接](https://pan.baidu.com/s/154WG0FldbSO_cxKaig4TQg) 密码: p7w0
不仅介绍了原理,还讲解了操作系统的算法。
- **《自己动手写操作系统》** [百度网盘链接](https://pan.baidu.com/s/1ypL__CxDuSF6tLEgqDQKwg) 密码: 7cf0
这本书从零开始实现一个操作系统内核,一步步指导读者用汇编和C语言实现一个可运行的操作系统内核。看完之后对操作系统最基本的原理有比较好的理解。
**《操作系统真象还原》** [百度网盘链接](https://pan.baidu.com/s/1Jz80lw9S3B5lqkfaDtFJfw) 密码: 4f3o
这本书也是从零开始实现一个操作系统,并且将一些 prerequisite 都已经讲解到位,只需跟着做就好了。
### 计算机网络
- **《计算机网络-自顶向下方法》** [百度网盘链接](https://pan.baidu.com/s/1S-u7hqmV5RHXEzeRey83LQ) 密码: cu10
这本书首创采用自顶向下的方法讲解计算机网络的原理和协议,将网络分层逐一拆解讲解,自顶向下循序渐进,能够帮助读者快速的理解整个网络世界,也经常被各大高校作为计算机网络的教材而使用。
推荐课程:斯坦福大学 CS 144 计算机网络 [B 站链接](https://www.bilibili.com/video/av96841516/)
### 数据库
- **DDIA** 即 *Designing Data-Intensive Applications*
被很多大佬推荐过的一本书,以数据为核心,详细讲了各种数据存储模型,包括传统关系型数据库、NoSQL、大数据存储、流式数据存储等等,由浅入深。
- **《MySQL 必知必会》** [百度网盘链接](https://pan.baidu.com/s/1ad4Wcq5MNN3gZES-7hZKgQ) 密码: vhn0
入门级
是一本稍厚的小册子,书中没有讲太多数据库的底层原理,但是条理清晰、简明扼要的介绍了初学者应该掌握的基础知识。
- **《MySQL 技术内幕:InnoDB 存储引擎》** [百度网盘链接](https://pan.baidu.com/s/1WeK80JBLQ1KVB-HzsQGNWw) 密码: 5bv1
底层原理级
通过对数据库底层数据结构、工作机制的分析,告诉我们如何编写 SQL 语句才是高效的,告诉我们索引如何利用才能发挥最佳效果。
举几个面试常见的问题,联合索引为什么要最左匹配?数据库的隔离级别是怎么实现的?都可以在里面找到答案,数据库绝对是开发适合面试考察的重点。这本书是通过大量的例子和插图进行知识讲解,会给人留下很直观印象。
- **《Redis 设计与实现》** [百度网盘链接](https://pan.baidu.com/s/1whz5prBIbHVeYdVM_qlW_g) 密码: de2i
Redis 是世界上最受欢迎的非关系型数据库之一,常常用来当作缓存和 MySQL 配套使用。
Redis 本身的语法并不复杂,同学们可以找到很多这方面的语法教学资料。
面试时候常常会被问到,Redis 为什么会这么快?如果只是回答因为它是基于内存的数据库,那么面试就凉凉啦。真正的关键秘诀是在于 Redis 的设计与实现,阅读这本书你会发现,Redis 是通过一系列底层设计来保证它快速存取的性能。
## 语言和框架
### Java
- **面试必看——JAVA核心知识点整理** [百度网盘链接](https://pan.baidu.com/s/1bKLdoqsZxW8DBVUcDni_yg) 密码: m18b
- **《Java 技术核心 卷I》** [百度网盘链接](https://pan.baidu.com/s/1ieVmgFCoGED-dYM_0o_8dw) 密码: vjiw
入门 Java 的基础书籍
- ***Head First Java*** [百度网盘链接](https://pan.baidu.com/s/1wn0Lt8mq10bBJs2gFd_aBg) 密码: hout
也是入门书籍
- ***Effective Java*** [百度网盘链接](https://pan.baidu.com/s/1d_8KxdBhDvBFQ6C1eezxiw) 密码: 3ku9
不必多说,经典中的经典
我的介绍视频:[点击这里](https://www.zhihu.com/zvideo/1322665938030694400)
- **《深入理解 Java 虚拟机》** [百度网盘链接](https://pan.baidu.com/s/1XgZAVhJHYjGmNEodu-FxAw) 密码: wpul
学习 JVM 必看的书
- **《Java 并发编程的艺术》** [百度网盘链接](https://pan.baidu.com/s/1Y_XphroMZTA9HTZj9Mr86w) 密码: hl7d
高并发必读
- **《Spring 实战》** [百度网盘链接](https://pan.baidu.com/s/1pvYdr7_LjB9c9aGv7lJ75g) 密码: 6b6w
学习一门语言和框架我认为最好的方式就是做项目,Java 的 Spring 框架是必须要用的。
### C/C++
- ***C++ Primer*** [百度网盘链接](https://pan.baidu.com/s/1XYgb8fVoOXxv8ZwgyHrL7g) 密码: svw3
学习 C/C++ 的必备书。前几章讲 C 的,后面才是 C++,包含了 C++ 的方方面面。
- ***Effective C++*** [百度网盘链接](https://pan.baidu.com/s/1GWL5hWsd6SjdM0d4mrdsfQ) 密码: 7thh
经典中的经典,不论学习任何语言我都认为非常值得一读。对理解面向对象编程有非常大的帮助。
我的介绍视频:[点击这里](https://www.zhihu.com/zvideo/1322665938030694400)
- ***More Effective C++*** [百度网盘链接](https://pan.baidu.com/s/1-EuYr3MUQBgAGgJXn8V8ZA) 密码: duoh
进阶版
|
Java | UTF-8 | 319 | 2.34375 | 2 | [] | no_license | package algorithms.sorting.heap.operations;
import lombok.Getter;
/**
* Created by Chen Li on 2018/2/10.
*/
public abstract class AbstractHeapOperations<K extends Comparable<K>> implements HeapOperations<K> {
@Getter
protected int compares = 0;
protected abstract boolean isHigherPriority(K key1, K key2);
}
|
Java | UTF-8 | 2,846 | 1.617188 | 2 | [] | no_license | package com.motoli.apps.allsubjects;
/**
* Part of Project Motoli All Subjects
* for Education Technology For Development
* created by Aaron D Michaelis Borsay
* on 8/12/2015.
*/
final class Constants {
static final String LOGCAT = "My Logs";
static final String GUEST_NAME="Guest";
static final int NUMBER_CORRECT=5;
/*
* NOTICE:
* INA_ROW_CORRECT=INA_ROW_CORRECT_WORDS=1 currently but once app released
* INA_ROW_CORRECT=2 while INA_ROW_CORRECT_WORDS remains =1
*/
static final int INA_ROW_CORRECT_HIGHER=8;
static final int ALL_MAX_LEVELS=37;
static final int INA_ROW_CORRECT=2;
static final int INA_ROW_CORRECT_WORDS=1;
static final int MATH_OPERATIONS_INA_ROW_CORRECT=15;
static final int NUMBER_VARIABLES=8;
static final int NUMBER_VARIABLES_SIX=6;
static final int NUMBER_QN_VARIABLES=10;
static final int NUMBER_PHONIC_VARIABLES=10;
static final int NUMBER_SYLLABLE_VARIABLES=10;
static final int MATH_OPERATIONS_UPPER_VARIABLES=7;
static final int MATH_OPERATIONS_VARIABLES=11;
static final int MAX_CORRECT_INA_ROW=15;
/*
* Loader Switch Data
*/
static final int SECTIONS_LOADER=1;
static final int TRACING_LOADER=2;
static final int ACTIVITIES_LOADER=3;
static final int TRACING_SHAPES=4;
static final int TRACING_NUMBERS=5;
static final int MATH_SHAPE_LEVELS=8;
static final int ACTIVITY_CURRENT_SYLLABLES=9;
static final int MATCHING_PHONIC_LETTERS_WORDS=10;
static final int ACTIVITY_CURRENT_LETTERS=11;
static final int ACTIVITY_CURRENT_WRDS_LTRS=12;
static final int UPDATE_LEVELS=13;
static final int CURRENT_PHONIC_LETTERS=14;
static final int CURRENT_PHONIC_LETTERS_WORDS=15;
static final int CURRENT_SYLLABLE_WRDS=17;
static final int CURRENT_SYLLABLE=18;
static final int BOOKS_READ_ALOUD =19;
static final int BOOK_PAGES_READ_ALOUD=20;
static final int ACTIVITY_GROUP_SECTION_LEVEL_COMPLETE=21;
static final int CURRENT_WORDS=24;
static final int GUESS_WORDS=25;
static final int ALL_LOWERCASE_LETTERS=26;
static final int CURRENT_PHONIC_LETTERS_WORDS_SINGLE=27;
static final int SECTION_AWARDS_LOADER=29;
static final int CURRENT_EXTRA_PHONICS=28;
static final int CURRENT_MATH_SHAPES=30;
static final int EXTRA_MATH_SHAPES=31;
static final int MATHCING_MATH_SHAPE=32;
static final int MATH_SHAPES_SET=33;
static final int MATH_NUMBERS_SET=34;
static final int EXTRA_MATH_NUMBERS=35;
static final int MATH_OPERATIONS=36;
static final int UPDATE_SEPARATE_LEVELS=38;
static final int UPDATE_SEPARATE_LEVELS_FULL=39;
static final int RESET_LEVELS=40;
static final int SINGLE_DEFAULT = 41;
}
|
Java | UTF-8 | 3,011 | 3.84375 | 4 | [
"MIT"
] | permissive | package opgave2;
import java.util.Arrays;
public class SorteretTabel {
//vi starter med at lave nogle variabler
int[] array;
int a;
//We make differnet constructors debending on what we want to do with the input. Java knows what constructor to use
//for certain input types
public SorteretTabel(SorteretTabel a, SorteretTabel b) {
//arrays in java have a specifik lenght, so we need to make sure that we create the new array in the right way.
//we have used arraylist in python. Arraylist could also be used here, nut decided not to, as we have never used them in java before
//We want to add all the numbers from the to difrent tabels, even if they are the same, so we now know the length of the array
int g = a.array.length + b.array.length;
array = new int[g];
int ia = 0;
int ib = 0;
//we run the size of the new array, and use some logic to determine the what number is the biggest.
for (int i = 0; i < g; i++) {
if (ia == a.array.length || !(ib == b.array.length || a.array[ia] <= b.array[ib])) {
array[i] = b.array[ib++];
} else {
array[i] = a.array[ia++];
}
}
}
public boolean exists(int holger) {
//hehe, we thought we would use the length a bit more, so it is a variable now
//We could change it...
int f = array.length;
//we check every element of the array, and look for Holger
for (int i = 0; i <= f-1; i++) {
if (array[i] == holger) {
return true;
} else if (array[i] > holger) {
return false;
}
}
return false;
}
public int find(int holger) {
//we first determine if holger even exist
if(exists(holger)) {
//we call the helping function, with a starting and a end determitor
return helpFinder(holger, 0, array.length);
}else {
return -1;
}
}
private int helpFinder(int holger, int start, int end) {
//we use a while loop, to check if we have reached the end of the array
while (start < end) {
//we look at the middle of start and end
int i = (start + end - 1) / 2;
int elem = array[i];
if (elem == holger) {
return i;
} else if (elem < holger) {
//thay are sortet, so if holger is bigger then we have a new start location, if less the na new end location
start = i;
} else {
end = i;
}
if (end - start == 1) {
return -1;
}
}
return -1;
//we keep doing so, until we find Holger. of till the start is bigger than the end
}
public SorteretTabel(int[] a) {
array = a;
//we just make sure that what we have, is a sortet tabel
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
System.out.println("Fejl");
return;
}
}
}
public SorteretTabel(int a) {
//making an array with one element
int[] single = { a };
this.array = single;
}
public SorteretTabel() {
//empty array
int[] empty = {};
this.array = empty;
}
public String toString() {
//this function overrides the normal toString in Java, and lets us print the arrays
String s = Arrays.toString(array);
return s;
}
} |
C | UTF-8 | 3,945 | 2.515625 | 3 | [
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | //------------------------------------------------------------------------------
// LAGr_SampleDegree: sample the degree median and mean
//------------------------------------------------------------------------------
// LAGraph, (c) 2019-2022 by The LAGraph Contributors, All Rights Reserved.
// SPDX-License-Identifier: BSD-2-Clause
//
// For additional details (including references to third party source code and
// other files) see the LICENSE file or contact permission@sei.cmu.edu. See
// Contributors.txt for a full list of contributors. Created, in part, with
// funding and support from the U.S. Government (see Acknowledgments.txt file).
// DM22-0790
// Contributed by Timothy A. Davis, Texas A&M University
//------------------------------------------------------------------------------
// LAGr_SampleDegree computes estimates of the mean and median of the
// row or column degree of a graph.
#define LG_FREE_ALL LAGraph_Free ((void **) &samples, NULL) ;
#include "LG_internal.h"
int LAGr_SampleDegree
(
// output:
double *sample_mean, // sampled mean degree
double *sample_median, // sampled median degree
// input:
const LAGraph_Graph G, // graph of n nodes
bool byout, // if true, sample G->out_degree, else G->in_degree
int64_t nsamples, // number of samples
uint64_t seed, // random number seed
char *msg
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
LG_CLEAR_MSG ;
int64_t *samples = NULL ;
LG_ASSERT (sample_mean != NULL, GrB_NULL_POINTER) ;
LG_ASSERT (sample_median != NULL, GrB_NULL_POINTER) ;
nsamples = LAGRAPH_MAX (nsamples, 1) ;
LG_TRY (LAGraph_CheckGraph (G, msg)) ;
GrB_Vector Degree ;
if (G->kind == LAGraph_ADJACENCY_UNDIRECTED ||
(G->kind == LAGraph_ADJACENCY_DIRECTED &&
G->is_symmetric_structure == LAGraph_TRUE))
{
// the structure of A is known to be symmetric
Degree = G->out_degree ;
}
else
{
// A is not known to be symmetric
Degree = (byout) ? G->out_degree : G->in_degree ;
}
LG_ASSERT_MSG (Degree != NULL, LAGRAPH_NOT_CACHED, "degree unknown") ;
//--------------------------------------------------------------------------
// allocate workspace
//--------------------------------------------------------------------------
LG_TRY (LAGraph_Malloc ((void **) &samples, nsamples, sizeof (int64_t),
msg)) ;
//--------------------------------------------------------------------------
// pick nsamples nodes at random and determine their degree
//--------------------------------------------------------------------------
// See also the hashed sampling method in LG_CC_FastSV6, which computes a
// fast estimate of the mode of an integer vector. This method does not
// require a hash table. However, the mode estimator in LG_CC_FastSV6
// would be a good candidate to add as an LAGraph_SampleMode utility
// function.
GrB_Index n ;
GRB_TRY (GrB_Vector_size (&n, Degree)) ;
int64_t dsum = 0 ;
for (int k = 0 ; k < nsamples ; k++)
{
uint64_t result = LG_Random60 (&seed) ;
int64_t i = result % n ;
// d = Degree (i)
int64_t d ;
GRB_TRY (GrB_Vector_extractElement (&d, Degree, i)) ;
samples [k] = d ;
dsum += d ;
}
// find the mean degree
(*sample_mean) = ((double) dsum) / nsamples ;
// find the median degree
LG_qsort_1a (samples, nsamples) ;
(*sample_median) = (double) samples [nsamples/2] ;
//--------------------------------------------------------------------------
// free workspace and return result
//--------------------------------------------------------------------------
LG_FREE_ALL ;
return (GrB_SUCCESS) ;
}
|
SQL | UTF-8 | 2,340 | 3.3125 | 3 | [
"MIT"
] | permissive |
CREATE VIEW [Valid].[LearnerEmploymentStatusDenorm]
AS
SELECT
les.[UKPRN]
,les.[LearnRefNumber]
,les.[EmpStat]
,les.EmpId
,les.[DateEmpStatApp]
,les.[AgreeId]
,[EmpStatMon_BSI].ESMCode AS ESMCode_BSI
,[EmpStatMon_EII].ESMCode AS ESMCode_EII
,[EmpStatMon_LOE].ESMCode AS ESMCode_LOE
,[EmpStatMon_LOU].ESMCode AS ESMCode_LOU
,[EmpStatMon_PEI].ESMCode AS ESMCode_PEI
,[EmpStatMon_SEI].ESMCode AS ESMCode_SEI
,[EmpStatMon_SEM].ESMCode AS ESMCode_SEM
FROM
Valid.[LearnerEmploymentStatus] as les
left join Valid.[EmploymentStatusMonitoring] as [EmpStatMon_BSI]
on [EmpStatMon_BSI].LearnRefNumber=les.LearnRefNumber
AND [EmpStatMon_BSI].UKPRN = LES.UKPRN
and [EmpStatMon_BSI].DateEmpStatApp = les.DateEmpStatApp
and [EmpStatMon_BSI].[ESMType]='BSI'
left join Valid.[EmploymentStatusMonitoring] as [EmpStatMon_EII]
on [EmpStatMon_EII].LearnRefNumber=les.LearnRefNumber
AND [EmpStatMon_EII].UKPRN = LES.UKPRN
and [EmpStatMon_EII].DateEmpStatApp = les.DateEmpStatApp
and [EmpStatMon_EII].[ESMType]='EII'
left join Valid.[EmploymentStatusMonitoring] as [EmpStatMon_LOE]
on [EmpStatMon_LOE].LearnRefNumber=les.LearnRefNumber
AND [EmpStatMon_LOE].UKPRN = LES.UKPRN
and [EmpStatMon_LOE].DateEmpStatApp = les.DateEmpStatApp
and [EmpStatMon_LOE].[ESMType]='LOE'
left join Valid.[EmploymentStatusMonitoring] as [EmpStatMon_LOU]
on [EmpStatMon_LOU].LearnRefNumber=les.LearnRefNumber
AND [EmpStatMon_LOU].UKPRN = LES.UKPRN
and [EmpStatMon_LOU].DateEmpStatApp = les.DateEmpStatApp
and [EmpStatMon_LOU].[ESMType]='LOU'
left join Valid.[EmploymentStatusMonitoring] as [EmpStatMon_PEI]
on [EmpStatMon_PEI].LearnRefNumber=les.LearnRefNumber
AND [EmpStatMon_PEI].UKPRN = LES.UKPRN
and [EmpStatMon_PEI].DateEmpStatApp = les.DateEmpStatApp
and [EmpStatMon_PEI].[ESMType]='PEI'
left join Valid.[EmploymentStatusMonitoring] as [EmpStatMon_SEI]
on [EmpStatMon_SEI].LearnRefNumber=les.LearnRefNumber
AND [EmpStatMon_SEI].UKPRN = LES.UKPRN
and [EmpStatMon_SEI].DateEmpStatApp = les.DateEmpStatApp
and [EmpStatMon_SEI].[ESMType]='SEI'
left join Valid.[EmploymentStatusMonitoring] as [EmpStatMon_SEM]
on [EmpStatMon_SEM].LearnRefNumber=les.LearnRefNumber
AND [EmpStatMon_SEM].UKPRN = LES.UKPRN
and [EmpStatMon_SEM].DateEmpStatApp = les.DateEmpStatApp
and [EmpStatMon_SEM].[ESMType]='SEM'
|
Python | UTF-8 | 2,386 | 3.859375 | 4 | [] | no_license | # importing "heapq" to implement heap queue
import heapq
# initializing list
li = [5, 7, 9, 1, 3]
# using heapify to convert list into heap
heapq.heapify(li)
# printing created heap
print ("The created heap is : ",(list(li)))
heapq.heappush(li,8)
print ("The created heap is : ",(list(li)))
heapq.heappop(li)
print ("The created heap is : ",(list(li)))
class Node:
def __init__(self, value=0, left=None, right=None):
self.left = left
self.right = right
self.value = value
# Min heap is complete binary tree in which the value of each
# internal node is smaller than or equal to the values in the childeren.
# It's implemented via array because it's more efficient and allows to maintain
# the complete binary tree property.
# Possible to do it with Binary tree as well that will make it more complicated.
class BinHeap:
def __init__(self):
self.heapL = [0]
self.currentSize = 0
def minChild(self, i):
if ((i * 2) + 1 > self.currentSize):
return i * 2 # There is only one child
else:
if self.heapL[i * 2] < self.heapL[i * 2 + 1]: # compare childs
return i * 2
else:
return i * 2 + 1
def moveUp(self, i):
while i // 2 > 0: # i // 2 gives idx of parent i.e. if not root
if self.heapL[i] < self.heapL[i // 2]: # if parent is bigger then swap
tmp = self.heapL[i // 2]
self.heapL[i // 2] = self.heapL[i]
self.heapL[i] = tmp
i = i // 2 # Move up to parent
def moveDown(self, i):
while (i * 2) <= self.currentSize:
mc_idx = self.minChild(i)
if self.heapL[i] < self.heapL[mc_idx]: # if parent is bigger then swap
tmp = self.heapL[mc_idx]
self.heapL[mc_idx] = self.heapL[i]
self.heapL[i] = tmp
i = mc_idx # move down to the min child idx
def insert(self, val):
self.heapL.append(val)
self.currentSize += 1
self.moveUp(self.currentSize)
def delete(self):
ret_val = self.heapL[1]
self.heapL[1] = self.heapL[self.currentSize]
self.currentSize -= 1
self.heapL.pop()
self.moveDown(1)
return ret_val
def print(self):
print("heap: ", (list(self.heapL)))
H = BinHeap()
"""
H.insert(3)
H.insert(2)
H.insert(20)
H.insert(1)
"""
H.insert(5)
H.insert(7)
H.insert(9)
H.insert(1)
H.insert(3)
H.print()
print("min val: ", H.delete())
H.print()
print("min val: ", H.delete())
H.print()
|
Java | UTF-8 | 634 | 1.632813 | 2 | [] | no_license | package com.htsoft.oa.service.info;
import java.util.Date;
import java.util.List;
import com.htsoft.core.service.BaseService;
import com.htsoft.core.web.paging.PagingBean;
import com.htsoft.oa.model.info.Notice;
public abstract interface NoticeService extends BaseService<Notice> {
public abstract List<Notice> findByNoticeId(Long paramLong, PagingBean paramPagingBean);
public abstract List<Notice> findBySearch(Notice paramNotice, Date paramDate1, Date paramDate2,
PagingBean paramPagingBean);
public abstract List<Notice> findBySearch(String paramString, PagingBean paramPagingBean);
}
|
JavaScript | UTF-8 | 994 | 2.6875 | 3 | [] | no_license | const notificationAtStart = ''
const initialState = notificationAtStart
const notificationReducer = (state = initialState, action) => {
console.log('state now: ', state)
console.log('action', action)
switch (action.type) {
case 'CREATE_NOTIFICATION':
return action.data
case 'REMOVE_NOTIFICATION':
return ''
default:
return state
}
}
export const createNotification = (content, time) => {
return async (dispatch) => {
dispatch({
type: 'CREATE_NOTIFICATION',
data: content
})
setTimeout(() => {
dispatch({
type: 'REMOVE_NOTIFICATION',
})
}, time * 1000)
}
}
export const removeNotification = (id) => {
return {
type: 'REMOVE_NOTIFICATION',
data: {
id
}
}
}
export default notificationReducer |
SQL | UTF-8 | 1,484 | 3.1875 | 3 | [] | no_license | CREATE TABLE CRM_T_BIZ_CHAIN_CONTACT
(
C_PID VARCHAR2(32) NOT NULL ENABLE,
C_ROLE VARCHAR2(10),
C_NAME VARCHAR2(20),
C_DUTY VARCHAR2(20),
C_PHONENUMBER VARCHAR2(20),
C_DECISION_WEIGHT VARCHAR2(20),
C_SUPPORT_LEVEL VARCHAR2(20),
C_BIZ_ORG_ID VARCHAR2(32)
)
tablespace TS_CRM
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
COMMENT ON COLUMN CRM_T_BIZ_CHAIN_CONTACT.C_PID IS 'primary key';
COMMENT ON COLUMN CRM_T_BIZ_CHAIN_CONTACT.C_ROLE IS '角色';
COMMENT ON COLUMN CRM_T_BIZ_CHAIN_CONTACT.C_NAME IS '姓名';
COMMENT ON COLUMN CRM_T_BIZ_CHAIN_CONTACT.C_DUTY IS '职务';
COMMENT ON COLUMN CRM_T_BIZ_CHAIN_CONTACT.C_PHONENUMBER IS '联系电话';
COMMENT ON COLUMN CRM_T_BIZ_CHAIN_CONTACT.C_DECISION_WEIGHT IS '决策权重';
COMMENT ON COLUMN CRM_T_BIZ_CHAIN_CONTACT.C_SUPPORT_LEVEL IS '对我司支持程度';
COMMENT ON COLUMN CRM_T_BIZ_CHAIN_CONTACT.C_BIZ_ORG_ID IS '商机组织ID';
COMMENT ON TABLE CRM_T_BIZ_CHAIN_CONTACT IS '商机决策链联系人表';
-- Create/Recreate indexes
-- Create/Recreate primary, unique and foreign key constraints
alter table CRM_T_BIZ_CHAIN_CONTACT
add constraint PT_M_T_BIZ_CHAIN_CONTACT primary key (C_PID)
using index
tablespace TS_CRM
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
); |
Shell | UTF-8 | 702 | 3.203125 | 3 | [] | no_license | #!/bin/bash
# Install dependencies (debbootstrap)
sudo apt-get install debootstrap curl
# Fetch the latest Kali debootstrap script from git
curl "http://git.kali.org/gitweb/?p=packages/debootstrap.git;a=blob_plain;f=scripts/kali;h=50d7ef5b4e9e905cc6da8655416cdf3ef559911e;hb=refs/heads/kali/master" > kali-debootstrap &&\
sudo debootstrap kali-rolling ./kali-root http://repo.kali.org/kali ./kali-debootstrap &&\
sudo tar -C kali-root -c . | sudo docker import - andrewkrug/kali-linux-docker &&\
sudo rm -rf ./kali-root &&\
TAG=rolling
echo "Tagging kali with $TAG" &&\
sudo docker tag andrewkrug/kali-linux-docker:latest andrewkrug/kali-linux-docker:$TAG &&\
echo "Build OK" || echo "Build failed!"
|
JavaScript | UTF-8 | 5,329 | 3.015625 | 3 | [
"MIT"
] | permissive | const ticTacToe = {
playerNames: {
player1: "Player 1",
player2: "Player 2"
},
rows: 3,
columns: 3,
turns: [],
currentPlayerId: "player1",
firebase: {
createId: function() {
return firebase
.database()
.ref("games")
.push().key;
},
createGame: function(gameId, playerId = "") {
firebase
.database()
.ref(`games/${gameId}`)
.set(
{
player1: playerId,
player2: ""
},
function(error) {
if (error) {
console.log(error);
} else {
//console.log("game created");
}
}
);
},
setPlayerIds: function(gameId, playerId, userId) {
firebase
.database()
.ref(`games/${gameId}/playerIds/${playerId}`)
.set(userId, function(error) {
if (error) {
console.log(error);
} else {
//console.log("player ID updated");
}
});
},
setPlayerName: function(gameId, playerName, playerId) {
firebase
.database()
.ref(`games/${gameId}/playerNames/${playerId}`)
.set(playerName, function(error) {
if (error) {
console.log(error);
} else {
//console.log("player name updated");
}
});
},
setCurrentPlayerId: function(gameId, currentPlayerId) {
firebase
.database()
.ref(`games/${gameId}/currentPlayerId`)
.set(currentPlayerId, function(error) {
if (error) {
console.log(error);
} else {
//console.log("set current player id");
}
});
},
onCurrentPlayerIdChange: function(gameId) {
firebase
.database()
.ref(`games/${gameId}/currentPlayerId`)
.on("value", function(snapshot) {
ticTacToe.currentPlayerId = snapshot.val() || "player1";
});
},
onTurnsChange: function(gameId, callBack) {
firebase
.database()
.ref(`games/${gameId}/turns`)
.on("value", callBack);
},
getGameData: function(gameId) {
return firebase
.database()
.ref(`games/${gameId}`)
.once("value")
.then(snapshot => {
console.log(snapshot.val());
});
},
onNameChange: function(gameId, callBack) {
firebase
.database()
.ref(`games/${gameId}/playerNames`)
.on("value", callBack);
},
setPlayerTurns: function(gameId, turns) {
firebase
.database()
.ref(`games/${gameId}/turns`)
.set(turns, function(error) {
if (error) {
console.log(error);
} else {
//console.log("added player turn to firebase");
}
});
}
},
addPlayerTurn: function(gameId, playerId, squareId) {
this.turns = [...this.turns, { player: playerId, square: squareId }];
this.firebase.setPlayerTurns(gameId, this.turns);
},
removePlayerTurn: function(gameId, playerId, squareId) {
this.turns = this.turns.filter(
turn => turn.square && turn.square !== squareId
);
this.firebase.setPlayerTurns(gameId, this.turns);
},
changePlayer: function(gameId) {
const playerIds = Object.keys(this.playerNames);
const indexOfNextPlayer = playerIds.indexOf(this.currentPlayerId) + 1;
const nextPlayer = playerIds[indexOfNextPlayer];
this.firebase.setCurrentPlayerId(gameId, nextPlayer || playerIds[0]);
},
getAllTurns: function(extraTurns = { playerIds: [], squareIds: [] }) {
const totalSquares = this.rows * this.columns;
const squares = Array.from({ length: totalSquares }).map(value => "");
const playerIds = [
...this.turns.map(turn => turn.player),
...extraTurns.playerIds
];
const squareIds = [
...this.turns.map(turn => turn.square),
...extraTurns.squareIds
];
const squareIndexes = squareIds.map(squareId =>
squareId.slice(squareIds[0].length - 1)
);
const convertToXAndO = squareIds.map((square, index) => {
if (playerIds[index] === "player1") return "cross";
return "nought";
});
squareIndexes.forEach((squareIndex, index) => {
squares[squareIndex] = convertToXAndO[index];
});
return squares;
},
checkWinner: function(extraTurns = { playerIds: [], squareIds: [] }) {
const indexesToCheck = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
const mapAllRows = indexesToCheck.map(row =>
row.map((square, index) => this.getAllTurns(extraTurns)[row[index]])
);
const isEqual = allSymbols =>
allSymbols.every((symbol, index, array) => symbol === array[0]);
const winningLines = mapAllRows.filter(row => isEqual(row));
const winner = winningLines
.map(winningLine => {
if (winningLine[0]) return winningLine[0];
})
.filter(each => each !== undefined)[0];
if (winner)
return winner === "cross"
? this.playerNames.player1
: this.playerNames.player2;
const maxTurns = this.rows * this.columns;
if (this.turns.length === maxTurns) return "none";
}
};
|
C | UTF-8 | 453 | 2.921875 | 3 | [] | no_license | /**
* \file Erreur.h
* \brief Macro Permettant d'affichier des erreurs
* \author PINTO Bruno
*
*
*/
#ifndef __ERREUR__
#define __ERREUR__
/* ### BIBLIOTHEQUE ### */
#include <stdio.h>
#include <stdlib.h>
/* ### MACRO ### */
#define ERROR(STR) fprintf(stderr, "%s ligne: %d dans %s\n", STR, __LINE__, __FILE__);
#define FATAL_ERROR(STR) {fprintf(stderr, "%s ligne: %d dans %s\n", STR, __LINE__, __FILE__); \
exit(EXIT_FAILURE);}
#endif
|
C++ | UTF-8 | 60,401 | 2.53125 | 3 | [
"MIT"
] | permissive | #define _WIN32_WINNT 0x0500
#include <iostream>
#include <windows.h>
#include <conio.h>
#include <time.h>
#include <queue>
#include <iomanip>
#include <sstream>
#include <fstream>
#define Void_Block 100
#define Grass_Block 101
#define Rabbit_Grass 102
#define Rabbit_Block 103
#define Hare_Grass 104
#define Hare_Block 105
#define Rabbit_Hare 106
#define Rabbit_Rabbit 107
#define Hare_Hare 108
#define Wolf_Grass 109
#define Wolf_Block 110
#define BitchWolf_Grass 111
#define BitchWolf_Block 112
#define Wolf_Hare 113
#define Wolf_Wolf 114
#define BitchWolf_BitchWolf 115
#define Wolf_Rabbit 116
#define BitchWolf_Rabbit 117
#define BitchWolf_Hare 118
#define Wolf_BitchWolf 119
#define cls system ("cls");
#define Male true
#define Female false
#include "gameprocess.h"
#include "animals.h"
using namespace std;
string Int_To_String (int Number) {
ostringstream NumToString;
NumToString << Number;
return NumToString.str();
} // функция перевода из int в string
class ModelProcess {
public:
int N; // размерность поля - кол-во строк
int M; // размерность поля - кол-во столбцов
int** Field; // поле модели
bool** Grass_Map; // расположение травы на карте
int Days; // кол-во дней, от начала работы модели
int CountGrass; // кол-во травы на карте
int HowRabbitsMan_OnMap; // кол-во зайцев на карте
int HowRabbitsWoman_OnMap; // кол-во зайчих на карте
int HowWolfsMan_OnMap; // кол-во волков на карте
int HowWolfsWoman_OnMap; // кол-во волчих на карте
string TimeOfYear; // время года
ModelProcess (int Rows, int Columns) {
this->N = Rows;
this->M = Columns;
Field = new int* [N];
Grass_Map = new bool* [N];
for (int i = 0; i < N; i++) {
Field[i] = new int [M];
Grass_Map[i] = new bool [M];
for (int c = 0; c < M; c++) {
Field[i][c] = Void_Block;
Grass_Map[i][c] = false;
}
}
this->Days = 0;
this->CountGrass = 0;
HowRabbitsMan_OnMap = 0;
HowRabbitsWoman_OnMap = 0;
HowWolfsMan_OnMap = 0;
HowWolfsWoman_OnMap = 0;
TimeOfYear = "\0";
}
~ModelProcess (void) {
for (int i = 0; i < N; i++) {
delete [] Field[i];
delete [] Grass_Map[i];
}
delete Field;
delete Grass_Map;
}
void Field_Clear (void) {
int Old_Field[N][M];
for (int i = 0; i < this->N; i++) {
for (int c = 0; c < this->M; c++) {
Old_Field[i][c] = Void_Block;
Grass_Map[i][c] = false;
if (Field[i][c] == Grass_Block || Field[i][c] == Rabbit_Grass || Field[i][c] == Hare_Grass || Field[i][c] == Wolf_Grass || Field[i][c] == BitchWolf_Grass) {
Old_Field[i][c] = Grass_Block;
Grass_Map[i][c] = true;
}
Field[i][c] = Void_Block;
}
}
for (int i = 0; i < this->N; i++)
for (int c = 0; c < this->M; c++)
Field[i][c] = Old_Field[i][c];
} // метод очистки поля
void Default_Settings (void) {
srand (time (NULL));
COORD coord;
coord=GetLargestConsoleWindowSize(GetStdHandle(STD_OUTPUT_HANDLE));
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),coord);
ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
keybd_event(VK_MENU,0x38,0,0);
keybd_event(VK_RETURN,0x1c,0,0);
keybd_event(VK_RETURN,0x1c,KEYEVENTF_KEYUP,0);
keybd_event(VK_MENU,0x38,KEYEVENTF_KEYUP,0);
SetCursorPos(0, 5000);
void *handle = GetStdHandle (STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO structCursorInfo;
GetConsoleCursorInfo (handle, &structCursorInfo);
structCursorInfo.bVisible = FALSE;
SetConsoleCursorInfo (handle, &structCursorInfo); // Отключение каретки
setlocale (LC_CTYPE, "Russian"); // Кириллица в консоли
system ("title Зайцы против волков"); // Заголовок программы
system ("color B"); // Светло-голубой цвет текста
} // метод настройки приложения
void CardLegend (GameProcess& Game, int Line) {
unsigned short int Number = 0;
string Str1 = "\0", Str2 = "\0";
switch (Line) {
case 0: Str1 = " Легенда карты"; Str2 = "\0"; Number = 11; break;
case 1: Str1 = " **"; Str2 = " - Трава"; Number = 10; break;
case 2: Str1 = " &&"; Str2 = " - Заяц"; Number = 15; break;
case 3: Str1 = " &&"; Str2 = " - Зайчиха"; Number = 14; break;
case 4: Str1 = " @@"; Str2 = " - Волк"; Number = 12; break;
case 5: Str1 = " @@"; Str2 = " - Волчиха"; Number = 13; break;
default: Str1 = "\0"; Str2 = "\0"; Number = 0; break;
}
SetConsoleTextAttribute (hConsole, (WORD) ((0 << 4) | Number));
cout << Str1;
Game.Set_BackgroundColor ();
cout << Str2;
} // метод отрисовки легенды карты
string Determine_TimeOfYear (void) {
int DaysCount = this->Days;
while (DaysCount > 364)
DaysCount -= 364;
if (DaysCount > 336 || DaysCount < 63)
TimeOfYear = "Зима";
else if (DaysCount > 62 && DaysCount < 155)
TimeOfYear = "Весна";
else if (DaysCount > 154 && DaysCount < 247)
TimeOfYear = "Лето";
else
TimeOfYear = "Осень";
return this->TimeOfYear;
} // метод, определяющий месяц года
void Random_Grass (void) {
for (int i = 0; i < this->N; i++) {
for (int c = 0; c < this->M; c++) {
if (Field[i][c] == Void_Block) {
unsigned short int Number = 0 + rand () % 101;
if (Number > 90)
this->Field[i][c] = Grass_Block;
}
}
}
} // метод рандомизации роста травы на карте
bool Random_Sex (void) {
unsigned short int Number = 0 + rand () % 101;
if (Number < 50)
return false;
return true;
} // метод рандомизации пола животного
int Random_Reproduction (string Animal) {
unsigned short int Number = 0 + rand () % 101;
if (Animal == "Rabbit") {
if (Number >= 0 && Number <= 33)
return 1;
else if (Number >= 34 && Number <= 66)
return 2;
else if (Number >= 67 && Number <= 100)
return 3;
} // для зайцев - от 1 до 5 особей
else if (Animal == "Wolf") {
if (Number >= 0 && Number <= 50)
return 1;
else if (Number >= 51 && Number <= 100)
return 2;
} // для волков - от 1 до 5 особей
return 0;
} // метод рандомизации кол-ва особей при рождении
int Data_Input (GameProcess& Game, string TypeDate) {
int Number = 0; // вводимое число
int LeftLimit = -1; // левая граница отрезка (левый предел)
int RightLimit = 0; // правая граница отрезка (правый предел)
if (TypeDate == "StartCount")
RightLimit = 1001;
else if (TypeDate == "Coordinates")
RightLimit = 10;
while (true) {
while (! (cin >> Number) || (cin.peek() != '\n')) {
cin.clear();
while (cin.get() != '\n');
Game.Center(": ");
}
if (Number > LeftLimit && Number < RightLimit)
break;
else {
Game.Center(": ");
cout << "Введите значение в диапазоне от " << LeftLimit + 1 << " до " << RightLimit - 1 << ": ";
}
}
return Number;
} // метод для корректного ввода данных
}; // класс модели
class ModelLogs {
public:
string Event_A; // первое событие - скрещивание волков
string Event_B; // второе событие - скрещивание зайцев
string Event_C; // третье событие - поедание волком зайца
int CountEvents_A; // кол-во первых событий
int CountEvents_B; // кол-во вторых событий
int CountEvents_C; // кол-во третих событий
ModelLogs (void) {
ClearEvents ();
ofstream Write_CountRabbits ("Rabbits.txt");
Write_CountRabbits << "\0";
Write_CountRabbits.close ();
ofstream Write_CountWolfs ("Wolfs.txt");
Write_CountWolfs << "\0";
Write_CountWolfs.close ();
ofstream Write_CountGrass ("Grass.txt");
Write_CountGrass << "\0";
Write_CountGrass.close ();
}
~ModelLogs (void) {}
void ClearEvents (void) {
Event_A = "\0";
Event_B = "\0";
Event_C = "\0";
CountEvents_A = 0;
CountEvents_B = 0;
CountEvents_C = 0;
} // очистка значений
void Show_Events (GameProcess& Game, int Line) {
unsigned short int Number = 0;
string Str1 = "\0", Str2 = "\0";
if (CountEvents_A > 0 || CountEvents_B > 0 || CountEvents_C > 0) {
switch (Line) {
case 6: Str1 = " События:"; Str2 = "\0"; Number = 11; break;
case 7: Str1 = " "; Str2 = Event_A; Number = 15; break;
case 8: Str1 = " "; Str2 = Event_B; Number = 15; break;
case 9: Str1 = " "; Str2 = Event_C; Number = 15; break;
default: Str1 = "\0"; Str2 = "\0"; Number = 0; break;
}
SetConsoleTextAttribute (hConsole, (WORD) ((0 << 4) | Number));
cout << Str1;
cout << Str2;
Game.Set_BackgroundColor ();
}
} // метод отображения событий
void Save_Logs_Output (ModelProcess& Model) {
ofstream Write_CountRabbits ("Rabbits.txt", ios::app);
Write_CountRabbits << Model.HowRabbitsMan_OnMap + Model.HowRabbitsWoman_OnMap << "\n";
Write_CountRabbits.close ();
ofstream Write_CountWolfs ("Wolfs.txt", ios::app);
Write_CountWolfs << Model.HowWolfsMan_OnMap + Model.HowWolfsWoman_OnMap << "\n";;
Write_CountWolfs.close ();
ofstream Write_CountGrass ("Grass.txt", ios::app);
Write_CountGrass << Model.CountGrass << "\n";
Write_CountGrass.close ();
} // сохранение данных модели во внешний файл
}; // класс логов модели
int Minimum_Count (int& DefaultCount, int& StartCount) {
if (DefaultCount < StartCount)
return DefaultCount;
return StartCount;
} // функция, возвращающая минимальное значение среди RabbitsCount / WolfsCount и StartAnimalCount соответствено
int main (void) {
GameProcess Game;
ModelProcess* Model = new ModelProcess (Game.Rows_Count, Game.Columns_Count);
ModelLogs Log;
Model->Default_Settings ();
unsigned short int Button = 0; // нажатая кнопка
bool Start = false; // первый запуск модели с новыми входными параметрами
while (true) { // жизненный цикл программы
Game.Preview ();
Game.Center("_________________________________________\n");
Game.Center("| Enter. Запуск биологической модели |\n");
Game.Center("|----------------------------------------|\n");
Game.Center("| Esc. Выход из программы |\n");
Game.Center("|________________________________________|\n");
while (true) {
Button = getch ();
if (Button == 27) {
Model->~ModelProcess();
free (Model);
exit (0);
}
else if (Button == 13)
break;
}
if (Button == 13) {
while (true) {
Button = 0;
Start = false;
queue <int> Field_Draw; // очередь на отрисовку поля
queue <int> Rabbit_Reproduction; // очередь на размножение зайцев
queue <int> Wolf_Reproduction; // очередь на размножение волков
cout.flush (); // очистка буфера в консоли
Game.Preview ();
Game.Center ("Выберите способ размещения первых животных в модели\n");
Game.Center ("_____________________________________________\n");
Game.Center ("| 1. Задать вручную |\n");
Game.Center ("|-------------------------------------------|\n");
Game.Center ("| 2. Рандомизировать размещение |\n");
Game.Center ("|-------------------------------------------|\n");
Game.Center ("| Esc. Вернуться в меню |\n");
Game.Center ("|___________________________________________|\n");
while (true) {
Button = getch ();
if (Button == 49 || Button == 50 || Button == 27 || Button == 55)
break;
}
if (Button == 27)
break;
cls;
Game.Preview ();
Game.Center ("Задайте начальные значения для размещения животных:\n\n");
Game.Center ("Максимальное количество зайцев в модели: ");
Game.RabbitsCount = Model->Data_Input (Game, "StartCount");
cout << "\n\n";
Game.Center ("Максимальное количество волков в модели: ");
Game.WolfsCount = Model->Data_Input (Game, "StartCount");
cout << "\n\n";
Game.Center ("Стартовое количество зайцев на карте: ");
Game.Rabbit_StartCount = Model->Data_Input (Game, "StartCount");
cout << "\n\n";
Game.Center ("Стартовое количество волков на карте: ");
Game.Wolf_StartCount = Model->Data_Input (Game, "StartCount");
Rabbits Rabbit[Game.RabbitsCount]; // массив объектов зайцев
Wolfs Wolf[Game.WolfsCount]; // массив объектов волков
while (true) { // жизненный цикл модели
if (Start == false) { // если это первый запуск
if (Button == 49) { // начало размещения животных вручную
cls;
Game.Preview();
Game.Center ("Задайте начальные координаты расположения для всех ");
cout << Game.RabbitsCount << " зайцев и " << Game.WolfsCount << " волков (карта " << Game.Rows_Count << "x" << Game.Columns_Count << "):\n\n";
Game.Center ("Расположение зайцев:\n");
for (int i = 0; i < Minimum_Count(Game.RabbitsCount, Game.Rabbit_StartCount); i++) {
Game.Center ("");
cout << "X[" << i + 1 << "]: ";
Rabbit[i].X = Model->Data_Input (Game, "Coordinates");
Game.Center ("");
cout << "Y[" << i + 1 << "]: ";
Rabbit[i].Y = Model->Data_Input (Game, "Coordinates");
cout << "\n";
}
cls;
Game.Preview ();
Game.Center ("Расположение волков:\n");
for (int i = 0; i < Minimum_Count(Game.WolfsCount, Game.Wolf_StartCount); i++) {
Game.Center ("");
cout << "X[" << i + 1 << "]: ";
Wolf[i].X = Model->Data_Input (Game, "Coordinates");
Game.Center ("");
cout << "Y[" << i + 1 << "]: ";
Wolf[i].Y = Model->Data_Input (Game, "Coordinates");
cout << "\n";
}
} // конец размещения животных вручную
else if (Button == 50) { // рандомное размещение животных
for (int i = 0; i < Minimum_Count(Game.RabbitsCount, Game.Rabbit_StartCount); i++) {
Rabbit[i].X = 0 + rand () % 10;
Rabbit[i].Y = 0 + rand () % 10;
} // рандомизация для зайцев
for (int i = 0; i < Minimum_Count(Game.WolfsCount, Game.Wolf_StartCount); i++) {
Wolf[i].X = 0 + rand () % 10;
Wolf[i].Y = 0 + rand () % 10;
} // рандомизация для волков
} // конец рандомного размещения животных
for (int i = 0; i < Minimum_Count(Game.RabbitsCount, Game.Rabbit_StartCount); i++) {
Rabbit[i].Life = true;
Rabbit[i].Sex = Model->Random_Sex ();
} // общие стартовые значения для зайцев
for (int i = 0; i < Minimum_Count(Game.WolfsCount, Game.Wolf_StartCount); i++) {
Wolf[i].Life = true;
Wolf[i].Sex = Model->Random_Sex ();
} // общие стартовые значения для волков
for (int i = 0; i < Model->N; i++) {
for (int c = 0; c < Model->M; c++)
Model->Field[i][c] = Void_Block;
}
Model->Days = 100; // старт дней с весны
Game.Rabbit_Breeding = true;
Game.Wolf_Breeding = true;
Start = true;
}
// начало работы модели
Model->CountGrass = 0;
Model->HowRabbitsMan_OnMap = 0;
Model->HowRabbitsWoman_OnMap = 0;
Model->HowWolfsMan_OnMap = 0;
Model->HowWolfsWoman_OnMap = 0;
cls;
Model->Random_Grass ();
Model->Field_Clear();
Log.ClearEvents ();
for (int i = 0; i < Model->N; i++) {
for (int k = 0; k < Model->M; k++)
cout << " _______";
cout << "\n";
for (int c = 0; c < Model->M; c++) {
for (int g = 0; g < Game.RabbitsCount; g++) {
if (Rabbit[g].Life == true) { // если заяц жив - существует
if (Rabbit[g].X == i && Rabbit[g].Y == c) { // если координата зайца соответствует ячейке на карте
if (Model->Grass_Map[i][c] == true) {
Rabbit[g].Food += 11;
Model->Field[i][c] = Void_Block;
Model->Grass_Map[i][c] = false; // один заяц - есть всю клетку с травой
} // в блок есть трава, зайцы ее съедят
if (g == 0) {
if (((Rabbit[g].Sex == true && Rabbit[g + 1].Sex == false) || (Rabbit[g].Sex == false && Rabbit[g + 1].Sex == true)) && (Rabbit[g].X == Rabbit[g + 1].X && Rabbit[g].Y == Rabbit[g + 1].Y)) {
Model->Field[i][c] = Rabbit_Hare;
}
} // в самой первой ячейке
else if (g > 0 && g < Game.RabbitsCount - 1) {
if (((Rabbit[g].Sex == true && Rabbit[g + 1].Sex == false) || (Rabbit[g].Sex == false && Rabbit[g + 1].Sex == true) || (Rabbit[g].Sex == true && Rabbit[g - 1].Sex == false) || (Rabbit[g].Sex == false && Rabbit[g - 1].Sex == true)) && ((Rabbit[g].X == Rabbit[g + 1].X && Rabbit[g].Y == Rabbit[g + 1].Y) || (Rabbit[g].X == Rabbit[g - 1].X && Rabbit[g].Y == Rabbit[g - 1].Y))) {
Model->Field[i][c] = Rabbit_Hare;
}
}
else if (g == Game.RabbitsCount - 1) {
if (((Rabbit[g].Sex == true && Rabbit[g - 1].Sex == false) || (Rabbit[g].Sex == false && Rabbit[g - 1].Sex == true)) && (Rabbit[g].X == Rabbit[g - 1].X && Rabbit[g].Y == Rabbit[g - 1].Y)) {
Model->Field[i][c] = Rabbit_Hare;
}
} // в самой первой ячейке
// случай когда заяц с зайяихой в одном блоке
if (Model->Field[i][c] == Rabbit_Hare) {
if (Model->TimeOfYear != "Зима" && Rabbit[g].Food > 5 && (Rabbit[g].MaxDays > 10 && Rabbit[g].MaxDays < 2100)) { // зимой размножения не будет
for (int k = 0; k < Model->Random_Reproduction("Rabbit"); k++) {
Rabbit_Reproduction.push(Rabbit[g].X);
Rabbit_Reproduction.push(Rabbit[g].Y);
}
Log.Event_B = "Скрещевание зайцев в ячейке [" + Int_To_String(Rabbit[g].X + 1) + "][" + Int_To_String(Rabbit[g].Y + 1) + "]";
Log.CountEvents_B++;
}
continue;
} // раз заяц в клетке с зайчихой, значит будут размножаться
else if (Model->Field[i][c] != Rabbit_Hare) { // если эта клетка не занята зайцем и зайчихой
if (Rabbit[g].Sex == true) { // если это заяц мужского пола
if (g == 0) { // для самой первой ячейки
if ( (Rabbit[g].Sex == true && Rabbit[g + 1].Sex == true) && ((Model->Field[i][c] == Rabbit_Block) || (Model->Field[i][c] == Rabbit_Grass) || (Model->Field[i][c] == Rabbit_Rabbit)) ) {
Model->Field[i][c] = Rabbit_Rabbit;
continue;
}
} // два зайца в одном блоке
else if (g > 0 && g < Game.RabbitsCount - 1) { // для всех остальных
if ( ((Rabbit[g].Sex == true && Rabbit[g + 1].Sex == true) || (Rabbit[g].Sex == true && Rabbit[g - 1].Sex == true)) && ((Model->Field[i][c] == Rabbit_Block) || (Model->Field[i][c] == Rabbit_Grass) || (Model->Field[i][c] == Rabbit_Rabbit)) ) {
Model->Field[i][c] = Rabbit_Rabbit;
continue;
}
} // два зайца в одном блоке
else if (g == Game.RabbitsCount - 1) { // для самой последней ячейки
if ( (Rabbit[g].Sex == true && Rabbit[g - 1].Sex == true) && ((Model->Field[i][c] == Rabbit_Block) || (Model->Field[i][c] == Rabbit_Grass) || (Model->Field[i][c] == Rabbit_Rabbit)) ) {
Model->Field[i][c] = Rabbit_Rabbit;
continue;
}
} // два зайца в одном блоке
if ( Model->Field[i][c] == Grass_Block || Model->Field[i][c] == Rabbit_Grass) // если в ячейке уже есть трава
Model->Field[i][c] = Rabbit_Grass;
else if (Model->Field[i][c] != Rabbit_Grass || Model->Field[i][c] == Void_Block) // если в ячейке нет травы
Model->Field[i][c] = Rabbit_Block;
} // конец мужского пола зайцев
else if (Rabbit[g].Sex == false) { // если это зайчиха женского пола
if (g == 0) { // для самой первой ячейки
if ( (Rabbit[g].Sex == false && Rabbit[g + 1].Sex == false) && ((Model->Field[i][c] == Hare_Block) || (Model->Field[i][c] == Hare_Grass) || (Model->Field[i][c] == Hare_Hare)) ) {
Model->Field[i][c] = Hare_Hare;
continue;
}
} // две зайчихи в одном блоке
else if (g > 0 && g < Game.RabbitsCount - 1) { // для всех остальных
if ( ((Rabbit[g].Sex == false && Rabbit[g + 1].Sex == false) || (Rabbit[g].Sex == false && Rabbit[g - 1].Sex == false)) && ((Model->Field[i][c] == Hare_Block) || (Model->Field[i][c] == Hare_Grass) || (Model->Field[i][c] == Hare_Hare)) ) {
Model->Field[i][c] = Hare_Hare;
continue;
}
} // две зайчихи в одном блоке
else if (g == Game.RabbitsCount - 1) { // для самой последней ячейки
if ( (Rabbit[g].Sex == false && Rabbit[g - 1].Sex == false) && ((Model->Field[i][c] == Hare_Block) || (Model->Field[i][c] == Hare_Grass) || (Model->Field[i][c] == Hare_Hare)) ) {
Model->Field[i][c] = Hare_Hare;
continue;
}
} // две зайчихи в одном блоке
if (Model->Field[i][c] == Grass_Block || Model->Field[i][c] == Rabbit_Grass) // если в ячейке уже есть трава
Model->Field[i][c] = Hare_Grass;
else if (Model->Field[i][c] != Rabbit_Grass || Model->Field[i][c] == Void_Block) // если в ячейке нет травы
Model->Field[i][c] = Hare_Block;
} // конец зайчихи женского пола
} // конец проверки, что заяц не находится в одной клетке с зайчихой
} // конец проверки координатов зайцев с полем
} // конец проверки жизни зайца
} // конец цикла перебора зайцев
////////////////////////////////////////////////////////////
for (int g = 0; g < Game.WolfsCount; g++) {
if (Wolf[g].Life == true) { // если волк жив - существует
if (Wolf[g].X == i && Wolf[g].Y == c) { // если координата зайца соответствует ячейке на карте
if ((Model->Field[i][c] == Rabbit_Grass || Model->Field[i][c] == Rabbit_Block || Model->Field[i][c] == Rabbit_Hare || Model->Field[i][c] == Rabbit_Rabbit) && (Wolf[g].X == Rabbit[g].X && Wolf[g].Y == Rabbit[g].Y)) {
if (Wolf[g].Sex == true)
Model->Field[i][c] = Wolf_Rabbit;
else if (Wolf[g].Sex == false)
Model->Field[i][c] = BitchWolf_Rabbit;
Rabbit[g].Life = false; // зайца съедают
Wolf[g].Food += 20; // волк кушает
Log.Event_C = "Волк съел зайца в ячейке [" + Int_To_String(Wolf[g].X + 1) + "][" + Int_To_String(Wolf[g].Y + 1) + "]";
Log.CountEvents_C++;
}
else if ((Model->Field[i][c] == Hare_Grass || Model->Field[i][c] == Hare_Block || Model->Field[i][c] == Hare_Hare) && (Wolf[g].X == Rabbit[g].X && Wolf[g].Y == Rabbit[g].Y)) {
if (Wolf[g].Sex == true)
Model->Field[i][c] = Wolf_Hare;
else if (Wolf[g].Sex == false)
Model->Field[i][c] = BitchWolf_Hare;
Rabbit[g].Life = false; // зайца съедают
Wolf[g].Food += 20; // волк кушает
Log.Event_C = "Волк съел зайца в ячейке [" + Int_To_String(Wolf[g].X + 1) + "][" + Int_To_String(Wolf[g].Y + 1) + "]";
Log.CountEvents_C++;
}
// волк с зайцем - в одной клетке
if (Model->Field[i][c] != Wolf_Rabbit && Model->Field[i][c] != Wolf_Hare && Model->Field[i][c] != BitchWolf_Rabbit && Model->Field[i][c] != BitchWolf_Hare) {
if (g == 0) {
if (((Wolf[g].Sex == true && Wolf[g + 1].Sex == false) || (Wolf[g].Sex == false && Wolf[g + 1].Sex == true)) && (Wolf[g].X == Wolf[g + 1].X && Wolf[g].Y == Wolf[g + 1].Y)) {
Model->Field[i][c] = Wolf_BitchWolf;
}
} // в самой первой ячейке
else if (g > 0 && g < Game.WolfsCount - 1) {
if (((Wolf[g].Sex == true && Wolf[g + 1].Sex == false) || (Wolf[g].Sex == false && Wolf[g + 1].Sex == true) || (Wolf[g].Sex == true && Wolf[g - 1].Sex == false) || (Wolf[g].Sex == false && Wolf[g - 1].Sex == true)) && ((Wolf[g].X == Wolf[g + 1].X && Wolf[g].Y == Wolf[g + 1].Y) || (Wolf[g].X == Wolf[g - 1].X && Wolf[g].Y == Wolf[g - 1].Y))) {
Model->Field[i][c] = Wolf_BitchWolf;
}
}
else if (g == Game.WolfsCount - 1) {
if (((Wolf[g].Sex == true && Wolf[g - 1].Sex == false) || (Wolf[g].Sex == false && Wolf[g - 1].Sex == true)) && (Wolf[g].X == Wolf[g - 1].X && Wolf[g].Y == Wolf[g - 1].Y)) {
Model->Field[i][c] = Wolf_BitchWolf;
}
} // в самой первой ячейке
// случай когда волк с волчихой в одном блоке
if (Model->Field[i][c] == Wolf_BitchWolf) {
if (Model->TimeOfYear != "Зима" && Wolf[g].Food > 15 && (Wolf[g].MaxDays > 500 && Wolf[g].MaxDays < 3600)) { // зимой размножения не будет
for (int k = 0; k < Model->Random_Reproduction("Wolf"); k++) {
Wolf_Reproduction.push(Wolf[g].X);
Wolf_Reproduction.push(Wolf[g].Y);
}
Log.Event_A = "Скрещевание волков в ячейке [" + Int_To_String(Wolf[g].X + 1) + "][" + Int_To_String(Wolf[g].Y + 1) + "]";
Log.CountEvents_A++;
}
continue;
} // раз волк в клетке с волчихой, значит будут размножаться
else if (Model->Field[i][c] != Wolf_BitchWolf) { // если эта клетка не занята волком и волчихой
if (Wolf[g].Sex == true) { // если это волк мужского пола
if (g == 0) { // для самой первой ячейки
if ( (Wolf[g].Sex == true && Wolf[g + 1].Sex == true) && ((Model->Field[i][c] == Wolf_Block) || (Model->Field[i][c] == Wolf_Grass) || (Model->Field[i][c] == Wolf_Wolf)) ) {
Model->Field[i][c] = Wolf_Wolf;
continue;
}
} // два волка в одном блоке
else if (g > 0 && g < Game.WolfsCount - 1) { // для всех остальных
if ( ((Wolf[g].Sex == true && Wolf[g + 1].Sex == true) || (Wolf[g].Sex == true && Wolf[g - 1].Sex == true)) && ((Model->Field[i][c] == Wolf_Block) || (Model->Field[i][c] == Wolf_Grass) || (Model->Field[i][c] == Wolf_Wolf)) ) {
Model->Field[i][c] = Wolf_Wolf;
continue;
}
} // два волка в одном блоке
else if (g == Game.WolfsCount - 1) { // для самой последней ячейки
if ( (Wolf[g].Sex == true && Wolf[g - 1].Sex == true) && ((Model->Field[i][c] == Wolf_Block) || (Model->Field[i][c] == Wolf_Grass) || (Model->Field[i][c] == Wolf_Wolf)) ) {
Model->Field[i][c] = Wolf_Wolf;
continue;
}
} // два волка в одном блоке
if ( Model->Field[i][c] == Grass_Block || Model->Field[i][c] == Wolf_Grass) // если в ячейке уже есть трава
Model->Field[i][c] = Wolf_Grass;
else if (Model->Field[i][c] != Wolf_Grass || Model->Field[i][c] == Void_Block) // если в ячейке нет травы
Model->Field[i][c] = Wolf_Block;
} // конец мужского пола волка
else if (Wolf[g].Sex == false) { // если это волчихи женского пола
if (g == 0) { // для самой первой ячейки
if ( (Wolf[g].Sex == false && Wolf[g + 1].Sex == false) && ((Model->Field[i][c] == BitchWolf_Block) || (Model->Field[i][c] == BitchWolf_Grass) || (Model->Field[i][c] == BitchWolf_BitchWolf)) ) {
Model->Field[i][c] = BitchWolf_BitchWolf;
continue;
}
} // две волчихи в одном блоке
else if (g > 0 && g < Game.WolfsCount - 1) { // для всех остальных
if ( ((Wolf[g].Sex == false && Wolf[g + 1].Sex == false) || (Wolf[g].Sex == false && Wolf[g - 1].Sex == false)) && ((Model->Field[i][c] == BitchWolf_Block) || (Model->Field[i][c] == BitchWolf_Grass) || (Model->Field[i][c] == BitchWolf_BitchWolf)) ) {
Model->Field[i][c] = BitchWolf_BitchWolf;
continue;
}
} // две волчихи в одном блоке
else if (g == Game.WolfsCount - 1) { // для самой последней ячейки
if ( (Wolf[g].Sex == false && Wolf[g - 1].Sex == false) && ((Model->Field[i][c] == BitchWolf_Block) || (Model->Field[i][c] == BitchWolf_Grass) || (Model->Field[i][c] == BitchWolf_BitchWolf)) ) {
Model->Field[i][c] = BitchWolf_BitchWolf;
continue;
}
} // две волчихи в одном блоке
if (Model->Field[i][c] == Grass_Block || Model->Field[i][c] == Wolf_Grass) // если в ячейке уже есть трава
Model->Field[i][c] = BitchWolf_Grass;
else if (Model->Field[i][c] != Wolf_Grass || Model->Field[i][c] == Void_Block) // если в ячейке нет травы
Model->Field[i][c] = BitchWolf_Block;
} // конец волчихи женского пола
} // конец проверки, что волк не находится в одной клетке с волчихой
} // конец проверки, что это не блок волков с зайцем
} // конец проверки координатов волков с полем
} // конец проверки жизни волков
} // конец цикла перебора волков
////////////////////////////////////////////////////////////
Field_Draw.push(Model->Field[i][c]);
if (Model->Field[i][c] == Grass_Block || Model->Field[i][c] == Rabbit_Grass || Model->Field[i][c] == Hare_Grass || Model->Field[i][c] == Wolf_Grass || Model->Field[i][c] == BitchWolf_Grass)
Model->CountGrass++;
} // конец просчета по столбцам
while (!Field_Draw.empty ()) {
Game.DrawBlock (Field_Draw.front ());
Field_Draw.pop ();
}
Model->CardLegend (Game, i);
Log.Show_Events (Game, i);
cout << "\n";
for (int k = 0; k < Model->M; k++)
cout << " |_____|";
cout << "\n\n";
} // конец просчета всего поля
for (int g = 0; g < Game.RabbitsCount; g++) {
if (Rabbit[g].Life == true) {
if (Rabbit[g].Sex == true)
Model->HowRabbitsMan_OnMap++;
else if (Rabbit[g].Sex == false)
Model->HowRabbitsWoman_OnMap++;
Rabbit[g].Move();
Rabbit[g].MaxDays -= 10;
if (Rabbit[g].MaxDays <= 0)
Rabbit[g].Life = false; // смерть от старости
Rabbit[g].Food--; // уменьшение запаса пищи в организме
if (Rabbit[g].Food <= 0)
Rabbit[g].Life = false; // смерть от голода
}
else if (Game.Rabbit_Breeding == true && Rabbit[g].Life != true && !Rabbit_Reproduction.empty()) {
Rabbit[g].Life = true;
Rabbit[g].Sex = Model->Random_Sex ();
Rabbit[g].X = Rabbit_Reproduction.front ();
Rabbit_Reproduction.pop ();
Rabbit[g].Y = Rabbit_Reproduction.front ();
Rabbit_Reproduction.pop ();
Rabbit[g].Food = 30;
Rabbit[g].MaxDays = 2200;
}
} // повторный проход по всем зайцам, для произведения вычислений
for (int g = 0; g < Game.WolfsCount; g++) {
if (Wolf[g].Life == true) {
if (Wolf[g].Sex == true)
Model->HowWolfsMan_OnMap++;
else if (Wolf[g].Sex == false)
Model->HowWolfsWoman_OnMap++;
Wolf[g].Move();
Wolf[g].Move();
Wolf[g].Move();
Wolf[g].MaxDays -= 10;
if (Wolf[g].MaxDays <= 0)
Wolf[g].Life = false; // смерть от старости
Wolf[g].Food -= 1; // уменьшение запаса пищи в организме
if (Wolf[g].Food <= 0)
Wolf[g].Life = false; // смерть от голода
}
else if (Game.Wolf_Breeding == true && Wolf[g].Life != true && !Wolf_Reproduction.empty()) {
Wolf[g].Life = true;
Wolf[g].Sex = Model->Random_Sex ();
Wolf[g].X = Wolf_Reproduction.front ();
Wolf_Reproduction.pop ();
Wolf[g].Y = Wolf_Reproduction.front ();
Wolf_Reproduction.pop ();
Wolf[g].Food = 50;
Wolf[g].MaxDays = 3700;
}
} // повторный проход по всем волкам, для произведения вычислений
Log.Save_Logs_Output (*Model);
Model->Days += 10;
Model->Determine_TimeOfYear ();
cout << "\nПрошло дней: " << Model->Days - 100 << setw (10) << " Время года: " << Model->TimeOfYear << "\n\n";
cout << "Количество зайцев: " << Model->HowRabbitsMan_OnMap << setw (10) << " Количество волков: " << Model->HowWolfsMan_OnMap << "\n\n";
cout << "Количество зайчих: " << Model->HowRabbitsWoman_OnMap << setw (10) << " Количество волчих: " << Model->HowWolfsWoman_OnMap << "\n\n";
cout << "Количество блоков с травой: " << Model->CountGrass;
if (Model->HowRabbitsMan_OnMap == 0 && Model->HowRabbitsWoman_OnMap == 0 && Model->HowWolfsMan_OnMap == 0 && Model->HowWolfsWoman_OnMap == 0)
cout << " | Ничья, погибли все!";
else {
if (Model->HowRabbitsMan_OnMap == 0 && Model->HowRabbitsWoman_OnMap == 0)
cout << " | Зайцы умерли, волки победили!";
else if (Model->HowWolfsMan_OnMap == 0 && Model->HowWolfsWoman_OnMap == 0)
cout << " | Волки умерли, зайцы победили!";
}
if (Game.Rabbit_Breeding == true && (Model->HowRabbitsMan_OnMap == 0 || Model->HowRabbitsWoman_OnMap == 0))
Game.Rabbit_Breeding = false;
if (Game.Wolf_Breeding == true && (Model->HowWolfsMan_OnMap == 0 || Model->HowWolfsWoman_OnMap == 0))
Game.Wolf_Breeding = false;
while (true) {
Button = getch ();
if (Button == 27 || Button == 13)
break;
} // продолжение / завершение работы модели
if (Button == 27)
break;
} // конец жизненного цикла модели
} // конец Button == 13
} // конец запуска модели
} // конец жизненного цикла программы
}
|
Java | UTF-8 | 2,973 | 4.09375 | 4 | [] | no_license | import java.util.*;
/*
249. Group Shifted Strings
Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
"abc" -> "bcd" -> ... -> "xyz"
Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"],
Return:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
Note: For the return value, each inner list's elements must follow the lexicographic order.
*/
/**
* HashMap solution
*
* The problem requires us to group strings with same shift pattern together.
* Shift pattern can be got from analyzing string itself.
* The difference between chars are numbers from 0 to 25, so the shift pattern can actually be represented by a string
* In this solution, I convert the difference to a small alphabet. So HashMap key will be a word consist from alphabets.
* Of course we can use other ways like appending delimiter after each char like 1#25#13, etc
*
* Time complexity: O(N)
* Space complexity: O(N)
*
* @author hpPlayer
* @date Feb 25, 2016 3:35:06 PM
*/
public class Group_Shifted_Strings_p249_sol1 {
public List<List<String>> groupStrings(String[] strings) {
//HashMap solution, we use HashMap to group strings. Key is the representation of shift pattern, value is list of strings having this pattern
//to avoid mixing each char's difference we use string as shift pattern representation
HashMap<String, List<String>> hs = new HashMap<String, List<String>>();
//sort the array first so all strings will be sorted in lexicographic order
Arrays.sort(strings);
for(String str : strings){
String key = getKey(str);
if(!hs.containsKey(key)) hs.put(key, new ArrayList<String>());
hs.get(key).add(str);
}
//we have grouped strings based on pattern, now add it to result list
List<List<String>> result = new ArrayList<List<String>>();
for(String key : hs.keySet()){
result.add(new ArrayList<String>(hs.get(key)));
}
return result;
}
public String getKey(String s){
StringBuilder sb = new StringBuilder();
//based on the diff between two chars, we can get the shift pattern
for(int i = 0; i < s.length() - 1; i++){
int diff = s.charAt(i+1) - s.charAt(i);
//diff may be negative like za and ab share same pattern, but za has diff = -25
//we need add 26 to convert it to positive. For positive diff, we leave it as it is
if(diff < 0) diff += 26;
//we convert diff to a small alphabet, so we can distinguish each diff
sb.append('a' + diff);
}
return sb.toString();
}
}
|
C# | UTF-8 | 887 | 2.6875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Adventure.Feature.EventSearchComponent.Filtering.Interfaces;
using Adventure.Feature.EventSearchComponent.Models;
namespace Adventure.Feature.EventSearchComponent.Filtering
{
public class SortByFilter : IFilter<EventSearchSettings, EventDetailsSearchItem>
{
public IQueryable<EventDetailsSearchItem> Execute(EventSearchSettings filterSettings,
IQueryable<EventDetailsSearchItem> input)
{
var methods = new Dictionary<string, Expression<Func<EventDetailsSearchItem, object>>>
{
{"name", i => i.Title},
{"difficulty", i => i.Difficulty},
{"date", i => i.StartDate}
};
return !string.IsNullOrWhiteSpace(filterSettings.OrderBy) && methods.ContainsKey(filterSettings.OrderBy)
? input.OrderBy(methods[filterSettings.OrderBy])
: input;
}
}
} |
Swift | UTF-8 | 450 | 2.953125 | 3 | [] | no_license | //
// WACurrentWeatherData.swift
// Weather-App
//
// Created by Дарья Астапова on 1.03.21.
//
import Foundation
struct WACurrentWeatherData: Decodable {
let name: String
let main: Main
let weather: [Weather]
}
struct Main: Decodable {
let temp: Double
let feelsLike: Double
enum CodingKeys: String, CodingKey {
case temp
case feelsLike = "feels_like"
}
}
struct Weather: Decodable {
let id: Int
}
|
Shell | UTF-8 | 509 | 2.640625 | 3 | [] | no_license | #!/bin/bash
# This script guides user through benchmarking process on Linux systems.
cd "${0%/*}" # This changes your current directory to the one where the file is placed
./make.sh
echo "Chess"
../build/benchmark ../extern/rbgGames/games/chess.rbg --depth 4
echo "Reversi"
../build/benchmark ../extern/rbgGames/games/reversi.rbg --depth 4
echo "Amazons"
../build/benchmark ../extern/rbgGames/games/amazons.rbg --depth 2
echo "TicTacToe"
../build/benchmark ../extern/rbgGames/games/ticTacToe.rbg --depth 9
|
C | UTF-8 | 218 | 2.6875 | 3 | [] | no_license | #include <stdio.h>
int main(int argc, char *argv[], char *envp[])
{
int i =0;
while(envp[i] != NULL)
{
if(strncmp(envp[i],"USER=", 5) ==0)
{
printf("Hello %s!\n", envp[i]+5);
}
i++;
}
return 0;
}
|
JavaScript | UTF-8 | 863 | 2.65625 | 3 | [] | no_license | import '@testing-library/jest-dom';
import {getHeroeById, getHeroesByOwner} from '../../base/08-imp-exp'
import heroes from '../../data/heroes'
// gives title
describe('08 test', () => {
//first test
test('return heros with id', ()=>{
const id = 1;
const hero = getHeroeById( id );
const heroeData = heroes.find(h => h.id === id);
expect(hero).toEqual(heroeData);
})
test('return heros with id undefiend', ()=>{
const id = 10;
const hero = getHeroeById( id );
const heroeData = heroes.find(h => h.id === id);
expect(hero).toBe(undefined);
})
test('return heros with owner', ()=>{
const owner = 'DC';
const hero = getHeroesByOwner( owner );
const heroeData = heroes.filter( (heroe) => heroe.owner === owner );
expect(hero).toEqual(heroeData);
expect(hero.length).toBe(3);
})
})
|
C++ | UTF-8 | 80,093 | 2.515625 | 3 | [] | no_license | // Universidade Federal do Rio Grande do Sul
// Instituto de Informática
// Departamento de Informática Aplicada
//
// INF01047 Fundamentos de Computação Gráfica
// Prof. Eduardo Gastal
//
// LABORATÓRIO 5
//
// Arquivos "headers" padrões de C podem ser incluídos em um
// programa C++, sendo necessário somente adicionar o caractere
// "c" antes de seu nome, e remover o sufixo ".h". Exemplo:
// #include <stdio.h> // Em C
// vira
// #include <cstdio> // Em C++
//
#include <cmath>
#include <cstdio>
#include <cstdlib>
// Headers abaixo são específicos de C++
#include <map>
#include <stack>
#include <string>
#include <vector>
#include <limits>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <algorithm>
// Headers das bibliotecas OpenGL
#include <glad/glad.h> // Criação de contexto OpenGL 3.3
#include <GLFW/glfw3.h> // Criação de janelas do sistema operacional
// Headers da biblioteca GLM: criação de matrizes e vetores.
#include <glm/mat4x4.hpp>
#include <glm/vec4.hpp>
#include <glm/gtc/type_ptr.hpp>
// Headers da biblioteca para carregar modelos obj
#include <tiny_obj_loader.h>
#include <stb_image.h>
// Headers locais, definidos na pasta "include/"
#include "utils.h"
#include "matrices.h"
//OBJETOS QUE SÃO DESENHADOS
#define TROPHY 0
#define FLOOR 1
#define TOWER 2
#define ROBOTTOP 3
#define ROBOTBOTTOM 4
#define SPHERE 5
#define CUBE 6
//TIPOS DE CAMERA
#define CHARACTER_CAMERA 1
#define LOOK_AT_CAMERA 2
#define FREE_CAMERA 3
//ESCALANDO .OBJS PARA TAMANHOS SENSATOS
#define ROBOT_SCALE 0.008f
#define TROPHY_SCALE 0.003f
#define TOWER_SCALE 0.4f
#define SPHERE_SCALE 0.4f
#define SPHERE_RADIUS 2.54558420181f //raio da esfera no .obj
#define WINDOW_SCALE 0.8
// Estrutura que representa um modelo geométrico carregado a partir de um
// arquivo ".obj". Veja https://en.wikipedia.org/wiki/Wavefront_.obj_file .
struct ObjModel
{
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
// Este construtor lê o modelo de um arquivo utilizando a biblioteca tinyobjloader.
// Veja: https://github.com/syoyo/tinyobjloader
ObjModel(const char* filename, const char* basepath = NULL, bool triangulate = true)
{
printf("Carregando modelo \"%s\"... ", filename);
std::string err;
bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, filename, basepath, triangulate);
if (!err.empty())
fprintf(stderr, "\n%s\n", err.c_str());
if (!ret)
throw std::runtime_error("Erro ao carregar modelo.");
printf("OK.\n");
}
};
// Declaração de funções utilizadas para pilha de matrizes de modelagem.
void PushMatrix(glm::mat4 M);
void PopMatrix(glm::mat4& M);
// Declaração de várias funções utilizadas em main(). Essas estão definidas
// logo após a definição de main() neste arquivo.
void BuildTrianglesAndAddToVirtualScene(ObjModel*); // Constrói representação de um ObjModel como malha de triângulos para renderização
void ComputeNormals(ObjModel* model); // Computa normais de um ObjModel, caso não existam.
void LoadShadersFromFiles(); // Carrega os shaders de vértice e fragmento, criando um programa de GPU
void LoadTextureImage(const char* filename); // Função que carrega imagens de textura
void DrawVirtualObject(const char* object_name, int bbox_id); // Desenha um objeto armazenado em g_VirtualScene
GLuint LoadShader_Vertex(const char* filename); // Carrega um vertex shader
GLuint LoadShader_Fragment(const char* filename); // Carrega um fragment shader
void LoadShader(const char* filename, GLuint shader_id); // Função utilizada pelas duas acima
GLuint CreateGpuProgram(GLuint vertex_shader_id, GLuint fragment_shader_id); // Cria um programa de GPU
void PrintObjModelInfo(ObjModel*); // Função para debugging
// Declaração de funções auxiliares para renderizar texto dentro da janela
// OpenGL. Estas funções estão definidas no arquivo "textrendering.cpp".
void TextRendering_Init();
float TextRendering_LineHeight(GLFWwindow* window);
float TextRendering_CharWidth(GLFWwindow* window);
void TextRendering_PrintString(GLFWwindow* window, const std::string &str, float x, float y, float scale = 1.0f);
void TextRendering_PrintMatrix(GLFWwindow* window, glm::mat4 M, float x, float y, float scale = 1.0f);
void TextRendering_PrintVector(GLFWwindow* window, glm::vec4 v, float x, float y, float scale = 1.0f);
void TextRendering_PrintMatrixVectorProduct(GLFWwindow* window, glm::mat4 M, glm::vec4 v, float x, float y, float scale = 1.0f);
void TextRendering_PrintMatrixVectorProductMoreDigits(GLFWwindow* window, glm::mat4 M, glm::vec4 v, float x, float y, float scale = 1.0f);
void TextRendering_PrintMatrixVectorProductDivW(GLFWwindow* window, glm::mat4 M, glm::vec4 v, float x, float y, float scale = 1.0f);
// Funções abaixo renderizam como texto na janela OpenGL algumas matrizes e
// outras informações do programa. Definidas após main().
void TextRendering_ShowModelViewProjection(GLFWwindow* window, glm::mat4 projection, glm::mat4 view, glm::mat4 model, glm::vec4 p_model);
void TextRendering_ShowProjection(GLFWwindow* window);
void TextRendering_ShowFramesPerSecond(GLFWwindow* window);
// Funções callback para comunicação com o sistema operacional e interação do
// usuário. Veja mais comentários nas definições das mesmas, abaixo.
void FramebufferSizeCallback(GLFWwindow* window, int width, int height);
void ErrorCallback(int error, const char* description);
void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mode);
void MouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
void CursorPosCallback(GLFWwindow* window, double xpos, double ypos);
void ScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
// Definimos uma estrutura que armazenará dados necessários para renderizar
// cada objeto da cena virtual.
struct SceneObject
{
std::string name; // Nome do objeto
size_t first_index; // Índice do primeiro vértice dentro do vetor indices[] definido em BuildTrianglesAndAddToVirtualScene()
size_t num_indices; // Número de índices do objeto dentro do vetor indices[] definido em BuildTrianglesAndAddToVirtualScene()
GLenum rendering_mode; // Modo de rasterização (GL_TRIANGLES, GL_TRIANGLE_STRIP, etc.)
GLuint vertex_array_object_id; // ID do VAO onde estão armazenados os atributos do modelo
glm::vec3 bbox_min; // Axis-Aligned Bounding Box do objeto
glm::vec3 bbox_max;
};
// Abaixo definimos variáveis globais utilizadas em várias funções do código.
// A cena virtual é uma lista de objetos nomeados, guardados em um dicionário
// (map). Veja dentro da função BuildTrianglesAndAddToVirtualScene() como que são incluídos
// objetos dentro da variável g_VirtualScene, e veja na função main() como
// estes são acessados.
std::map<std::string, SceneObject> g_VirtualScene;
// Pilha que guardará as matrizes de modelagem.
std::stack<glm::mat4> g_MatrixStack;
// Razão de proporção da janela (largura/altura). Veja função FramebufferSizeCallback().
float g_ScreenRatio = 1.0f;
// "g_LeftMouseButtonPressed = true" se o usuário está com o botão esquerdo do mouse
// pressionado no momento atual. Veja função MouseButtonCallback().
bool g_LeftMouseButtonPressed = false;
// Variáveis que definem um programa de GPU (shaders). Veja função LoadShadersFromFiles().
GLuint vertex_shader_id;
GLuint fragment_shader_id;
GLuint program_id = 0;
GLint model_uniform;
GLint view_uniform;
GLint projection_uniform;
GLint object_id_uniform;
GLint bbox_min_uniform;
GLint bbox_max_uniform;
// Número de texturas carregadas pela função LoadTextureImage()
GLuint g_NumLoadedTextures = 0;
//////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
//Nossas funções
void LoadLosingScreen(GLFWwindow* window); //Carrega tela de derrota (usuario foi atigido pelo meteoro)
void LoadWinningScreen(GLFWwindow* window); //Carrega tela de vitoria (usuario encostou no troféu)
void TowerTopCollisions();//Fazendo teste de colisão do ponto no topo da torre e o robo, se enconstar o jogador ganha
void MeteorCollisions(); //Fazendo testes de colisão do meteoro com o robo e as plataformas
bool CanPlatformMove(int platform_id, glm::mat4 towerModel); //Calcula se a plataforma pode andar (compara com torre e com robo)
bool CanRobotMove(glm::mat4 towerModel); //Calcula se a intersecção do robo com algo caso ele se mova
void BezierMeteorMove(float t); // Move o meteoro de acordo com o tempo e uma curva de bézier de grau 3
bool ComparePoint_AABB(glm::vec4 p, int bbox_id,glm::mat4 model);//Compara bbox com ponto, retorna true caso intersecção
bool CompareSphere_AABB(float radius, glm::vec4 center, int bbox_id,glm::mat4 model);
bool CompareAABB_AABB(int bbox_id1, glm::mat4 model1, int bbox_id2,glm::mat4 model2); //Compara duas bbox, retorna true caso intersecçao
void LoadCharacterCamera(GLFWwindow* window); //Calcula os vetor view_vector e as posições do centro e lookat da camera do personagem
void LoadLookAtCamera(glm::vec4 look_at_point); //Calcula os vetor view_vector e as posições do centro e lookat da camera lookat
void LoadFreeCamera(GLFWwindow* window); //Calcula os vetor view_vector e as posições do centro e lookat da camera free
void LoadTexturesAndModels(); //Carrega os modelos .obj e texturas que serão utilizadas
void DrawObjectModels(); //Desenha o modelo dos objetos na cena
glm::mat4 ComputeProjectionMatrix(); //Cria matriz de projeção
//VARIAVEIS QUE CONTROLAM SE O JOGADOR GANHOU/PERDEU O JOGO
bool lost_game = false;
bool won_game = false;
//DEFINIÇÕES DA CAMÊRA E POSIÇÃO DO PERSONAGEM
//POSIÇÃO REAL DO PERSONAGEM
glm::vec4 chr_pos = glm::vec4(0.0f,0.0f,15.0f,1.0f); //Posição atual do personagem
glm::vec4 chr_pos_old = glm::vec4(0.0f,0.0f,15.0f,1.0f); //Posição do personagem uma iteração atras
int camera_type = CHARACTER_CAMERA;
float chr_speed =12; //velocidade do robo
float chr_rotate_angle; //angulo de rotação do robo(acompanhará a camera)
float chr_cam_phi_max =0.1;//Controlando phi para a camera do personagem
float chr_cam_phi_min= chr_cam_phi_max - 0.25;
float gravity =5; //gravidade irá empurrar o personagem para baixo a cada 2 iterações
bool gravity_iteration = false; //uma a cada duas iterações irá empurrar o personagem para baixo
bool jump_activated =false; //se o personagem está pulando
bool can_jump = true;//se o robo está numa posição em que ele possa pular (em cima de uma plataforma/chão)
int jump_strength = 20; //o quão forte é o pulo
int jump_initial_height=0; //altura inicial ao pular
int jump_height = 2; //quantidade de passos de um pulo
float on_top_of_y = 0; //indica o chão mais próximo de onde o robo está ( a gravidade descerá até esse ponto)
//////////////////////////////////////////////////////////////////////
//DEFINIÇÕES DAS OUTRAS CAMERAS
float g_CameraTheta = 0.0; // Ângulo no plano ZX em relação ao eixo Z
float g_CameraPhi = -0.15f; // Ângulo em relação ao eixo Y
float g_CameraDistance = 5.0f; // Distância da câmera para camera_lookat_l (raio da esfera)
glm::vec4 camera_position_c, camera_lookat_l, camera_view_vector,w,u; //Vetores utilizados nos cálculos da câmera
glm::vec4 camera_up_vector = glm::vec4(0.0f,1.0f,0.0f,0.0f); // Vetor "up" fixado para apontar para o "céu" (eito Y global)
float r,x,y,z;
float camera_speed =5;
//////////////////////////////////////////////////////////////////////////////
// VARIAVEIS PARA AS DIMENSÕES DA TELA
int window_h;
int window_w;
int mousetype = 0; // 0 é mouse preso, 1 é mouse livre
////////////////////////////////////////////////////////////////////////////////////////////
//VÁRIAVEIS UTILIZADAS PARA GARANTIR QUE ANIMAÇÕES SEJAM INDEPENDENTES DE TEMPO DE EXECUÇÃO
float t_prev = glfwGetTime();
float t_dif,t_atual;
///////////////////////////////////////////////////
//PARA CRIAÇÃO E MOVIMENTAÇÃO DE PLATAFORMAS(CUBOS)
#define NUM_PLATFORMS 20
glm::mat4 random_cube_models[NUM_PLATFORMS];
float initialize = true; //Flag para sabermos se é necessario inicializar (model carregado somente uma vez)
float move_cubeX[NUM_PLATFORMS]; //Movimenta-se os cubos em relação a X pressionando Q
float move_cubeZ[NUM_PLATFORMS]; //Movimenta-se os cubos em relação a Z pressionando E
float move_cubeXOld[NUM_PLATFORMS]; //Posição do cubo uma iteração atras
float move_cubeZOld[NUM_PLATFORMS]; //Posiçao do cubo uma iteração atras
int on_top_of_platform = -1; //Indica que o robo está em cima desse cubo, o que impede o movimento do mesmo
///////////////////////////////////////////////////////
//ESFERA/METEORO
#define CURVE_TIME 15 //tempo que demora para a curva toda ser feita
glm::vec4 sphere_pos= glm::vec4(0.0f,15.0f,0.0f,1.0f);
float bzier_t = 0;
////////////////////////////////////////////////////
//BBOX DE TODOS OBJETOS QUE UTILIZAM COMPARAÇÕES
std::map<int,glm::vec4> mapBboxMax;
std::map<int,glm::vec4> mapBboxMin;
int main(int argc, char* argv[])
{
// Inicializamos a biblioteca GLFW, utilizada para criar uma janela do
// sistema operacional, onde poderemos renderizar com OpenGL.
int success = glfwInit();
if (!success)
{
fprintf(stderr, "ERROR: glfwInit() failed.\n");
std::exit(EXIT_FAILURE);
}
// Definimos o callback para impressão de erros da GLFW no terminal
glfwSetErrorCallback(ErrorCallback);
// Pedimos para utilizar OpenGL versão 3.3 (ou superior)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
// Pedimos para utilizar o perfil "core", isto é, utilizaremos somente as
// funções modernas de OpenGL.
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
window_w = mode->width;
window_h = mode->height;
GLFWwindow* window;
window = glfwCreateWindow(window_w*WINDOW_SCALE, window_h*WINDOW_SCALE, "Mr Robot Reaches the Top",NULL, NULL);
glfwSetWindowPos(window, 250, 50);
if (!window)
{
glfwTerminate();
fprintf(stderr, "ERROR: glfwCreateWindow() failed.\n");
std::exit(EXIT_FAILURE);
}
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); //ESCONDE CURSOR
// Definimos a função de callback que será chamada sempre que o usuário
// pressionar alguma tecla do teclado ...
glfwSetKeyCallback(window, KeyCallback);
// ... ou clicar os botões do mouse ...
glfwSetMouseButtonCallback(window, MouseButtonCallback);
// ... ou movimentar o cursor do mouse em cima da janela ...
glfwSetCursorPosCallback(window, CursorPosCallback);
// ... ou rolar a "rodinha" do mouse.
glfwSetScrollCallback(window, ScrollCallback);
// Indicamos que as chamadas OpenGL deverão renderizar nesta janela
glfwMakeContextCurrent(window);
// Carregamento de todas funções definidas por OpenGL 3.3, utilizando a
// biblioteca GLAD.
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
// Definimos a função de callback que será chamada sempre que a janela for
// redimensionada, por consequência alterando o tamanho do "framebuffer"
glfwSetFramebufferSizeCallback(window, FramebufferSizeCallback);
FramebufferSizeCallback(window,window_w*WINDOW_SCALE,window_h*WINDOW_SCALE); // Forçamos a chamada do callback acima, para definir g_ScreenRatio.
//Carregando as texturas e .objs que utilizamos
LoadTexturesAndModels();
// Inicializamos o código para renderização de texto.
TextRendering_Init();
// Habilitamos o Z-buffer. Veja slides 104-116 do documento Aula_09_Projecoes.pdf.
glEnable(GL_DEPTH_TEST);
// Habilitamos o Backface Culling. Veja slides 23-34 do documento Aula_13_Clipping_and_Culling.pdf.
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
// Variáveis auxiliares utilizadas para chamada à função
// TextRendering_ShowModelViewProjection(), armazenando matrizes 4x4.
glm::mat4 the_projection;
glm::mat4 the_model;
glm::mat4 the_view;
//inicializando cubos
for(int i=0; i< NUM_PLATFORMS; i++){
move_cubeZ[i] = 0;
move_cubeX[i] = 0;
move_cubeZOld[i] = 0;
move_cubeXOld[i] = 0;
}
srand(2); //Essa seed é boa pois cria um jogo nao muito dificil, pode trocar o valor para obter partidas diferentes
// Ficamos em loop, renderizando, até que o usuário feche a janela
while (!glfwWindowShouldClose(window))
{
if(lost_game){
LoadLosingScreen(window);
} else if(won_game){
LoadWinningScreen(window);
} else {
glClearColor(0.6f, 0.8f, 1.0f, 0.8f); //COR DE FUNDO AZUL
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //PINTA O BUFFER COM A COR ACIMA
glUseProgram(program_id); //GPU UTILIZA OS SHADERS ACIMA
//Obtem a diferença de tempo atual
t_atual = glfwGetTime();
t_dif = t_atual - t_prev;
t_prev = t_atual;
//Calculando o valor t para curva de bzier
bzier_t+= t_dif;
//resetando a cada CURVE_TIME
if(bzier_t >= CURVE_TIME){
bzier_t =0;
}
//Mover o meteoro numa curva de bézier
BezierMeteorMove(bzier_t/CURVE_TIME);
//TIPO DE CAMERA UTILIZADA
switch(camera_type){
case CHARACTER_CAMERA:
LoadCharacterCamera(window);
break;
case LOOK_AT_CAMERA:
LoadLookAtCamera(chr_pos);
break;
case FREE_CAMERA:
LoadFreeCamera(window);
break;
}
// Computamos a matriz "View" utilizando os parâmetros da câmera para definir o sistema de coordenadas da câmera.
glm::mat4 view = Matrix_Camera_View(camera_position_c, camera_view_vector, camera_up_vector);
//Calculando a matrix de projeção perspectiva
glm::mat4 projection = ComputeProjectionMatrix();
//Envia as matrizes para a gpu
glUniformMatrix4fv(view_uniform , 1 , GL_FALSE , glm::value_ptr(view));
glUniformMatrix4fv(projection_uniform , 1 , GL_FALSE , glm::value_ptr(projection));
//Desenhando cada objeto na cena
DrawObjectModels();
//Testando colisões da esfera com jogador e plataformas e realizando a operação adequada
MeteorCollisions();
//Testando colisoes do jogador com um ponto no topo da torre, dando a vitoria caso ocorra
TowerTopCollisions();
///////////////////////////////////////////
//Imprimindo informações na tela
TextRendering_ShowFramesPerSecond(window);
glfwSwapBuffers(window); //Troca de buffers permitindo a visualização dos objetos
glfwPollEvents(); //Verificando eventos de iteração do usuário
}
}
// Finalizamos o uso dos recursos do sistema operacional
glfwTerminate();
// Fim do programa
return 0;
}
//Tela de vitoria
void LoadWinningScreen(GLFWwindow* window){
glClearColor(0, 1,0, 0.2f); //COR DE FUNDO VERMELHA
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //PINTA O BUFFER COM A COR ACIMA
//Imprime na tela a mensagem de derrota
float charwidth = TextRendering_CharWidth(window);
TextRendering_PrintString(window, "VITORIA: O robo chegou no topo da torre.",0-charwidth*(20), 0, 1.0f);
glUseProgram(program_id); //diz quais shaders a gpu usa
glfwSwapBuffers(window); //Troca de buffers permitindo a visualização dos objetos
glfwPollEvents(); //Verificando eventos de iteração do usuário ( caso ele aperte ESC)
}
//Tela de Derrota
void LoadLosingScreen(GLFWwindow* window){
glClearColor(1, 0,0, 0.2f); //COR DE FUNDO VERMELHA
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //PINTA O BUFFER COM A COR ACIMA
//Imprime na tela a mensagem de derrota
float charwidth = TextRendering_CharWidth(window);
TextRendering_PrintString(window, "DERROTA: O robo foi atingido pelo meteoro.",0-charwidth*(21), 0, 1.0f);
glUseProgram(program_id); //diz quais shaders a gpu usa
glfwSwapBuffers(window); //Troca de buffers permitindo a visualização dos objetos
glfwPollEvents(); //Verificando eventos de iteração do usuário ( caso ele aperte ESC)
}
//Colisão com um ponto no topo da torre torna o usuário vitorioso
void TowerTopCollisions(){
glm::mat4 modelCompareRobot = Matrix_Translate(chr_pos[0],chr_pos[1],chr_pos[2])*Matrix_Scale(ROBOT_SCALE,ROBOT_SCALE,ROBOT_SCALE); //Diminuindo o tamanho do robo
glm::vec4 towerMax = Matrix_Scale(TOWER_SCALE,TOWER_SCALE,TOWER_SCALE)*mapBboxMax[TOWER]; //conseguindo a bbox_max da torre
glm::vec4 p = glm::vec4(0,towerMax.y,0,1); //ponto no topo da torre
if(ComparePoint_AABB(p,ROBOTTOP,modelCompareRobot) || ComparePoint_AABB(p,ROBOTBOTTOM,modelCompareRobot)){
won_game =true; //Se encostar no ponto, ganha o jogo
}
}
//Colisões do meteoro: Com jogador, ele perde o jogo
// Com plataforma, gera uma plataforma nova na altura Y, a antiga some
void MeteorCollisions(){
float radius = SPHERE_RADIUS*SPHERE_SCALE;
glm::mat4 modelCompareRobot = Matrix_Translate(chr_pos[0],chr_pos[1],chr_pos[2])*Matrix_Scale(ROBOT_SCALE,ROBOT_SCALE,ROBOT_SCALE); //Diminuindo o tamanho do robo
//testa se a esfera colidiu com o robo
if(CompareSphere_AABB(radius, sphere_pos,ROBOTTOP,modelCompareRobot) || CompareSphere_AABB(radius, sphere_pos,ROBOTBOTTOM,modelCompareRobot)){
lost_game = true;
}
float translate_x,translate_z;
//testa se a esfera colidiu com uma plataforma
for(int i=0; i<NUM_PLATFORMS; i++){
//calculando model dos cubos
glm::mat4 cubeModel = Matrix_Translate(move_cubeX[i],0,move_cubeZ[i])*random_cube_models[i];
if(CompareSphere_AABB(radius, sphere_pos,CUBE,cubeModel)){
//GERA UMA PLATAFORMA NOVA
move_cubeZ[i] = 0; move_cubeX[i] = 0; move_cubeZOld[i] = 0; move_cubeXOld[i] = 0;
random_cube_models[i] = Matrix_Scale((rand()%100)/200+0.75,((rand()%100)/250)+0.2,(rand()%100)/200+0.75); //Achatamento aleatorio
translate_x = (rand()%10) - 5;
translate_z = (rand()%10) - 5;
//gerando plataformas que não estao dentro da torre ( entre -2 e 2)
while(translate_x <= 2 && translate_x >= -2){
translate_x = (rand()%10) - 5;
}
while(translate_z <= 2 && translate_z >= -2){
translate_z = (rand()%10) - 5;
}
random_cube_models[i] = Matrix_Translate(translate_x,i*0.5 + 1, translate_z)*random_cube_models[i]; //Deslocamento
//Garante que nao seja gerada em cima do robo
glm::mat4 modelCompareRobot = Matrix_Translate(chr_pos[0],chr_pos[1],chr_pos[2])*Matrix_Scale(ROBOT_SCALE,ROBOT_SCALE,ROBOT_SCALE); //Diminuindo o tamanho do robo
cubeModel = Matrix_Translate(move_cubeX[i],0,move_cubeZ[i])*random_cube_models[i];
if(CompareAABB_AABB(ROBOTTOP,modelCompareRobot,CUBE,cubeModel) || CompareAABB_AABB(ROBOTBOTTOM,modelCompareRobot,CUBE,cubeModel)){
i--;
}
}
}
}
//Movendo o meteoro numa curva de bézier de grau 3
void BezierMeteorMove(float t){ //t é calculado com base no tempo e vai de 0 até 1
float b03,b13,b23,b33;
//Definindo os ponto p1,p2,p3,p4 (uma curva que começa em cima da torre a desce girando)
glm::vec4 p1,p2,p3,p4;
float curve_radius = 9;
p1 = glm::vec4(-curve_radius,15,-curve_radius,1.0f); //em cima da torre (posiçao inicial da esfera)
p2 = glm::vec4(curve_radius,12.5,-curve_radius,1.0f);
p3 = glm::vec4(curve_radius,11,curve_radius,1.0f);
p4 = glm::vec4(-curve_radius/2,0,0,1.0f);
//Usando bernstein polinomials para calcular nossa curva (slide 81 da aula 16)
b03 = (1-t)*(1-t)*(1-t);
b13 = 3*t*(1-t)*(1-t);
b23 = 3*t*t*(1-t);
b33 = t*t*t;
sphere_pos = p1*b03 + p2*b13 + p3*b23 + p4*b33;
}
//Compara ponto e AABB retornando true caso intersecção
bool ComparePoint_AABB(glm::vec4 p, int bbox_id,glm::mat4 model){
//Obtendo as bboxes e multiplicando por seus modelos
glm::vec4 bbox_max = model*mapBboxMax[bbox_id];
glm::vec4 bbox_min = model*mapBboxMin[bbox_id];
// TESTE DE INTERSECÇÃO ENTRE AABB e PONTO (simplesmente testa se o ponto ta dentro dos intervalos da aabb
return (p.x >= bbox_min.x && p.x <= bbox_max.x) &&
(p.y >= bbox_min.y && p.y <= bbox_max.y) &&
(p.z >= bbox_min.z && p.z <= bbox_max.z);
}
//Compara uma esfera com uma bounding box, retorna true caso ocorra interecção
bool CompareSphere_AABB(float radius, glm::vec4 sphere_center, int bbox_id,glm::mat4 model){
glm::vec4 bbox_max = model*mapBboxMax[bbox_id]; //Obtendo posição real da bounding box
glm::vec4 bbox_min = model*mapBboxMin[bbox_id]; //Obtendo posição real da bounding box
//Calculando o ponto mais próximo a esfera
//Tecnica de clamping
float closest_pointX = std::max(bbox_min.x, std::min(sphere_center.x, bbox_max.x));
float closest_pointY = std::max(bbox_min.y, std::min(sphere_center.y, bbox_max.y));
float closest_pointZ = std::max(bbox_min.z, std::min(sphere_center.z, bbox_max.z));
//Calculando a distancia entre esse ponto e o centro da esfera (cálculo de distancia euclediana)
float distance = sqrt( (closest_pointX - sphere_center.x) * (closest_pointX - sphere_center.x) +
(closest_pointY - sphere_center.y) * (closest_pointY - sphere_center.y) +
(closest_pointZ - sphere_center.z) * (closest_pointZ - sphere_center.z));
return distance <= radius; //Retorna sim se a distancia entre o ponto mais próximo a esfera da AABB
//é menor que o raio, pois isso implica que ele deve estar dentro da esfera
}
//Compara duas bounding boxes, retorna true caso se intersecção
bool CompareAABB_AABB(int bbox_id1, glm::mat4 model1, int bbox_id2,glm::mat4 model2){
//Obtendo as bboxes e multiplicando por seus modelos
glm::vec4 bbox_max1 = model1*mapBboxMax[bbox_id1];
glm::vec4 bbox_min1 = model1*mapBboxMin[bbox_id1];
glm::vec4 bbox_max2 = model2*mapBboxMax[bbox_id2];
glm::vec4 bbox_min2 = model2*mapBboxMin[bbox_id2];
// TESTE DE INTERSECÇÃO ENTRE AABB
return (bbox_min1.x <= bbox_max2.x && bbox_max1.x >= bbox_min2.x) &&
(bbox_min1.y <= bbox_max2.y && bbox_max1.y >= bbox_min2.y) &&
(bbox_min1.z <= bbox_max2.z && bbox_max1.z >= bbox_min2.z);
}
void LoadCharacterCamera(GLFWwindow* window){ //LoadCharacterCamera é uma mistura de free camera com uma lookat posicionada no personagem(um pouco deslocada)
//Uma a cada duas iterações irão simplesmente empurrar o personagem para baixo, simulando gravidade
if(gravity_iteration){
chr_pos[1] -= t_dif*gravity; //Movendo o personagem verticalmente para baixo
if(chr_pos[1] <= on_top_of_y){ //Impede que o robo atravesse o chão/plataforma que está embaixo dele
chr_pos[1] = on_top_of_y;
can_jump = true;
}
gravity_iteration = false;
}else{
//Calculando W e U para realizar as na posição do personagem
glm::vec4 w = -camera_view_vector/norm(camera_view_vector) /* cálculo do vetor w */;
glm::vec4 u = crossproduct(camera_up_vector,w)/norm(crossproduct(camera_up_vector,w)) ;/* cálculo do vetor u */;
// Normalizamos os vetores u e w
w = w / norm(w);
u = u / norm(u);
float y= chr_pos[1]; // O personagem não se mexe verticalmente pelo controlador
chr_pos_old = chr_pos; //salva a posição atual caso o objeto nao possa se mover
//Moving using W,A,S,D e SPACE
// Movimentamos o personagem
if (glfwGetKey(window,GLFW_KEY_W ) == GLFW_PRESS)
{
chr_pos-= w*chr_speed*t_dif;
}
if (glfwGetKey(window,GLFW_KEY_A ) == GLFW_PRESS)
{
chr_pos -= u*chr_speed*t_dif;
}
if (glfwGetKey(window,GLFW_KEY_S ) == GLFW_PRESS)
{
chr_pos += w*chr_speed*t_dif;
}
if (glfwGetKey(window,GLFW_KEY_D ) == GLFW_PRESS)
{
chr_pos += u*chr_speed*t_dif;
}
if ( (glfwGetKey(window,GLFW_KEY_SPACE ) == GLFW_PRESS) && can_jump ) //iniciar um pulo
{
jump_activated = true;
can_jump = false;
jump_initial_height = chr_pos[1];
}
if(jump_activated){
chr_pos[1] = y + jump_strength*t_dif;
if((chr_pos[1]-jump_initial_height) >= jump_height){ //testa se o pulo acabou, resetando variaveis
jump_activated = false;
}
}
else{
chr_pos[1] = y;
}
//Deslocado um pouco para cima para que o usuario tenha um campo de visão maior
LoadLookAtCamera(Matrix_Translate(0,1.5,0)*chr_pos); //Faz o calculo do vetor de view com base no look at camera
//O movimento da camera do robo para cima e para baixo é limitado
if(g_CameraPhi > chr_cam_phi_max){
g_CameraPhi = chr_cam_phi_max;
}
if(g_CameraPhi < chr_cam_phi_min){
g_CameraPhi = chr_cam_phi_min;
}
gravity_iteration = true;
}
}
//Calculates camera position,lookatposition and view_vector for look at camera
//Recebe como entrada o ponto a qual a camera irá look-at
void LoadLookAtCamera(glm::vec4 look_at_point){
camera_lookat_l = look_at_point; // Ponto para onde a câmera (look-at) estará sempre olhando
r = g_CameraDistance;
x = (r*cos(g_CameraPhi)*sin(g_CameraTheta)) + camera_lookat_l[0]; //Somando camera_lookat_l para que o ponto esteja no centro da esfera
y = (r*sin(g_CameraPhi)) + camera_lookat_l[1];
z = (r*cos(g_CameraPhi)*cos(g_CameraTheta)) + camera_lookat_l[2];
camera_position_c = glm::vec4(x,y,z,1.0f); // Ponto "c", centro da câmera
camera_view_vector = camera_lookat_l - camera_position_c; // Vetor "view", sentido para onde a câmera está virada
}
void LoadFreeCamera(GLFWwindow* window){
//Calculando W e U para realizar as alterações na posição da camera
glm::vec4 w = -camera_view_vector/norm(camera_view_vector) /* cálculo do vetor w */;
glm::vec4 u = crossproduct(camera_up_vector,w)/norm(crossproduct(camera_up_vector,w)) ;/* cálculo do vetor u */;
// Normalizamos os vetores u e w
w = w / norm(w);
u = u / norm(u);
//Moving using W,A,S,D
// Se o usuário apertar sa teclas W,A,S,D.
if (glfwGetKey(window,GLFW_KEY_W ) == GLFW_PRESS)
{
camera_position_c-= w*camera_speed*t_dif; //multiplicando por t_dif para garantir que o tempo de execução
}
if (glfwGetKey(window,GLFW_KEY_A ) == GLFW_PRESS)
{
camera_position_c-= u*camera_speed*t_dif;
}
if (glfwGetKey(window,GLFW_KEY_S ) == GLFW_PRESS)
{
camera_position_c+= w*camera_speed*t_dif;
}
if (glfwGetKey(window,GLFW_KEY_D ) == GLFW_PRESS)
{
camera_position_c+= u*camera_speed*t_dif;
}
camera_lookat_l = camera_position_c + glm::vec4(0,0,-1,0); //Isso garante que a rotação em torno do eixo X funcione.
camera_view_vector = camera_lookat_l - camera_position_c;
//Adicionando as rotações relacionadas ao movimento do mouse
camera_view_vector = camera_view_vector*Matrix_Rotate_X(g_CameraPhi)*Matrix_Rotate_Y(-g_CameraTheta);
}
//CARREGANDO AS TEXTURAS E .OBJ QUE SERÃO UTILIZADOS
void LoadTexturesAndModels(){
// Carregamos os shaders de vértices e de fragmentos que serão utilizados para renderização.
LoadShadersFromFiles();
// CARREGANDO TEXTURAS QUE SERÃO UTILIZADAS
LoadTextureImage("../../data/gold-texture.jpg"); // TextureOuro
LoadTextureImage("../../data/grass-texture.jpg"); // TextureGrama
LoadTextureImage("../../data/brick-texture.jpg"); // TextureTijolo
LoadTextureImage("../../data/light-metal-texture.jpg"); // TextureMetalClara
LoadTextureImage("../../data/dark-metal-texture.jpg"); // TextureMetalEscura
LoadTextureImage("../../data/meteor-texture.jpg"); // TextureMeteoro
// CARREGANDO .OBJS QUE SERÃO UTILIZADOS
ObjModel trophymodel("../../data/trophy.obj");
ComputeNormals(&trophymodel);
BuildTrianglesAndAddToVirtualScene(&trophymodel);
ObjModel floormodel("../../data/floor.obj");
ComputeNormals(&floormodel);
BuildTrianglesAndAddToVirtualScene(&floormodel);
ObjModel towermodel("../../data/tower.obj");
ComputeNormals(&towermodel);
BuildTrianglesAndAddToVirtualScene(&towermodel);
ObjModel robotmodel("../../data/robot.obj");
ComputeNormals(&robotmodel);
BuildTrianglesAndAddToVirtualScene(&robotmodel);
ObjModel spheremodel("../../data/sphere.obj");
ComputeNormals(&spheremodel);
BuildTrianglesAndAddToVirtualScene(&spheremodel);
ObjModel cubemodel("../../data/cube.obj");
ComputeNormals(&cubemodel);
BuildTrianglesAndAddToVirtualScene(&cubemodel);
}
//Desenhando cada objeto na cena
void DrawObjectModels(){
glm::mat4 model; //
// DESENHANDO O TROFÉU
//O .obj do troféu possui ele divido em várias partes
//Diminuindo bastante o tamanho do troféu, seu .obj é grande
//Translating ele para o topo da torre
model = Matrix_Translate(0,9,0)*Matrix_Scale(TROPHY_SCALE,TROPHY_SCALE,TROPHY_SCALE);
glUniformMatrix4fv(model_uniform, 1 , GL_FALSE , glm::value_ptr(model));
glUniform1i(object_id_uniform, TROPHY);
DrawVirtualObject("trophy",TROPHY);
glUniformMatrix4fv(model_uniform, 1 , GL_FALSE , glm::value_ptr(model));
glUniform1i(object_id_uniform, TROPHY);
DrawVirtualObject("trophybase",-1); //Bbox id sendo -1 significa que nao será utilizado
glUniformMatrix4fv(model_uniform, 1 , GL_FALSE , glm::value_ptr(model));
glUniform1i(object_id_uniform, TROPHY);
DrawVirtualObject("trophyhandle",-1);
/////////////////////////////////////////////////
// DESENHANDO O CHÃO
model = Matrix_Identity();
glUniformMatrix4fv(model_uniform, 1 , GL_FALSE , glm::value_ptr(model));
glUniform1i(object_id_uniform, FLOOR);
DrawVirtualObject("floor",-1);
///////////////////////////////////////////////
// DESENHANDO A TORRE
glm::mat4 towerModel = Matrix_Scale(TOWER_SCALE,TOWER_SCALE,TOWER_SCALE); //Diminuindo o tamanho da torre
glUniformMatrix4fv(model_uniform, 1 , GL_FALSE , glm::value_ptr(towerModel));
glUniform1i(object_id_uniform, TOWER);
DrawVirtualObject("tower",TOWER);
////////////////////////////////////////////////////////////////////
//// DESENHANDO O ROBO
//A cabeça do robo nao deve se mexer em outras posições da camera
if(camera_type == CHARACTER_CAMERA){
chr_rotate_angle = g_CameraTheta -1.25;
}
float scale = 0.008;
//Testa se o robo pode se mover para essa nova posição
if(!CanRobotMove( towerModel)){
chr_pos = chr_pos_old; //Se não, volta para sua posiçao anterior
}
glm::mat4 robotModel = Matrix_Translate(chr_pos[0],chr_pos[1],chr_pos[2])
*Matrix_Rotate_Y(chr_rotate_angle) //Rotação que move a cabeça do robo para onde a camera esta olhando
*Matrix_Scale(scale,scale,scale); //Diminuindo o tamanho do robo
glUniformMatrix4fv(model_uniform, 1 , GL_FALSE , glm::value_ptr(robotModel));
glUniform1i(object_id_uniform, ROBOTTOP);
DrawVirtualObject("robotTop",ROBOTTOP);
glUniformMatrix4fv(model_uniform, 1 , GL_FALSE , glm::value_ptr(robotModel));
glUniform1i(object_id_uniform, ROBOTBOTTOM);
DrawVirtualObject("robotBottom",ROBOTBOTTOM);
///////////////////////////////////////////////////
//DESENHANDO CUBOS (PLATAFORMAS)
//só é necessario calcular uma unica vez as random_cube_model
//
if(initialize){//Gerando a matriz modelo de forma aleatoria
for(int i =0 ; i<NUM_PLATFORMS; i++){
random_cube_models[i] = Matrix_Scale((rand()%100)/200+0.75,((rand()%100)/250)+0.2,(rand()%100)/200+0.75); //Achatamento aleatorio
float translate_x = (rand()%10) - 5;
float translate_z = (rand()%10) - 5;
//gerando plataformas que não estao dentro da torre ( entre -2 e 2)
while(translate_x <= 2 && translate_x >= -2){
translate_x = (rand()%10) - 5;
}
while(translate_z <= 2 && translate_z >= -2){
translate_z = (rand()%10) - 5;
}
random_cube_models[i] = Matrix_Translate(translate_x,i*0.5 + 1, translate_z)*random_cube_models[i]; //Deslocamento
}
}
//Transladando os cubos para sua posição controlada pelo usario
for(int i =0 ; i<NUM_PLATFORMS; i++){
model = random_cube_models[i]; //Definida anteriormente, uma matriz com escalas e transalações aleatorias para cada plataforma
if(!CanPlatformMove(i,towerModel)){ //Se a plataforma nao pode se mover, mantém ela na posição antiga
move_cubeX[i] = move_cubeXOld[i];
move_cubeZ[i] = move_cubeZOld[i];
}
model = Matrix_Translate(move_cubeX[i],0,move_cubeZ[i])*model;
glUniformMatrix4fv(model_uniform, 1 , GL_FALSE , glm::value_ptr(model));
glUniform1i(object_id_uniform, CUBE);
DrawVirtualObject("cube",CUBE);
move_cubeXOld[i] = move_cubeX[i];
move_cubeZOld[i] = move_cubeZ[i];
}
//UTILIZANDO UMA ESFERA COMO METEORO
//Translada ela de acordo com a curva de bezier, rotaciona ela utilizando o t de bzier para dar um efeito de giro
model = Matrix_Translate(sphere_pos[0],sphere_pos[1],sphere_pos[2])*Matrix_Rotate_Y(bzier_t)*Matrix_Rotate_X(bzier_t)*Matrix_Scale(SPHERE_SCALE,SPHERE_SCALE,SPHERE_SCALE);
glUniformMatrix4fv(model_uniform, 1 , GL_FALSE , glm::value_ptr(model));
glUniform1i(object_id_uniform, SPHERE);
DrawVirtualObject("sphere",-1 ); //bbox id da sphere é zero pois utilizamos comparação com esfera
chr_pos_old = chr_pos;
initialize = false;
}
bool CanPlatformMove(int platform_id, glm::mat4 towerModel){
//Calcula a matriz modelo do cubo
glm::mat4 modelPlatform = Matrix_Translate(move_cubeX[platform_id],0,move_cubeZ[platform_id])*random_cube_models[platform_id];
//Calculando matriz modelo do robo
glm::mat4 robotMode = Matrix_Translate(chr_pos[0],chr_pos[1],chr_pos[2])*Matrix_Scale(ROBOT_SCALE,ROBOT_SCALE,ROBOT_SCALE);
//Comparando as AABB do robo e da torre para evitar colisões
bool towerCollision =CompareAABB_AABB(CUBE,modelPlatform,TOWER,towerModel);
bool robotCollision = (CompareAABB_AABB(ROBOTTOP,robotMode,CUBE,modelPlatform) || CompareAABB_AABB(ROBOTBOTTOM,robotMode,CUBE,modelPlatform));
return !(towerCollision || robotCollision);
}
//Testando se o robo consegue se mover (se ocorre colisão)
bool CanRobotMove(glm::mat4 towerModel){
on_top_of_y = 0; //sempre assumimindo que ele está no chão se ele não entrar em contato com nenhuma plataforma
on_top_of_platform=-1;//sempre assumindo que não estamos em cima de nenhuma plataforma
float delta = 30*t_dif;
//Nao utilizando a rotação da cabeça do robo nas comparações
glm::mat4 modelCompareRobot = Matrix_Translate(chr_pos[0],chr_pos[1],chr_pos[2])*Matrix_Scale(ROBOT_SCALE,ROBOT_SCALE,ROBOT_SCALE); //Diminuindo o tamanho do robo
//////////////////////////////////////////////////////////////////
//Testando se o robo irá ter intersecção com alguma plataforma
bool platformCollision = false;
glm::mat4 cubeModel;
for(int i=0; i<NUM_PLATFORMS; i++){
cubeModel = Matrix_Translate(move_cubeX[i],0,move_cubeZ[i])*random_cube_models[i];
if(CompareAABB_AABB(ROBOTTOP,modelCompareRobot,CUBE,cubeModel) || CompareAABB_AABB(ROBOTBOTTOM,modelCompareRobot,CUBE,cubeModel)){
glm::vec4 cubeBboxmax = cubeModel*mapBboxMax[CUBE];
platformCollision = true;
jump_activated= false;
//Isso significa que o personagem está em cima da plataforma (testa as alturas y do robo e da plataforma com um pequeno intervalo (delta))
if( (chr_pos[1] <= cubeBboxmax[1]+delta) && (chr_pos[1] >= cubeBboxmax[1]-delta)){
on_top_of_y = chr_pos[1];//avisa a gravidade para nao empurrar o robo para baixo
on_top_of_platform = i; //indica que essa plataforma nao poderá ser movida
can_jump = true; //avisa que o robo pode pular
platformCollision = false; //permite o robo a se mover (pois ele está em cima da plataforma)
}
}
}
///////////////////////////////////////////////////////////////////////////////////////
//Testando se o robo irá ter intersecção com a torre
bool towerCollision = (CompareAABB_AABB(ROBOTTOP,modelCompareRobot,TOWER,towerModel) || CompareAABB_AABB(ROBOTBOTTOM,modelCompareRobot,TOWER,towerModel));
if(towerCollision){
jump_activated= false;
}
//Testando se o robo está em cima da torre
glm::vec4 towerBboxmax= towerModel*mapBboxMax[TOWER];
//Isso significa que o personagem está em cima da torre (testa as alturas y do robo e da plataforma com um pequeno intervalo(delta))
if( towerCollision && (chr_pos[1] <= towerBboxmax[1]+delta) && (chr_pos[1] >= towerBboxmax[1]-delta)){
on_top_of_y = chr_pos[1]; //avisa a gravidade para nao empurrar o robo para baixo
can_jump = true; //avisa que o robo pode pular
towerCollision = false; //permite o robo a se mover (pois ele está em cima da torre)
}
return !(towerCollision || platformCollision);
}
//Usando matriz perspectiva
glm::mat4 ComputeProjectionMatrix(){
float nearplane = -0.1f; // Posição do "near plane"
float farplane = -200.0f; // Posição do "far plane"
// Projeção Perspectiva.
float field_of_view = 3.141592 / 3.0f;
return Matrix_Perspective(field_of_view, g_ScreenRatio, nearplane, farplane);
}
// Função que carrega uma imagem para ser utilizada como textura
void LoadTextureImage(const char* filename)
{
printf("Carregando imagem \"%s\"... ", filename);
// Primeiro fazemos a leitura da imagem do disco
stbi_set_flip_vertically_on_load(true);
int width;
int height;
int channels;
unsigned char *data = stbi_load(filename, &width, &height, &channels, 3);
if ( data == NULL )
{
fprintf(stderr, "ERROR: Cannot open image file \"%s\".\n", filename);
std::exit(EXIT_FAILURE);
}
printf("OK (%dx%d).\n", width, height);
// Agora criamos objetos na GPU com OpenGL para armazenar a textura
GLuint texture_id;
GLuint sampler_id;
glGenTextures(1, &texture_id);
glGenSamplers(1, &sampler_id);
// Veja slides 95-96 do documento Aula_20_Mapeamento_de_Texturas.pdf
glSamplerParameteri(sampler_id, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glSamplerParameteri(sampler_id, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// Parâmetros de amostragem da textura.
glSamplerParameteri(sampler_id, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glSamplerParameteri(sampler_id, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Agora enviamos a imagem lida do disco para a GPU
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
GLuint textureunit = g_NumLoadedTextures;
glActiveTexture(GL_TEXTURE0 + textureunit);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glBindSampler(textureunit, sampler_id);
stbi_image_free(data);
g_NumLoadedTextures += 1;
}
// Função que desenha um objeto armazenado em g_VirtualScene. Veja definição
// dos objetos na função BuildTrianglesAndAddToVirtualScene().
void DrawVirtualObject(const char* object_name, int bbox_id)
{
// "Ligamos" o VAO. Informamos que queremos utilizar os atributos de
// vértices apontados pelo VAO criado pela função BuildTrianglesAndAddToVirtualScene(). Veja
// comentários detalhados dentro da definição de BuildTrianglesAndAddToVirtualScene().
glBindVertexArray(g_VirtualScene[object_name].vertex_array_object_id);
// Setamos as variáveis "bbox_min" e "bbox_max" do fragment shader
// com os parâmetros da axis-aligned bounding box (AABB) do modelo.
glm::vec3 bbox_min = g_VirtualScene[object_name].bbox_min;
glm::vec3 bbox_max = g_VirtualScene[object_name].bbox_max;
glUniform4f(bbox_min_uniform, bbox_min.x, bbox_min.y, bbox_min.z, 1.0f);
glUniform4f(bbox_max_uniform, bbox_max.x, bbox_max.y, bbox_max.z, 1.0f);
//Carregando uma unica vez as bboxes
if(bbox_id != -1 && initialize){//precisamos de somente algumas bboxs
mapBboxMax[bbox_id] = glm::vec4(bbox_max.x, bbox_max.y, bbox_max.z, 1.0f);
mapBboxMin[bbox_id]= glm::vec4(bbox_min.x, bbox_min.y, bbox_min.z, 1.0f);
}
// Pedimos para a GPU rasterizar os vértices dos eixos XYZ
// apontados pelo VAO como linhas. Veja a definição de
// g_VirtualScene[""] dentro da função BuildTrianglesAndAddToVirtualScene(), e veja
// a documentação da função glDrawElements() em
// http://docs.gl/gl3/glDrawElements.
glDrawElements(
g_VirtualScene[object_name].rendering_mode,
g_VirtualScene[object_name].num_indices,
GL_UNSIGNED_INT,
(void*)(g_VirtualScene[object_name].first_index * sizeof(GLuint))
);
// "Desligamos" o VAO, evitando assim que operações posteriores venham a
// alterar o mesmo. Isso evita bugs.
glBindVertexArray(0);
}
// Função que carrega os shaders de vértices e de fragmentos que serão
// utilizados para renderização. Veja slides 176-196 do documento Aula_03_Rendering_Pipeline_Grafico.pdf.
//
void LoadShadersFromFiles()
{
vertex_shader_id = LoadShader_Vertex("../../src/shader_vertex.glsl");
fragment_shader_id = LoadShader_Fragment("../../src/shader_fragment.glsl");
// Deletamos o programa de GPU anterior, caso ele exista.
if ( program_id != 0 )
glDeleteProgram(program_id);
// Criamos um programa de GPU utilizando os shaders carregados acima.
program_id = CreateGpuProgram(vertex_shader_id, fragment_shader_id);
// Buscamos o endereço das variáveis definidas dentro do Vertex Shader.
// Utilizaremos estas variáveis para enviar dados para a placa de vídeo
// (GPU)! Veja arquivo "shader_vertex.glsl" e "shader_fragment.glsl".
model_uniform = glGetUniformLocation(program_id, "model"); // Variável da matriz "model"
view_uniform = glGetUniformLocation(program_id, "view"); // Variável da matriz "view" em shader_vertex.glsl
projection_uniform = glGetUniformLocation(program_id, "projection"); // Variável da matriz "projection" em shader_vertex.glsl
object_id_uniform = glGetUniformLocation(program_id, "object_id"); // Variável "object_id" em shader_fragment.glsl
bbox_min_uniform = glGetUniformLocation(program_id, "bbox_min");
bbox_max_uniform = glGetUniformLocation(program_id, "bbox_max");
// Variáveis em "shader_fragment.glsl" para acesso das imagens de textura
glUseProgram(program_id);
glUniform1i(glGetUniformLocation(program_id, "TextureOuro"), TROPHY);
glUniform1i(glGetUniformLocation(program_id, "TextureGrama"), FLOOR);
glUniform1i(glGetUniformLocation(program_id, "TextureTijolo"), TOWER);
glUniform1i(glGetUniformLocation(program_id, "TextureMetalClaro"), ROBOTTOP);
glUniform1i(glGetUniformLocation(program_id, "TextureMetalEscuro"),ROBOTBOTTOM);
glUniform1i(glGetUniformLocation(program_id, "TextureMeteoro"),SPHERE);
glUseProgram(0);
}
// Função que pega a matriz M e guarda a mesma no topo da pilha
void PushMatrix(glm::mat4 M)
{
g_MatrixStack.push(M);
}
// Função que remove a matriz atualmente no topo da pilha e armazena a mesma na variável M
void PopMatrix(glm::mat4& M)
{
if ( g_MatrixStack.empty() )
{
M = Matrix_Identity();
}
else
{
M = g_MatrixStack.top();
g_MatrixStack.pop();
}
}
// Função que computa as normais de um ObjModel, caso elas não tenham sido
// especificadas dentro do arquivo ".obj"
void ComputeNormals(ObjModel* model)
{
if ( !model->attrib.normals.empty() )
return;
// Primeiro computamos as normais para todos os TRIÂNGULOS.
// Segundo, computamos as normais dos VÉRTICES através do método proposto
// por Gouraud, onde a normal de cada vértice vai ser a média das normais de
// todas as faces que compartilham este vértice.
size_t num_vertices = model->attrib.vertices.size() / 3;
std::vector<int> num_triangles_per_vertex(num_vertices, 0);
std::vector<glm::vec4> vertex_normals(num_vertices, glm::vec4(0.0f,0.0f,0.0f,0.0f));
for (size_t shape = 0; shape < model->shapes.size(); ++shape)
{
size_t num_triangles = model->shapes[shape].mesh.num_face_vertices.size();
for (size_t triangle = 0; triangle < num_triangles; ++triangle)
{
assert(model->shapes[shape].mesh.num_face_vertices[triangle] == 3);
glm::vec4 vertices[3];
for (size_t vertex = 0; vertex < 3; ++vertex)
{
tinyobj::index_t idx = model->shapes[shape].mesh.indices[3*triangle + vertex];
const float vx = model->attrib.vertices[3*idx.vertex_index + 0];
const float vy = model->attrib.vertices[3*idx.vertex_index + 1];
const float vz = model->attrib.vertices[3*idx.vertex_index + 2];
vertices[vertex] = glm::vec4(vx,vy,vz,1.0);
}
const glm::vec4 a = vertices[0];
const glm::vec4 b = vertices[1];
const glm::vec4 c = vertices[2];
const glm::vec4 n = crossproduct(b-a,c-a);
for (size_t vertex = 0; vertex < 3; ++vertex)
{
tinyobj::index_t idx = model->shapes[shape].mesh.indices[3*triangle + vertex];
num_triangles_per_vertex[idx.vertex_index] += 1;
vertex_normals[idx.vertex_index] += n;
model->shapes[shape].mesh.indices[3*triangle + vertex].normal_index = idx.vertex_index;
}
}
}
model->attrib.normals.resize( 3*num_vertices );
for (size_t i = 0; i < vertex_normals.size(); ++i)
{
glm::vec4 n = vertex_normals[i] / (float)num_triangles_per_vertex[i];
n /= norm(n);
model->attrib.normals[3*i + 0] = n.x;
model->attrib.normals[3*i + 1] = n.y;
model->attrib.normals[3*i + 2] = n.z;
}
}
// Constrói triângulos para futura renderização a partir de um ObjModel.
void BuildTrianglesAndAddToVirtualScene(ObjModel* model)
{
GLuint vertex_array_object_id;
glGenVertexArrays(1, &vertex_array_object_id);
glBindVertexArray(vertex_array_object_id);
std::vector<GLuint> indices;
std::vector<float> model_coefficients;
std::vector<float> normal_coefficients;
std::vector<float> texture_coefficients;
for (size_t shape = 0; shape < model->shapes.size(); ++shape)
{
size_t first_index = indices.size();
size_t num_triangles = model->shapes[shape].mesh.num_face_vertices.size();
const float minval = std::numeric_limits<float>::min();
const float maxval = std::numeric_limits<float>::max();
glm::vec3 bbox_min = glm::vec3(maxval,maxval,maxval);
glm::vec3 bbox_max = glm::vec3(minval,minval,minval);
for (size_t triangle = 0; triangle < num_triangles; ++triangle)
{
assert(model->shapes[shape].mesh.num_face_vertices[triangle] == 3);
for (size_t vertex = 0; vertex < 3; ++vertex)
{
tinyobj::index_t idx = model->shapes[shape].mesh.indices[3*triangle + vertex];
indices.push_back(first_index + 3*triangle + vertex);
const float vx = model->attrib.vertices[3*idx.vertex_index + 0];
const float vy = model->attrib.vertices[3*idx.vertex_index + 1];
const float vz = model->attrib.vertices[3*idx.vertex_index + 2];
//printf("tri %d vert %d = (%.2f, %.2f, %.2f)\n", (int)triangle, (int)vertex, vx, vy, vz);
model_coefficients.push_back( vx ); // X
model_coefficients.push_back( vy ); // Y
model_coefficients.push_back( vz ); // Z
model_coefficients.push_back( 1.0f ); // W
bbox_min.x = std::min(bbox_min.x, vx);
bbox_min.y = std::min(bbox_min.y, vy);
bbox_min.z = std::min(bbox_min.z, vz);
bbox_max.x = std::max(bbox_max.x, vx);
bbox_max.y = std::max(bbox_max.y, vy);
bbox_max.z = std::max(bbox_max.z, vz);
// Inspecionando o código da tinyobjloader, o aluno Bernardo
// Sulzbach (2017/1) apontou que a maneira correta de testar se
// existem normais e coordenadas de textura no ObjModel é
// comparando se o índice retornado é -1. Fazemos isso abaixo.
if ( idx.normal_index != -1 )
{
const float nx = model->attrib.normals[3*idx.normal_index + 0];
const float ny = model->attrib.normals[3*idx.normal_index + 1];
const float nz = model->attrib.normals[3*idx.normal_index + 2];
normal_coefficients.push_back( nx ); // X
normal_coefficients.push_back( ny ); // Y
normal_coefficients.push_back( nz ); // Z
normal_coefficients.push_back( 0.0f ); // W
}
if ( idx.texcoord_index != -1 )
{
const float u = model->attrib.texcoords[2*idx.texcoord_index + 0];
const float v = model->attrib.texcoords[2*idx.texcoord_index + 1];
texture_coefficients.push_back( u );
texture_coefficients.push_back( v );
}
}
}
size_t last_index = indices.size() - 1;
SceneObject theobject;
theobject.name = model->shapes[shape].name;
theobject.first_index = first_index; // Primeiro índice
theobject.num_indices = last_index - first_index + 1; // Número de indices
theobject.rendering_mode = GL_TRIANGLES; // Índices correspondem ao tipo de rasterização GL_TRIANGLES.
theobject.vertex_array_object_id = vertex_array_object_id;
theobject.bbox_min = bbox_min;
theobject.bbox_max = bbox_max;
g_VirtualScene[model->shapes[shape].name] = theobject;
}
GLuint VBO_model_coefficients_id;
glGenBuffers(1, &VBO_model_coefficients_id);
glBindBuffer(GL_ARRAY_BUFFER, VBO_model_coefficients_id);
glBufferData(GL_ARRAY_BUFFER, model_coefficients.size() * sizeof(float), NULL, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, model_coefficients.size() * sizeof(float), model_coefficients.data());
GLuint location = 0; // "(location = 0)" em "shader_vertex.glsl"
GLint number_of_dimensions = 4; // vec4 em "shader_vertex.glsl"
glVertexAttribPointer(location, number_of_dimensions, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(location);
glBindBuffer(GL_ARRAY_BUFFER, 0);
if ( !normal_coefficients.empty() )
{
GLuint VBO_normal_coefficients_id;
glGenBuffers(1, &VBO_normal_coefficients_id);
glBindBuffer(GL_ARRAY_BUFFER, VBO_normal_coefficients_id);
glBufferData(GL_ARRAY_BUFFER, normal_coefficients.size() * sizeof(float), NULL, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, normal_coefficients.size() * sizeof(float), normal_coefficients.data());
location = 1; // "(location = 1)" em "shader_vertex.glsl"
number_of_dimensions = 4; // vec4 em "shader_vertex.glsl"
glVertexAttribPointer(location, number_of_dimensions, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(location);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
if ( !texture_coefficients.empty() )
{
GLuint VBO_texture_coefficients_id;
glGenBuffers(1, &VBO_texture_coefficients_id);
glBindBuffer(GL_ARRAY_BUFFER, VBO_texture_coefficients_id);
glBufferData(GL_ARRAY_BUFFER, texture_coefficients.size() * sizeof(float), NULL, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, texture_coefficients.size() * sizeof(float), texture_coefficients.data());
location = 2; // "(location = 1)" em "shader_vertex.glsl"
number_of_dimensions = 2; // vec2 em "shader_vertex.glsl"
glVertexAttribPointer(location, number_of_dimensions, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(location);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
GLuint indices_id;
glGenBuffers(1, &indices_id);
// "Ligamos" o buffer. Note que o tipo agora é GL_ELEMENT_ARRAY_BUFFER.
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_id);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), NULL, GL_STATIC_DRAW);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, indices.size() * sizeof(GLuint), indices.data());
// glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // XXX Errado!
//
// "Desligamos" o VAO, evitando assim que operações posteriores venham a
// alterar o mesmo. Isso evita bugs.
glBindVertexArray(0);
}
// Carrega um Vertex Shader de um arquivo GLSL. Veja definição de LoadShader() abaixo.
GLuint LoadShader_Vertex(const char* filename)
{
// Criamos um identificador (ID) para este shader, informando que o mesmo
// será aplicado nos vértices.
GLuint vertex_shader_id = glCreateShader(GL_VERTEX_SHADER);
// Carregamos e compilamos o shader
LoadShader(filename, vertex_shader_id);
// Retorna o ID gerado acima
return vertex_shader_id;
}
// Carrega um Fragment Shader de um arquivo GLSL . Veja definição de LoadShader() abaixo.
GLuint LoadShader_Fragment(const char* filename)
{
// Criamos um identificador (ID) para este shader, informando que o mesmo
// será aplicado nos fragmentos.
GLuint fragment_shader_id = glCreateShader(GL_FRAGMENT_SHADER);
// Carregamos e compilamos o shader
LoadShader(filename, fragment_shader_id);
// Retorna o ID gerado acima
return fragment_shader_id;
}
// Função auxilar, utilizada pelas duas funções acima. Carrega código de GPU de
// um arquivo GLSL e faz sua compilação.
void LoadShader(const char* filename, GLuint shader_id)
{
// Lemos o arquivo de texto indicado pela variável "filename"
// e colocamos seu conteúdo em memória, apontado pela variável
// "shader_string".
std::ifstream file;
try {
file.exceptions(std::ifstream::failbit);
file.open(filename);
} catch ( std::exception& e ) {
fprintf(stderr, "ERROR: Cannot open file \"%s\".\n", filename);
std::exit(EXIT_FAILURE);
}
std::stringstream shader;
shader << file.rdbuf();
std::string str = shader.str();
const GLchar* shader_string = str.c_str();
const GLint shader_string_length = static_cast<GLint>( str.length() );
// Define o código do shader GLSL, contido na string "shader_string"
glShaderSource(shader_id, 1, &shader_string, &shader_string_length);
// Compila o código do shader GLSL (em tempo de execução)
glCompileShader(shader_id);
// Verificamos se ocorreu algum erro ou "warning" durante a compilação
GLint compiled_ok;
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compiled_ok);
GLint log_length = 0;
glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &log_length);
// Alocamos memória para guardar o log de compilação.
// A chamada "new" em C++ é equivalente ao "malloc()" do C.
GLchar* log = new GLchar[log_length];
glGetShaderInfoLog(shader_id, log_length, &log_length, log);
// Imprime no terminal qualquer erro ou "warning" de compilação
if ( log_length != 0 )
{
std::string output;
if ( !compiled_ok )
{
output += "ERROR: OpenGL compilation of \"";
output += filename;
output += "\" failed.\n";
output += "== Start of compilation log\n";
output += log;
output += "== End of compilation log\n";
}
else
{
output += "WARNING: OpenGL compilation of \"";
output += filename;
output += "\".\n";
output += "== Start of compilation log\n";
output += log;
output += "== End of compilation log\n";
}
fprintf(stderr, "%s", output.c_str());
}
// A chamada "delete" em C++ é equivalente ao "free()" do C
delete [] log;
}
// Esta função cria um programa de GPU, o qual contém obrigatoriamente um
// Vertex Shader e um Fragment Shader.
GLuint CreateGpuProgram(GLuint vertex_shader_id, GLuint fragment_shader_id)
{
// Criamos um identificador (ID) para este programa de GPU
GLuint program_id = glCreateProgram();
// Definição dos dois shaders GLSL que devem ser executados pelo programa
glAttachShader(program_id, vertex_shader_id);
glAttachShader(program_id, fragment_shader_id);
// Linkagem dos shaders acima ao programa
glLinkProgram(program_id);
// Verificamos se ocorreu algum erro durante a linkagem
GLint linked_ok = GL_FALSE;
glGetProgramiv(program_id, GL_LINK_STATUS, &linked_ok);
// Imprime no terminal qualquer erro de linkagem
if ( linked_ok == GL_FALSE )
{
GLint log_length = 0;
glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &log_length);
// Alocamos memória para guardar o log de compilação.
// A chamada "new" em C++ é equivalente ao "malloc()" do C.
GLchar* log = new GLchar[log_length];
glGetProgramInfoLog(program_id, log_length, &log_length, log);
std::string output;
output += "ERROR: OpenGL linking of program failed.\n";
output += "== Start of link log\n";
output += log;
output += "\n== End of link log\n";
// A chamada "delete" em C++ é equivalente ao "free()" do C
delete [] log;
fprintf(stderr, "%s", output.c_str());
}
// Os "Shader Objects" podem ser marcados para deleção após serem linkados
glDeleteShader(vertex_shader_id);
glDeleteShader(fragment_shader_id);
// Retornamos o ID gerado acima
return program_id;
}
// Definição da função que será chamada sempre que a janela do sistema
// operacional for redimensionada, por consequência alterando o tamanho do
// "framebuffer" (região de memória onde são armazenados os pixels da imagem).
void FramebufferSizeCallback(GLFWwindow* window, int width, int height)
{
// Indicamos que queremos renderizar em toda região do framebuffer. A
// função "glViewport" define o mapeamento das "normalized device
// coordinates" (NDC) para "pixel coordinates". Essa é a operação de
// "Screen Mapping" ou "Viewport Mapping" vista em aula ({+ViewportMapping2+}).
glViewport(0, 0, width, height);
// Atualizamos também a razão que define a proporção da janela (largura /
// altura), a qual será utilizada na definição das matrizes de projeção,
// tal que não ocorra distorções durante o processo de "Screen Mapping"
// acima, quando NDC é mapeado para coordenadas de pixels. Veja slides 205-215 do documento Aula_09_Projecoes.pdf.
//
// O cast para float é necessário pois números inteiros são arredondados ao
// serem divididos!
g_ScreenRatio = (float)width / height;
}
// Variáveis globais que armazenam a última posição do cursor do mouse, para
// que possamos calcular quanto que o mouse se movimentou entre dois instantes
// de tempo. Utilizadas no callback CursorPosCallback() abaixo.
double g_LastCursorPosX, g_LastCursorPosY;
// Função callback chamada sempre que o usuário aperta algum dos botões do mouse
void MouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
{
return;
/*
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)
{
g_LeftMouseButtonPressed = true;
glfwGetCursorPos(window, &g_LastCursorPosX, &g_LastCursorPosY);
}
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE)
{
g_LeftMouseButtonPressed = false;
}
*/
}
// Função callback chamada sempre que o usuário movimentar o cursor do mouse em
// cima da janela OpenGL.
void CursorPosCallback(GLFWwindow* window, double xpos, double ypos)
{
//Nao queremos movimentar se o usuario estiver usando o cursor
//if(!g_LeftMouseButtonPressed )
// return;
// Deslocamento do cursor do mouse em x e y de coordenadas de tela!
float dx = xpos - g_LastCursorPosX;
float dy = ypos - g_LastCursorPosY;
// Atualizamos parâmetros da câmera com os deslocamentos
g_CameraTheta -= 0.0025f*dx;
g_CameraPhi += 0.0025f*dy;
// Em coordenadas esféricas, o ângulo phi deve ficar entre -pi/2 e +pi/2.
float phimax = 3.141592f/2;
float phimin = -phimax;
if (g_CameraPhi > phimax)
g_CameraPhi = phimax;
if (g_CameraPhi < phimin)
g_CameraPhi = phimin;
// Atualizamos as variáveis globais para armazenar a posição atual do
// cursor como sendo a última posição conhecida do cursor.
g_LastCursorPosX = xpos;
g_LastCursorPosY = ypos;
}
// Função callback chamada sempre que o usuário movimenta a "rodinha" do mouse.
void ScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
// Atualizamos a distância da câmera para a origem utilizando a
// movimentação da "rodinha", simulando um ZOOM.
g_CameraDistance -= 0.1f*yoffset;
// Uma câmera look-at nunca pode estar exatamente "em cima" do ponto para
// onde ela está olhando, pois isto gera problemas de divisão por zero na
// definição do sistema de coordenadas da câmera. Isto é, a variável abaixo
// nunca pode ser zero. Versões anteriores deste código possuíam este bug,
// o qual foi detectado pelo aluno Vinicius Fraga (2017/2).
const float verysmallnumber = std::numeric_limits<float>::epsilon();
if (g_CameraDistance < verysmallnumber)
g_CameraDistance = verysmallnumber;
}
// Definição da função que será chamada sempre que o usuário pressionar alguma
// tecla do teclado. Veja http://www.glfw.org/docs/latest/input_guide.html#input_key
void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mod)
{
// ==============
// Não modifique este loop! Ele é utilizando para correção automatizada dos
// laboratórios. Deve ser sempre o primeiro comando desta função KeyCallback().
for (int i = 0; i < 10; ++i)
if (key == GLFW_KEY_0 + i && action == GLFW_PRESS && mod == GLFW_MOD_SHIFT)
std::exit(100 + i);
// ==============
// Se o usuário pressionar a tecla ESC, fechamos a janela.
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
////////////////////////////////////////////////////////////////////
//MOVIMENTAÇÃO DAS PLATAFORMAS EIXO X E Z
float cube_speed = 0.1;
if (glfwGetKey(window,GLFW_KEY_Q) == GLFW_PRESS)
{
for(int i =0; i<NUM_PLATFORMS; i++){
move_cubeXOld[i] = move_cubeX[i]; //Salva a posição caso o cubo nao possa se mover
if(i != on_top_of_platform){ //Se o personagem está em cima do cubo, ele não se mexe
move_cubeX[i] += (mod & GLFW_MOD_SHIFT) ? -cube_speed : cube_speed;
}
}
}
if (glfwGetKey(window,GLFW_KEY_E) == GLFW_PRESS)
{
for(int i =0; i<NUM_PLATFORMS; i++){
move_cubeZOld[i] = move_cubeZ[i]; //Salva a posição caso o cubo nao possa se mover
if(i != on_top_of_platform){ //Se o personagem está em cima do cubo, ele não se mexe
move_cubeZ[i] += (mod & GLFW_MOD_SHIFT) ? -cube_speed : cube_speed;
}
}
}
///////////////////////////////////////////////////////
// CONTROLE DA TELA
if (key == GLFW_KEY_F && action == GLFW_PRESS){
//Trocando entre mouse preso e mouse livre
mousetype++;
mousetype = mousetype%2;
switch(mousetype){
case 0: //MOUSE PRESO
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
break;
case 1: //MOUSE LIVRE
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); //MOSTRA O CURSOR
break;
}
}
/////////////////////////////////////////////////
// CAMERA
//Alterando o tipo de camêra de acordo com a tecla pressionada
//Tecla 1: Camêra em primeira pessoa do personagem
//Tecla 2: Camêra look at em volta do personagem
//Tecla 3: Camêra free por todo o cenário (noclip)
if (key == GLFW_KEY_1 && action == GLFW_PRESS)
{
camera_type = CHARACTER_CAMERA;
g_CameraPhi = 0.0825f;
}
if (key == GLFW_KEY_2 && action == GLFW_PRESS)
{
camera_type = LOOK_AT_CAMERA;
chr_pos[1] = on_top_of_y;
g_CameraPhi = 0.0825f;
}
if (key == GLFW_KEY_3 && action == GLFW_PRESS)
{
camera_type = FREE_CAMERA;
chr_pos[1] = on_top_of_y;
}
}
// Definimos o callback para impressão de erros da GLFW no terminal
void ErrorCallback(int error, const char* description)
{
fprintf(stderr, "ERROR: GLFW: %s\n", description);
}
// Escrevemos na tela o número de quadros renderizados por segundo (frames per
// second).
void TextRendering_ShowFramesPerSecond(GLFWwindow* window)
{
// Variáveis estáticas (static) mantém seus valores entre chamadas
// subsequentes da função!
static float old_seconds = (float)glfwGetTime();
static int ellapsed_frames = 0;
static char buffer[20] = "?? fps";
static int numchars = 7;
ellapsed_frames += 1;
// Recuperamos o número de segundos que passou desde a execução do programa
float seconds = (float)glfwGetTime();
// Número de segundos desde o último cálculo do fps
float ellapsed_seconds = seconds - old_seconds;
if ( ellapsed_seconds > 1.0f )
{
numchars = snprintf(buffer, 20, "%.2f fps", ellapsed_frames / ellapsed_seconds);
old_seconds = seconds;
ellapsed_frames = 0;
}
float lineheight = TextRendering_LineHeight(window);
float charwidth = TextRendering_CharWidth(window);
TextRendering_PrintString(window, buffer, 1.0f-(numchars + 1)*charwidth, 1.0f-lineheight, 1.0f);
}
// Função para debugging: imprime no terminal todas informações de um modelo
// geométrico carregado de um arquivo ".obj".
// Veja: https://github.com/syoyo/tinyobjloader/blob/22883def8db9ef1f3ffb9b404318e7dd25fdbb51/loader_example.cc#L98
void PrintObjModelInfo(ObjModel* model)
{
const tinyobj::attrib_t & attrib = model->attrib;
const std::vector<tinyobj::shape_t> & shapes = model->shapes;
const std::vector<tinyobj::material_t> & materials = model->materials;
printf("# of vertices : %d\n", (int)(attrib.vertices.size() / 3));
printf("# of normals : %d\n", (int)(attrib.normals.size() / 3));
printf("# of texcoords : %d\n", (int)(attrib.texcoords.size() / 2));
printf("# of shapes : %d\n", (int)shapes.size());
printf("# of materials : %d\n", (int)materials.size());
for (size_t v = 0; v < attrib.vertices.size() / 3; v++) {
printf(" v[%ld] = (%f, %f, %f)\n", static_cast<long>(v),
static_cast<const double>(attrib.vertices[3 * v + 0]),
static_cast<const double>(attrib.vertices[3 * v + 1]),
static_cast<const double>(attrib.vertices[3 * v + 2]));
}
for (size_t v = 0; v < attrib.normals.size() / 3; v++) {
printf(" n[%ld] = (%f, %f, %f)\n", static_cast<long>(v),
static_cast<const double>(attrib.normals[3 * v + 0]),
static_cast<const double>(attrib.normals[3 * v + 1]),
static_cast<const double>(attrib.normals[3 * v + 2]));
}
for (size_t v = 0; v < attrib.texcoords.size() / 2; v++) {
printf(" uv[%ld] = (%f, %f)\n", static_cast<long>(v),
static_cast<const double>(attrib.texcoords[2 * v + 0]),
static_cast<const double>(attrib.texcoords[2 * v + 1]));
}
// For each shape
for (size_t i = 0; i < shapes.size(); i++) {
printf("shape[%ld].name = %s\n", static_cast<long>(i),
shapes[i].name.c_str());
printf("Size of shape[%ld].indices: %lu\n", static_cast<long>(i),
static_cast<unsigned long>(shapes[i].mesh.indices.size()));
size_t index_offset = 0;
assert(shapes[i].mesh.num_face_vertices.size() ==
shapes[i].mesh.material_ids.size());
printf("shape[%ld].num_faces: %lu\n", static_cast<long>(i),
static_cast<unsigned long>(shapes[i].mesh.num_face_vertices.size()));
// For each face
for (size_t f = 0; f < shapes[i].mesh.num_face_vertices.size(); f++) {
size_t fnum = shapes[i].mesh.num_face_vertices[f];
printf(" face[%ld].fnum = %ld\n", static_cast<long>(f),
static_cast<unsigned long>(fnum));
// For each vertex in the face
for (size_t v = 0; v < fnum; v++) {
tinyobj::index_t idx = shapes[i].mesh.indices[index_offset + v];
printf(" face[%ld].v[%ld].idx = %d/%d/%d\n", static_cast<long>(f),
static_cast<long>(v), idx.vertex_index, idx.normal_index,
idx.texcoord_index);
}
printf(" face[%ld].material_id = %d\n", static_cast<long>(f),
shapes[i].mesh.material_ids[f]);
index_offset += fnum;
}
printf("shape[%ld].num_tags: %lu\n", static_cast<long>(i),
static_cast<unsigned long>(shapes[i].mesh.tags.size()));
for (size_t t = 0; t < shapes[i].mesh.tags.size(); t++) {
printf(" tag[%ld] = %s ", static_cast<long>(t),
shapes[i].mesh.tags[t].name.c_str());
printf(" ints: [");
for (size_t j = 0; j < shapes[i].mesh.tags[t].intValues.size(); ++j) {
printf("%ld", static_cast<long>(shapes[i].mesh.tags[t].intValues[j]));
if (j < (shapes[i].mesh.tags[t].intValues.size() - 1)) {
printf(", ");
}
}
printf("]");
printf(" floats: [");
for (size_t j = 0; j < shapes[i].mesh.tags[t].floatValues.size(); ++j) {
printf("%f", static_cast<const double>(
shapes[i].mesh.tags[t].floatValues[j]));
if (j < (shapes[i].mesh.tags[t].floatValues.size() - 1)) {
printf(", ");
}
}
printf("]");
printf(" strings: [");
for (size_t j = 0; j < shapes[i].mesh.tags[t].stringValues.size(); ++j) {
printf("%s", shapes[i].mesh.tags[t].stringValues[j].c_str());
if (j < (shapes[i].mesh.tags[t].stringValues.size() - 1)) {
printf(", ");
}
}
printf("]");
printf("\n");
}
}
for (size_t i = 0; i < materials.size(); i++) {
printf("material[%ld].name = %s\n", static_cast<long>(i),
materials[i].name.c_str());
printf(" material.Ka = (%f, %f ,%f)\n",
static_cast<const double>(materials[i].ambient[0]),
static_cast<const double>(materials[i].ambient[1]),
static_cast<const double>(materials[i].ambient[2]));
printf(" material.Kd = (%f, %f ,%f)\n",
static_cast<const double>(materials[i].diffuse[0]),
static_cast<const double>(materials[i].diffuse[1]),
static_cast<const double>(materials[i].diffuse[2]));
printf(" material.Ks = (%f, %f ,%f)\n",
static_cast<const double>(materials[i].specular[0]),
static_cast<const double>(materials[i].specular[1]),
static_cast<const double>(materials[i].specular[2]));
printf(" material.Tr = (%f, %f ,%f)\n",
static_cast<const double>(materials[i].transmittance[0]),
static_cast<const double>(materials[i].transmittance[1]),
static_cast<const double>(materials[i].transmittance[2]));
printf(" material.Ke = (%f, %f ,%f)\n",
static_cast<const double>(materials[i].emission[0]),
static_cast<const double>(materials[i].emission[1]),
static_cast<const double>(materials[i].emission[2]));
printf(" material.Ns = %f\n",
static_cast<const double>(materials[i].shininess));
printf(" material.Ni = %f\n", static_cast<const double>(materials[i].ior));
printf(" material.dissolve = %f\n",
static_cast<const double>(materials[i].dissolve));
printf(" material.illum = %d\n", materials[i].illum);
printf(" material.map_Ka = %s\n", materials[i].ambient_texname.c_str());
printf(" material.map_Kd = %s\n", materials[i].diffuse_texname.c_str());
printf(" material.map_Ks = %s\n", materials[i].specular_texname.c_str());
printf(" material.map_Ns = %s\n",
materials[i].specular_highlight_texname.c_str());
printf(" material.map_bump = %s\n", materials[i].bump_texname.c_str());
printf(" material.map_d = %s\n", materials[i].alpha_texname.c_str());
printf(" material.disp = %s\n", materials[i].displacement_texname.c_str());
printf(" <<PBR>>\n");
printf(" material.Pr = %f\n", materials[i].roughness);
printf(" material.Pm = %f\n", materials[i].metallic);
printf(" material.Ps = %f\n", materials[i].sheen);
printf(" material.Pc = %f\n", materials[i].clearcoat_thickness);
printf(" material.Pcr = %f\n", materials[i].clearcoat_thickness);
printf(" material.aniso = %f\n", materials[i].anisotropy);
printf(" material.anisor = %f\n", materials[i].anisotropy_rotation);
printf(" material.map_Ke = %s\n", materials[i].emissive_texname.c_str());
printf(" material.map_Pr = %s\n", materials[i].roughness_texname.c_str());
printf(" material.map_Pm = %s\n", materials[i].metallic_texname.c_str());
printf(" material.map_Ps = %s\n", materials[i].sheen_texname.c_str());
printf(" material.norm = %s\n", materials[i].normal_texname.c_str());
std::map<std::string, std::string>::const_iterator it(
materials[i].unknown_parameter.begin());
std::map<std::string, std::string>::const_iterator itEnd(
materials[i].unknown_parameter.end());
for (; it != itEnd; it++) {
printf(" material.%s = %s\n", it->first.c_str(), it->second.c_str());
}
printf("\n");
}
}
// set makeprg=cd\ ..\ &&\ make\ run\ >/dev/null
// vim: set spell spelllang=pt_br :
|
C++ | UTF-8 | 2,580 | 2.796875 | 3 | [] | no_license | /*
Problema - Monitorando a Amazônia
http://br.spoj.com/problems/MONAMAZ/
Guilherme Leobas
*/
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <deque>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <stack>
#include <queue>
#include <cmath>
#include <fstream>
#include <functional>
#include <iomanip>
using namespace std;
#define PI acos(-1)
#define cnt PI/180
#define INF 99999999
typedef vector<vector<pair<int, int> > > graph;
double dist[1010][1010];
struct point {
int x, y, i;
point (){
x = INF;
y = INF;
}
point (int _x, int _y, int _i){
x = _x;
y = _y;
i = _i;
}
};
int calc_dist (point a, point b){
return ( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
}
bool bfs (vector<point> &P){
queue<int> q;
vector<int> visited (P.size(), 0);
int atual, next1, next2, n = P.size();
double dist1, dist2;
q.push (0);
visited[0] = 1;
while (!q.empty()){
atual = q.front();
q.pop();
next1 = -1;
dist1 = INF;
next2 = -1;
dist2 = INF;
for (int i=0; i<n; i++){
if (i == atual)
continue;
// cout << i << ' ' << dist[atual][i] << endl;
if (dist1 > dist[atual][i]){
dist1 = dist[atual][i];
next1 = i;
}
else if (dist1 == dist[atual][i]){
if (P[next1].x > P[i].x){
next1 = i;
}
else if (P[next1].x == P[i].x){
if (P[next1].y > P[i].y){
next1 = i;
}
}
}
}
for (int i=0; i<n; i++){
if (i == next1 || i == atual)
continue;
if (dist2 > dist[atual][i]){
dist2 = dist[atual][i];
next2 = i;
}
else if (dist2 == dist[atual][i]){
if (P[next2].x > P[i].x){
next2 = i;
}
else if (P[next2].x == P[i].x){
if (P[next2].y > P[i].y){
next2 = i;
}
}
}
}
if (next1 != -1 && !visited[next1]){
q.push (next1);
visited[next1] = 1;
}
if (next2 != -1 && !visited[next2]){
q.push (next2);
visited[next2] = 1;
}
}
for (int i=0; i<visited.size(); i++){
if (!visited[i])
return false;
}
return true;
}
int main (){
ios::sync_with_stdio(false);
int n, x, y;
vector<point> P;
while (true){
cin >> n;
if (!n)
break;
P.clear();
P.resize (n);
for (int i=0; i<n; i++){
cin >> x >> y;
P[i] = point (x, y, i);
}
for (int i=0; i<n; i++){
for (int j=i+1; j<n; j++){
dist[i][j] = calc_dist (P[i], P[j]);
dist[j][i] = dist[i][j];
}
}
if (bfs (P)){
cout << "All stations are reachable.\n";
}
else {
cout << "There are stations that are unreachable.\n";
}
}
return 0;
}
|
C# | UTF-8 | 226 | 3.140625 | 3 | [] | no_license | private int myProperty;
public int MyProperty
{
get { return myProperty; }
set { myProperty = value; } // value is an implicit parameter containing the value being assigned to the property.
}
|
Python | UTF-8 | 1,710 | 2.828125 | 3 | [] | no_license | from os import makedirs
from os import listdir
from shutil import copyfile
from random import seed
from random import random
from CreateLabelsDictonary import create_labels_dictionary
from pathlib import PureWindowsPath, Path
from keras.preprocessing.image import ImageDataGenerator
l = 3
# set the location of the dataset
dataset_home = Path('')
labels_dictionary = create_labels_dictionary('labels.txt')
sub_directories = ['train/, test/']
# Make Directories
for subdir in sub_directories:
labels_dirctories = {str(x).join('/') for _, x in labels_dictionary.items()}
for labeldir in labels_dictionary:
new_directory = Path(dataset_home + subdir + labeldir)
makedirs(new_directory, exist_ok=True)
# set random seed
seed(1)
# Define the data used fro validation ratio
validation_ratio = 0.25
# Copy images into subdirectories
# set the location of the source directory where dataset is located
source_directory = dataset_home
for file in listdir(source_directory):
source = Path(source_directory + '/' + file)
destination_directory = '/train'
if random() < validation_ratio:
destination_directory = '/test'
destination = Path(dataset_home + destination_directory + labels_dictionary[file[0:l]] + '/' + file)
copyfile(source, destination)
# prepare iterations
dataGenerator = ImageDataGenerator()
train = dataGenerator.flow_from_directory(Path(dataset_home + 'train/'), class_mode='categorical', batch_size=32,
target_size=(200, 200))
test = dataGenerator.flow_from_directory(Path(dataset_home + 'test/'), class_mode='categorical', batch_size=32,
target_size=(200, 200))
|
Java | UTF-8 | 368 | 1.640625 | 2 | [] | no_license | package com.course2go.model.notice;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class NoticeCreateRequest {
private String noticeUid;
private Integer noticeType;
private String noticeFromUid;
private Integer noticeNnid;
private boolean noticeIsnew;
}
|
C | UTF-8 | 15,203 | 2.609375 | 3 | [] | no_license |
#include "ntpapis.h"
tspkt *timeanchor = NULL;
ntpinfo *ntp_anchor = NULL;
int prevOffset = INT_MAX;
//char payload[10] = "1234567890";
static const unsigned char payload[] = {
0x00,
};
/* calculate the T1 timestamping using SO_TI**** APIS*/
struct timeval sendTimeofPacket(int seqnum){
/* give me seq num and I will give you the tx of that packet */
tspkt *current = timeanchor;
struct timeval error;
if(timeanchor == NULL){
/* no such value */
goto error;
} else {
do{
if(current->seqnum == seqnum){
return current->sendtime;
}
current = current->next;
}while(current != NULL);
}
error:
error.tv_sec = -1;
error.tv_usec = -1;
return error;
}
struct timeval recvTimeofPacket(int seqnum){
/* give me seq num and I will give you the tx of that packet */
tspkt *current = timeanchor;
struct timeval error;
if(timeanchor == NULL){
/* no such value */
goto error;
} else {
do{
if(current->seqnum == seqnum){
return current->recvtime;
}
current = current->next;
}while(current != NULL);
}
error:
error.tv_sec = -1;
error.tv_usec = -1;
return error;
}
int bindAddress(int sock , int reuseaddr , struct in_addr *ip ){
struct sockaddr_in inInAddr;
int ret , set_option_on = 1;
inInAddr.sin_addr.s_addr = ip->s_addr; //inet_addr(ip); /*INADDR_ANY;*/
inInAddr.sin_port = htons(CNTP_PORT);
inInAddr.sin_family = AF_INET;
if(reuseaddr){
ret = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on, sizeof(set_option_on));
if(0 > ret){
perror("UDP SO_REUSEADDR\n");
//exit(1);
return -1;
}
ret = setsockopt(sock, SOL_SOCKET, 15, (char*) &set_option_on, sizeof(set_option_on));
if(0 > ret){
perror("UDP SO_REUSEADDR\n");
//exit(1);
return -1;
}
}
ret = bind(sock, (struct sockaddr *) &inInAddr, sizeof(struct sockaddr_in));
if (0 > ret){
perror("UDP bind() failed:\n");
return -1;
}
return 1;
}
int createUDPSocket(){
int sock;
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock < 0){
perror("socket");
return -1;
//exit(1);
}
return sock;
}
int addtstolist(int seqnum , struct timeval *sendts , struct timespec *recvts){
tspkt *current = timeanchor , *node;
/* check if node with seqnum exists */
do{
if(current == NULL)
break;
if(seqnum == current->seqnum){
break;
}
current = current->next;
}while(current != NULL);
if(current == NULL){
current = timeanchor;
node = (tspkt*)malloc(sizeof(tspkt));
if(node == NULL){
printf("SOme memory issue:\n");
return -1;
//exit(1);
}
/*copy data into node */
node->next = NULL;
node->seqnum = seqnum;
if(sendts == NULL ){
node->recvtime.tv_sec = recvts->tv_sec;
node->recvtime.tv_usec = (recvts->tv_nsec)/1000;
} else if(recvts == NULL){
node->sendtime.tv_sec = sendts->tv_sec;
node->sendtime.tv_usec = sendts->tv_usec;
}
if(timeanchor == NULL){
timeanchor = node;
}else{
while(current->next != NULL){
current = current->next;
}
current->next = node;
}
} else {
/* node already exists */
if(sendts == NULL ){
current->recvtime.tv_sec = recvts->tv_sec;
current->recvtime.tv_usec = (recvts->tv_nsec)/1000;
} else if(recvts == NULL){
current->sendtime.tv_sec = sendts->tv_sec;
current->sendtime.tv_usec = sendts->tv_usec;
}
}
return 1;
}
int freetslist(){
tspkt *current = timeanchor;
if(timeanchor == NULL){
return 1;
} else {
while(current != NULL){
free(current);
current = current->next;
}
}
return 1;
}
/* send packet to specific interface IP */
int ntpsendto(char *ip , int seq , ntpPacket *send_pkt , int fd){
struct sockaddr_in daddr;
struct timeval t1;
int ret;
//ntpPacket send_pkt;
memset(&daddr, 0, sizeof(daddr));
daddr.sin_family = AF_INET;
daddr.sin_port = htons(CNTP_PORT);
daddr.sin_addr.s_addr = inet_addr(ip);
send_pkt->seqnum = seq;
//gettimeofday(&t1, NULL);
//printf("time (app): %lus.%luus\n", t1.tv_sec, t1.tv_usec);
ret = sendto(fd, send_pkt, sizeof(ntpPacket), 0,
(void *) &daddr, sizeof(daddr));
if (ret != sizeof(ntpPacket)) {
perror("sendto");
return -1;
}
return 1;
}
int ntprecvfrom(ntpPacket *recv_pkt , int sock , int recvmsg_flags){
char data[256];
struct msghdr msg;
struct iovec entry;
struct sockaddr_in from_addr;
struct {
struct cmsghdr cm;
char control[512];
} control;
int res;
memset(&msg, 0, sizeof(msg));
msg.msg_iov = &entry;
msg.msg_iovlen = 1;
entry.iov_base = data;
entry.iov_len = sizeof(data);
msg.msg_name = (caddr_t)&from_addr;
msg.msg_namelen = sizeof(from_addr);
msg.msg_control = &control;
msg.msg_controllen = sizeof(control);
res = recvmsg(sock, &msg, recvmsg_flags );
if (res < 0) {
/* printf("%s %s: %s\n",
"recvmsg",
(recvmsg_flags & MSG_ERRQUEUE) ? "error" : "regular",
strerror(errno));*/
} else {
if(!(recvmsg_flags & MSG_ERRQUEUE)){
memcpy(recv_pkt , data , sizeof(ntpPacket));
// printf("seq we got:=%d\n",recv_pkt->seqnum );
} else {
memcpy((void*)recv_pkt, data + res - sizeof(ntpPacket), sizeof(ntpPacket));
}
printpacket(&msg, res, data,
sock , recvmsg_flags , recv_pkt);
}
return res;
}
void printpacket(struct msghdr *msg, int res,
char *data,
int sock , int recvmsg_flags , ntpPacket *recv_pkt)
{
struct cmsghdr *cmsg;
ntpPacket payload ;
struct timeval *sendTime = NULL ;
struct timespec *recvTime = NULL;
for (cmsg = CMSG_FIRSTHDR(msg);
cmsg;
cmsg = CMSG_NXTHDR(msg, cmsg)) {
switch (cmsg->cmsg_level) {
case SOL_SOCKET:
switch (cmsg->cmsg_type) {
case SO_TIMESTAMP: {
sendTime = (struct timeval *)CMSG_DATA(cmsg);
/* printf("Recieving Timestamp(T4) ");
printf(" %ld.%06ld",
(long)sendTime->tv_sec,
(long)sendTime->tv_usec);*/
break;
}
case SO_TIMESTAMPING: {
recvTime = (struct timespec *)CMSG_DATA(cmsg);
/* printf("Sending Timestamp(T1) ");
printf(" %ld.%06ld ",
(long)recvTime->tv_sec,
((long)recvTime->tv_nsec/1000));*/
break;
}
default:
printf("type %d", cmsg->cmsg_type);
break;
}
break;
case IPPROTO_IP:
switch (cmsg->cmsg_type) {
case IP_RECVERR: {
struct sock_extended_err *err =
(struct sock_extended_err *)CMSG_DATA(cmsg);
assert(err);
if (res < sizeof(ntpPacket))
printf(" => truncated data?!");
break;
}
default:
printf("type %d", cmsg->cmsg_type);
break;
}
break;
default:
printf("level %d type %d",
cmsg->cmsg_level,
cmsg->cmsg_type);
break;
}
// printf("\n");
}
//printf("Recieved Packet : %s",(recvmsg_flags & MSG_ERRQUEUE) ? "errorQPacket\n" : "regularPacket\n");
//printf("Seqnum = %d\n",recv_pkt->seqnum);
if(recvmsg_flags & MSG_ERRQUEUE){
addtstolist(recv_pkt->seqnum , sendTime , NULL);
} else {
addtstolist(recv_pkt->seqnum , NULL , recvTime);
}
}
int setSOCflags(int sockfd , int ifsend){
int flags;
if(ifsend){
flags = SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_SOFTWARE;
if (setsockopt(sockfd, SOL_SOCKET, SO_TIMESTAMPING, &flags, sizeof(flags))) {
perror("setsockopt SO_TIMESTAMPING");
return -1;
}
}else {
flags = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_TIMESTAMP,
&flags, sizeof(flags)) < 0){
perror("setsockopt SO_TIMESTAMP");
return -1;
}
}
return 1;
}
int setMulticast(int sock){
struct ip_mreq imr;
struct in_addr iaddr;
inet_aton("224.0.1.130", &iaddr); /* alternate PTP domain 1 */
//addr.sin_addr = iaddr;
imr.imr_multiaddr.s_addr = iaddr.s_addr;
imr.imr_interface.s_addr = INADDR_ANY;
// ((struct sockaddr_in *)&device.ifr_addr)->sin_addr.s_addr;
if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF,
&imr.imr_interface.s_addr, sizeof(struct in_addr)) < 0){
perror("set multicast");
return -1;//(1);
}
/* join multicast group, loop our own packet */
if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
&imr, sizeof(struct ip_mreq)) < 0){
perror("join multicast group");
return -1;
}
return 1;
}
/* this function will use select syscall and check if the packet is ready to receive*/
int ifPacketReady(int sock){
fd_set readfs, errorfs;
int res;
struct timeval delta;
/* timer for 5 sec timeout */
delta.tv_sec = 5;
delta.tv_usec = 0;
FD_ZERO(&readfs);
FD_ZERO(&errorfs);
FD_SET(sock, &readfs);
FD_SET(sock, &errorfs);
res = select(sock + 1, &readfs, 0, &errorfs, &delta);
if (res > 0) {
if (FD_ISSET(sock, &readfs)){
//printf("ready for reading\n");
return 1;
}
if (FD_ISSET(sock, &errorfs)){
printf("has error\n");
return 0;
}
} else {
return 0;
}
return 0;
}
/* create the number of threads according to interface */
void createThread(pthread_t *threadid , void *(*func) (void *) , ntpinfo *info){
/* write now we dont need interface */
int myerrno = -1 ;
if((myerrno = pthread_create(threadid, 0,func, (void*)info ))){
fprintf(stderr, "pthread_create[0] %s\n",strerror(myerrno));
pthread_exit(0);
}
}
/* join if threads */
void joinThreads(int count , pthread_t *threadIds){
int i =0 , myerrno =0;
for (i=0; i< count;i++) {
if((myerrno = pthread_join(threadIds[i], 0))){
fprintf(stderr, "pthread_join[i] %s\n",strerror(myerrno));
pthread_exit(0);
}
}
}
long time_diff(struct timeval x , struct timeval y)
{
long x_ms, y_ms, msec;
x_ms = (long)x.tv_sec*1000000 + (long)x.tv_usec;
y_ms = (long)y.tv_sec*1000000 + (long)y.tv_usec;
msec = (long)y_ms - (long)x_ms;
return msec;
}
void removefromlist(int seqnum){
tspkt *current = timeanchor;
do{
if(current->seqnum == seqnum){
// return current->sendtime;
}
current = current->next;
}while(current != NULL);
if(current == NULL){
printf("SOmeting wrong in logic\n");
exit(1);
}
/* adjust the node */
free(current);
// return;
}
/* calculate the network delay */
int calcnetdelay(ntpPacket *packet , int stratum){
assert(stratum < packet->stratum);
struct timeval t1 , t2 , t3 , t4 ;
int delay;
int offset;
FILE *fp;
t1 = sendTimeofPacket(packet->seqnum);
t2 = packet->t2;
t3 = packet->t3;
t4 = recvTimeofPacket(packet->seqnum);
(packet->t1).tv_sec = t1.tv_sec;
(packet->t1).tv_usec = t1.tv_usec;
(packet->t4).tv_sec = t4.tv_sec;
(packet->t4).tv_usec = t4.tv_usec;
printf("**************** SEQ NUM = %d *******************\n",packet->seqnum);
printf("**************** T1 = %lus.%lus *****************\n", t1.tv_sec , t1.tv_usec);
printf("**************** T2 = %lus.%lus *****************\n", t2.tv_sec , t2.tv_usec);
printf("**************** T3 = %lus.%lus *****************\n", t3.tv_sec , t3.tv_usec);
printf("**************** T4 = %lus.%lus *****************\n", t4.tv_sec , t4.tv_usec );
delay = time_diff(t1 , t4) - time_diff(t2 , t3);
offset = (time_diff(t1 , t2) + time_diff(t4 , t3))/2;
printf("*************** Network Delay = %d ******************** \n",delay);
printf("**************** offset = %d *******************\n",offset);
packet->networkdelay = delay;
packet->offset = offset;
fp = fopen("Offset_readings.txt","a+");
fprintf(fp , "%d\n" , offset);
/* do later memory leak*/
//removefromlist(packet->seqnum);
fclose(fp);
return delay;
}
/* calculate the delay error due to jitter */
int calcdelayerror(ntpPacket *packet){
int t3jitter;
struct timeval t3kernel = sendTimeofPacket(packet->oldseqnum);
t3jitter = packet->networkdelay + time_diff(packet->t4 , packet->t1) + time_diff(packet->t2 , t3kernel);
return t3jitter;
}
int updatetime(ntpPacket *packet){
int recvjitter;
struct timeval tuser , tkernel , tfinal;
int sectoadd , usectoadd , t3jitter;
printf("PrevOffset = %d and New Offset = %d\n",prevOffset , packet->offset );
if(abs(prevOffset) < abs(packet->offset))
return 1;
prevOffset = packet->offset;
/* faulty */
t3jitter = calcdelayerror(packet);
printf("t3jitter = %d\n",t3jitter);
printf("Delay = %d\n",packet->networkdelay);
usectoadd = (packet->networkdelay) % 999999;
sectoadd = (packet->networkdelay) / 999999;
gettimeofday(&tuser , 0);
tkernel = recvTimeofPacket(packet->seqnum);
recvjitter = time_diff(tkernel , tuser);
tfinal.tv_sec = (packet->mastertime).tv_sec + (sectoadd/2) +SLEEPTIME;
tfinal.tv_usec = (packet->mastertime).tv_usec + recvjitter + (usectoadd/2) - t3jitter;
settimeofday(&tfinal , 0);
printf(" tkernel = %ld.%06ld :: tuser = %ld.%06ld \n",
(long)tkernel.tv_sec,
(long)tkernel.tv_usec,
(long)tuser.tv_sec,
(long)tuser.tv_usec
);
return 1;
}
FILE *openFile(char *filename){
FILE *fd;
fd = fopen(filename , "r");
if(fd == NULL){
printf("No slave or master of this client exist \n");
return NULL;
}
return fd;
}
int getifaceIP(struct ifreq *device ,char *iface , int sock ){
memset(device, 0, sizeof(device));
strncpy(device->ifr_name, iface, sizeof(device->ifr_name));
if (ioctl(sock, SIOCGIFADDR, device) < 0){
perror("getting interface IP address");
return -1;
//exit(1);
}
return 1;
}
ntpinfo *addntpinfotolist(ntpinfo **ntp_anchor , struct in_addr *ip , int sendsock , char *iface ,char *slaveip ){
ntpinfo *add;
ntpinfo *current = *ntp_anchor;
add = (ntpinfo*)malloc(sizeof(ntpinfo));
if(add == NULL){
printf("Error while malloc!\n");
exit(1);
}
add->sockfd = sendsock;
strncpy(add->interface ,iface ,sizeof(iface)+1);
strncpy(add->slaveip ,slaveip ,sizeof(slaveip)+1);
strncpy((char*)&add->myip ,(char*)ip ,sizeof(ip)+1);
add->next = NULL;
if(*ntp_anchor == NULL){
*ntp_anchor = add;
} else {
while (current->next != NULL) {
current = current->next;
}
current->next = add;
}
return add;
}
void freentpinfolist(){
ntpinfo *current = ntp_anchor;
if(ntp_anchor == NULL){
printf("Something wrong with list..NO elements\n");
exit(1);
} else {
while(current != NULL){
free(current);
current = current->next;
}
}
// return 1;
}
ntpinfo *fillntpinfo(char *slaveip , char *iface , char *myip , void *(*func) (void *) , pthread_t *thread , int threadcount){
ntpinfo *info;
struct ifreq device;
int ret , sendsock;
struct in_addr ip_inaddr;
sendsock = createUDPSocket();
if(sendsock < 0)
freeresources(1);
//goto free;
ret = setSOCflags(sendsock , 1);
if(ret < 0)
freeresources(1);
//goto free;
ret = setSOCflags(sendsock , 0);
if(ret < 0)
freeresources(1);
//goto free;
ret = getifaceIP(&device , iface , sendsock);
if(ret < 0)
freeresources(1);
//goto free;
ip_inaddr = ((struct sockaddr_in *)&device.ifr_addr)->sin_addr;
/* store ip , sendsock , ifaceIP to ll */
info = addntpinfotolist(&ntp_anchor , &ip_inaddr , sendsock , iface ,slaveip );
if(info == NULL){
printf("Somehting wrong in LL\n");
return NULL;
//goto free;
}
ret = bindAddress(sendsock , 1 , &ip_inaddr);
if(ret < 0)
freeresources(1);
//goto free;
createThread(&thread[threadcount] , func , info );
printf("thread create = %d",threadcount);
return info;
}
|
C# | UTF-8 | 3,150 | 2.578125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TranslatorService.Speech;
using HMF_KOMAI_CSHARP.Properties;
using SpeechLib;
namespace HMF_KOMAI_CSHARP.Services
{
public class UcommSpeaker
{
private SpeechSynthesizer speaker;
private SpVoice voice;
private SpeechVoiceSpeakFlags voiceFlag;
/// <summary>
/// constructor
/// </summary>
public UcommSpeaker()
{
voice = new SpVoice();
voice.Volume = 100;
voice.Rate = 0;
voiceFlag = SpeechVoiceSpeakFlags.SVSFlagsAsync | SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak;
speaker = new SpeechSynthesizer(Properties.Settings.Default.AZURE_CLIENT_ID, Properties.Settings.Default.AZURE_CLIENT_SECRET);
}
/// <summary>
/// 認証前のアナウンス
/// </summary>
public void PromoteCertification()
{
voice.Speak("指紋センサーに指を置いて、認証を行ってください。", voiceFlag);
}
/// <summary>
/// 認証完了のアナウンス
/// </summary>
public void CompleteCertificate(string username = "Test")
{
voice.Speak("認証が完了しました。" + CreateGreeting() + String.Format( " {0}さん", username), voiceFlag);
}
/// <summary>
/// 検索結果を喋らせる
/// </summary>
/// <param name="str"></param>
public void speechSearchResult(String str)
{
}
/// <summary>
/// スケジュールを喋らせる。
/// TODO: スケジュール用のオブジェクトとか必要かも
/// </summary>
public void speechSchedule()
{
}
/// <summary>
/// 自由に喋らせる
/// </summary>
/// <param name="str">喋らせたい文字列</param>
public void freeSpeech(String str)
{
}
public void changeMode(String str) {
}
/// <summary>
/// 読み上げスピードの変更
/// </summary>
/// <param name="positive"></param>
public void changeSpeechSpeed(bool positive)
{
}
/// <summary>
/// 読み上げ音量の変更
/// </summary>
/// <param name="positive"></param>
public void changeSpeechVolume(bool positive)
{
}
private string CreateGreeting()
{
string greet = String.Empty;
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString());
if (now.Hour >= 6 && now.Hour <= 10)
greet = Resources.SPEAK_GREETING_MORNING;
else if (now.Hour >= 15)
greet = Resources.SPEAK_GREETING_EVENING;
else
greet = Resources.SPEAK_GREETING_NIGHT;
return greet;
}
}
}
|
C# | UTF-8 | 2,991 | 2.703125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
namespace MarioProgrammer
{
public enum HeroNames
{
Nerd,
Chewbacca,
Princess
}
public enum SkinNames
{
StandLeft,
StandRight,
MovingLeftFirst,
MovingLeftSecond,
MovingRightFirst,
MovingRightSecond
}
public enum HeroPhrases
{
Hello,
Bye,
SaveMe,
Ok,
Aagh
}
public enum Music
{
MainTheme,
CalmMusic,
BattleMusic
}
public class SkinData
{
public string Name { get; private set; }
public Image[] Skins { get; private set; }
public SoundPlayer[] Phrases { get; private set; }
public SoundPlayer[] Music { get; private set; }
public bool Unlocked { get; private set; }
public void Unlock()
{
Unlocked = true;
}
public SkinData(string name, Image[] skins, SoundPlayer[] sounds, SoundPlayer[] musics, bool unlocked)
{
Name = name;
for (var i = 0; i < sounds.Length; i++)
Phrases[i] = sounds[i];
for (var i = 0; i < musics.Length; i++)
Music[i] = musics[i];
for (var i = 0; i < skins.Length; i++)
Skins[i] = skins[i];
Unlocked = unlocked;
}
}
public class Achievement
{
public string Name { get; private set; }
public bool Unlocked { get; private set; }
public void Unlock()
{
Unlocked = true;
}
}
class GameData
{
public DateTime TimeInGame { get; private set; }
public int Money { get; private set; }
public int[] BestPoints { get; private set; }
public SkinData[] Skins { get; private set; }
public Dictionary<string, Achievement> Achievements { get; private set; }
public string[] Paths { get; private set; }
public GameData()
{
var gameFile = File.ReadAllLines("/Architecture/GameMap.txt");
TimeInGame = DateTime.Parse(gameFile[0]);
Money = int.Parse(gameFile[1]);
var countBestPoints = int.Parse(gameFile[2]);
BestPoints = new int[countBestPoints];
var count = 3;
for (var i = 0; i < countBestPoints; i++)
{
BestPoints[count] = int.Parse(gameFile[count]);
count++;
}
var skinPaths = int.Parse(gameFile[count]);
for (var i = 0; i < skinPaths; i++)
{
SetSkin(gameFile[count]);
count++;
}
var countAchievement = gameFile[count];
count++;
}
private void SetSkin(string path)
{
}
}
}
|
PHP | UTF-8 | 1,299 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$param =[
'id' => '1',
'username' => 'sans',
'mail' => 'sans@gmail.com',
'password' => 'megarovania',
'bio'=> 'Should be burning in hell.',
'images' => '',
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
];
DB::table('users')->insert($param);
$param =[
'id' => '2',
'username' => 'mettaton',
'mail' => 'mettaton@gmail.com',
'password' => 'Death by Glamour',
'bio' => 'His metal body renders him invulnerable to attack.',
'images' => '',
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
];
DB::table('users')->insert($param);
$param =[
'id' => '3',
'username' => 'asgore',
'mail' => 'asgore@gmail.com',
'password' => 'ASGORE',
'bio' => 'What kind of monster are you…?',
'images' => '',
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
];
DB::table('users')->insert($param);
}
}
|
C# | UTF-8 | 3,693 | 3.21875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace XCRI.Validation.ContentValidation
{
/// <summary>
/// Validates that an element is (or is not, depending upon <see cref="EnforcementType"/>)
/// empty. Empty is defined as either a self-closing element (for example: <element />)
/// or an element with no child elements (for example: <element></element>).
/// </summary>
/// <seealso cref="IValidator"/>
public class EmptyElementValidator : Validator
{
/// <summary>
/// Whether to force that the item is empty or not. Defaults to ForceNotEmpty.
/// </summary>
public EnforcementTypes EnforcementType { get; set; }
public EmptyElementValidator()
: base()
{
this.EnforcementType = EnforcementTypes.ForceNotEmpty;
}
public override bool PassesValidation(System.Xml.Linq.XObject input, out string details)
{
details = null;
if (null == input)
throw new ArgumentNullException("input");
string value;
if (input is XElement)
value = (input as XElement).Value;
else
throw new ArgumentException("The input parameter type " + input.GetType().FullName + " was not expected", "input");
switch (this.EnforcementType)
{
case EnforcementTypes.ForceEmpty:
if (false == String.IsNullOrWhiteSpace(value))
{
details = String.Format
(
"Element has a value of '{0}'",
value
);
return false;
}
if ((input as XElement).DescendantNodes().Count() > 0)
{
details = String.Format
(
"Element has {0} children (none allowed)",
(input as XElement).DescendantNodes().Count()
);
return false;
}
return true;
case EnforcementTypes.ForceNotEmpty:
if (String.IsNullOrWhiteSpace(value))
{
details = "Element has no value when one was expected";
return false;
}
if ((input as XElement).DescendantNodes().Count() == 0)
{
details = String.Format
(
"Element has 0 child nodes when they were expected",
(input as XElement).DescendantNodes().Count()
);
return false;
}
return true;
default:
throw new NotImplementedException();
}
}
/// <summary>
/// Whether to enforce that the element is empty or not.
/// </summary>
public enum EnforcementTypes
{
/// <summary>
/// Forces that the element is not empty
/// </summary>
ForceNotEmpty = 1,
/// <summary>
/// Forces that the element is empty
/// </summary>
ForceEmpty = 2
}
}
}
|
Python | UTF-8 | 5,861 | 2.765625 | 3 | [] | no_license | from src.utils import museumpiece
__author__ = 'colin'
from sqlalchemy import Column, Integer, Date, func
from alchemical_base import Base
import bisect
import datetime
from models import *
class Month(Base):
"""A contiguous block of 28 days (in practice, but could be more or less),
not necessarily corresponding to the calendar definition of "month". In
practice, we'll be creating a bunch of these covering overlapping periods.
"""
__tablename__ = 'months'
id = Column(Integer, primary_key=True)
first = Column(Date)
last = Column(Date) # Should be first+27
# TODO: design question, should I include month-specific network vars here
# like effective size?
def __cmp__(self, other):
"""Compare two Months based on start date.
"""
return cmp(self.first, other.first)
@property
def fname(self, ext='csv'):
return str(self.first) + '.' + ext
def bugmonths(self, session):
pass
def prev(self, session):
"""Return the latest preceding NON-OVERLAPPING month, or None if none
exists.
"""
#if self.id <= 2:
# raise ValueError("No previous month in table.")
last = session.query(Month).filter_by(id = self.id-2).scalar()
assert last is None or (self.first - last.first).days == 28
return last
def next(self, session):
"""Return the next NON-OVERLAPPING month, or None if none
exists.
"""
#if self.id <= 2:
# raise ValueError("No previous month in table.")
next = session.query(Month).filter_by(id = self.id+2).scalar()
assert next is None or (next.first - self.first).days == 28
return next
def get_network(self):
raise NotImplementedError
@staticmethod
def sorted_months(session):
months = session.query(Month).all()
months.sort()
return months
def __str__(self):
return "Month with id %d from %s to %s" % (self.id, str(self.first), str(self.last))
def __repr__(self):
return str(self)
class Quarter(object):
quarterspan = datetime.timedelta(days=28*3-1)
def __init__(self, **kwargs):
# Hackety hack hack hack
if 'next' in kwargs:
self.last = kwargs['next'].first - datetime.timedelta(days=1)
self.first = self.last - self.quarterspan
elif 'first' in kwargs:
self.first = kwargs['first'].first
self.last = self.first + self.quarterspan
elif 'last' in kwargs:
self.last = kwargs['last'].last
self.first = self.last - self.quarterspan
else:
raise ValueError("Specify either the first or the last month")
def prev(self, session):
# If we've hit the end of our data, return None
dayone = session.query(func.min(Month.first)).scalar()
if dayone > self.first:
return None
return Quarter(next=self)
class MonthSet(object):
"""A sorted collection of Months."""
def __init__(self, months):
self.months = months
self.months.sort()
self.firsts = [month.first for month in self.months]
self.lasts = [month.last for month in self.months]
def __len__(self):
return len(self.months)
@staticmethod
def from_session(session):
months = session.query(Month).all()
return MonthSet(months)
def after(self, date, end=False, eq=False):
"""Return the starting index for months beginning after the given date.
If end is True, then return months ENDING after the given date (i.e.
return one extra result).
If eq is true then after becomes after or equal to.
"""
array = self.lasts if end else self.firsts
if eq:
return bisect.bisect_left(array, date)
else:
return bisect.bisect_right(array, date)
def monthafter(self, date, end=False, eq=False):
"""Return the first month beginning after the given date.
If end is True, then return month ENDING after the given date.
If eq is true then after becomes after or equal to.
@throws: Indexerror, if this date is in the last month
"""
array = self.lasts if end else self.firsts
# This is kind of tricky. We're relying on the parallel structure of array and self.months
if eq:
return self[bisect.bisect_left(array, date)]
else:
return self[bisect.bisect_right(array, date)]
def __getitem__(self, item):
# Are we okay with just returning a list, or should it be another MonthSet?
return self.months.__getitem__(item)
@museumpiece
def populate_months(session):
if session.query(Month).count() > 0:
raise Exception("Months table is already populated.")
demimonth = datetime.timedelta(days=14)
first_chat = session.query(func.min(Chat.date)).scalar()
first_bugevent = session.query(func.min(BugEvent.date)).scalar()
start_date = max(first_chat, first_bugevent)
print "First chat is " + str(first_chat)
print "First bug event is " + str(first_bugevent)
print "Starting months on " + str(start_date)
last_chat = session.query(func.max(Chat.date)).scalar()
last_bugevent = session.query(func.max(BugEvent.date)).scalar()
end_date = min(last_chat, last_bugevent)
print "Last chat is " + str(last_chat)
print "Last bug event is " + str(last_bugevent)
print "End months on or around " + str(end_date)
start = start_date
end = start_date + datetime.timedelta(days=27) # start + 27 days = 28 day span
while end < end_date:
month = Month(first=start, last=end)
session.add(month)
start += demimonth
end += demimonth
session.commit()
|
Python | UTF-8 | 863 | 2.890625 | 3 | [] | no_license | from nltk.corpus import wordnet
from tkinter import Tk,Label,Entry,Text,END,Button
root=Tk()
root.title("Dictionary")
root.geometry('1000x800')
root.configure(bg="orange")
label1 = Label(root, text="Search",font="Helvetica 20 bold",bg="orange")
E1 = Entry(root, bd =5,font="gotham",bg="white")
def code():
word=E1.get()
syn = wordnet.synsets(word)
T = Text(root,height=9, width=500,bd=5,font="gotham",bg="white")
T.pack(side="bottom",expand=True)
try:
for i in range(1,101):
T.insert(END,str(i)+")"+str(syn[i].definition()).capitalize()+"\n")
except IndexError:
T.insert(END,"Sorry!!! No more meanings available")
submit = Button(root, text ="Submit", command = code,font="gotham",bg="orange",bd=5,relief="raised")
label1.pack()
E1.pack()
submit.pack()
root.mainloop() |
Shell | UTF-8 | 532 | 2.921875 | 3 | [] | no_license | #!/bin/sh -xe
# 閏年は考慮していないし、31日に実行するとだめになる
CURRENT_MONTH=`date +"%m"`
DAY=30
if [ $CURRENT_MONTH = 03 ]; then
DAY=28
fi
YEAR=`date +"%Y" -D %s -d "$(($(date +%s) - 86400 * DAY))"`
MONTH=`date +"%m" -D %s -d "$(($(date +%s) - 86400 * DAY))"`
HOST=$1
ROSTERNAME=$2
./rads-cli -y $YEAR -m $MONTH -f $ROSTERNAME -H $HOST
wget --post-data='{ "Title":"勤務表","Message":"勤務表をドライブにコピーしました" }' --header=Content-Type:application/json $HOST/postSlack |
C# | UTF-8 | 1,974 | 3.078125 | 3 | [] | no_license | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
namespace GraduationTracker.Tests.Unit
{
[TestClass]
public class RepositoryTests
{
[TestMethod]
public void GetRequirementById()
{
// Arrange
var mockRequirement = new Requirement
{
Id = 100,
Name = "Math",
MinimumMark = 50,
CourseIds = new int[] { 1 },
Credits = 1
};
// Act
var requirementFromRepo = Repository.GetRequirement(100);
// Assert
Assert.AreEqual(mockRequirement.Id, requirementFromRepo.Id);
}
[TestMethod]
public void GetStudentById()
{
// Arrange
var mockStudent = new Student
{
Id = 1,
Courses = new Course[]
{
new Course{Id = 1, Name = "Math", Mark = 95 },
new Course{Id = 2, Name = "Science", Mark = 95 },
new Course{Id = 3, Name = "Literature", Mark = 95 },
new Course{Id = 4, Name = "Physichal Education", Mark = 95 }
}
};
// Act
var studentFromRepo = Repository.GetStudent(1);
// Assert
Assert.AreEqual(mockStudent.Id, studentFromRepo.Id);
}
[TestMethod]
public void GetDiplomaById()
{
// Arrange
var mockDiploma = new Diploma
{
Id = 1,
Credits = 4,
Requirements = new int[] { 100, 102, 103, 104 }
};
// Act
var diplomaFromRepo = Repository.GetDiploma(1);
// Assert
Assert.AreEqual(mockDiploma.Id, diplomaFromRepo.Id);
}
}
}
|
Ruby | UTF-8 | 835 | 3.546875 | 4 | [] | no_license | require_relative 'board'
class WebGame
def initialize(computer_player)
@board = Board.new
@computer_player = computer_player
end
def board_matrix
@board.to_matrix.map do |row|
row.map do |cell|
_cell_format(cell)
end
end
end
def play(move)
if @board.available_moves.include?(move)
@board = @board.play(move)
if !game_over?
computer_move = @computer_player.move(@board)
@board = @board.play(computer_move)
end
end
end
def game_over?
@board.game_over?
end
def game_result
if @board.game_over?
if @board.tie?
return 'The game was a tie.'
end
return "#{@board.winner} won the game."
end
''
end
private
def _cell_format(cell)
if cell == '-'
return ''
end
cell
end
end
|
C# | UTF-8 | 3,670 | 2.515625 | 3 | [] | no_license | // ***********************************************************************
// Assembly : XianaCore.Infrastructure
// Author : Jhoel Aicardi
// Created : 09-29-2020
//
// Last Modified By : Jhoel Aicardi
// Last Modified On : 11-04-2020
// ***********************************************************************
// <copyright file="UnitOfwork.cs" company="XianaCore.Infrastructure">
// Copyright (c) XianaApp. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
namespace XianaCore.Infrastructure.Classes
{
using System;
using System.Threading.Tasks;
using XianaCore.Infrastructure.Data;
using XianaCore.Infrastructure.Entities;
using XianaCore.Infrastructure.Interfaces;
/// <summary>
/// Class UnitOfwork.
/// Implements the <see cref="XianaCore.Infrastructure.Interfaces.IUnitOfWork" />
/// </summary>
/// <seealso cref="XianaCore.Infrastructure.Interfaces.IUnitOfWork" />
/// <remarks>Jhoel Aicardi</remarks>
public class UnitOfwork : IUnitOfWork
{
/// <summary>
/// The context
/// </summary>
private readonly XianaDbContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="UnitOfwork" /> class.
/// </summary>
/// <param name="context">The context.</param>
/// <remarks>Jhoel Aicardi</remarks>
public UnitOfwork(XianaDbContext context)
{
this._context = context;
}
/// <summary>
/// The avertisement repository
/// </summary>
private Repository<Employees> employeesRepository;
/// <summary>
/// Gets the avertisement repository.
/// </summary>
/// <value>The avertisement repository.</value>
/// <remarks>Jhoel Aicardi</remarks>
public Repository<Employees> EmployeesRepository
{
get
{
if (this.employeesRepository == null)
this.employeesRepository = new Repository<Employees>(_context);
return employeesRepository;
}
}
#region Entity
/// <summary>
/// Saves this instance.
/// </summary>
/// <returns>System.Int32.</returns>
/// <remarks>Jhoel Aicardi</remarks>
public int Save() => _context.SaveChanges();
/// <summary>
/// save as an asynchronous operation.
/// </summary>
/// <returns>Task<System.Int32>.</returns>
/// <remarks>Jhoel Aicardi</remarks>
public async Task<int> SaveAsync() => await _context.SaveChangesAsync();
/// <summary>
/// The disposed
/// </summary>
private bool disposed = false;
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
/// <remarks>Jhoel Aicardi</remarks>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_context.Dispose();
}
}
this.disposed = true;
}
/// <summary>
/// Disposes this instance.
/// </summary>
/// <remarks>Jhoel Aicardi</remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
|
Java | UTF-8 | 520 | 2.84375 | 3 | [] | no_license | package com.company;
import java.util.ArrayList;
import java.util.Objects;
/**
* Created by Coder on 12/9/2015.
*/
public class Database {
private ArrayList<DataTable> tables = new ArrayList<DataTable>();
private int totalTables = 0;
public void addTables(DataTable table){
tables.add(table);
totalTables++;
}
public ArrayList<DataTable> getTablesList(){
return tables;
}
public int getTotalTables(){
return totalTables;
}
}
|
C | UTF-8 | 289 | 2.765625 | 3 | [] | no_license | #include <stdio.h>
int main(void){
int m = 10, n, o;
int *z = &m;
printf("z store address = %#x\n", z);
printf("z = %d\n", *z);
printf("m address = %#x\n", &m);
printf("m = %d\n", m);
printf("n address = %#x\n", &n);
printf("o address = %#x\n", &o);
return 0;
}
|
Java | UTF-8 | 451 | 1.984375 | 2 | [] | no_license | package com.jcrspace.imageeditor.common;
/**
* Created by jiangchaoren on 2017/10/12.
*/
/**
* 图片编辑View的状态
*/
public enum ImageEditorState {
//选中
SELECTING,
//划线编辑中
LINE_EDITING,
//框选编辑中
RECT_EDITING,
//文本编辑中
TEXT_EDITING,
//新框选
NEW_RECT,
//新划线,
NEW_LINE,
//新文本,
NEW_TEXT,
//移动,
MOVING,
//空闲
IDLE
}
|
C++ | UTF-8 | 1,065 | 2.609375 | 3 | [] | no_license | //
// Created by Robert on 01-Nov-19.
//
#ifndef SDA_LISTADUBLUINTALNTUITATEMPLATE_H
#define SDA_LISTADUBLUINTALNTUITATEMPLATE_H
#include "Program.h"
class ListaDubluIntalntuitaTemplate : public Program {
public:
void exe() override ;
void info() override ;
private:
typedef int Valoare;
struct Nod {
Valoare val;
Nod* urm;
Nod* anter;
Nod() {
val = 0;
urm = NULL;
anter = NULL;
}
Nod(Valoare _val) {
val = _val;
urm = NULL;
anter = NULL;
}
Nod(Nod const &nod){
val = nod.val;
urm = nod.urm;
anter = nod.anter;
}
bool operator ==(const Nod& other);
};
void inserareNod(Nod* &cap, Nod nodDeInserat, int pozitie);
void stergeNod(Nod* &cap, int pozitie);
void afisare(Nod* &cap);
void adaugaInFata(Nod* &cap, Nod nodDeAdaugat);
void adaugaLaFinal(Nod* &cap, Nod nodDeAdaugat);
};
#endif //SDA_LISTADUBLUINTALNTUITATEMPLATE_H
|
Java | UTF-8 | 199 | 2.046875 | 2 | [] | no_license |
package utils;
public class ControleDeSaisieException extends Exception {
String msg;
public ControleDeSaisieException(String msg) {
super(msg);
this.msg = msg;
}
}
|
C++ | UTF-8 | 4,993 | 2.65625 | 3 | [] | no_license | /**
*
* @author G.Gilet, Guillaume.Gilet@unilim.fr
* @date 20 August 2017
* @version 1.0
*/
#ifndef _ENGINE_GL_H
#define _ENGINE_GL_H
#include <map>
#include <string>
#include <stack>
#include <GL/glew.h>
#include "Engine/Base/Engine.h"
#include "Engine/Base/NodeCollectors/StandardCollector.h"
#include "Materials/LightMaterial/LightMaterial.h"
#include "GPUResources/Query/GPUQuery.h"
#include "Engine/OpenGL/Lighting/LightingModelGL.h"
#include "Materials/BoundingBoxMaterial/BoundingBoxMaterial.h"
#include "GPUResources/GPUInfo.h"
#include "EngineGLState.h"
/**
* @brief This class is the parent class for creating an forward rendering engine using OpenGL
*
* @details Each project should have its own engine which inherit this parent engine
*
*/
class EngineGL : public Engine
{
public:
/**
* @brief Creates an forward rendering engine
* @details Creates an forward rendering engine with predefined cameraGL, timers objects and a LightingModelGL
* @param width as rendering frame width
* @param height as rendering frame height
*/
EngineGL(int width, int height);
/**
* @brief Destroy an engine
*/
~EngineGL();
/**
* @brief Initialize the scene and various objects (node, models, materials, effects, FBO...) used by the engine
* @param filename of a target scene in a known format (.DAE,.3DS,.OBJ)
* @return success of the initialization
*/
virtual bool init(std::string filename="");
/**
* @brief Load a Scene according to the provided filename
* @param filename of a target scene in a known format (.DAE,.3DS,.OBJ)
* @return success of the loading operation
*/
virtual bool loadScene(std::string filename);
/**
* @brief Render the scene. In the parent class, this is a forward rendering of each node of the scene
*/
virtual void render();
/**
* @brief Animate the scene. This function should provide update for camera movement, node animation (by calling the animate function of each node) and update the lighting and common buffers.
*/
virtual void animate(const int elapsedTime);
/**
* @brief Resize the viewport
* @param w as width of the viewport
* @param h as height of the viewport
*/
virtual void onWindowResize(int w,int h);
/**
* @brief Get Time stamp of the last rendered frame
* @return timestamp of the last rendered frame
*/
double getFrameTime();
/**
* @brief Get width of the current frame
* @return width of the frame
*/
int getWidth();
/**
* @brief Get height of the current frame
* @return height of the frame
*/
int getHeight();
void setWidth(int w);
/**
* @brief Set width of the current frame
* @param w width of the frame
*/
void setHeight(int h);
/**
* @brief Set height of the current frame
* @param h height of the frame
*/
bool drawLights;
bool drawBoundingBoxes;
/**
* @brief Add a light to the scene. Helper function to quickly add lights to the scene
* @details Create a LighNode and add it to the top node of the scene
* @param name name of the light
* @param position position of the light
* @param color color of the light
* @param type type of the light (not available for now : use SPOT_LIGHT)
* @param lMat a valid Material for rendering the light. If NULL , create a standard lightMaterial
*/
void addLight(string name, glm::vec3 position, glm::vec4 color = glm::vec4(1.0),int type = SPOT_LIGHT, LightMaterial* lMat = NULL);
/**
* @brief Add a Object to the scene. Helper function to quickly add obects to the scene
* @details Create a Node, load its geometricModelGL with a valid object defined by its filename, and add it to the top node of the scene
* @param name name of the node
* @param path name of the file containing the geometric model for this node
* @param m a valid material for rendering the node
* @param scale scale operation applid to the node frame
* @param translate translate operation applid to the node frame
* @param rotate rotate operation applid to the node frame
*/
void addObject(string name, string path, Material* m, glm::vec3 scale = glm::vec3(1.0), glm::vec3 translate = glm::vec3(0.0), glm::vec4 rotate = glm::vec4(0.0));
/**
* @brief Draw Bounding Boxes and lights. Not in use for now
*/
void drawBBAndLight();
/**
* @brief Define the background color
* @param color the background color
*/
void setClearColor(glm::vec4 color);
/**
* @brief Prepare the engine for rendering. Should be called at the end of init
* @details Set up the engine. Parse nodes using standard collectors, bind and populates the lighting model with LightNodes
*/
virtual void setUpEngine();
/**
* @brief Display interface for the engine (using imgui)
*/
virtual void displayInterface();
protected:
int w_Width;
int w_Height;
NodeCollector *allNodes;
NodeCollector *renderedNodes;
LightingModelGL *lightingModel;
BoundingBoxMaterial *boundingBoxMat;
GPUQuery* timeQuery;
EngineGLState* glState;
};
#endif
|
C# | UTF-8 | 585 | 3.171875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Constructors
{
public class Program
{
static void Main(string[] args)
{
const int id1 = 200;
var person1 = new Person("Bruce", id1);
Person person2 = new Person("Austin");
Console.WriteLine("Person 1 name {0} and person 1 ID {1} \nPerson 2 name {2} and person 2 ID{3} ", person1.Name, person1.Id, person2.Name, person2.Id);
Console.ReadLine();
}
}
}
|
Python | UTF-8 | 163 | 2.671875 | 3 | [] | no_license | # https://www.acmicpc.net/problem/9085
T = int(input())
for i in range(T):
N = int(input())
array = list(map(int, input().split()))
print(sum(array))
|
Python | UTF-8 | 1,790 | 3.34375 | 3 | [] | no_license | #!/usr/bin/env python3
from copy import deepcopy
def is_occupied(seat_map, y, x):
if 0 <= y < len(seat_map) and 0 <= x < len(seat_map[0]):
return seat_map[y][x] == '#'
return False
def part1(seat_map, y, x):
return [
is_occupied(seat_map, yi, xi)
for yi in range(y - 1, y + 2)
for xi in range(x - 1, x + 2)
if y != yi or x != xi
].count(True)
def part2(seat_map, y, x):
directions = [(ud, lr)
for ud in range(-1, +2)
for lr in range(-1, +2)
if ud != 0 or lr != 0]
neighbors = []
for (yd, xd) in directions:
yi, xi = y + yd, x + xd
while 0 <= yi < len(seat_map) and 0 <= xi < len(seat_map[yi]) and seat_map[yi][xi] == '.':
yi += yd
xi += xd
neighbors.append(is_occupied(seat_map, yi, xi))
return neighbors.count(True)
def advance(seat_map, limit, occupied):
changes = []
for y, row in enumerate(seat_map):
for x, seat in enumerate(row):
if seat == '.':
continue
occupied_neighbors = occupied(seat_map, y, x)
if seat == 'L' and occupied_neighbors == 0:
changes.append((y, x, '#'))
if seat == '#' and occupied_neighbors >= limit:
changes.append((y, x, 'L'))
for (y, x, val) in changes:
seat_map[y][x] = val
return len(changes)
def solve(seat_map, limit, func):
while advance(seat_map, limit=limit, occupied=func):
pass
return sum(row.count('#') for row in seat_map)
def read(file='input.txt'):
with open(file, 'r') as f:
return [list(l) for l in f.read().strip().splitlines()]
def main():
seat_map = read()
print("Part 1:", solve(deepcopy(seat_map), limit=4, func=part1))
print("Part 2:", solve(deepcopy(seat_map), limit=5, func=part2))
if __name__ == "__main__":
main()
|
Ruby | UTF-8 | 1,477 | 2.9375 | 3 | [] | no_license | # frozen_string_literal: true
split_for_nearby = INPUT.split("\n\nnearby tickets:\n")
nearby_tickets = split_for_nearby.last.each_line.map { |line| line.chomp.split(",").map(&:to_i) }
split_for_fields = split_for_nearby.first.split("\n\nyour ticket:\n")
your_ticket = split_for_fields.last.chomp.split(",").map(&:to_i)
fields = {}
split_for_fields.first.each_line do |line|
split_for_key = line.chomp.split(": ")
key = split_for_key.first
split_for_ranges = split_for_key.last.split(" or ")
value_array = split_for_ranges.map do |range|
min, max = range.split("-")
(min.to_i..max.to_i).to_a
end
fields[key] = value_array
end
value_options = fields.values.flatten.uniq
part_one = nearby_tickets.flatten.map { |number| number unless value_options.include?(number) }.compact.reduce(:+)
puts part_one
good_nearby_tickets = nearby_tickets.map { |ticket| ticket if ticket.all? { |t| value_options.include? t } }.compact
remaining_fields = fields.keys
ordered_fields = []
index = 0
until ordered_fields.length == fields.keys.length
remaining_fields.each do |key|
next unless good_nearby_tickets.all? { |t| fields[key].flatten.include? t[index] }
ordered_fields << key
remaining_fields.delete(key)
break
end
index += 1
end
# TODO: as far as i can tell from the example, this should work; runs too slow
part_two = ordered_fields.each_with_index.map { |f, fi| your_ticket[fi] if f.include?("departure") }.compact.reduce(:*)
puts part_two
|
Markdown | UTF-8 | 3,000 | 3.65625 | 4 | [] | no_license | ---
title: Leetcode416分割等和子集
date: 2020-10-13
tags:
- 01背包
- 动态规划
categories:
- LeetCode
---
:::tip
给定一个**只包含正整数**的**非空**数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
:::
<!-- more -->
## 题目
[416. 分割等和子集](https://leetcode-cn.com/problems/partition-equal-subset-sum/)
给定一个**只包含正整数**的**非空**数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
注意:
1. 每个数组中的元素不会超过 100
2. 数组的大小不会超过 200
示例 1:
> 输入: [1, 5, 11, 5]
>
> 输出: true
>
> 解释: 数组可以分割成 [1, 5, 5] 和 [11].
>
示例 2:
> 输入: [1, 2, 3, 5]
>
> 输出: false
>
## 思路
1. 假设此数组的元素和为Sum,如果Sum%2!=0,那么一定不能分割成两个元素和相等的子集。
2. sum/2的01背包问题。
**状态:**`dp[i][j] `表示数组元素下标为【0,i】范围内,能否组成j。
**状态转移方程:** `dp[i][j] = dp[i-1][j] || dp[i - 1][j - nums[i]];`
其中:`j >= nums[i]`
**初始化:**
当nums[0] <= sum/2,就可以nums[0]将其加入背包。
```java
class Solution {
public boolean canPartition(int[] nums) {
int sum = sumOf(nums);
if(sum % 2 == 1){
return false;
}
int target = sum / 2;
int len = nums.length;
boolean[][] dp = new boolean[len][target + 1];
if(nums[0]<=target)
dp[0][nums[0]] = true;
for(int i = 1;i < len;i++){
for(int j = 1;j <= target;j++){
if(j >= nums[i])
dp[i][j] = dp[i-1][j] || dp[i - 1][j - nums[i]];
else
dp[i][j] = dp[i - 1][j];
}
}
return dp[len - 1][target];
}
public int sumOf(int[] nums){
int sum = 0;
for(int num: nums){
sum+= num;
}
return sum;
}
}
```

**空间优化:**
因为当前行只是用到 上一行的数据,所以去掉一维,然后对内循环采用倒序。
```java
class Solution {
public boolean canPartition(int[] nums) {
int sum = sumOf(nums);
if(sum % 2 == 1){
return false;
}
int target = sum / 2;
int len = nums.length;
boolean[] dp = new boolean[target + 1];
if(nums[0]<=target)
dp[nums[0]] = true;
for(int i = 1;i < len;i++){
for(int j = target;j >= nums[i];j--){
dp[j] = dp[j] || dp[j - nums[i]];
}
}
return dp[target];
}
public int sumOf(int[] nums){
int sum = 0;
for(int num: nums){
sum+= num;
}
return sum;
}
}
```

|
Swift | UTF-8 | 923 | 2.734375 | 3 | [] | no_license | //
// ViewController.swift
// StarWarsAPI-App
//
// Created by Agha Saad Rehman on 16/07/2021.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let api = StarWarsAPI()
// api.getOneWithId(resource: "people", withId: 1, requiredAttributes: ["height","gender"]) { res in
// switch res {
// case .success(let attribute):
// print(attribute)
// case .failure(_):
// print("Failed")
// }
// }
api.getAll(resource: "people",
requiredAttributes: ["height","gender"]) { res in
switch res {
case .success(let attribute):
print(attribute)
case .failure(_):
print("Failed")
}
}
}
}
|
Java | UTF-8 | 2,669 | 3.46875 | 3 | [] | no_license | package wednesday;
import java.util.List;
import java.awt.*;
public class FunnyArraySorter {//@author Vasil Trifonov
enum Operations {//iskam da rabotish
Subtraction, Division, None
};
final private int mPivot;//dsa da sda fd
public FunnyArraySorter(final int pivot) {//field comment is required
mPivot = pivot;
}
private List<Integer> naturalSort(List<Integer> array, int pivot, Operations operation) {
int i = 0;
int j = 0;
int min = array.get(0);
int temp = min;
int comparisonValue = 0;//more comments are required
for (i = 0; i < array.size(); i++) {
for (j = i; j < array.size(); j++) {
min = array.get(i);
switch (operation) {
case None: {
comparisonValue = min;
}
case Subtraction: {
comparisonValue = min - pivot;
}
case Division: {
comparisonValue = min / pivot;
}
}
if (comparisonValue > array.get(j)) {
comparisonValue = array.get(j);
temp = array.get(i);
array.set(i, comparisonValue);
array.set(j, temp);
}
}
}
return array;
}
private List<Integer> backwardsSort(List<Integer> array) {
int i = 0;
int j = 0;
int max = array.get(0);
int temp = max;
for (i = 0; i < array.size(); i++) {
for (j = i; j < array.size(); j++) {
max = array.get(i);
if (max < array.get(j)) {
max = array.get(j);
temp = array.get(i);
array.set(i, max);
array.set(j, temp);
}
}
}
return array;
}
List<Integer> reverseSort(List<Integer> array) {
class ReverseSort extends FunnyArraySorter {
public ReverseSort(int pivot) {
super(pivot);
}
public List<Integer> sort(List<Integer> array) {
return backwardsSort(array);
}
}
;
ReverseSort reverseSorter = new ReverseSort(mPivot);
return reverseSorter.sort(array);
}
List<Integer> pivotSubstractionSort(List<Integer> array) {
class PivotSubtractionSort extends FunnyArraySorter {
public PivotSubtractionSort(int pivot) {
super(pivot);
}
public List<Integer> sort(List<Integer> array) {
return naturalSort(array, mPivot, Operations.Subtraction);
}
}
;
PivotSubtractionSort pivotSubtractionSorter = new PivotSubtractionSort(mPivot);
return pivotSubtractionSorter.sort(array);
}
List<Integer> pivotDivisionSort(List<Integer> array) {
class PivotDivisionSort extends FunnyArraySorter {
public PivotDivisionSort(int pivot) {
super(pivot);
}
public List<Integer> sort(List<Integer> array) {
return naturalSort(array, mPivot, Operations.Division);
}
}
;
PivotDivisionSort pivotDivisionSorter = new PivotDivisionSort(mPivot);
return pivotDivisionSorter.sort(array);
}
}
|
JavaScript | UTF-8 | 844 | 3.015625 | 3 | [] | no_license | /**
* Created by Purexo on 11/06/2017.
*/
$(function () {
var $excuse = $('#excuse');
$excuse.removeAttr('style');
var $button = $('#generate');
var $fills = [1,2,3,4,5,6].reduce(function (prev, value) {
prev.push($excuse.find('#tirage-' + value));
return prev;
}, []);
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function fill() {
$fills.forEach(function ($fill, index) {
var potential_part = PARTIE_PHRASE_TIRAGE[index];
var part = potential_part[getRandomInt(0, potential_part.length - 1)];
$fill.text(part);
});
}
fill();
$button.click(fill);
}); |
Java | UTF-8 | 2,844 | 2.1875 | 2 | [] | no_license | package com.bunakari.sambalpurifashion.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bunakari.sambalpurifashion.R;
import com.bunakari.sambalpurifashion.model.BasicFunction;
import com.bunakari.sambalpurifashion.model.SubCategoryResponse;
import com.bunakari.sambalpurifashion.network.RetroClass;
import com.bunakari.sambalpurifashion.view.ProductActivity;
import java.util.List;
public class SubCateRecycleAdapter extends RecyclerView.Adapter<SubCateRecycleAdapter.SubViewHolder> {
private Context context;
private List<SubCategoryResponse> responseList;
public SubCateRecycleAdapter(Context context, List<SubCategoryResponse> responseList) {
this.context = context;
this.responseList = responseList;
}
@NonNull
@Override
public SubViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.hcate_list_item,parent,false);
return new SubViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull SubViewHolder holder, int position) {
holder.subCateTextView.setText(responseList.get(position).subcategory);
BasicFunction.showImage(RetroClass.CATEGORY_PATH + responseList.get(position).img,context,holder.subCateImageView,holder.progressBar);
}
@Override
public int getItemCount() {
if (responseList.size() > 10){
return 10;
}else {
return responseList.size();
}
}
public class SubViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView subCateTextView;
private ImageView subCateImageView;
private ProgressBar progressBar;
public SubViewHolder(@NonNull View itemView) {
super(itemView);
subCateImageView = itemView.findViewById(R.id.cateImgView);
subCateTextView = itemView.findViewById(R.id.cateNameTextView);
progressBar = itemView.findViewById(R.id.progressBar);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Intent intent = new Intent(context, ProductActivity.class);
intent.putExtra("catid",responseList.get(getAdapterPosition()).getSid());
intent.putExtra("catname",responseList.get(getAdapterPosition()).getSubcategory());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
}
|
Python | UTF-8 | 10,150 | 2.90625 | 3 | [] | no_license | from sys import exit
from random import randint
import webbrowser
new = 2
url = "http://i.imgur.com/C70LMTN.gif"
url2 = "https://youtu.be/TJI5EBxdP6k?t=1m4s"
url3 = "https://www.youtube.com/watch?v=-mPKV6-Zwlc"
url4 = "https://youtu.be/3-Rzb6fpwBc?t=14s"
url5 = "https://www.youtube.com/watch?v=hFeEALBfXUY"
url6 = "https://youtu.be/m5Pb8MHIy2s?t=54s"
url7 = "https://youtu.be/sR7uE4nSbas"
url8 = "https://youtu.be/7dY6noZ2BCk"
url9 = "https://youtu.be/nyPHJZ77VRA"
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enter()."
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
while True and current_scene is not None:
print "\n--------"
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
class GameOver(Scene):
quips = [
"Wow, you're horrible at this. You HAVE watched the show, right?",
"Yeah, you suck. Adjourn your ass and watch more 'Wire'.",
"I hope Omar caresses you in your sleep. You SUCK! Watch more 'Wire'!",
"Your wackness is on proud display. WATCH THE SHOW and start over!"
"I should have Prez pistol whip you...watch the show again and come back\nwhen you actually know what the fuck you're doing."
]
def enter(self):
print GameOver.quips[randint(0, len(self.quips)-1)]
exit(1)
class FuneralHome(Scene):
def enter(self):
print "You are Stringer Bell, now in charge of the Barksdale Empire while Avon does"
print "his bid in Jessup. While in charge, your main connect for the"
print "product believes Avon's sentence was 'too light' and now you're"
print "having to find a new connect. Also, D\'Angelo, who is carrying"
print "the weight of a 20-year bid, seems to be distancing himself from"
print "Avon, Donette, and his mom. You know this could be trouble..."
print "Time for you to make some moves!"
print "Type 'Product' to continue..."
choice = raw_input("> ")
if choice == "Product":
print "Welp, your previous connect now believes Avon is a snitch."
print "Saw that he only got 7 years for a massive drug conspiracy case"
print "and is now shutting you out. What you gon' do?\n"
print "1. Put your business acumen to use and find a connect yourself."
print "2. Finish up your BCCC degree and get out the game."
print "3. Suggest to Avon that they should buy from Proposition Joe."
decision = raw_input("> ")
if decision == "1":
return 'game_over'
elif decision == "2":
return 'game_over'
elif decision == "3":
print "Bold idea, but there's something (read: someone) you need to take care of"
print "first. Type 'D\'Angelo' to proceed...you heartless bastard."
else:
print "That's not a choice, DUMBASS!"
return 'funeral_home'
dangelo = raw_input("> ")
print "D\'Angelo has been out of pocket. He won\'t listen to Avon, nor Donette."
print "You already had a brief altercation with him in Jersey when he got stopped"
print "bringing back a key of dope. You know he can't be trusted. What would Stringer"
print "do in this situation?\n"
print "1. Reach out to someone in D.C."
print "2. Convince Avon that he needs to take out his nephew to protect the Empire."
print "3. Convince Wee Bey to take out D\'Angelo without Avon\'s knowledge."
decision = raw_input("> ")
if decision == "1":
print "Wow, you've got SOME reach there, String! Ya man has a cousin in there."
print "Seriously, he's damn good. See for yourself..."
webbrowser.open(url2, new=new)
return 'jessup'
elif decision == "2":
return 'game_over'
elif decision == "3":
return 'game_over'
else:
print "Really? You have 3 options...stop being a DUMBASS and start over!"
return 'funeral_home'
class Jessup(Scene):
def enter(self):
print "You sinister genius! You\'ve eliminated D\'Angelo without Avon knowing it was you."
print "The prison is taking it as a suicide AND you\'re piping his baby mama. Hooray!!!!"
print "Now, at D\'s funeral, Prop Joe approaches you about your current plight with having"
print "shitty dope and prime real estate.\nHe's got that raw, but needs more territory to slang it."
print "Now that D is out of the mix, time to revisit your earlier decision with Avon about\n Prop Joe\'s..."
print "Proposition.\n"
print "Press RETURN to continue."
raw_input("> ")
print "So you told Avon about Prop Joe\'s offer. Safe to say he was none too pleased..."
print "Press RETURN to see Avon\'s reaction."
raw_input("> ")
webbrowser.open(url, new=new)
print "Knowing his contempt for Joe, and knowing the fact that y\'all have been"
print "selling dogshit up in them towers, you now have to face respecting loyalty"
print "or respecting the almighty dollar. What\'s your play, String?\n"
print "1. Loyalty"
print "2. Money"
decision = raw_input("> ")
if decision == "1":
print "You\'re a loyal friend, String. You told Prop Joe the offer is declined and"
print "you and Avon are brothers for life!!!!"
print "However, your product fucking sucks, the fiends went East and the Empire is dead. Way to go, loser."
return 'finished'
elif decision == "2":
print "Wow, willing to backdoor your boy to make this happen."
print "Time to see the fat man and strike a partnership...behind Avon's back."
return 'prop_joe'
class PropJoe(Scene):
def enter(self):
print "FANTASTIC! The towers are flooded with high quality dope! Way to go!"
print "But, you KNOW there's a catch. You gave up 3 of the towers AND"
print "you lied to Avon stating that you didn't have enough muscle to"
print "hold down the towers. So Avon reached out to NY and brought to"
print "Baltimore, Brother Mouzone. Oops. Press RETURN to see what you did."
raw_input("> ")
webbrowser.open(url3, new=new)
print "Oh, Stringer...you THOUGHT you had time before Mouzone arrived. Alas..."
print "Press RETURN to proceed"
raw_input("> ")
webbrowser.open(url4, new=new)
print "This is a MAJOR problem. With Brother Mouzone firmly entrenched in the towers"
print "running those East Baltimore gentlemen off, you're now faced with a dilemma."
print "What's your play, String?\n"
print "1. Go speak to Mouzone yourself and explain the situation."
print "2. Devise a genius plan to put Omar on Mouzone."
print "3. Stay loyal to Avon and let Mouzone do his thing."
decision = raw_input("> ")
if decision == "1":
print "*smh*"
return 'game_over'
elif decision == "2":
print "YOU sir are going to great lengths to make sure your vision of"
print "reforming the drug game comes true. Already feeling yourself after"
print "the successful hit on D\'Angelo, you\'re now setting your sights on"
print "tricking your local town enemy into believing Brother Mouzone was"
print "responsible for what happened to Omar\'s lover Brandon. Wow,"
print "you are ONE DEVIOUS MU'FUCKA!"
return 'butchies'
elif decision == "3":
print "Gave up that easily? Wow..."
return 'game_over'
else:
print "Um, WHAT!?"
return 'prop_joe'
class Butchies(Scene):
def enter(self):
print "Proposition Joe has spoken to Butchie about you wanting to 'clarify' what"
print "happened to Brandon to Omar and, reluctantly, he\'s agreed to set it up."
print "Time to have a sitdown with Mr. Omar Little. Press RETURN to proceed.\n"
raw_input("> ")
webbrowser.open(url5, new=new)
print "So now you\'ve succeeded in convincing Omar to hit Mouzone."
print "Your problem is solved right?"
print "1. Yep!"
print "2. Nope!"
solved = raw_input("> ")
if solved == "1":
return 'game_over'
if solved == "2":
print "Too easy right? Seems that Omar decided to have a lil chat with"
print "Brother Mouzone before he felt the need to finish him."
print "Press RETURN to proceed."
raw_input("> ")
webbrowser.open(url6, new=new)
return 'hospital'
class Hospital(Scene):
def enter(self):
print "So THAT didn't work. Brother Mouzone is laid up in a hospital bed after"
print "taking a bullet from Omar. Why isn't he dead though? Obviously,"
print "you decide to make a trip to the hospital to find out because you\'re"
print "'concerned'. Press RETURN to proceed."
raw_input("> ")
webbrowser.open(url7, new=new)
print "Well THAT wasn\'t the smartest thing to do. And now, Mouzone is looking"
print "at you sideways for asking him who came at him. Time to go let Avon know"
print "what went down."
return 'jessup2'
class Jessup2(Scene):
def enter(self):
print "You\'re back at Jessup to let Avon know what happened to Brother Mouzone."
print "I\'m sure he\'ll be in a great mood..."
print "Press RETURN to proceed."
raw_input("> ")
webbrowser.open(url8, new=new)
print "Bruh, safe to say having that much power went to your head a lil bit."
print "While you succeeded in having D\'Angelo killed and you were able to"
print "flex your business skills in getting Prop Joe\'s product in the towers,"
print "you\'ve now created issues with Avon (his disappointment with you"
print "was obvious during your last conversation with him), and oh yeah,"
print "Omar has his sights set on you too... Press RETURN to proceed."
raw_input("> ")
webbrowser.open(url9, new=new)
print "So with Avon coming home soon, and Omar looking for revenge,"
print "can you hold on to what you\'ve been building since you became"
print "Interim Boss #1???????"
class FuneralHome2(Scene):
def enter(self):
print "It's a new day in Baltimore. "
return 'finished'
class Map(object):
scenes = {
'funeral_home': FuneralHome(),
'jessup': Jessup(),
'prop_joe': PropJoe(),
'butchies': Butchies(),
'hospital': Hospital(),
'jessup2': Jessup2(),
'funeral_home2': FuneralHome2(),
'game_over': GameOver()
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('funeral_home')
a_game = Engine(a_map)
a_game.play() |
Ruby | UTF-8 | 1,636 | 2.96875 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'rubygems'
require 'sudden_motion_sensor'
require 'gosu'
include Gosu
class GameWindow < Gosu::Window
def initialize
@window_x = 1024; @window_y = 768
@x_scale = ((@window_x/254)/2).ceil; @y_scale = ((@window_y/254)/2).ceil
@draw_dots=true
@dotsize = 2
@draw_lines=true
super(@window_x, @window_y, false)
self.caption = "Sketch-n-etch"
@center_x = (@window_x/2).ceil
@center_y = (@window_y/2).ceil
@positions = []
end
def update
x,y,z = SuddenMotionSensor.values
@cursor_x = @center_x+(x*@x_scale)
@cursor_y = @center_y-(y*@y_scale)
@cursor_z = z
@positions.shift if @positions.size > 100
@positions << {:x => @cursor_x, :y => @cursor_y, :color => Color.new(0xFF0088FF + rand(z.abs ** 2))}
end
def draw
@positions.each_with_index do |p, i|
if @draw_dots
self.draw_line(p[:x]-@dotsize, p[:y]-@dotsize, p[:color], p[:x]-@dotsize, p[:y]+@dotsize, p[:color])
self.draw_line(p[:x]-@dotsize, p[:y]+@dotsize, p[:color], p[:x]+@dotsize, p[:y]+@dotsize, p[:color])
self.draw_line(p[:x]+@dotsize, p[:y]+@dotsize, p[:color], p[:x]+@dotsize, p[:y]-@dotsize, p[:color])
self.draw_line(p[:x]+@dotsize, p[:y]-@dotsize, p[:color], p[:x]-@dotsize, p[:y]-@dotsize, p[:color])
end
if @draw_lines
self.draw_line(p[:x], p[:y], p[:color], @positions[i-1][:x], @positions[i-1][:y], p[:color]) unless i==0
end
end
end
def button_down(id)
if id == Gosu::Button::KbEscape
close
end
end
end
window = GameWindow.new
window.show
|
Ruby | UTF-8 | 648 | 2.953125 | 3 | [] | no_license | # Testing for exceptions is tricky business.
# Refactor the spec below to use the raise_error matcher with an expect block.
describe Zombie do
it 'raises a Zombie::NotSmartEnoughError if not able to make a decision' do
zombie = Zombie.new
begin
zombie.make_decision!
rescue Zombie::NotSmartEnoughError => e
e.should be_an_instance_of(Zombie::NotSmartEnoughError)
end
end
end
# solved below #
describe Zombie do
it 'raises a Zombie::NotSmartEnoughError if not able to make a decision' do
zombie = Zombie.new
expect {zombie.make_decision!}.to raise_error(
Zombie::NotSmartEnoughError
)
end
end
|
Python | UTF-8 | 981 | 2.6875 | 3 | [] | no_license | import vtk
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('filename')
args = parser.parse_args()
fn = args.filename
#create reader
imr = vtk.vtkMetaImageReader()
imr.SetFileName(fn)
imr.Update()
print imr
#create polydataalgorithm
#this operates on an image and
#returns a polydata object
mc = vtk.vtkMarchingCubes()
mc.AddInputData(imr.GetOutput())
mc.ComputeNormalsOn()
mc.ComputeGradientsOn()
mc.SetValue(0,1.0)
#create polydata mapper
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(mc.GetOutput())
mapper.ScalarVisibilityOff()
#create actor to store the polydata object
actor = vtk.vtkActor()
actor.GetProperty().SetColor(1,1,1)
actor.SetMapper(mapper)
#create renderer
renderer = vtk.vtkRenderer()
renderer.AddActor(actor)
#create render window
renwin = vtk.vtkRenderWindow()
renwin.AddRenderer(renderer)
#create render window interactor
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renwin)
iren.Initialize()
iren.Start()
|
Markdown | UTF-8 | 2,710 | 2.609375 | 3 | [] | no_license | # avro-cli-examples
Examples on how to use the command line tools in Avro Tools to read and write Avro files.
See my original article
[Reading and Writing Avro Files From the Command Line](http://www.michael-noll.com/blog/2013/03/17/reading-and-writing-avro-files-from-the-command-line/#json-to-binary-avro)
from April 2013 for more information about using Avro Tools.
# Getting Avro Tools
You can get a copy of the latest stable Avro Tools jar file from the
[Avro Releases](http://avro.apache.org/releases.html#Download) page. The actual file is in the ``java`` subdirectory
of a given Avro release version.
Here is a direct link to [avro-tools-1.7.4.jar](http://www.us.apache.org/dist/avro/avro-1.7.4/java/avro-tools-1.7.4.jar)
(11 MB) on the US Apache mirror site.
# File overview
* [twitter.avro](https://github.com/miguno/avro-cli-examples/blob/master/twitter.avro) -- data records in uncompressed
binary Avro format
* [twitter.snappy.avro](https://github.com/miguno/avro-cli-examples/blob/master/twitter.snappy.avro) -- data records in
Snappy-compressed binary Avro format
* [twitter.avsc](https://github.com/miguno/avro-cli-examples/blob/master/twitter.avsc) -- Avro schema (in JSON
representation) of the data records in ``twitter.avro``, ``twitter.snappy.avro`` and ``twitter.json``.
* [twitter.json](https://github.com/miguno/avro-cli-examples/blob/master/twitter.avro) -- data records in plain-text
JSON format
# JSON to binary Avro
Without compression:
$ java -jar ~/avro-tools-1.7.4.jar fromjson --schema-file twitter.avsc twitter.json > twitter.avro
With Snappy compression:
$ java -jar ~/avro-tools-1.7.4.jar fromjson --codec snappy --schema-file twitter.avsc twitter.json
If you run into ``SnappyError: [FAILED_TO_LOAD_NATIVE_LIBRARY]`` when trying to compress the data with Snappy make sure
you use JDK 6 and not JDK 7.
# Binary Avro to JSON
The same command will work on both uncompressed and compressed data.
$ java -jar ~/avro-tools-1.7.4.jar tojson twitter.avro > twitter.json
$ java -jar ~/avro-tools-1.7.4.jar tojson twitter.snappy.avro > twitter.json
If you run into ``SnappyError: [FAILED_TO_LOAD_NATIVE_LIBRARY]`` when trying to decompress the data with Snappy make
sure you use JDK 6 and not JDK 7.
# Retrieve Avro schema from binary Avro
The same command will work on both uncompressed and compressed data.
$ java -jar ~/avro-tools-1.7.4.jar getschema twitter.avro > twitter.avsc
$ java -jar ~/avro-tools-1.7.4.jar getschema twitter.snappy.avro > twitter.avsc
[](http://githalytics.com/miguno/avro-cli-examples)
|
C++ | UTF-8 | 591 | 3.109375 | 3 | [] | no_license | #include "UniversityReg.h"
#include <iostream>
#include <sstream>
#include <string>
int main(){
/*
//test cpy construktor
Person* p1 = new Student("name1", "email", 123);
Person* p2 = p1;
p1->toString;
p2->toString;
//test deep copying
p1->setName("BOB");
cout << p1->toString();
cout << p2->toString();
*/
UniversityReg bth;
bth.addPerson("name1", "name1@bth.se", 123);
bth.addEmployee("name2", "name2@bth.se", 2000, "IT");
bth.printAllPersons;
UniversityReg kth;
kth.addStudent("name3", "name3@kth.se", 456);
kth = bth;
kth.printAllPersons();
return 0;
} |
Java | UTF-8 | 232 | 1.914063 | 2 | [] | no_license | package com.android.structure.callbacks;
import com.android.structure.adapters.SpinnerDialogAdapter;
public interface OnSpinnerItemClickListener {
void onItemClick(int position, Object object, SpinnerDialogAdapter adapter);
}
|
Shell | UTF-8 | 657 | 3.328125 | 3 | [
"MIT"
] | permissive | #! /bin/bash
PRGNAME="patch"
### Patch
# Программа для изменения или создания файлов путем применения файлов *.patch,
# обычно создаваемых программой diff
# http://www.linuxfromscratch.org/lfs/view/stable/chapter05/patch.html
# Home page: https://savannah.gnu.org/projects/patch/
# Download: http://ftp.gnu.org/gnu/patch/patch-2.7.6.tar.xz
source "$(pwd)/check_environment.sh" || exit 1
source "$(pwd)/unpack_source_archive.sh" "${PRGNAME}" || exit 1
./configure \
--prefix=/tools || exit 1
make || make -j1 || exit 1
make check
make install
|
JavaScript | UTF-8 | 622 | 2.609375 | 3 | [
"MIT"
] | permissive | import {
SIGNUP,
LOGIN
} from "../constants"
/*
user: [{
username: String,
firstName: String,
lastName: String,
password: String
}]
*/
const defaultState = {username: 'avik', firstName: 'Avik', lastName: 'Jain', 'password':'pass'};
export default function(state = defaultState, action) {
switch(action.type) {
case SIGNUP:
if(action.status == 'received')
return action.user;
// handle signup error
return state;
break;
case LOGIN:
if(action.status == 'received')
return action.user;
return state;
default: return state;
}
} |
Java | UTF-8 | 592 | 2.515625 | 3 | [] | no_license | package com.todos.model;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import com.todos.types.PhoneType;
@Embeddable
public class Phone {
@Column(name="number")
private String number;
@Column(name="type")
private PhoneType type;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public PhoneType getType() {
return type;
}
public void setType(PhoneType type) {
this.type = type;
}
public Phone(String number, PhoneType type) {
this.number = number;
this.type = type;
}
}
|
Python | UTF-8 | 1,028 | 3.734375 | 4 | [
"MIT"
] | permissive | # a = [[1,2],[1,2,3]]
# print(a)
#
# b = (1,2,3)
# print(b)
# print(a[0])
# print(b[0])
# b[0]=4
# d = {"key":{"key2":"bob"}}
# d['key3'] = 4
# print(d.get("key4",0))
# x=4
# if x>3:
# print(x)
# elif x == 3:
# print(x+1)
# else:
# print(x-1)
# x=0
# while x<4:
# print(x)
# x+=1
def add(x,y):
return x+y
#
# print(add(1,2))
# print(add(1.0,3.0))
# print(add("1",3.0))
# print(add("Hi ","bob"))
#
# b = " a fun sentence for an example "
# print(b.rstrip().lstrip() + "hello")
class Human:
species="H. sapiens" #hopefully
def __init__(self, name):
self.name=name
self.age=0
def say(self,msg):
return "{name}:{message}".format(name=self.name, message=msg)
class Student(Human):
def __init__(self, name, year):
Human.__init__(self,name)
self.year = year
def say(self,msg):
return "{name}:{year}:{message}".format(name=self.name, year=self.year, message=msg)
H = Human("bob")
H2 = Student("Chris",2018)
print(H2.say("hello"))
|
Markdown | UTF-8 | 871 | 2.90625 | 3 | [
"MIT"
] | permissive | ## Day 68
**Calculator -Part 4**
Our Calculator is almost finished. Pumped up !!!
I know you are ...so lets work!!!
**Challenge Description:**
1. Initialise the value for tips you want to offer.
2. Create a class component input initialise the state value as -- active: 0, keyInput: '' ;
3. Define method handleStyleChange(i) - if (this.state.active === i) is true ,return 'selected-tipPerc' otherwise return blank.
4. Define method handleTipSelect(i) - initialise this.setState({ active: i }); and this.props.getTipPercentage(i)
5. Render and return the value of Bill Total,PartyCount,tipPercentages,Tip Total.
Complete this and See you in the next Challenge
Continue...
For References:
1. https://reactjs.org/docs/getting-started.html
2. https://www.w3schools.com/react/
3. https://www.golangprograms.com/bill-and-discount-calculator-in-react-js.html
|
Java | UTF-8 | 3,830 | 3.40625 | 3 | [] | no_license | package com.szx.downFileInZip.util;
import java.io.File;
/**
*
* @author SHENZHIXAING418
*
*/
public class FileUtil {
/**
* 删除文件,可以是文件或文件夹
*
* @param fileName 要删除的文件名
* @return 删除成功返回true,否则返回false
*/
public static boolean delete(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
System.out.println("删除文件失败:" + fileName + "不存在!");
return false;
} else {
if (file.isFile())
return deleteFile(fileName);
else
return deleteDirectory(fileName);
}
}
/**
* 删除单个文件
*
* @param fileName 要删除的文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
System.out.println("删除单个文件" + fileName + "成功!");
return true;
} else {
System.out.println("删除单个文件" + fileName + "失败!");
return false;
}
} else {
System.out.println("删除单个文件失败:" + fileName + "不存在!");
return false;
}
}
/**
* 删除目录及目录下的文件
*
* @param dir 要删除的目录的文件路径
* @return 目录删除成功返回true,否则返回false
*/
public static boolean deleteDirectory(String dir) {
// 如果dir不以文件分隔符结尾,自动添加文件分隔符
if (!dir.endsWith(File.separator))
dir = dir + File.separator;
File dirFile = new File(dir);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
System.out.println("删除目录失败:" + dir + "不存在!");
return false;
}
boolean flag = true;
// 删除文件夹中的所有文件包括子目录
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
}
// 删除子目录
else if (files[i].isDirectory()) {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag)
break;
}
}
if (!flag) {
System.out.println("删除目录失败!");
return false;
}
// 删除当前目录
if (dirFile.delete()) {
System.out.println("删除目录" + dir + "成功!");
return true;
} else {
return false;
}
}
/**
* 根据制定文件的文件头判断其文件类型
* @param filePaht
* @return
*/
public static String getFileType(byte[] b){
String fileCode = bytesToHexString(b).toUpperCase();
if(fileCode.contains("FFD8FF")){
return "jpeg";
}else if(fileCode.contains("89504E47")){
return "png";
}else if(fileCode.contains("47494638")){
return "gif";
}else if(fileCode.contains("49492A00")){
return "tif";
}else if(fileCode.contains("424D")){
return "bmp";
}else{
return null;
}
}
/**
* 得到上传文件的文件头
* @param src
* @return
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
}
|
Java | UTF-8 | 925 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | package com.baidu.dsp.common.constraint.validation;
import java.math.BigDecimal;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import com.baidu.dsp.common.constraint.DoubleMax;
/**
* @author liaoqiqi
*/
public class MaxValidatorForDouble implements ConstraintValidator<DoubleMax, Double> {
private double maxValue;
public void initialize(DoubleMax maxValue) {
this.maxValue = maxValue.value();
}
public boolean isValid(Double value, ConstraintValidatorContext constraintValidatorContext) {
// null values are valid
if (value == null) {
return true;
}
BigDecimal premium = BigDecimal.valueOf(value);
BigDecimal netToCompany = BigDecimal.valueOf(maxValue);
BigDecimal commission = premium.subtract(netToCompany);
return commission.compareTo(BigDecimal.ZERO) <= 0;
}
} |
Markdown | UTF-8 | 7,422 | 2.765625 | 3 | [
"MIT"
] | permissive | # Open SAE J1939
SAE J1939 is a protocol for shaping the CAN-bus message in a specific way that suits industrial vehicles such as tractors, machinery, trucks and more.
SAE J1939 is a very easy protocol to use, but there is a lack of information about SAE J1939, due to the cost of the protocol document, available how to shape a CAN-bus message according to SAE J1939 protocol standard. So therefore I’m writing a SAE J1939 protocol available for free to use on any embedded systems such as STM32, Arduino, AVR, PIC etc or PC.
To learn to build on this project, you need first to understand SAE J1939. I have written this project in `C` language because C is an industry standard. The `C` language dialect I have chosen is `C99` and I don't use dynamical memory allocation in this library. So it will work with `MISRA C` standard.
With this library, you can communicate with valves, engines, actuators, machinery, hardware and all other things that are suitable for heavy industrial mobile applications. I have build up a basic structure of the project and I hope that other users will send pull request of their `C` code for extra functionality to SAE J1939 standard because SAE J1939 is a huge standard.
# Getting started
The first thing you need to know is to read the document `Open SAE J1939.pdf` inside the `Documentation` folder.
Learn the structure of the project, else you won't be able to understand SAE J1939.
After you have got a basic understanding of the project, you are able to build on it. Keep it simple and follow the
SAE J1939 standard!
After you have understand the structure of the project, then select processor choice in `Processor_choice.h` file.
Here you can select for example `STM32`, `Arduino`, `PIC`, `AVR` etc. or if you want to run it on PC first, then select `PROCESSOR_CHOICE 0` and run some examples.
That's the debugging mode for internal CAN feedback.
# How to use the project
- Step 1: Download this repository
- Step 2: Go to `Processor_choice.h` and select your processor, if it's not avaiable, please write code for it and send me a pull request
- Step 3: Copy over the `Src` folder to your project folder inside your IDE. Rename `Src` to for example `Open SAE J1939`. That's a good name.
- Step 4: Past the header files inside your application code. This is just an example.
```
#include <stdlib.h>
#include <stdio.h>
#include "ISO_11783/ISO_11783-7_Application_Layer/Application_Layer.h"
#include "Open_SAE_J1939/Open_SAE_J1939.h"
#include "SAE_J1939/SAE_J1939-71_Application_Layer/Application_Layer.h"
#include "SAE_J1939/SAE_J1939-73_Diagnostics_Layer/Diagnostics_Layer.h"
#include "SAE_J1939/SAE_J1939-81_Network_Management_Layer/Network_Management_Layer.h"
```
- Step 5: Create the `J1939 j1939 = {0};` inside your application code. You can see inside the examples how I have done
- Step 6: Set the other ECU addresses to broadcast address `0xFF`
```
/* Important to sent all non-address to 0xFF - Else we cannot use ECU address 0x0 because this library remembers the ECU addresses. */
for(uint8_t i = 0; i < 255; i++)
j1939.other_ECU_address[i] = 0xFF; /* 0xFF is not an ECU address, only a broadcast address according to SAE J1939 */
```
- Step 7: Set your ECU address between `0x0` to `0xFD`. I select `0x80`
```
j1939.this_ECU_address = 0x80;
```
- Step 8: Create `NAME`. It's a `SAE J1939` standard for sending out the `NAME` of the ECU at the start up. Don't forget to look in `SAE J1939 Enums` folder for more predefined fields for `NAME`
```
/* Set NAME for ECU 1 */
j1939.this_name.identity_number = 100; /* From 0 to 2097151 */
j1939.this_name.manufacturer_code = 300; /* From 0 to 2047 */
j1939.this_name.function_instance = 10; /* From 0 to 31 */
j1939.this_name.ECU_instance = 2; /* From 0 to 7 */
j1939.this_name.function = FUNCTION_VDC_MODULE; /* From 0 to 255 */
j1939.this_name.vehicle_system = 100; /* From 0 to 127 */
j1939.this_name.arbitrary_address_capable = 0; /* From 0 to 1 */
j1939.this_name.industry_group = INDUSTRY_GROUP_CONSTRUCTION; /* From 0 to 7 */
j1939.this_name.vehicle_system_instance = 10; /* From 0 to 15 */
```
Step 9: Broadcast the `NAME`
```
SAE_J1939_Response_Request_Address_Claimed(&j1939); /* This function send out the NAME to all ECU */
```
- Step 10: Implement your reading function inside a while loop
```
while(1) {
/* Read incoming messages */
Open_SAE_J1939_Listen_For_Messages(&j1939);
/* Your application code here */
....
....
....
}
```
Now you can use the `Open SAE J1939` library
# The structure of the project

# SAE J1939 functionality
- SAE J1939:21 Transport Layer
- Acknowledgement
- Request
- Transport Protocol Connection Management
- Transport Protocol Data Transfer
- SAE J1939:71 Application Layer
- Request Component Identification
- Request ECU Identification
- Request Software Identification
- SAE J1939:73 Diagnostics Layer
- DM1
- DM2
- DM3
- DM14
- DM15
- DM16
- SAE J1939:81 Network Management Layer
- Address Claimed
- Commanded Address
- Address Not Claimed
- Delete Address
# Extra functionality
- ISO 11783 Tractors And Machinery For Agriculture And Forestry
- ISO 11783-7 Implement Messages Application Layer
- Auxiliary Valve Command
- Auxiliary Valve Estimated Flow
- Auxiliary Valve Measured Position
- General Purpose Valve Command
- General Purpose Valve Estimated Flow
# Questions and answers
- Q: Can this library be used with `C++`?
- A: Yes it can be used with `C++`
- Q: I want to build on this library, what should I do?
- A: First you need to know `C99` and bitwise operations. Then you need to understand the `SAE J1939:21 Transport Layer` structure. Don't forget to update the PDF with your new functionality.
- Q: Can I use this on my Arduino?
- A: Yes, this `C` code is 100% pure `C` code and only using `C` standard library and also the code does not take account of what hardware you are using.
- Q: Do I need to install the library for to use the library?
- A: No, just copy over the `.c` and `.h` files to your project and compile. I have used this with QT framework.
- Q: This project is quite old now and not so much updates, is it still worth to use it?
- A: Yes, this library only updates when I or other includes more functionality from SAE J1939. The reason why I wrote this in `C99` is because it's an industry standard and will you will always be able to compile this library and use it.
- Q: What is your plan with the library?
- A: To make SAE J1939 available for everybody
- Q: I don't have CAN-bus, but can I use this library anyway with UART, USB, WiFi etc?
- A: Yes. This is only a way to shape a massage in a specific way.
- Q: Can I send data with this library, even if I don't have CAN-bus?
- A: Yes. There are something called DM14 transmit request, DM15 status response and DM16 binary transfer. Use that if you want to transfer data in an industrial way. |
Java | UTF-8 | 269 | 1.851563 | 2 | [] | no_license | package cn.naivenet.User;
class ControllerHeart extends NaiveNetController {
public ControllerHeart() {
super("heart");
}
@Override
public NaiveNetResponseData onRequest(NaiveNetMessage msg) {
msg.user.setPing(new String(msg.param));
return null;
}
}
|
Markdown | UTF-8 | 2,144 | 2.75 | 3 | [] | no_license | ```yaml
area: Hertfordshire
og:
description: Detectives investigating two burglaries in Bricket Wood are appealing for anyone with information to come forward.
publish:
date: 22 Dec 2017
title: Appeal for information following burglaries in Bricket Wood
url: https://www.herts.police.uk/news-and-appeals/appeal-for-information-following-burglaries-in-bricket-wood
```
* ### Both incidents occurred in Oakwood Road.
* ### Asian gold jewellery and designer handbags were stolen.
* ### Police are trying to trace a silver Audi spotted around the times of the burglaries.
Detectives investigating two burglaries in Bricket Wood are appealing for anyone with information to come forward.
Both incidents occurred in Oakwood Road.
The first took place on December 7, between 6pm and 9pm. Offender(s) gained access to the property by forcing a rear kitchen window. A large quantity of Asian gold jewellery was taken ( _pictured_ ).
Between 8am and 7.40pm on Wednesday, December 20, entry was gained to a property by smashing the glass in a rear patio door. A search was carried out and jewellery, designer handbags and a Rolex watch were stolen.
Both incidents are being linked by police.
Detective Constable Paul Edmondson, from the St Albans Local Crime Unit, said: "It has been reported that a silver Audi was spotted in the area around the time of both burglaries. I am appealing for anyone who may have seen this vehicle or its occupants to please get in touch.
"I would also like to hear from anyone who may have seen similar jewellery offered for sale."
Anyone with information about the burglary is asked to contact the St Albans Local Crime Unit on the non-emergency number 101, quoting crime reference F3/17/2705. You can also email paul.edmondson@herts.pnn.police.uk or report information online here
Alternatively, you can contact the independent crime-fighting charity Crimestoppers anonymously on 0800 555 111 or through their Anonymous Online Form at www.crimestoppers-uk.org. No personal details are taken, information cannot be traced or recorded and you will never need to go to court.
Asian gold jewellery was stolen during one of the burglaries
|
Markdown | UTF-8 | 2,882 | 2.578125 | 3 | [] | no_license | ---
layout: post
title: '工作紀實 2018年 12月'
date: 2018-12-31 21:00
image: ''
description: ''
categories:
- 工作紀實
tags:
- 月報
- 知識科技
---
# MS & FSB 產品
由於 MS 當年採用效能不高的 PHP/MySQL 所開發,加上其架構設計並未考慮效率,以致於整體吞吐量有限(FSB 基於 MS)。
近期由於客戶的 LINE@ 帳號透過廣告推廣,同時湧入的消費者使得系統過載,影響所有客戶的操作。
為了避免已排程的廣告再次發生這樣的嚴重狀況,我製作一個*前端緩衝器*,透過它放慢特定 LINE 帳戶的訊息速度即可避免癱瘓所有客戶。
由於高效能是第一考量,我直接採用了**沒碰過**的 ***GO*** 程式語言以及屬於 **NoCQL** 的 ***Cassandra*** 來開發此一程式。
而為了趕上廣告排程,我只好加班趕工(累)。幸虧最終完成的效能符合需求,僅用 2 cores CPU 與機械硬碟的主機,壓力測試跑出了 **peak 350** req/sec 的成績。
而且瓶頸是在 CPU ,Cassandra 的**寫入能力**超越我的預期,而系統上線後也順利解決了癱瘓的問題。
原本是二代產品才要用上的新技術線,沒想到臨時就提槍上陣了呢...(暈)
## 已完成
* #2054 實做一個訊息緩衝前端伺服器降低特定客戶的流量衝擊
* #2069 一對一手動派單 bug修復 拖用戶進群組會帶入其他人
* 設定客戶網域強制使用 HTTPS
* 修復資料庫同步備份
+ MySQL 副資料庫因故而資料損毀導致備份機制故障
+ 使用 GCP snapshot 取得完整資料重新同步副資料庫
# Beehive 產品
這是新產品線的內部**開發用代號**,由我們 R&D 票選而出,我個人覺得蠻貼切的,哈。
由於這產品線的特性,使得我們要採用新的技術線。
例如 GO 語言、各種 NoSQL 資料庫以及 K8S 叢集管理系統等,也使得這產品開發的難度高了許多。
因此以專任的開發小組負責,最終希望這產品線的開發經驗可以讓二代系統受益。
* 協助系統架構設計
* 使用 Azure 建立測試叢集並執行靜態網頁
+ K8S + Caddy web server + HTTPS
+ 已進行壓力測試: 8 cores CPU + SSD **連續壓載**達 **465** trans/sec, 0% failed
# 鍋專案
* 協助調整伺服器與主機提昇效能
* 協助改善特定頁面的前端程式效能
# 其他
* 協助調查客戶移機之後的效能問題
+ 調整伺服器與主機參數等
* 建置自動化快照於 S4 作為定時自動備份
* 協助調查客戶網域收信問題
# 後記
一眨眼已經是 2018 年底了呢,回顧這一年來,真、的、是、過、得、非、常、地、緊、湊(倒地)。
然後如同往年一樣地沒梗,希望來年一切順利~~~(傻笑)
|
Markdown | UTF-8 | 915 | 2.78125 | 3 | [] | no_license | # Article 74 B
Un décret fixe les conditions d'application des articles 74 et 74 A. Il précise en outre :
– les modalités de détermination du revenu imposable tel qu'il est défini à l'article 74 ;
– les conditions d'exercice et la durée de validité des options prévues à l'article 69 ;
– les règles applicables en cas de changement de régime d'imposition ;
– la nature et le contenu des documents que doivent produire les exploitants agricoles.
**Nota:**
Voir les articles 38 sexdecies JC à 38 sexdecies JE, 38 sexdecies OE, 38 sexdecies P à 38 sexdecies QA et 38 sexdecies RB de
l'annexe III.
**Liens relatifs à cet article**
_Modifié par_:
- Loi n°76-1220 du 28 décembre 1976 - art. 3 (V) JORF 29 décembre 1976
_Cite_:
- Code général des impôts, CGI. - art. 69 (V)
- Code général des impôts, CGI. - art. 74 (V)
_Codifié par_:
- Décret n°84-875 1984-10-01
|
TypeScript | UTF-8 | 2,051 | 2.84375 | 3 | [] | no_license | import { BookStoreService } from "./book-store.service";
import { Observable} from "rxjs/Observable";
import 'rxjs/add/observable/of';
import { Book } from "./book";
describe('BookStoreService', () => {
let bookStoreService: BookStoreService,
mockHttp;
// dato che l'oggetto BookStoreService si aspetta di ricevere il paramtero http nel costruttore per eseguire le chiamate
// e l'oggetto http usa i metodi get, post, delete devo simulare questo comportamento.
// jasmine.createSpyObj mi permette di creare un oggetto finto con all'interno i metodi. (1°par: nome oggetto, 2° par: array metodi)
beforeEach( () => {
mockHttp = jasmine.createSpyObj('mockHttp', ['get', 'post', 'delete']);
bookStoreService = new BookStoreService(mockHttp);
});
describe('deleteBook', ()=> {
it('should remove the book', () => {
const book: Book = {
id: 12,
isbn: 9781849692380,
title: 'test title',
authors: 'test author',
published: 'test date',
description: 'test description',
coverImage: 'test image'
};
// testo la cancellazione di un libro.
// stiamo interrrogando l'oggetto bookStoreService ma non stiamo utilizzando il servizio http,
// bensì stiamo utilizzando passando un oggetto mock al posto di http dovremmo simulare una chiamata http
// utilizzando: mockHttp.delete.and.returnValue(Observable.of(book));
mockHttp.delete.and.returnValue(Observable.of(book));
const response = bookStoreService.deleteBook(12);
//console.log(response);
response.subscribe( value => {
expect( value ).toBe(book);
});
});
it('should call http delete method with right url', () => {
const id = 12;
const url = `http://58e15045f7d7f41200261f77.mockapi.io/api/v1/books/${id}`;
mockHttp.delete.and.returnValue(Observable.of(true));
const response = bookStoreService.deleteBook(id);
expect(mockHttp.delete).toHaveBeenCalledWith(url, jasmine.any(Object));
});
});
});
|
Go | UTF-8 | 863 | 3.0625 | 3 | [
"MIT"
] | permissive | package errors_test
import (
"net/http"
"testing"
"github.com/redpkg/errors/v2"
"github.com/stretchr/testify/assert"
)
func TestNew(t *testing.T) {
assert := assert.New(t)
err := errors.New(50000, "server error").
SetInternal(errors.New(40000, "foobar"))
assert.Equal(http.StatusInternalServerError, err.StatusCode)
assert.Equal(50000, err.Code)
assert.Equal("server error", err.Message)
assert.EqualError(err, "server error")
assert.EqualError(err.Unwrap(), "foobar")
err.SetStatusCode(http.StatusNotImplemented)
assert.Equal(http.StatusNotImplemented, err.StatusCode)
}
func TestFlatten(t *testing.T) {
assert := assert.New(t)
err1 := errors.New(1, "error 1")
err2 := errors.New(2, "error 2").SetInternal(err1)
err3 := errors.New(3, "error 3").SetInternal(err2)
assert.EqualValues([]error{err3, err2, err1}, errors.Flatten(err3))
}
|
Python | UTF-8 | 1,023 | 3.46875 | 3 | [] | no_license | def convert(numerator, denominator):
result = str(numerator // denominator) + '.'
remainders = [numerator % denominator]
while 0 not in remainders:
numerator = numerator % denominator * 10
result += str(numerator // denominator)
if numerator % denominator in remainders:
i = remainders.index(numerator % denominator)
return result[:i + 2] + '(' + result[i + 2:] + ')'
remainders += [numerator % denominator]
return result
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert convert(1, 3) == "0.(3)", "1/3 Classic"
assert convert(5, 3) == "1.(6)", "5/3 The same, but bigger"
assert convert(3, 8) == "0.375", "3/8 without repeating part"
assert convert(7, 11) == "0.(63)", "7/11 prime/prime"
assert convert(29, 12) == "2.41(6)", "29/12 not and repeating part"
assert convert(11, 7) == "1.(571428)", "11/7 six digits"
assert convert(0, 117) == "0.", "Zero"
|
Python | UTF-8 | 1,816 | 4.21875 | 4 | [] | no_license | # In tic tac toe board, "" means empty, x means x and o means o
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
def check_mate():
# horizontal
for i in range(3):
if board[i][0] != " " and board[i][0] == board[i][1] and board[i][0] == board[i][2]:
return True
# verital
for j in range(3):
if board[0][j] != " " and board[0][j] == board[1][j] and board[0][j] == board[2][j]:
return True
# diagonal
if board[0][0] != " " and board[0][0] == board[1][1] and board[0][0] == board[2][2]:
return True
if board[2][0] != " " and board[2][0] == board[1][1] and board[2][0] == board[0][2]:
return True
return False
def print_board():
for i in range(3):
print(board[i])
print()
def check_end():
for i in range(3):
for j in range(3):
if board[i][j] == " ":
return False
return True
def put( xo, i, j ):
if i < 0 or i > 2 or j < 0 or j > 2 or ( xo != "o" and xo != "x" ):
return False
elif board[i][j] != " ":
return False
board[i][j] = xo
return True
def switch( data ):
if data == "x":
return "o"
else:
return "x"
def play():
chess = "x"
while not check_mate() and not check_end():
row_column = input(chess + " turns. Please enter row and column (e.g. 1 1 ): ").split()
if len(row_column) == 2:
if row_column[0].isdigit() and row_column[1].isdigit():
if put( chess, int(row_column[0]), int(row_column[1])):
print_board()
if not check_mate():
chess = switch(chess)
return chess
# main
print_board()
chess = play()
if check_end():
print("draw")
else:
print( chess + " win")
|
C++ | UTF-8 | 785 | 2.9375 | 3 | [] | no_license | #ifndef HAND_H_INCLUDED
#define HAND_H_INCLUDED
#include <memory>
#include <list>
#include <iostream>
#include "AnimalCard.h"
class Hand
{
std::list<std::shared_ptr<AnimalCard>>* playerHand;
public:
Hand();
Hand& operator += (std::shared_ptr<AnimalCard>);
Hand& operator -= (std::shared_ptr<AnimalCard>);
std::shared_ptr<AnimalCard> operator[] (int);
int noCards();
std::list<std::shared_ptr<AnimalCard>>& getList();
friend std::ostream& operator << (std::ostream&, Hand&) {
for (int i = 0; i < playHand.noCards(); i++) {
output << i << " ";
}
output << std::endl;
for (std::list<std::shared_ptr<AnimalCard>>::iterator iter = playHand.getList().begin();
iter != playHand.getList().end(); iter++) {
output << *iter;
}
return output;
}
};
#endif
|
Python | UTF-8 | 6,948 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | from abc import ABC, abstractmethod
from collections import deque
from typing import Any
import z3
from .ast import AST, ASTNode
from ..dsl import Node, AtomNode
from ..logger import get_logger
logger = get_logger('forest')
class RegexEnumerator(ABC):
@abstractmethod
def __init__(self, dsl):
z3.Z3_DEBUG = False
self.z3_solver = z3.Solver()
self.variables = {}
self.variables_fun = []
self.trees = []
self.nodes = []
self.model = None
self.dsl = dsl
self.max_children = self.max_children()
self._get_range_values()
@abstractmethod
def update(self, info: Any = None) -> None:
'''
Update the internal state of the enumerator. This can be useful when trying to prune the search space.
By default, it does nothing.
'''
raise NotImplementedError
@staticmethod
def build_k_tree(children, depth, tree_id):
""" Builds a K-tree that will contain the program """
tree = AST(tree_id)
root = ASTNode(1, 1, None, tree_id)
nb = 1
tree.head = root
d = deque()
d.append(root)
tree.nodes.append(root)
while len(d) != 0:
current = d.popleft()
current.children = []
for x in range(0, children):
nb += 1
c = ASTNode(nb, current.depth + 1, None, tree_id)
tree.nodes.append(c)
current.children.append(c)
if c.depth < depth:
d.append(c)
return tree
def max_children(self) -> int:
""" Finds the maximum number of children in the productions """
return max(map(lambda p: len(p.rhs), self.dsl.productions()))
def _get_range_values(self):
""" Organizes DSL's range values into dictionaries based on their upper and
lower bounds """
range_val_ty = self.dsl.get_type("RangeLit")
if range_val_ty is None:
return
range_val_enum = self.dsl.get_productions_with_lhs(range_val_ty)
self.range_lower_bounds = {}
self.range_upper_bounds = {}
for range_val in range_val_enum:
data = range_val.rhs[0]
data = data.split(',')
if len(data) < 2: # probably sketches
break
range_node = AtomNode(range_val)
if data[0] not in self.range_lower_bounds:
self.range_lower_bounds[data[0]] = []
self.range_lower_bounds[data[0]].append(range_node)
if data[1] not in self.range_upper_bounds:
self.range_upper_bounds[data[1]] = []
self.range_upper_bounds[data[1]].append(range_node)
@staticmethod
def _check_arg_types(pred, python_tys):
if pred.num_args() < len(python_tys):
msg = 'Predicate "{}" must have at least {} arguments. Only {} is found.'.format(
pred.name, len(python_tys), pred.num_args())
raise ValueError(msg)
for index, (arg, python_ty) in enumerate(zip(pred.args, python_tys)):
if not isinstance(arg, python_ty):
msg = 'Argument {} of predicate {} has unexpected type.'.format(
index, pred.name)
raise ValueError(msg)
@abstractmethod
def _resolve_is_not_parent_predicate(self, pred):
raise NotImplementedError
@abstractmethod
def _resolve_block_subtree_predicate(self, pred):
raise NotImplementedError
@abstractmethod
def _resolve_block_tree_predicate(self, pred):
raise NotImplementedError
@abstractmethod
def _resolve_block_first_tree_predicate(self, pred):
raise NotImplementedError
@abstractmethod
def _resolve_char_must_occur_predicate(self, pred):
raise NotImplementedError
@abstractmethod
def _resolve_block_range_lower_bound_predicate(self, pred):
raise NotImplementedError
@abstractmethod
def _resolve_block_range_upper_bound_predicate(self, pred):
raise NotImplementedError
def resolve_predicates(self, predicates):
for pred in predicates:
if pred.name == 'is_not_parent':
self._resolve_is_not_parent_predicate(pred)
elif pred.name == 'block_subtree':
self._resolve_block_subtree_predicate(pred)
elif pred.name == 'block_tree':
self._resolve_block_tree_predicate(pred)
elif pred.name == 'block_first_tree':
self._resolve_block_first_tree_predicate(pred)
elif pred.name == 'char_must_occur':
self._resolve_char_must_occur_predicate(pred)
elif pred.name == 'block_range_lower_bound':
self._resolve_block_range_lower_bound_predicate(pred)
elif pred.name == 'block_range_upper_bound':
self._resolve_block_range_upper_bound_predicate(pred)
else:
logger.warning('Predicate not handled: {}'.format(pred))
def next(self):
if self.z3_solver.check() == z3.sat:
self.model = {}
for var in self.variables:
self.model[var] = int(str(self.z3_solver.model()[self.variables[var]]))
else:
self.model = None
if self.model is not None:
return self.build_program()
else:
logger.debug(f'Enumerator exhausted.')
return None
def _block_subtree_rec(self, subtree: ASTNode, program: Node):
""" Auxiliary function for block_subtree. """
head_var = self.variables[subtree]
production_id = program.production.id
block = [head_var != z3.IntVal(production_id)]
if len(program.children) == 1:
assert len(subtree.children) == 2
children_vars = list(map(lambda x: self.variables[x], subtree.children))
assert len(children_vars) == 2
block += self._block_subtree_rec(subtree.children[0], program.children[0])
elif len(program.children) == 2:
assert len(subtree.children) == 2
block += self._block_subtree_rec(subtree.children[0], program.children[0])
block += self._block_subtree_rec(subtree.children[1], program.children[1])
return block
def block_subtree(self, subtree: ASTNode, program: Node):
""" Block the subtree below the program node from happening in the
subtree ASTNode. """
block = self._block_subtree_rec(subtree, program)
self.z3_solver.add(z3.Or(block))
@abstractmethod
def build_program(self):
raise NotImplementedError
def __str__(self):
name = self.__class__.__name__
if "Enumerator" in name:
name = name.replace("Enumerator", "")
if "MultiTree" in name:
name = name.replace("MultiTree", "MT")
return name
|
C++ | UTF-8 | 754 | 3.5 | 4 | [] | no_license | /*
* 编译需要C++支持:
* g++ -std=c++11 example-05.cpp -o test05
*/
#include <iostream>
#include <memory> //declarations of std::auto_ptr
#include <utility> //declarations of std::unique_ptr
class Person
{
public:
Person(const int i):age(i)
{
std::cout<<"Person::Person()"<<std::endl;
}
~Person()
{
std::cout<<"Person::~Person()"<<std::endl;
}
void Print()
{
std::cout<<"Person::age="<<age<<std::endl;
}
public:
int age;
};
int main(int argc,char *argv[])
{
std::auto_ptr<Person> p0(new Person(1));
if(p0.get())
{
p0->Print();
p0.reset();
}
std::unique_ptr<Person> p1(new Person(1));
if(p1.get())
{
p1->Print();
//std::unique_ptr<Person> p2=p1; #不能编译通过
//p2->Print();
}
return 0;
}
|
Java | UTF-8 | 630 | 2.375 | 2 | [] | no_license | package xyz.dicky99.rpc.registry;
import java.net.InetSocketAddress;
/**
* @author Ysj
* @version 1.0
* @description 服务注册表通用接口
* @date 2021/5/7 23:29
*/
public interface ServiceRegistry {
/**
* 将一个服务注册进注册表
* @param serviceName 待注册的服务名称
* @param inetSocketAddress 服务地址
*/
void register(String serviceName, InetSocketAddress inetSocketAddress);
/**
* 根据服务名称获取服务实体
* @param serviceName 服务名称
* @return 服务地址
*/
InetSocketAddress lookupService(String serviceName);
}
|
TypeScript | UTF-8 | 2,175 | 2.90625 | 3 | [] | no_license | module objects
{
export class Supply extends GameObject
{
// PRIVATE INSTANCE MEMBERS
private _verticalSpeed?:number;
private _activeTime: number =0;
// PUBLIC PROPERTIES
// CONSTRUCTOR
constructor()
{
super(config.Game.TEXTURE_ATLAS, "bullet1", new Vector2(), true);
this.Start();
}
// PRIVATE METHODS
protected _checkBounds(): void
{
if(this.y >= config.Game.SCREEN_HEIGHT + this.height)
{
this.Reset();
}
}
protected _checkTime(): void
{
if(this.isActive== true){
this._activeTime++;
}
if(this._activeTime>=300){
if(this._activeTime%40==20){
this.alpha=0.5;
}
if(this._activeTime%40==0){
this.alpha=1;
}
}
if(this._activeTime==500){
this.Reset();
}
}
// PUBLIC METHODS
public Start(): void
{
this.isActive=false;
this.type = enums.GameObjectType.SUPPLY;
this.position = new Vector2(-1000,-1000);
this.Reset();
}
public Update(): void
{
this._checkTime();
}
public Reset(): void
{
this.alpha=1;
this._activeTime=0;
this.isActive=false;
this.position = new Vector2(-1000,-1000);
let randomSupply= Math.floor(util.Mathf.RandomRange(1,10));
console.log(randomSupply);
if(randomSupply<6)
{
this.gotoAndPlay("bullet1");
}
else if(randomSupply<9)
{
this.gotoAndPlay("bullet2");
}
else if(randomSupply<11)
{
this.gotoAndPlay("bullet3");
}
}
}
} |
C++ | UTF-8 | 781 | 2.734375 | 3 | [
"MIT"
] | permissive | /**
* MIT License
* Copyright (c) 2020 Adrian T. Visarra
**/
#include "baba/cancellable_task.h"
namespace baba {
cancellable_task_ptr cancellable_task_::create() noexcept {
return std::make_shared<cancellable_task_>(private_tag());
}
cancellable_task_::cancellable_task_(private_tag) noexcept : cancellable_task_() {}
task_fn cancellable_task_::operator()(const task_fn &task) noexcept {
std::weak_ptr<cancellable_task_> w = shared_from_this();
return [task, w = std::move(w)]() {
if (const auto o = w.lock()) {
std::lock_guard l(o->_in_scope_mtx);
if (o->_in_scope) {
task();
}
}
};
}
void cancellable_task_::cancel() noexcept {
std::lock_guard l(_in_scope_mtx);
_in_scope = false;
}
} // namespace baba |
Java | UTF-8 | 927 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | package com.sfe.ssm.quartz;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
/**
* @author 廖志群
* @version 1.00
* @date 八月 02 2017,14:45
* 重置JobFactory Quartz才能使用注入bean
*/
public class ResetJobFactory extends AdaptableJobFactory {
//这个对象Spring会帮我们自动注入进来,也属于Spring技术范畴.
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
//调用父类的方法
Object jobInstance = super.createJobInstance(bundle);
//进行注入,这属于Spring的技术,不清楚的可以查看Spring的API.
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
|
Markdown | UTF-8 | 11,148 | 2.859375 | 3 | [] | no_license | # jfaker
Generate fake data, great for databases! Ported from stympy's Ruby gem: https://github.com/stympy/faker
# Usage
Install the package
```
$ npm i jfaker
```
Require then use jfaker in your JavaScript files
```js
const faker = require('jfaker')
```
To view all generators in a category you can use this (I will be creating a doc file explaining each category and the values it has)
```js
console.log(faker.overwatch)
```
Will return
```js
{ heroes: [Function: heroes],
locations: [Function: locations],
quotes: [Function: quotes] }
```
So the random generators you have available for **`overwatch`** are: `heroes()`, `locations()` and `quotes()`.
```js
console.log(faker.overwatch.heroes())
console.log(faker.overwatch.locations())
console.log(faker.overwatch.quotes())
```
```
=> Bastion
=> Volskaya Industries
=> Oh, let's break it down!
```
# Notice
132 of 148 categories have been ported so far. Some of them are still missing a few convert/generate functions but I'm slowing getting them implemented.
If you find any bugs or have any suggestions you can let me know here: https://github.com/timwaldron/jfaker/issues
# v1.2.0
100% implemented the following libraries
```
address
app
book
buffy
coffee
commerce
company
dota
dune
job
markdown
name
```
Fixed/not 100% implemented
```
bank Missing functions
id_number Missing functions
lorem Missing functions
compass Disabled while finding solution
```
# v1.1.3
Updated README.md layout, fixed corrupted libraries.
# v1.1.2
Removed duplicate text in README.md
# v1.1.0
Additional 63 categories added.
|A - F|G - O|P - Z|
|:---|:---|:---|
|back_to_the_future|game|parks_and_rec|
|bank|game_of_thrones|princess_bride|
|bojack_horseman|ghostbusters|programming_language|
|breaking_bad|grateful_dead|rick_and_morty|
|buffy|greek_philosophers|rupaul|
|chuck_norris|hacker|shakespeare|
|color|hey_arnold|silicon_valley|
|commerce|hitchhikers_guide_to_the_galaxy|simpsons|
|community|hobbit|sonic_the_hedgehog|
|company|house|source|
|construction|how_i_met_your_mother|south_park|
|cosmere|job|stargate|
|crypto_coin|kpop|stranger_thing|
|dc_comics|lebowski|stripe|
|dr_who|lord_of_the_rings|sword_art_online|
|dumb_and_dumber|lorem|the_expanse|
|dune|michael_scott|the_it_crowd|
|esport|music|twin_peaks|
|fallout|name|v_for_vendetta|
|friends|nation|world_of_warcraft|
| |new_girl|zelda
| |overwatch| |
# Categories (v1.0.0)
* jfaker
* address
* city_prefix
* city_suffix
* country
* state (USA)
* state_abbr (USA)
* time_zone
* ancient
* god
* primordial
* titan
* hero
* animal
* name
* app
* name
* version
* appliance
* brand
* equipment
* aqua_teen_hunger_force
* character
* artist
* names
* basketball
* beer
* brand
* name
* hop
* yeast
* malt
* style
* book
* title
* author
* publisher
* genre
* bossa_nova
* artists
* songs
* business
* credit_card_numbers
* credit_card_types
* cannabis
* strains
* cannabinoid_abbreviations
* cannabinoids
* terpenes
* medical_uses
* health_benefits
* categories
* types
* buzzwords
* cat
* name
* breed
* registry
* code
* asin
* coffee
* country
* brazil
* colombia
* sumatra
* ethiopia
* honduras
* kenya
* uganda
* mexico
* guatemala
* nicaragua
* costa_rica
* tanzania
* el_salvador
* rwanda
* burundi
* panama
* yemen
* india
* variety
* intensifier
* body
* descriptor
* notes
* name_1
* name_2
* blend_name
* coin
* compass
* word
* abbreviation
* azimuth
* culture_series
* currency
* code
* name
* symbol
* demographic
* race
* sex
* demonym
* educational_attainment
* marital_status
* dessert
* variety
* topping
* flavor
* device
* model_name
* platform
* manufacturer
* serial
* dog
* name
* breed
* sound
* meme_phrase
* age
* coat_length
* size
* dota
* hero
* quote
* item
* team
* player
* dragon_ball
* characters
* educator
* name
* secondary
* type
* subject
* course_number
* elder_scrolls
* race
* creature
* region
* dragon
* city
* first_name
* last_name
* electrical_components
* active
* passive
* electromechanical
* family_guy
* character
* location
* quote
* file
* extension
* mime_type
* food
* dish
* descriptions
* ingredients
* fruits
* vegetables
* spices
* measurements
* measurement_sizes
* metric_measurements
* sushi
* football
* teams
* players
* coaches
* competitions
* positions
* fresh_prince_of_bel_air
* characters
* celebrities
* funny_name
* name
* gender
* types
* binary_types
* half_life
* character
* enemy
* location
* harry_potter
* characters
* locations
* quotes
* books
* houses
* spells
* heroes
* names
* specialties
* klasses
* heroes_of_the_storm
* battlegrounds
* classes
* heroes
* quotes
* hipster
* words
* horse
* name
* breed
* id_number
* valid
* invalid
* industry_segments
* industry
* super_sector
* sector
* sub_sector
* invoice
* check_digit_method
* pattern
* league_of_legends
* champion
* location
* quote
* summoner_spell
* masteries
* rank
* lovecraft
* fhtagn
* deity
* location
* tome
* words
* markdown
* headers
* emphasis
* marketing
* buzzwords
* measurement
* height
* length
* volume
* weight
* metric_height
* metric_length
* metric_volume
* metric_weight
* military
* army_rank
* marines_rank
* navy_rank
* air_force_rank
* dod_paygrade
* movie
* quote
* nato_phonetic_alphabet
* code_word
* one_piece
* characters
* seas
* islands
* locations
* quotes
* akumas_no_mi
* opera
* phish
* song
* phone_number
* formats
* country_code
* pokemon
* names
* locations
* moves
* quote
* famous_last_words
* matz
* most_interesting_man_in_the_world
* robin
* singular_siegler
* yoda
* relationship
* direct
* extended
* in_law
* spouse
* parent
* sibling
* restaurant
* rock_band
* name
* science
* element
* element_symbol
* scientist
* seinfeld
* character
* quote
* business
* slack_emoji
* people
* nature
* food_and_drink
* celebration
* activity
* travel_and_places
* objects_and_symbols
* custom
* space
* planet
* moon
* galaxy
* nebula
* star_cluster
* constellation
* star
* agency
* agency_abv
* nasa_space_craft
* company
* distance_measurement
* meteorite
* launch_vehicule
* star_trek
* character
* location
* specie
* villain
* subscription
* plans
* statuses
* payment_methods
* subscription_terms
* payment_terms
* super_smash_bros
* superhero
* power
* prefix
* suffix
* descriptor
* team
* creature
* sport
* mascot
* the_thick_of_it
* characters
* positions
* departments
* umphreys_mcgee
* song
* university
* prefix
* suffix
* venture_bros
* character
* organization
* vehicle
* quote
* verbs
* base
* past
* past_participle
* simple_present
* ing_form
* witcher
* characters
* witchers
* schools
* locations
* quotes
* monsters
* yoda
* quotes
|
Swift | UTF-8 | 568 | 2.703125 | 3 | [
"MIT"
] | permissive | //
// LoginService.swift
// TPInjector_Example
//
// Created by Eliran Ben-Ezra on 4/8/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import TPInjector
protocol LoginService {
func login()
}
class LoginServiceImpl: LoginService, Injectable {
private let networkService: NetworkService
init(networkService: NetworkService = inject(),
userName: String = inject("user_name")) {
self.networkService = networkService
print("UserName: \(userName)")
}
func login() {
print("Using network service to login: \(networkService)")
}
}
|
C++ | UTF-8 | 1,986 | 4.125 | 4 | [
"MIT"
] | permissive | /*
100. Same Tree Easy
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
*/
#include <iostream>
#include <cstdlib>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void add(TreeNode *root, int data) {
TreeNode *curr = root;
TreeNode *father = NULL;
while (curr != NULL) {
if (curr->val == data)
return;
father = curr;
curr = (data < curr->val) ?
curr->left : curr->right;
}
if (father->val > data) {
father->left = new TreeNode(data);
} else {
father->right = new TreeNode(data);
}
}
void validateTrees(TreeNode* p, TreeNode* q, bool &flag) {
if (p == NULL && q == NULL)
return;
if ((p == NULL && q != NULL) || (p != NULL && q == NULL)) {
flag = false;
return;
}
if (p->val != q->val) {
flag = false;
return;
}
validateTrees(p->left, q->left, flag);
validateTrees(p->right, q->right, flag);
}
bool isSameTree(TreeNode* p, TreeNode* q) {
bool flag = true;
validateTrees(p, q, flag);
return flag;
}
int main() {
TreeNode *p = new TreeNode(5);
TreeNode *q = new TreeNode(5);
add(p, 2);
add(q, 2);
add(p, 5);
add(q, 1);
add(p, 3);
add(q, 3);
add(p, 7);
add(q, 7);
add(p, 9);
add(q, 9);
add(p, 8);
add(q, 8);
add(p, 4);
add(q, 4);
bool flag = isSameTree(p, q);
if (flag)
cout << "Fer me caso contigo si es verdadero";
else
cout << "Chale";
return 0;
} |
Markdown | UTF-8 | 1,681 | 2.578125 | 3 | [] | no_license | +++
title = "Contra 1cc"
date = "2014-01-03"
slug = "contra-1cc"
Categories = ["konami", "contra", "1cc"]
+++
I didn't play many games seriously in 2013, mostly due to work being very demanding and just not
having the time to really get into a game. Sadly, I didn't 1CC a single game in 2013 that I
hadn't 1CC'd before. I spent most of my gaming time setting up my cabinet so that I could [stream](http://twitch.tv/pdp80)
from it and had some fun with that.
[I put the details of my setup here on the Shmups Forum](http://shmups.system11.org/viewtopic.php?f=6&t=45917)
if you're interested.
It's now 2014 and I will hopefully have more time to play games. In my few days off around the
holidays, I wanted to try and 1CC something and ease myself back into playing arcade games. I
picked [Contra](http://en.wikipedia.org/wiki/Contra_%28video_game%29). Everybody knows Contra and I
own the PCB. Contra on NES is a really hard game, but the arcade game isn't so bad, at least with
the dip switch settings mine was randomly set to.
I played the game for about 3 hours on New Years Day and reached the big beating heart final
boss. The next day on my 3rd credit of the day I beat it. I was streaming (with no one watching) and
captured the run.
{{< youtube 6RgctZ-Hbl4 >}}
The video does some weird things, my capture card doesn't seem to be able to handle the 57hz refresh
rate of the arcade PCB. Oh well, sorry!
I have set some STG/shmup goals for 2014, I'll post more about those later. I ordered a new PCB from
Japan that I'm super excited about and will write about when it arrives. But for now, this
Contra 1CC will serve as a good start to the year!
Happy New Year!
|
Java | UTF-8 | 2,465 | 2.546875 | 3 | [] | no_license | package me.viscar.townyrelationalcolors.townscoreboards;
import com.comphenix.protocol.events.PacketContainer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
public class WildernessTeamsContainer extends TownTeamsContainer {
public WildernessTeamsContainer(TownScoreboardManager tsbm) {
super(tsbm, null);
}
public void sendPacketsFromPlayer(Player player) {
ChatColor relColor = tsbm.getRankColor(player);
String prefix = tsbm.getPlayerPrefixes(player);
PacketContainer redundantPacket = PacketSender.createRedundantTeamPacket(relColor, prefix, Arrays.asList(player.getName()));
PacketContainer teamPacket = PacketSender.createTeamPacket(relColor, prefix, Arrays.asList(player.getName()));
try {
// Send packets for ranked members
for (Player wildPlayer : rankedTownMembers) {
protocolManager.sendServerPacket(wildPlayer, redundantPacket);
protocolManager.sendServerPacket(wildPlayer, teamPacket);
}
// Send packets for non ranked members
for (String playerName : nonRankedMembers) {
Player townMember = Bukkit.getPlayer(playerName);
if (townMember == null)
continue;
protocolManager.sendServerPacket(townMember, redundantPacket);
protocolManager.sendServerPacket(townMember, teamPacket);
}
} catch (InvocationTargetException e) {
Bukkit.getLogger().info("[RC] Runtime error while sending packets to townless players, aborting");
return;
}
}
public void sendPacketsToPlayer(Player player) {
// Send packets for non ranked members
if (!nonRankedMembers.isEmpty())
PacketSender.sendTeamPackets(player, ChatColor.WHITE, "", nonRankedMembers);
// Send packets for ranked members
if (!rankedTownMembers.isEmpty()) {
for (Player townMember : rankedTownMembers) {
ChatColor rankColor = tsbm.getRankColor(townMember);
String prefixes = tsbm.getPlayerPrefixes(townMember);
PacketSender.sendTeamPackets(player, rankColor, prefixes, Arrays.asList(townMember.getName()));
}
}
}
}
|
Markdown | UTF-8 | 6,264 | 3 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"OpenSSL"
] | permissive | ---
title: CREATE SEQUENCE statement [YSQL]
headerTitle: CREATE SEQUENCE
linkTitle: CREATE SEQUENCE
description: Use the CREATE SEQUENCE statement to create a sequence in the current schema.
menu:
v2.14:
identifier: ddl_create_sequence
parent: statements
type: docs
---
## Synopsis
Use the `CREATE SEQUENCE` statement to create a sequence in the current schema.
## Syntax
<ul class="nav nav-tabs nav-tabs-yb">
<li >
<a href="#grammar" class="nav-link active" id="grammar-tab" data-toggle="tab" role="tab" aria-controls="grammar" aria-selected="true">
<img src="/icons/file-lines.svg" alt="Grammar Icon">
Grammar
</a>
</li>
<li>
<a href="#diagram" class="nav-link" id="diagram-tab" data-toggle="tab" role="tab" aria-controls="diagram" aria-selected="false">
<img src="/icons/diagram.svg" alt="Diagram Icon">
Diagram
</a>
</li>
</ul>
<div class="tab-content">
<div id="grammar" class="tab-pane fade show active" role="tabpanel" aria-labelledby="grammar-tab">
{{% includeMarkdown "../../syntax_resources/the-sql-language/statements/create_sequence,sequence_name,sequence_options.grammar.md" %}}
</div>
<div id="diagram" class="tab-pane fade" role="tabpanel" aria-labelledby="diagram-tab">
{{% includeMarkdown "../../syntax_resources/the-sql-language/statements/create_sequence,sequence_name,sequence_options.diagram.md" %}}
</div>
</div>
## Semantics
### *create_sequence*
#### CREATE SEQUENCE *sequence_name* [ IF NOT EXISTS ]
Specify the name of the sequence (*sequence_name*). An error is raised if a sequence with that name already exists in the current schema and `IF NOT EXISTS` is not specified.
The sequence name must be distinct from any other sequences, tables, indexes, views, or foreign tables in the same schema.
### *sequence_options*
#### INCREMENT BY *increment*
Specify the *increment* value to add to the current sequence value to create a new value. The default value is `1`. A positive number
#### MINVALUE *minvalue* | NO MINVALUE
Specify the minimum value allowed in the sequence. If this value is reached (in a sequence with a negative increment), `nextval()` will return an error. If `NO MINVALUE` is specified, the default value will be used. Default is 1.
#### MAXVALUE *maxvalue* | NO MAXVALUE
Specify the maximum value allowed in the sequence. If this value is reached, `nextval()` will return an error. If `NO MAXVALUE` is specified, the default will be used. Default is `2<sup>63</sup> - 1`.
#### START WITH *start*
Specify the first value in the sequence. `start` cannot be less than `minvalue`. Default is `1`.
#### CACHE *cache*
Specify how many numbers from the sequence to cache in the client. Default is `100`.
When YB-TServer [ysql_sequence_cache_minval](../../../../../reference/configuration/yb-tserver/#ysql-sequence-cache-minval) configuration flag is not explicitly turned off (set to `0`), the maximum value of the flag and the cache clause will be used.
#### [ NO ] CYCLE
If `CYCLE` is specified, the sequence will wrap around once it has reached `minvalue` or `maxvalue`. If `maxvalue` was reached, `minvalue` will be the next number in the sequence. If `minvalue` was reached (for a descending sequence), `maxvalue` will be the next number in a sequence. `NO CYCLE` is the default.
## Cache
In YSQL as in PostgreSQL, the sequence's data is stored in a persistent system table. In YSQL this table has one row per sequence and it stores the sequence data in two values:
### *last_val*
Stores the last value used or the next value to be used.
### *is_called*
Stores whether `last_val` has been used. If false, `last_val` is the next value in the sequence. Otherwise, `last_val` + `INCREMENT` is the next one.
By default (when `INCREMENT` is 1), each call to `nextval()` updates `last_val` for that sequence. In YSQL, the table holding the sequence's data is replicated as opposed to being in the local file system. Each update to this table requires two RPCs (and will be optimized to one RPC in the future), In any case, the latency experienced by a call to `nextval()` in YSQL will be significantly higher than the same operation in Postgres. To avoid such performance degradation, Yugabyte recommends using a cache value with a value large enough. Cached values are stored in the memory of the local node, and retrieving such values avoids any RPCs, so the latency of one cache allocation can be amortized over all the numbers allocated for the cache.
`SERIAL` types create a sequence with a cache with default value of 1. So `SERIAL` types should be avoided, and their equivalent statement should be used.
Instead of creating a table with a `SERIAL` type like this:
```sql
CREATE TABLE t(k SERIAL)
```
You should create a sequence with a large enough cache first, and then set the column that you want to have a serial type to `DEFAULT` to `nextval()` of the sequence.
```sql
CREATE SEQUENCE t_k_seq CACHE 10000;
CREATE TABLE t(k integer NOT NULL DEFAULT nextval('t_k_seq'));
```
## Examples
Create a simple sequence that increments by 1 every time `nextval()` is called.
```sql
yugabyte=# CREATE SEQUENCE s;
```
```sql
CREATE SEQUENCE
```
Call `nextval()`.
```sql
yugabyte=# SELECT nextval('s');
```
```output
nextval
---------
1
(1 row)
```
Create a sequence with a cache of 10,000 values.
```sql
yugabyte=# CREATE SEQUENCE s2 CACHE 10000;
```
```sql
CREATE SEQUENCE
```
In the same session, select `nextval()`.
```sql
SELECT nextval('s2');
```
```output
nextval
---------
1
(1 row)
```
In a different session, select `nextval()`.
```sql
SELECT nextval('s2');
```
```output
nextval
---------
10001
(1 row)
```
Create a sequence that starts at 0. MINVALUE also has to be changed from its default 1 to something less than or equal to 0.
```sql
CREATE SEQUENCE s3 START 0 MINVALUE 0;
```
```sql
CREATE SEQUENCE
```
```sql
SELECT nextval('s3');
```
```output
nextval
---------
0
(1 row)
```
## See also
- [`ALTER SEQUENCE`](../ddl_alter_sequence)
- [`DROP SEQUENCE`](../ddl_drop_sequence)
- [`currval()`](../../../exprs/func_currval)
- [`lastval()`](../../../exprs/func_lastval)
- [`nextval()`](../../../exprs/func_nextval)
- [`setval()`](../../../exprs/func_setval)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.