branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>df = read.csv("BlackFriday-AgeGroups.csv")
library(userfriendlyscience)
library(rlist)
city_tests = c()
cities = c('A','B','C')
for(city in cities){
df_city = subset(df, City_Category == city)
print(paste('Games_Howell Test for City: ', city))
print(oneway(y = df_city$Purchase, x = df_city$Age, posthoc = 'games-howell'))
print('Means Between Age Groups:')
print(aggregate(df_city[, c('Purchase')], list(df_city$Age), mean))
print('-------')
}
library(dplyr)
df_test = subset(df, City_Category == 'A')
df_test = sample_n(df_test, 5000)
print(oneway(y = df_test$Purchase, x = df_test$Age, posthoc = 'games-howell'))
print(aggregate(df_test[, c('Purchase')], list(df_test$Age), mean))
oneway.test(Purchase ~Age, data = df_test, var.equal = FALSE)
LM = lm(Purchase ~ Age , data = df)
summary(LM)
<file_sep># BlackFridaySales
<h3> Please use: https://nbviewer.jupyter.org/github/DishantBhatt/BlackFridaySales/blob/master/BlackFridayAnalysis.ipynb to view project
if github not displaying Jupyter Note book </h3>
<p> This is an on going exploratory data analysis project on Black Friday Sales data from 3 cities. </p>
| 332aaaf32befcfaad629c64ed60d7fed2985575a | [
"Markdown",
"R"
] | 2 | R | DishantBhatt/BlackFridaySales | 13a4acca16e1dec39c8d81ec701264e1781d3446 | 08fe9149919dc9ef7162244673ab80dfb0269ce4 |
refs/heads/master | <file_sep><?php
//inclure un fichier
include "config.php";
//appel fonction
$base=connect();
//récupération des donnés
$e=$_REQUEST['email'];//il cherche l'input du fichier html ayant le nom 'email' et récupère sa valeur
$m=$_REQUEST['mdp'];
$mdpc=md5($m);//md5 permet de crypter le mdp toujours de la meme methode
$req="INSERT INTO users (id,email,password) VALUES(null,'$e','<PASSWORD>')";//les cotes parce que nous allons inserer les variables dans une chaine
//exec est la fonction qui fait l'execution de la requete//elle fonctionne avec INSERT,UPDATE et DELETE
//type de retour de l'exec est soit int soit bool
//elle retourne une variable int contient le nbre de lignes insérées si la requete s'est correctement exécutés
//elle retourne une variable bool cotenant la valeur false en cas d'echec
$resp=$base->exec($req);//la fonction exec va executer la requete $req sur la base $base et son resultat sera affecté à la variable $resp
if ($resp==1){//1:nbre de lignes que j'ai inséré
echo "Données insérées avec succès";
}
else{
echo "Vérifier la requete ou le fichier config";
}
?><file_sep><?php
//inclure un fichier
include "config.php";
//appel fonction
$base=connect();
$req="SELECT * FROM users";
//la fonction query ne fonctionne qu'avec la requete SELECT
$result=$base->query($req);
?>
<table>
<thead>
<tr>
<th>Email</th>
<th>Mdp</th>
</tr>
</thead>
</table>
<tbody>
<?php
//fetchObject:permet de récuperer le résutat de chaque itération et de l'affecter à un objet |fetchAssoc
while($user=$result->fetchObject()){
?>
<tr>
<td><?php echo $user->email; ?></td>
<td><?php echo $user->password; ?></td>
</tr>
<?php
}
?> | c743f143a20f582bd75a8719bee4aad103639ab4 | [
"PHP"
] | 2 | PHP | JamilaSallem/php_last | 5df0ddbcab5c2d8cdd8d031da9b3c1d677dd2adf | 89cceae9b01dc2ae67162d772d5fe2e056ef697d |
refs/heads/master | <repo_name>SamyakJain091998/day_32_assignment<file_sep>/README.md
# day_32_assignment
Just another assignment
<file_sep>/assignment_Problems_6.js
console.log("<----Problem set 6---->")
console.log("\n");
//Problem statement 1
console.log("<------Problem statement 1------>")
var prompt = require('prompt-sync')();
let inputTemperature;
let conversionSelection;
while (1) {
console.log("Enter the selection of conversion -----> \n1. degF to degC \n2. degC to degF : \n");
conversionSelection = prompt("Enter : ");
conversionSelection = parseInt(conversionSelection);
switch(conversionSelection){
case 1:
while (1) {
inputTemperature = prompt('Enter the temperature value between 32 degF and 212 degF : ');
if (inputTemperature < 32 || inputTemperature > 212) {
console.log("Enter a valid input!");
continue;
}
break;
}
break;
case 2:
while (1) {
inputTemperature = prompt('Enter the temperature value between 0 degC and 100 degC : ');
if (inputTemperature < 0 || inputTemperature > 100) {
console.log("Enter a valid input!");
continue;
}
break;
}
break;
default:
console.log("Enter a valid input!");
continue;
}
break;
// if (conversionSelection == 1) {
// while (1) {
// inputTemperature = prompt('Enter the temperature value between 32 degF and 212 degF : ');
// if (inputTemperature < 32 || inputTemperature > 212) {
// console.log("Enter a valid input!");
// continue;
// }
// break;
// }
// break;
// } else if (conversionSelection == 2) {
// while (1) {
// inputTemperature = prompt('Enter the temperature value between 0 degC and 100 degC : ');
// if (inputTemperature < 0 || inputTemperature > 100) {
// console.log("Enter a valid input!");
// continue;
// }
// break;
// }
// break;
// } else {
// console.log("Enter a valid selection");
// continue;
// }
}
if (conversionSelection == 1) {
let convertedValue = farheneitToCelsiusConverter(inputTemperature);
console.log("Temperature converted to celsius:");
console.log("Converted temperature is----> " + convertedValue);
} else if (conversionSelection == 2) {
let convertedValue = celsiusToFarheneitConverter(inputTemperature);
console.log("Temperature converted to fehreineit:");
console.log("Converted temperature is----> " + convertedValue);
} else {
console.log("Enter a valid input please!");
return;
}
//Conversion functions
function farheneitToCelsiusConverter(inputVariable) {
return (inputVariable - 32) * 5 / 9;
}
function celsiusToFarheneitConverter(inputVariable) {
return (inputVariable * 9 / 5) + 32;
}
console.log("\n");
//Problem statement 2
console.log("<------Problem statement 2------>")
var prompt = require('prompt-sync')();
var n1 = prompt('Enter the value of n1 -----> ');
var n2 = prompt('Enter the value of n2 -----> ');
function palindromeChecker(var1, var2) {
var localVariable = "";
while (var1 >= 1) {
localVariable += (var1 % 10);
var1 /= 10;
var1 = parseInt(var1);
}
if (parseInt(localVariable) == var2) {
return true;
}
}
var result = palindromeChecker(parseInt(n1), parseInt(n2));
if (result == true) {
console.log("Yes! The two numbers are palindromes...");
} else {
console.log("Oops! The two numbers are not palindromes...");
}
console.log("\n");
//Problem statement 3
console.log("<------Problem statement 3------>")
var prompt = require('prompt-sync')();
var n = prompt('Enter the value of n -----> ');
n = parseInt(n);
var result = primeNumberChecker(n);
if (result == true) {
console.log("The input number is a prime number..")
var result = palindromeChecker(n);
if (result == true) {
console.log("The palindrom is also a prime number..")
} else {
console.log("Oops! The palindrome is not a prime number..");
}
} else {
console.log("The input number is not a palindrome..");
}
function palindromeChecker(var1) {
var localVariable = "";
while (var1 >= 1) {
localVariable += (var1 % 10);
var1 /= 10;
var1 = parseInt(var1);
}
return (primeNumberChecker(parseInt(localVariable)));
}
function primeNumberChecker(var1) {
var index = true;
var halfValue = parseInt(var1 / 2);
for (var i = 2; i <= halfValue; i++) {
if (var1 % i == 0) {
index = false;
}
}
return index;
}<file_sep>/assignment_Problems_5.js
console.log("<----Problem set 5---->")
console.log("\n");
//Problem statement 1
console.log("<------Problem statement 1------>")
var prompt = require('prompt-sync')();
var n = prompt('Enter the value of n -----> ');
let localPower = 0;
while(Math.pow(2, localPower) <= 256 && localPower <= n){
console.log(Math.pow(2, localPower));
localPower++;
}
console.log("\n");
//Problem statement 2
console.log("<------Problem statement 2------>")
var prompt = require('prompt-sync')();
var n = prompt('Think of a nunmber between 1 and 100 -----> ');
if (n < 1 || n > 100) {
console.log("Please enter a valid entry");
return;
} else {
let count = 0;
let guess = prompt("Enter your guess...");
while (guess != n) {
guess = prompt("Enter your guess...");
count++;
if (guess > n) {
console.log("Oops! The number is lower than that!");
} else if (guess < n) {
console.log("Oops! The number is higher than that!");
}
}
console.log("Congratulations! You guessed it right in " + count + " times.");
}
console.log("\n");
//Problem statement 3
console.log("<------Problem statement 3------>")
console.log("\n");
let headsCount = 0;
let tailsCount = 0;
while (headsCount != 11 && tailsCount != 11) {
let randomNumber = Math.floor(Math.random() * 10) % 2;
if (randomNumber == 0) {
console.log("---heads---");
headsCount++;
} else {
console.log("tails");
tailsCount++;
}
}
console.log("\n");
console.log("Final heads count -----> " + headsCount);
console.log("Final tails count -----> " + tailsCount);
console.log("\n");
//Problem statement 3
console.log("<------Problem statement 3------>")
console.log("\n");
let initialMoney = 100;
let currentMoney = initialMoney;
var betAmount = 1;
let goalAmount = 200;
let winCount = 0;
let betCount = 0;
while (currentMoney < goalAmount && currentMoney > 1) {
let randomToss = Math.floor(Math.random() * 10) % 2;
betCount += 1;
if (randomToss == 0) {
currentMoney -= (betAmount * 1);
} else {
currentMoney += (betAmount * 2);
winCount += 1;
}
}
console.log("-------" + "Win count is : " + winCount + "-------");
console.log("-------" + "Total number of bets played : " + betCount + "-------");
console.log("-------" + "Current value of money : " + currentMoney + "-------");
if(currentMoney < 1){
console.log("Oops!! The player lost all the money..");
}else if(currentMoney >= 200){
console.log("Congratulations! The player reached his goal..");
}<file_sep>/assignment_Problems_4.js
console.log("<----Problem set 4---->")
console.log("\n");
//Problem statement 1
console.log("<------Problem statement 1------>")
var prompt = require('prompt-sync')();
var n = prompt('Enter the value of n -----> ');
let localPower = 0;
var localIndex = 1;
while (Math.pow(2, localIndex) <= Math.pow(2, n)) {
console.log(Math.pow(2, localIndex));
localIndex += 1;
}
console.log("\n");
//Problem statement 2
console.log("<------Problem statement 2------>")
var prompt = require('prompt-sync')();
var n = prompt('Enter the value of n -----> ');
let harmonicSum = 0;
for (let i = 1; i <= n; i++) {
harmonicSum += 1 / i;
}
console.log(harmonicSum);
console.log("\n");
//Problem statement 2
console.log("<------Problem statement 2------>")
var prompt = require('prompt-sync')();
var inputNumber = prompt('Enter the value of n -----> ');
function test_prime(n) {
if (n === 1) {
return false;
}
else if (n === 2) {
return true;
} else {
for (var x = 2; x < n; x++) {
if (n % x === 0) {
return false;
}
}
return true;
}
}
let isPrime = test_prime(inputNumber);
if (isPrime == true) {
console.log("Yes! It's a prime number");
} else {
console.log("No! It's not a prime number");
}
console.log("\n");
//Problem statement 3
console.log("<------Problem statement 3------>")
const args = process.argv.slice(2);
let inputNumber1 = parseInt(args[0]);
let inputNumber2 = parseInt(args[1]);
while (inputNumber1 <= inputNumber2) {
if (test_prime(inputNumber1) == true) {
console.log(inputNumber1 + " ");
}
inputNumber1++;
}
function test_prime(n) {
if (n === 1) {
return false;
}
else if (n === 2) {
return true;
} else {
for (var x = 2; x < n; x++) {
if (n % x === 0) {
return false;
}
}
return true;
}
}
console.log("\n");
//Problem statement 4
console.log("<------Problem statement 4------>")
var prompt = require('prompt-sync')();
var n = prompt('Enter the value of n -----> ');
var factorial = 1;
while (n > 0) {
factorial *= n;
n--;
}
console.log(factorial);
console.log("\n");
//Problem statement 5
console.log("<------Problem statement 5------>")
var prompt = require('prompt-sync')();
var n = prompt('Enter the value of n -----> ');
var i;
for (i = 1; i <= n / 2; i++) {
if (n % i == 0) {
console.log(i + "\n");
}
}
console.log("\n");
| 4057760590989e3612381bc14150bc16851d130f | [
"Markdown",
"JavaScript"
] | 4 | Markdown | SamyakJain091998/day_32_assignment | febc6a0b3feb5059f1f69668d08d7b1c2ea0d3e2 | 1e2da729c89999366d5975b26c91a381199084c1 |
refs/heads/main | <repo_name>caio-cunha/projeto-aquarela<file_sep>/sex_predictor.py
import argparse
import csv
import pandas as pd
import sys
import pickle
import numpy as np
import joblib
from sklearn.preprocessing import StandardScaler
def parser():
"""
Essa função tem como objetivo ler o parametro --input_file digitado no comando via CMD
_ _ _ _ _ _ _ _ _ _ _ _
Output:
Argparse
"""
parser = argparse.ArgumentParser(description='Ler arquivo csv')
parser.add_argument('-i','--input_file', type=argparse.FileType('r'), help='Ler arquivo csv')
args = parser.parse_args()
return args
def transformar_csv_dataframe(csv):
"""
Essa função tem como objetivo transformar o csv lido no CMD em um dataframe
_ _ _ _ _ _ _ _ _ _ _ _
Input:
csv: csv_reader object
Output:
df: pandas Dataframe do csv lido
"""
df = pd.DataFrame(csv_reader)
df.columns = df.iloc[0]
df = df.drop(0)
df = df.reset_index(drop=True)
df = df.set_index(['index'])
return df
def tratar_dados_para_predicao(df):
"""
Essa função tem como objetivo tratar os dados importados via CMD.
_ _ _ _ _ _ _ _ _ _ _ _
Input:
df: dataFrame pandas com os dados importados
Output:
df_tratado: dataFrame pandas com os dados tratados
"""
##Transformamando valores vazios em NANs
df = df.replace(r'', np.nan, regex=True)
##Tratando as valores nans
df = df.fillna(method='ffill')
##transformando todos os valores em float
df_tratado = df.round(0).astype(float)
##Normalizar os dados com o scaller salvo
scaler = joblib.load('scaler.save');
df_tratado = scaler.transform(df_tratado)
return df_tratado
def predicao_modelo(df):
"""
Essa funçã tem como objetivo de carregar o modelo e realizar predições sobre o modelo treinado
_ _ _ _ _ _ _ _ _ _ _ _ _
Input:
df: dataframe Pandas com os dados
Output:
df_saida: dataframe com as predições
"""
##Modelo treinado com o notbook 'treinador_modelo.ipnyb'
filename = 'modelo_treinado.sav'
##Carregando modelo treinado
modelo_carregado = pickle.load(open(filename, 'rb'))
if(modelo_carregado):
print('Modelo carregado com sucesso!')
##Predição do modelo treinado
predicao = []
for array_valores in df.values:
predicao.append(modelo_carregado.predict(array_valores.reshape(1, -1)))
return predicao
if __name__ == '__main__':
##Parser para obter CSV escolhido pelo usuário no CMD
args = parser()
##Ler CSV recebido no PARSER
csv_reader = csv.reader(args.input_file)
##Transformar CSV READER em DATAFRAME
df = transformar_csv_dataframe(csv_reader)
##Tratar os dados
df_tratado = tratar_dados_para_predicao(df)
df_tratado = pd.DataFrame(df_tratado)
##Predição modelo treinado
preditos = predicao_modelo(df_tratado)
df_preditos = pd.DataFrame(preditos,columns=['sex'])
##Transformando valores 0 e 1 em M e F
df_preditos.loc[(df_preditos['sex'] == 1,"sex")] = 'M'
df_preditos.loc[(df_preditos['sex'] == 0,"sex")] = 'F'
##Salvando CSV com RESULTADOS
df_preditos.to_csv ('newsample_PREDICTIONS_{Caio_Henrique_Oliveira_Cunha}.csv', index=False, header=True)
print('Resultados salvos com sucesso!')
<file_sep>/requirements.txt
joblib==1.0.1
numpy==1.20.2
pandas==1.2.4
python-dateutil==2.8.1
pytz==2021.1
scikit-learn==0.24.1
scipy==1.6.2
six==1.15.0
sklearn==0.0
threadpoolctl==2.1.0
<file_sep>/README.md
# Sobre o projeto
Esse projeto tem como objetivo criar um modelo capaz de identificar o sexo de um paciente com base em algumas informações do mesmo, bem como inferir novos dados ao modelo.
- Importação dos dados
- Análise dos dados
- Tratamento dos dados
- Normalização dos dados
- Separação dos dados de treinamento e teste
- Treinamento do modelo (Rede neural, Random Forest, XGB)
- Validação do Modelo
- Inferência de novos dados ao modelo
# Pré requisitos
A aplicação depedende dos seguintes componentes.
- Python > 3.7.x
- Git
# Criação virtualenv do Python
Criar um ambiente virtual.
- Abra o anaconda prompt ou o prompt (devidamente setado a variável de ambiente do python e git).
- Crie um diretório para o projeto
## Criar
```
virtualenv 'nome_ambiente'
```
## Ativar (Windows)
```
nome_ambiente/Scripts/activate
```
## Ativar (Mac OS / Linux)
```
source nome_ambiente/bin/activate
```
# Baixar Projeto
- Após ativar o ambiente vá ao diretório que deseja baixar o projeto.
```
git clone https://github.com/caio-cunha/projeto-portal-telemedicina.git
```
# Instalar dependências
- Entre no projeto baixado e digite o comando abaixo
```
python -m pip install -r requirements.txt
```
# Executar script de predição utilizando o modelo treinado
```
(ambiente venv) python sex_predictor.py --input_file newsample.csv
```
# Executar script de treinamento
```
Entrar no script treinador_modelo.ipynb e seguir as orientações do relatório
```
| b735c2928a0b6c07348fa2e4158d3fa8b8498a00 | [
"Markdown",
"Python",
"Text"
] | 3 | Python | caio-cunha/projeto-aquarela | b1dc9d6ca3720e2810f75305060f5e8f3a1ba53c | d48f542a6a1fe17a1b1cc6f8fc76c5b3bf9c6d67 |
refs/heads/master | <file_sep>function onEdit(event)
{
var sheet=event.source.getActiveSheet();
/* List1 Start */
if(sheet.getName()=="List1") /* the tab in which magic will happen */
{
var timezone = "GMT-2";
var timestamp_format = "dd.MM.yyyy"; // Timestamp Format.
var updateColName = "Customer"; /* Add the name of the column we are going to change */
var timeStampColName = "date"; /* A column in which the date will automatically be added */
var actRng = event.range;
var editColumn = actRng.getColumn();
var actRow = actRng.getRow();
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var dateCol = headers[0].indexOf(timeStampColName) + 1;
var updateCol = headers[0].indexOf(updateColName) + 1;
if (dateCol > 0 && actRow > 1 && editColumn == updateCol)
{
var cell = sheet.getRange(actRow, dateCol);
var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
cell.setValue(date);
}
}
/* List1 End */
}
/* For two tabs we repeat if (From "List1 Start" to "List1 End" including) */
/* For date and time change Timestamp Format "dd-MM-yyyy hh:mm:ss" */
/* Original: https://stackoverflow.com/questions/46162179/auto-timestamp-when-editing-column */
| a4e23ff066374efd73282edfd1bf621c73d39d4c | [
"JavaScript"
] | 1 | JavaScript | plezzz/GoogleScript | 763127a6fe7a4ba1309462f8a03b81e87ce3fe9f | dbfaf264efbbd97154c27491afd6d5a9c4b43dc7 |
refs/heads/master | <repo_name>tjphoton/WeiboPostBrandNames<file_sep>/CountBrandNames.py
import json
import os, os.path
from collections import OrderedDict
from dateutil.parser import parse
def get_fileList(fPath):
fList = []
for root, _, files in os.walk(fPath):
for f in files:
if not f.startswith('.'):
fList += [os.path.join(root, f)]
return fList
def calc_total_counts(fList):
postTotCount = 0;
userCountTot = {}
provinceCountTot = {}
postHourTotDict = {}
for fileName in fList:
with open(fileName, 'r') as f:
read_data = f.read()
info = json.loads(read_data)
postTotCount += 1 # total post counts ++
if info["user"]["name"] in userCountTot: # count users for all the posts
userCountTot[info["user"]["name"]] += 1
else:
userCountTot[info["user"]["name"]] = 1
# count locations for all the posts
if info["user"]["province"] == '400': # province = 400 for oversea countries
if len(info["user"]["location"]) == 2: # oversea, no nation name
province = info["user"]["location"].split()[0] # get location, "oversea"
else: # specific country name other than China
province = info["user"]["location"].split()[1] # get location, country name
else: # province != 400 for chinese province
province = info["user"]["location"].split()[0] # China province name
if province in provinceCountTot:
provinceCountTot[province] += 1
else:
provinceCountTot[province] = 1
postHour = parse(info["created_at"]).strftime("%H") # posts peak hour statistics
if postHour in postHourTotDict:
postHourTotDict[postHour] += 1
else:
postHourTotDict[postHour] = 1
return {'postTotCount': postTotCount,
'userCountTot': userCountTot,
'provinceCountTot': provinceCountTot,
'postHourTotDict': postHourTotDict }
def calc_brand_counts(fList, brand_name):
postMentionedCount = 0
userNames = []
postDateDict = {}
for fileName in fList:
with open(fileName, 'r') as f:
read_data = f.read()
info = json.loads(read_data)
# count posts containing variation of brand name, such as "<NAME>" or "<NAME>"
if brand_name.lower() in info["text"].lower() or brand_name.replace(" ", "").lower() in info["text"].lower():
postMentionedCount += 1 # count posts mentioning brand name
if info["user"]["name"] not in userNames: # add user names mentioning brand name
userNames.append(info["user"]["name"])
postDate = parse(info["created_at"]).strftime("%Y-%m-%d") # post date statistics
if postDate in postDateDict:
postDateDict[postDate] += 1
else:
postDateDict[postDate] = 1
return {'postMentionedCount': postMentionedCount,
'userNames': userNames,
'postDateDict': postDateDict}
def main():
filePath = '/Users/qiu/Downloads/Bomoda/weibo'
# '/Users/qiu/Downloads/Bomoda/weibo/comments'
# '/Users/qiu/Downloads/Bomoda/weibo/reposts'
# '/Users/qiu/Downloads/Bomoda/weibo/statuses'
fileList = get_fileList(filePath)
total_result = calc_total_counts(fileList)
print total_result['postTotCount'], "total number of posts"
print "The peak hour with the most posts:", \
OrderedDict(sorted(total_result['postHourTotDict'].items(), key=lambda x: x[1], reverse = True)).keys()[:1]
popular_users = OrderedDict(sorted(total_result['userCountTot'].items(), key=lambda x: x[1], reverse = True))
print " "
print "top 10 user names for total posts:"
print "user name: ", "post numbers"
for k, v in popular_users.items()[:10]:
print "%s: %s" % (k, v)
popular_provinces = OrderedDict(sorted(total_result['provinceCountTot'].items(), key=lambda x: x[1], reverse = True))
print " "
print "top 10 user provinces or nations for total posts:"
print "province or nation name: ", "post numbers"
for k, v in popular_provinces.items()[:10]:
print "%s: %s" % (k, v)
brands = ['<NAME>', '<NAME>']
for i in xrange(2):
brand_result = calc_brand_counts(fileList, brands[i])
print brand_result['postMentionedCount'], "number of posts mentioning \"", brands[i], "\""
print "The date that has the highest number of posts mentioning \"", brands[i], "\":", \
OrderedDict(sorted(brand_result['postDateDict'].items(), key=lambda x: x[1], reverse = True)).keys()[:1]
print len(brand_result['userNames']), "user names mentioning \"", brands[i], "\":", " ".join(brand_result['userNames'])
if __name__ == '__main__':
main()
<file_sep>/README.md
# WeiboPostBrandNames
project to analysis weibo posts mentioning brand names <NAME> and <NAME>
1. README.md - this file is me :)
2. CountBrandNames.py
1. Count the number of posts mentioning each of the included brand names
2. Count the number of the users who mentioned them
3. Find the date that has the highest number of posts mentioning each of the brands
4. List the top 10 users and locations (as province level in China and nation level worldwide) for total posts
5. Find the peak hour with the most posts
3. Top10CommonTerms.py - Top 10 mentioned Chinese terms associated with each brand from all texts
4. SamplingBias.py - possible sampling bias through Weibo
5. UserNameList.txt - Lists of users who mentioned the brand names
<file_sep>/SamplingBias.py
import json
import os, os.path
from collections import OrderedDict
def get_fileList(fPath):
fList = []
for root, _, files in os.walk(fPath):
for f in files:
if not f.startswith('.'):
fList += [os.path.join(root, f)]
return fList
def calc_total_counts(fList):
genderDict = {}
langDict = {}
for fileName in fList:
with open(fileName, 'r') as f:
read_data = f.read()
info = json.loads(read_data)
if info["user"]["gender"] in genderDict:
genderDict[info["user"]["gender"]] += 1
else:
genderDict[info["user"]["gender"]] = 1
if info["user"]["lang"] in langDict:
langDict[info["user"]["lang"]] += 1
else:
langDict[info["user"]["lang"]] = 1
return {'genderDict': genderDict,
'langDict' : langDict}
def main():
filePath = '/Users/qiu/Downloads/Bomoda/weibo'
fileList = get_fileList(filePath)
result = calc_total_counts(fileList)
print result['genderDict']
print result['langDict']
if __name__ == '__main__':
main()
<file_sep>/Top10CommonTerms.py
import json
import os, os.path
from collections import OrderedDict
import jieba
import jieba.analyse
import re
def get_fileList(fPath):
fList = []
for root, _, files in os.walk(fPath):
for f in files:
if not f.startswith('.'):
fList += [os.path.join(root, f)]
return fList
def gether_all_terms(fList, brand_name):
CommentTermDict = {}
for fileName in fList:
with open(fileName, 'r') as f:
read_data = f.read()
info = json.loads(read_data)
# count posts containing variation of brand name, such as "<NAME>" or "<NAME>"
if brand_name.lower() in info["text"].lower():
seg_list = jieba.analyse.extract_tags(" ".join(re.findall(ur'[\u4e00-\u9fff]+',info["text"])))
for tk in seg_list:
if tk in CommentTermDict:
CommentTermDict[tk] += 1
else:
CommentTermDict[tk] = 1
return CommentTermDict
def main():
filePath = '/Users/qiu/Downloads/Bomoda/weibo'
fileList = get_fileList(filePath)
brands = ['<NAME>', '<NAME>']
for i in xrange(2):
brand_result = gether_all_terms(fileList, brands[i])
sorted_result = OrderedDict(sorted(brand_result.items(), key=lambda x: x[1], reverse = True)).keys()[:10]
# print sorted_result
print "The top 10 mentioned Chinese terms associated with \"", brands[i], "\":", " ".join(sorted_result)
if __name__ == '__main__':
main()
| 005364261c2505dfc36edaf2af5616c55d13c0f6 | [
"Markdown",
"Python"
] | 4 | Python | tjphoton/WeiboPostBrandNames | 76972ff4e36620b53402c85e112562a06f456e2d | 2779791eb9f6a64f3a18f267172fdb83ddfde4ee |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityOSC;
using System.Text;
using System.Threading.Tasks;
public class Client : MonoBehaviour
{
#region Network Settings //----------追記
public string ip;
public int port;
#endregion //----------追記
string address;
string id = "Audio";
void Awake() {
IpGetter ipGetter = new IpGetter();
string myIP = ipGetter.GetIp();
ip = "192.168.1.21";
port = 8000;
Debug.Log("client IP : " + ip + " port : " + port);
OSCHandler.Instance.clientInit(id, ip,port);//ipには接続先のipアドレスの文字列を入れる。
}
void Start()
{
address = "/VP2";
}
// Update is called once per frame
void SendStart(int boise){
List<float> sendAudioList = new List<float>();
sendAudioList.Add(1);
sendAudioList.Add(boise);
OSCHandler.Instance.SendMessageToClient(id, address, sendAudioList);
}
void SendStop(){
List<float> sendAudioList = new List<float>();
sendAudioList.Add(0);
OSCHandler.Instance.SendMessageToClient(id, address, sendAudioList);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class headangle : MonoBehaviour
{
public GameObject ovrCam; //自分の頭(OVRCameraRig->trackingSpace->CenterEyeAnchor)
public Text text; //頭部の角度表示用テキスト
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float headangle = ovrCam.transform.localEulerAngles.y;
text.text = "Head Angle: " + headangle;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class beat : MonoBehaviour
{
public Text beatText;
bool state = false;
public void OnButtonClick(){
state = !state;
if(state){
this.beatText.text = "Beat ON";
} else {
this.beatText.text = "Beat OFF";
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class viewHacking : MonoBehaviour
{
OVRPassthroughLayer passthroughLayer;
private float alpha = 0.0f;
private float brightness = 0.0f;
public Text text;
public Text edgerenderText;
bool edgeRendering = false;
bool changing = false;
float time = 0.0f;
void Start()
{
GameObject ovrCameraRig = GameObject.Find("OVRCameraRig");
if (ovrCameraRig == null)
{
Debug.LogError("Scene does not contain an OVRCameraRig");
return;
}
passthroughLayer = ovrCameraRig.GetComponent<OVRPassthroughLayer>();
if (passthroughLayer == null)
{
Debug.LogError("OVRCameraRig does not contain an OVRPassthroughLayer component");
}
passthroughLayer.SetColorMapControls(0.7f, 0.0f, 0.0f, makeGradient(Color.black,Color.white));
}
void Update()
{
if(edgeRendering){
passthroughLayer.edgeRenderingEnabled = true;
edgerenderText.text = "EdgeRender: ON";
} else {
passthroughLayer.edgeRenderingEnabled = false;
edgerenderText.text = "EdgeRender: OFF";
}
time += Time.deltaTime;
float T = 60.0f;
float f = 1.0f / T;
if(changing){
if(time < 30.0f){
Color a = Color.black;
//Color a = Color.Lerp(Color.black, Color.green, time/30.0f);
Color b = Color.Lerp(Color.white, Color.blue, time/30.0f);
passthroughLayer.SetColorMapControls(0.7f, 0.3f, 0.0f, makeGradient(a,b));
//Color a = Color.Lerp(Color.black, Color.black, time/60.0f);
//Color b = Color.Lerp(Color.white, Color.white, time/60.0f);
//passthroughLayer.SetColorMapControls(1.0f, 0.0f, 0.0f);
//passthroughLayer.edgeRenderingEnabled = true;
//Color col = new Color(0, 1, 0, 1);
//passthroughLayer.edgeColor = col;
//alpha = Mathf.Abs(Mathf.Sin(2 * Mathf.PI * f * Time.time) * 0.3f);
} else{
Color a = Color.black;
//Color a = Color.Lerp(Color.black, Color.green, 1.0f);
Color b = Color.Lerp(Color.white, Color.blue, 1.0f);
//passthroughLayer.SetColorMapControls(1.0f, 0.0f, 0.0f);
//passthroughLayer.edgeRenderingEnabled = true;
//Color col = new Color(0, 1, 0, 1);
//passthroughLayer.edgeColor = col;
passthroughLayer.SetColorMapControls(0.7f, 0.3f, 0.0f, makeGradient(a,b));
}
}
text.text = "Time: " + time;
//passthroughLayer.SetColorMap(col.r, col.g, col.b, col.a);
//passthroughLayer.colorMapEditorContrast = 1.0f;
//passthroughLayer.colorMapEditorBrightness = 0.0f;
//passthroughLayer.colorMapEditorPosterize = 0.0f;
}
public void OnButtonClick(){
//edgeRendering = !edgeRendering;
time = 0.0f;
changing = true;
}
private Gradient makeGradient(Color a, Color b){
Gradient gradient = new Gradient();
GradientColorKey[] colorKey;
GradientAlphaKey[] alphaKey;
// Populate the color keys at the relative time 0 and 1 (0 and 100%)
colorKey = new GradientColorKey[2];
colorKey[0].color = a;
colorKey[0].time = 0.0f;
colorKey[1].color = b;
colorKey[1].time = 1.0f;
// Populate the alpha keys at relative time 0 and 1 (0 and 100%)
alphaKey = new GradientAlphaKey[2];
alphaKey[0].alpha = 1.0f;
alphaKey[0].time = 0.0f;
alphaKey[1].alpha = 0.0f;
alphaKey[1].time = 1.0f;
gradient.SetKeys(colorKey, alphaKey);
return gradient;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IpGetter {
public string ip = "";
public string GetIp() {
try {
string host = System.Net.Dns.GetHostName();
System.Net.IPAddress[] addr_arr = System.Net.Dns.GetHostAddresses(host);
foreach (System.Net.IPAddress addr in addr_arr) {
string addr_str = addr.ToString();
if (addr_str.IndexOf(".") > 0 && !addr_str.StartsWith("127.")) {
ip = addr_str;
break;
}
}
}
catch {
ip = "";
}
return ip;
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class hunger : MonoBehaviour
{
public Text hungerText;
bool state = false;
public void OnButtonClick(){
state = !state;
if(state){
this.hungerText.text = "Hunger ON";
} else {
this.hungerText.text = "Hunger OFF";
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityOSC;
using System.Text;
using System.Threading.Tasks;
public class Server : MonoBehaviour {
// Start is called before the first frame update
#region Network Settings //----------追記
public string serverName;
public int inComingPort; //----------追記
#endregion //----------追記
private Dictionary<string, ServerLog> servers;
void Awake() {
serverName = "Audio";
inComingPort = 8000;
// Debug.Log("server IP : " + serverName + " port : " + inComingPort);
OSCHandler.Instance.serverInit(serverName,inComingPort); //init OSC //----------変更
servers = new Dictionary<string, ServerLog>();
}
// Update is called once per frame
void Update() {
OSCHandler.Instance.UpdateLogs();
servers = OSCHandler.Instance.Servers;
}
void LateUpdate(){
foreach( KeyValuePair<string, ServerLog> item in servers ){
if(item.Value.log.Count > 0){
int lastPacketIndex = item.Value.packets.Count - 1;
var address = item.Value.packets[lastPacketIndex].Address.ToString();
Debug.Log("get");
if(address.Contains("/VP2")){
float onFlag = (float)item.Value.packets[lastPacketIndex].Data[0];
if(onFlag != 0){
int type = (int)item.Value.packets[lastPacketIndex].Data[1];
switch(type){
case 1:
Debug.Log("1を再生");
break;
case 2:
Debug.Log("2を再生");
break;
case 3:
Debug.Log("3を再生");
break;
default:
Debug.Log("なんすかそれ");
break;
}
}
else{
Debug.Log("音を止める");
// 音止める
}
}
}
}
// Debug.Log(Time.deltaTime);
}
} | 77d0d20a8f79060ba6273f191cad65057220be20 | [
"C#"
] | 7 | C# | hama1185/UnityHMDCreature | 8312e430964301adafc812fc4a522d6b94310822 | b96d1f5e577e60699e6e20ec8bbc34e0950bfea1 |
refs/heads/master | <file_sep>package carbon.animation
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.animation.ValueAnimator.AnimatorUpdateListener
import android.content.res.ColorStateList
import android.os.Parcel
import android.os.Parcelable
import android.util.StateSet
import android.view.animation.AccelerateDecelerateInterpolator
import carbon.internal.ArgbEvaluator
import java.lang.reflect.Field
import java.util.*
class AnimatedColorStateList(private val states: Array<IntArray>, colors: IntArray?, listener: AnimatorUpdateListener?) : ColorStateList(states, colors) {
private var currentState = IntArray(0)
private val colorAnimation: ValueAnimator
private var animatedColor = 0
companion object {
private var mStateSpecsField: Field? = null
private var mColorsField: Field? = null
private var mDefaultColorField: Field? = null
@JvmStatic
fun fromList(list: ColorStateList?, listener: AnimatorUpdateListener?): AnimatedColorStateList? {
val mStateSpecs: Array<IntArray> // must be parallel to mColors
val mColors: IntArray // must be parallel to mStateSpecs
val mDefaultColor: Int
try {
mStateSpecs = mStateSpecsField!![list] as Array<IntArray>
mColors = mColorsField!![list] as IntArray
mDefaultColor = mDefaultColorField!![list] as Int
val animatedColorStateList = AnimatedColorStateList(mStateSpecs, mColors, listener)
mDefaultColorField!![animatedColorStateList] = mDefaultColor
return animatedColorStateList
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
return null
}
val CREATOR: Parcelable.Creator<AnimatedColorStateList?> = object : Parcelable.Creator<AnimatedColorStateList?> {
override fun newArray(size: Int): Array<AnimatedColorStateList?> {
return arrayOfNulls(size)
}
override fun createFromParcel(source: Parcel): AnimatedColorStateList? {
val N = source.readInt()
val stateSpecs = arrayOfNulls<IntArray>(N)
for (i in 0 until N) {
stateSpecs[i] = source.createIntArray()
}
val colors = source.createIntArray()
return fromList(ColorStateList(stateSpecs, colors), null)
}
}
init {
try {
mStateSpecsField = ColorStateList::class.java.getDeclaredField("mStateSpecs")
mStateSpecsField!!.isAccessible = true
mColorsField = ColorStateList::class.java.getDeclaredField("mColors")
mColorsField!!.isAccessible = true
mDefaultColorField = ColorStateList::class.java.getDeclaredField("mDefaultColor")
mDefaultColorField!!.isAccessible = true
} catch (e: NoSuchFieldException) {
e.printStackTrace()
}
}
}
override fun getColorForState(stateSet: IntArray?, defaultColor: Int): Int {
synchronized(this@AnimatedColorStateList) {
if (Arrays.equals(stateSet, currentState) && colorAnimation.isRunning) {
return animatedColor
}
}
return super.getColorForState(stateSet, defaultColor)
}
fun setState(newState: IntArray) {
synchronized(this@AnimatedColorStateList) {
if (Arrays.equals(newState, currentState)) return
colorAnimation.end()
if (currentState.size != 0) {
for (state in states) {
if (StateSet.stateSetMatches(state, newState)) {
val firstColor = getColorForState(currentState, defaultColor)
val secondColor = super.getColorForState(newState, defaultColor)
colorAnimation.setIntValues(firstColor, secondColor)
currentState = newState
animatedColor = firstColor
colorAnimation.start()
return
}
}
}
currentState = newState
}
}
fun jumpToCurrentState() {
colorAnimation.end()
}
init {
colorAnimation = ValueAnimator.ofInt(0, 0)
colorAnimation.setEvaluator(ArgbEvaluator())
colorAnimation.duration = 200
colorAnimation.interpolator = AccelerateDecelerateInterpolator()
colorAnimation.addUpdateListener { animation: ValueAnimator ->
synchronized(this@AnimatedColorStateList) {
animatedColor = animation.animatedValue as Int
listener!!.onAnimationUpdate(animation)
}
}
colorAnimation.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
animatedColor = colorAnimation.animatedValue as Int
listener!!.onAnimationUpdate(colorAnimation)
}
})
}
} | 8213ecb1dac23bf09f6765fcabe3159b6bc582c3 | [
"Kotlin"
] | 1 | Kotlin | sarvex/Carbon | 95a94bacdbad092e6a49b3e0aee09c7eaf04cdb7 | 1e1492edd737ccae43418020ebef56bc3c11f3bd |
refs/heads/main | <repo_name>mahardikakdenie/NESTJS_CRUD<file_sep>/src/donation/donation.service.ts
/* eslint-disable prettier/prettier */
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateDonationDto } from './donation.dto';
import { Donation } from './donation.entity';
@Injectable()
export class DonationService {
constructor(
@InjectRepository(Donation)
private readonly donationRepository: Repository<Donation>,
) {}
findAll() {
return this.donationRepository.find({
relations: ['author'],
});
}
create(data: CreateDonationDto) {
const donation = new Donation();
donation.Nominal = data.Nominal;
donation.author = data.authorId;
return this.donationRepository.save(donation);
}
findByid(id: any) {
const qb = this.donationRepository
.createQueryBuilder('Donation')
.leftJoinAndSelect('Donation.author', 'author')
.where('Donation.id = :id', { id: id.id });
return qb.getOne();
}
update(data: CreateDonationDto, id: number) {
return this.donationRepository.update(id, { ...data });
}
delete(id: any) {
const qb = this.donationRepository
.createQueryBuilder('Donation')
.softDelete()
.where('Donation.id = :id', { id: id.id });
return qb.execute();
}
}
<file_sep>/src/userv2/user.dto.ts
/* eslint-disable prettier/prettier */
import { IsNotEmpty } from 'class-validator';
export class UserDto {
@IsNotEmpty()
username: string;
@IsNotEmpty()
password: string;
}
export class UserRO {
id: string;
usermame: string;
created_at: Date;
token: string;
}
<file_sep>/src/userv2/userv2.module.ts
/* eslint-disable prettier/prettier */
import { Module } from '@nestjs/common';
import { Userv2Controller } from './userv2.controller';
import { Service } from './.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserEntity } from './user.entity';
@Module({
controllers: [Userv2Controller],
imports: [TypeOrmModule.forFeature([UserEntity])],
providers: [Service],
})
export class Userv2Module {}
<file_sep>/src/donation/donation.dto.ts
/* eslint-disable prettier/prettier */
export class CreateDonationDto {
Nominal: number;
authorId: number;
}
<file_sep>/src/book/book.service.ts
/* eslint-disable prettier/prettier */
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Book } from './book.entity';
import { CreateBookDto } from './create-book-dto';
// import { Op } from 'sequelize';
@Injectable()
export class BookService {
constructor(
@InjectRepository(Book) private readonly bookRepository: Repository<Book>,
) {
useSoftDelete: true;
}
findById(id: number) {
return this.bookRepository.findOneOrFail(id);
}
findAll() {
return this.bookRepository.find({
relations: ['author'],
});
}
create(data: CreateBookDto) {
const book = new Book();
book.title = data.title;
book.publisher_name = data.publisher_name;
book.isActive = false;
book.author = data.authorId;
return this.bookRepository.save(book);
}
update(data: CreateBookDto, id: number) {
return this.bookRepository.update(id, { ...data });
}
delete(id: number) {
return this.bookRepository.softDelete(id);
}
}
<file_sep>/src/auth/auth.service.ts
/* eslint-disable prettier/prettier */
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateAuthDto } from './auth.dto';
import { Auth } from './auth.entity';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { Response } from 'express';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(Auth) private readonly authRepository: Repository<Auth>,
private jwtService: JwtService,
) {}
async register(data: CreateAuthDto) {
const auth = new Auth();
auth.name = data.name;
auth.email = data.email;
const saltOrRounds = 12;
const hashPassword = await bcrypt.hash(data.password, saltOrRounds);
data.password = <PASSWORD>;
auth.password = <PASSWORD>;
console.log(auth.password);
return this.authRepository.save(data);
}
async findOne(email: any, password: any, response: Response) {
const auth = this.authRepository
.createQueryBuilder('Auth')
.where('Auth.email = :email', { email: email.email })
.getOne();
const hash = await bcrypt.compare(password.password, (await auth).password);
console.log((await auth).password);
console.log(hash);
console.log(password.password);
if (!auth) {
throw new BadRequestException('Invalid');
}
if (!hash) {
throw new BadRequestException('Invalid');
}
console.log(bcrypt.compare(password.password, (await auth).password));
const jwt = await this.jwtService.signAsync({ id: (await auth).id });
response.cookie('jwt', jwt, { httpOnly: true });
return jwt;
}
findUser(data: any) {
return this.authRepository.findOne(data);
}
}
<file_sep>/src/author/author.service.ts
/* eslint-disable prettier/prettier */
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateAuthorDto } from './author.dto';
import { Author } from './author.entity';
@Injectable()
export class AuthorService {
constructor(
@InjectRepository(Author)
private readonly authorRepository: Repository<Author>,
) {
useSoftDelete: true;
}
async findAll(q: any, sort: any) {
const qb = await this.authorRepository
.createQueryBuilder('Author')
.leftJoinAndSelect('Author.books', 'books')
.leftJoinAndSelect('Author.donations', 'donations');
if (q.q) {
qb.where('Author.fullName = :fullName', {
fullName: q.q,
});
}
if (sort.sort === '-id') {
qb.orderBy('Author.id', 'DESC');
}
return qb.getMany();
}
create(data: CreateAuthorDto) {
const author = new Author();
author.fullName = data.fullName;
author.home_Address = data.home_adress;
author.isActive = false;
return this.authorRepository.save(author);
}
findById(id: any) {
const qb = this.authorRepository
.createQueryBuilder('Author')
.leftJoinAndSelect('Author.books', 'books')
.leftJoinAndSelect('Author.donations', 'donations')
.where('Author.id = :id', { id: id.id });
return qb.getOne();
}
delete(id: any) {
const qb = this.authorRepository
.createQueryBuilder('Author')
.softDelete()
.where('Author.id = :id', { id: id.id });
return qb.execute();
}
update(data: CreateAuthorDto, id: number) {
return this.authorRepository.update(id, { ...data });
}
}
<file_sep>/src/donation/donation.entity.ts
/* eslint-disable prettier/prettier */
import {
Column,
CreateDateColumn,
DeleteDateColumn,
Entity,
ManyToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { Author } from '../author/author.entity';
@Entity()
export class Donation {
@PrimaryGeneratedColumn()
id: number;
@Column()
Nominal: number;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@DeleteDateColumn()
deleted_at: Date;
@ManyToOne(() => Author, (author) => author.donations)
author: number;
}
<file_sep>/src/user/user.entity.ts
/* eslint-disable prettier/prettier */
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
fistName: string;
@Column()
lastName: string;
@Column({ default: false })
isActive: boolean;
}
<file_sep>/src/userv2/user.entity.ts
/* eslint-disable prettier/prettier */
import {
BeforeInsert,
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
} from 'typeorm';
import * as bcrypt from 'bcrypt';
import * as jwt from 'jsonwebtoken';
import { UserRO } from './user.dto';
@Entity('userv2')
export class UserEntity {
@PrimaryGeneratedColumn()
id: number;
@CreateDateColumn()
created_at: Date;
@Column({
type: 'text',
unique: true,
})
username: string;
@Column('text')
password: string;
@BeforeInsert()
async hashPassword() {
this.password = await bcrypt.hash(this.password, 10);
}
toResponseObject(showToken: boolean): UserRO {
const { id, created_at, username, token } = this;
const responseObject: any = {
id,
created_at,
username,
token,
};
if (showToken) {
responseObject.token = token;
}
return responseObject;
}
async comparePassword(attemp: string) {
return await bcrypt.compare(attemp, this.password);
}
private get token() {
const { id, username } = this;
return jwt.sign(
{
id,
username,
},
process.env.SECRET,
{ expiresIn: '7d' },
);
}
}
<file_sep>/src/auth/auth.controller.ts
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable prettier/prettier */
import {
BadRequestException,
Body,
Controller,
Get,
Post,
Res,
Req,
UnauthorizedException,
} from '@nestjs/common';
import { CreateAuthDto } from './auth.dto';
import { AuthService } from './auth.service';
import * as bcrypt from 'bcrypt';
import { Response, Request } from 'express';
import { JwtService } from '@nestjs/jwt';
@Controller('api')
export class AuthController {
constructor(
private readonly AuthService: AuthService,
private jwtService: JwtService,
) {}
@Post('register')
async register(@Body() data: CreateAuthDto) {
const user = this.AuthService.register(data);
delete (await user).password;
return user;
}
@Post('login')
async login(
@Body() email: string,
@Body() password: string,
@Res({ passthrough: true }) response: Response,
) {
return this.AuthService.findOne(email, password, response);
}
@Get('user')
async User(@Req() request: Request) {
try {
const cookie = request.cookies['jwt'];
const data = await this.jwtService.verifyAsync(cookie);
if (!data) {
throw new UnauthorizedException();
}
const user = await this.AuthService.findUser({ id: data['id'] });
const { password, ...result } = user;
return {
meta: {
status: true,
message: 'Success',
},
data: result,
};
} catch (err) {
throw new UnauthorizedException();
}
}
@Post('logout')
async logout(@Res({ passthrough: true }) response: Response) {
response.clearCookie('jwt');
return {
message: 'Success',
};
}
}
<file_sep>/src/author/author.entity.ts
/* eslint-disable prettier/prettier */
import { Book } from 'src/book/book.entity';
import {
Entity,
Column,
PrimaryGeneratedColumn,
OneToMany,
CreateDateColumn,
UpdateDateColumn,
DeleteDateColumn,
} from 'typeorm';
import { Donation } from '../donation/donation.entity';
@Entity()
export class Author {
@PrimaryGeneratedColumn()
id: number;
@Column()
fullName: string;
@Column()
home_Address: string;
@Column({ default: true })
isActive: boolean;
@CreateDateColumn()
creted_at: Date;
@UpdateDateColumn()
update_at: Date;
@DeleteDateColumn()
delete_at: Date;
@OneToMany(() => Donation, (donation) => donation.author)
donations: Donation[];
@OneToMany(() => Book, (book) => book.author)
books: Book[];
}
<file_sep>/src/app.module.ts
/* eslint-disable prettier/prettier */
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthController } from './auth/auth.controller';
import { Auth } from './auth/auth.entity';
import { AuthService } from './auth/auth.service';
import { AuthorController } from './author/author.controller';
import { Author } from './author/author.entity';
import { AuthorService } from './author/author.service';
import { BookController } from './book/book.controller';
import { Book } from './book/book.entity';
import { BookService } from './book/book.service';
import { DonationController } from './donation/donation.controller';
import { Donation } from './donation/donation.entity';
import { DonationService } from './donation/donation.service';
import { DatabaseConnectionService } from './shared/service/database.connection';
import { UserController } from './user/user.controller';
import { User } from './user/user.entity';
import { UserService } from './user/user.service';
import { Userv2Module } from './userv2/userv2.module';
@Module({
imports: [
TypeOrmModule.forRootAsync({
useClass: DatabaseConnectionService,
}),
TypeOrmModule.forFeature([User, Book, Author, Donation, Auth]),
JwtModule.register({
secret: 'secret',
signOptions: { expiresIn: '1d' },
}),
Userv2Module,
],
controllers: [
UserController,
BookController,
DonationController,
AuthorController,
AuthController,
],
providers: [
UserService,
BookService,
AuthorService,
DonationService,
AuthService,
],
})
export class AppModule {}
<file_sep>/src/author/author.controller.ts
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable prettier/prettier */
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Query,
UseGuards,
UnauthorizedException,
Req,
} from '@nestjs/common';
import { AuthGuard } from 'src/auth/auth.guard';
import { CreateAuthorDto } from './author.dto';
import { AuthorService } from './author.service';
import { JwtService } from '@nestjs/jwt';
// import { Response, Request } from 'express';
@Controller('author')
@UseGuards(new AuthGuard())
export class AuthorController {
constructor(
private readonly AuthorService: AuthorService,
private jwtService: JwtService,
) {}
@Get()
async findAll(
@Query() q: string,
@Query() sort: string,
// @Req() request: Request,
) {
// const cookie = request.cookies['jwt'];
// const data = await this.jwtService.verifyAsync(cookie);
// if (!data) {
// throw new UnauthorizedException();
// }
return {
meta: {
status: true,
message: 'Success',
},
data: await this.AuthorService.findAll(q, sort),
};
}
@Get(':id')
async findById(@Param() id: number) {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.AuthorService.findById(id),
};
}
@Post()
async create(@Body() data: CreateAuthorDto) {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.AuthorService.create(data),
};
}
@Patch(':id/edit')
async update(@Body() data: CreateAuthorDto, @Param() id: number) {
return {
meta: {
status: true,
message: 'Succes',
},
data: await this.AuthorService.update(data, id),
};
}
@Delete(':id/delete')
async delete(@Param() id: number) {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.AuthorService.delete(id),
};
}
}
<file_sep>/src/userv2/userv2.controller.ts
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
import { Service } from './.service';
import { UserDto } from './user.dto';
import { AuthGuard } from '../auth/auth.guard';
@Controller('api/userv2')
export class Userv2Controller {
constructor(private readonly userService: Service) {}
@Get()
@UseGuards(new AuthGuard())
showAllUsers() {
return this.userService.findAll();
}
@Post('/login')
login(@Body() data: UserDto) {
return this.userService.login(data);
}
@Post('/register')
register(@Body() data: UserDto) {
return this.userService.register(data);
}
}
<file_sep>/src/auth/auth.dto.ts
/* eslint-disable prettier/prettier */
export class CreateAuthDto {
name: string;
email: string;
password: string;
}
<file_sep>/src/user/user.controller.ts
/* eslint-disable prettier/prettier */
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
UseFilters,
UseGuards,
} from '@nestjs/common';
import { CreateUserDto } from './create-user.dto';
import { AuthGuard } from '../auth/auth.guard';
import { EntityNotFoundExceptionFilter } from './entity-not-found-exception-filter';
import { UserService } from './user.service';
@Controller('user/mahasiswa')
@UseGuards(new AuthGuard())
@UseFilters(new EntityNotFoundExceptionFilter())
export class UserController {
constructor(private readonly userService: UserService) {}
@Get()
async findAll() {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.userService.findAll(),
};
}
@Get(':id')
async findOne(@Param('id') id: number) {
return {
meta: {
status: true,
message: 'Succes',
},
data: await this.userService.findOne(id),
};
}
@Post('create')
async create(@Body() data: CreateUserDto) {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.userService.create(data),
};
}
@Put(':id/edit')
async update(@Body() data: CreateUserDto, @Param('id') id: number) {
return {
data: await this.userService.update(data, id),
};
}
@Delete(':id')
async delete(@Param('id') id: number) {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.userService.delete(id),
};
}
}
<file_sep>/src/book/create-book-dto.ts
/* eslint-disable prettier/prettier */
export class CreateBookDto {
title: string;
publisher_name: string;
isActive: boolean;
authorId: number;
}
<file_sep>/src/book/book.entity.ts
/* eslint-disable prettier/prettier */
import {
Column,
Entity,
ManyToOne,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
DeleteDateColumn,
} from 'typeorm';
import { Author } from '../author/author.entity';
@Entity()
export class Book {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column()
publisher_name: string;
@Column({ default: false })
isActive: boolean;
@CreateDateColumn()
creted_at: Date;
@UpdateDateColumn()
update_at: Date;
@DeleteDateColumn()
delete_at: Date;
@ManyToOne(() => Author, (author) => author.books)
author: number;
}
<file_sep>/src/author/author.dto.ts
/* eslint-disable prettier/prettier */
export class CreateAuthorDto {
fullName: string;
home_adress: string;
isActive: boolean;
}
<file_sep>/src/donation/donation.controller.ts
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable prettier/prettier */
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import { CreateDonationDto } from './donation.dto';
import { AuthGuard } from '../auth/auth.guard';
import { DonationService } from './donation.service';
@Controller('donation')
@UseGuards(new AuthGuard())
export class DonationController {
constructor(private readonly DonationService: DonationService) {
useSoftDelete: true;
}
@Get()
async findAll() {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.DonationService.findAll(),
};
}
@Get(':id')
async findById(@Param() id: number) {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.DonationService.findByid(id),
};
}
@Post()
async create(@Body() data: CreateDonationDto) {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.DonationService.create(data),
};
}
@Patch(':id/edit')
async update(@Body() data: CreateDonationDto, @Param() id: number) {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.DonationService.update(data, id),
};
}
@Delete(':id/delete')
async DataDestroy(@Param() id: number) {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.DonationService.delete(id),
};
}
}
<file_sep>/src/book/book.controller.ts
/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable prettier/prettier */
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
UseFilters,
UseGuards,
} from '@nestjs/common';
import { EntityNotFoundExceptionFilter } from './entity-not-found-exception-filter';
import { BookService } from './book.service';
import { AuthGuard } from '../auth/auth.guard';
import { CreateBookDto } from './create-book-dto';
@Controller('books')
@UseGuards(new AuthGuard())
@UseFilters(new EntityNotFoundExceptionFilter())
export class BookController {
constructor(private readonly BookService: BookService) {}
@Get()
async findAll() {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.BookService.findAll(),
};
}
@Get(':id')
async findOne(@Param('id') id: number) {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.BookService.findById(id),
};
}
@Post()
async create(@Body() data: CreateBookDto) {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.BookService.create(data),
};
}
@Patch(':id/edit')
async update(@Body() data: CreateBookDto, @Param() id: number) {
return {
meta: {
status: true,
message: 'Succes',
},
data: await this.BookService.update(data, id),
};
}
@Delete(':id/delete')
async delete(@Param() id: number) {
return {
meta: {
status: true,
message: 'Success',
},
data: await this.BookService.delete(id),
};
}
}
| 5cc0a96ed7614ac84ca4cd0b67cc679b941e4b68 | [
"TypeScript"
] | 22 | TypeScript | mahardikakdenie/NESTJS_CRUD | a3673c9ee75ad46b9c38c641d0396d0006d94d6e | 83347219e4944d4c9b19d086ebab238e0b9ee58d |
refs/heads/master | <file_sep>
const Test = require('tape');
const Enjoi = require('../index');
const Joi = require('@hapi/joi');
Test('enjoi', function (t) {
t.test('valid', function (t) {
t.plan(9);
const schema = Enjoi.schema({
'title': 'Example Schema',
'description': 'An example to test against.',
'type': 'object',
'properties': {
'firstName': {
'type': 'string',
'minLength': 0
},
'lastName': {
'type': 'string',
'minLength': 1
},
'tags': {
'type': 'array',
'items': {
'type': 'string',
'minLength': 1
}
},
'age': {
'type': 'integer',
'minimum': 0
}
},
'required': ['firstName', 'lastName']
});
t.equal(schema._type, 'object', 'defined object.');
t.equal(schema._flags.label, 'Example Schema');
t.equal(schema._description, 'An example to test against.', 'description set.');
t.equal(schema._inner.children.length, 4, '4 properties defined.');
Joi.validate({ firstName: 'John', lastName: 'Doe', age: 45, tags: ['man', 'human'] }, schema, function (error, value) {
t.ok(!error, 'no error.');
});
Joi.validate({ firstName: '', lastName: 'Doe', age: 45, tags: ['man', 'human'] }, schema, function (error, value) {
t.ok(!error, 'no error.');
});
Joi.validate({ firstName: 'John', age: 45, tags: ['man', 'human'] }, schema, function (error, value) {
t.ok(error, 'error.');
});
Joi.validate({ firstName: 'John', lastName: 'Doe', age: 45, tags: [1, 'human'] }, schema, function (error, value) {
t.ok(error, 'error.');
});
Joi.validate({ firstName: 'John', lastName: 'Doe', age: 45, tags: ['', 'human'] }, schema, function (error, value) {
t.ok(error, 'error.');
});
});
t.test('with ref', function (t) {
t.plan(1);
const schema = Enjoi.schema({
'title': 'Example Schema',
'type': 'object',
'properties': {
'name': {
'$ref': '#/definitions/name'
}
},
'definitions': {
'name': {
'type': 'string'
}
}
});
Joi.validate({ name: 'Joe' }, schema, function (error, value) {
t.ok(!error, 'no error.');
});
});
});
Test('enjoi defaults', function (t) {
t.test('defaults', function (t) {
t.plan(1);
const enjoi = Enjoi.defaults({
types: {
test: Joi.string()
}
});
const schema = enjoi.schema({
type: 'test'
});
Joi.validate('string', schema, function (error) {
t.ok(!error, 'no error.');
});
});
t.test('overrides', function (t) {
t.plan(1);
const enjoi = Enjoi.defaults({
types: {
test: Joi.string()
}
});
const schema = enjoi.schema({
type: 'test'
}, {
types: {
test: Joi.number()
}
});
Joi.validate('string', schema, function (error) {
t.ok(error, 'error.');
});
});
t.test('overrides extensions', function (t) {
t.plan(2);
const enjoi = Enjoi.defaults({
extensions: [
{
name: 'string',
language: {
foo: 'needs to be \'foobar\''
},
rules: [{
name: 'foo',
validate(params, value, state, options) {
return value === 'foobar' || this.createError('string.foo', null, state, options);
}
}]
}
],
types: {
foo() {
return this.string().foo();
}
}
});
const schema = enjoi.schema({
type: 'baz'
}, {
extensions: [
{
name: 'string',
language: {
baz: 'needs to be \'foobaz\''
},
rules: [{
name: 'baz',
validate(params, value, state, options) {
return value === 'foobaz' || this.createError('string.baz', null, state, options);
}
}]
}
],
types: {
baz() {
return this.string().baz();
}
}
});
Joi.validate('foobar', enjoi.schema({ type: 'foo' }), function (error) {
t.ok(!error, 'no error.');
});
Joi.validate('foobaz', schema, function (error) {
t.ok(!error, 'no error.');
});
});
});
<file_sep>
const Test = require('tape');
const Enjoi = require('../index');
const Joi = require('@hapi/joi');
Test('options features', function (t) {
t.test('refineType', function (t) {
t.plan(2);
const schema = Enjoi.schema({
type: 'string',
format: 'binary'
}, {
refineType(type, format) {
switch (type) {
case 'string': {
if (format === 'binary') {
return 'binary'
}
}
default:
return type;
}
},
types: {
binary: Joi.binary().encoding('base64')
}
});
Joi.validate('aGVsbG8=', schema, function (error, value) {
t.ok(!error, 'no error.');
t.equal(value.toString(), 'hello');
});
});
t.test('custom type', function (t) {
t.plan(2);
const schema = Enjoi.schema({
type: 'custom'
}, {
types: {
custom: Joi.string()
}
});
Joi.validate('string', schema, function (error, value) {
t.ok(!error, 'no error.');
});
Joi.validate(10, schema, function (error, value) {
t.ok(error, 'error.');
});
});
t.test('type function', function (t) {
t.plan(1);
const schema = Enjoi.schema({
type: 'test',
'x-value': 'example'
}, {
types: {
test(schema) {
return this.string().allow(schema['x-value']);
}
}
});
Joi.validate('example', schema, function (error, value) {
t.ok(!error, 'no error.');
});
});
t.test('custom complex type', function (t) {
t.plan(2);
const schema = Enjoi.schema({
type: 'file'
}, {
types: {
file: Enjoi.schema({
type: 'object',
properties: {
file: {
type: 'string'
},
consumes: {
type: 'string',
pattern: /multipart\/form-data/
}
}
})
}
});
schema.validate({ file: 'data', consumes: 'multipart/form-data' }, function (error, value) {
t.ok(!error, 'no error.');
});
schema.validate({ file: 'data', consumes: 'application/json' }, function (error, value) {
t.ok(error, 'error.');
});
});
t.test('with external ref', function (t) {
t.plan(1);
const schema = Enjoi.schema({
'title': 'Example Schema',
'type': 'object',
'properties': {
'name': {
'$ref': 'definitions#/name'
}
}
}, {
subSchemas: {
'definitions': {
'name': {
'type': 'string'
}
}
}
});
Joi.validate({ name: 'Joe' }, schema, function (error, value) {
t.ok(!error, 'no error.');
});
});
t.test('with both inline and external refs', function (t) {
t.plan(1);
const schema = Enjoi.schema({
'title': 'Example Schema',
'type': 'object',
'properties': {
'firstname': {
'$ref': '#/definitions/firstname'
},
'surname': {
'$ref': 'definitions#/surname'
}
},
'definitions': {
'firstname': {
'type': 'string'
}
}
}, {
subSchemas: {
'definitions': {
'surname': {
'type': 'string'
}
}
}
});
Joi.validate({ firstname: 'Joe', surname: 'Doe' }, schema, function (error, value) {
t.ok(!error, 'no error.');
});
});
});
Test('extensions', function (t) {
t.plan(2);
const schema = Enjoi.schema({
'type': 'foo'
}, {
extensions: [
{
name: 'string',
language: {
foo: 'needs to be \'foobar\''
},
rules: [{
name: 'foo',
validate(params, value, state, options) {
return value === 'foobar' || this.createError('string.foo', null, state, options);
}
}]
}
],
types: {
foo() {
return this.string().foo();
}
}
});
Joi.validate('foobar', schema, function (error, value) {
t.ok(!error, 'no error.');
});
Joi.validate('foo', schema, function (error, value) {
t.ok(error, 'error.');
});
});
| 93ac596923f0b3e6167ec6a2f022868fb4d7d663 | [
"JavaScript"
] | 2 | JavaScript | dimichgh/enjoi | 743c21fa8fead11777510188473ba5d18e7b52f6 | 7016e1b2165f2f2ffc45d90586594c463fe2e47f |
refs/heads/master | <repo_name>winxp5421/unifi-backup-decrypt<file_sep>/decrypt.sh
#!/bin/bash
INPUT=$1
OUTPUT=${INPUT%.unf}.zip
openssl enc -d -in "${INPUT}" -out "${OUTPUT}.tmp" -aes-128-cbc -K 626379616e676b6d6c756f686d617273 -iv 75626e74656e74657270726973656170 -nosalt -nopad
yes | zip -FF "${OUTPUT}.tmp" --out "${OUTPUT}"
rm "${OUTPUT}.tmp"
<file_sep>/README.md
some code snippet
```
final Cipher instance = Cipher.getInstance("AES/CBC/NoPadding");
instance.init(2, new SecretKeySpec("bcyangkmluohmars".getBytes(), "AES"), new IvParameterSpec("ubntenterpriseap".getBytes()));
return new CipherInputStream(inputStream, instance);
```
malformed zip files requires fixing before unzip
| 1628bdf4f11629f98567381345e0dcdbededeca1 | [
"Markdown",
"Shell"
] | 2 | Shell | winxp5421/unifi-backup-decrypt | 05e40a8ad37c3d9bc2c75ebddb2aa24497efe78d | f37b4ced8c64469a3c6e256d100c54086510abef |
refs/heads/master | <file_sep>package com.example.mylibrary.weigets;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.example.mylibrary.R;
public class ClearableEditTextWithIcon extends AppCompatEditText implements TextWatcher, View.OnTouchListener,
View.OnFocusChangeListener {
private Drawable right;
// public ClearableEditTextWithIcon(Context context) {
// super(context);
// init();
// }
public ClearableEditTextWithIcon(Context context, AttributeSet attrs) {
super(context, attrs);
init(context,attrs);
}
public ClearableEditTextWithIcon(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context,attrs);
}
private void init(Context context,AttributeSet attrs){
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.custom_edittext);
right = typedArray.getDrawable(R.styleable.custom_edittext_icon);
if(right == null){
right = getResources().getDrawable(R.drawable.clean_icon);
}
addTextChangedListener(this);
setOnFocusChangeListener(this);
setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (event.getX() > getWidth() - getPaddingRight() - right.getIntrinsicWidth() && null != getCompoundDrawables()[2]) {
setText("");
}
}
return false;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 0 && hasFocus())
setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
else
setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[0], getCompoundDrawables()[1], null, getCompoundDrawables()[3]);
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus && getText().length() > 0){
setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
}else {
setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[0], getCompoundDrawables()[1], null, getCompoundDrawables()[3]);
}
}
}
<file_sep>自定义带删除图标的Edittext
引用:
implementation 'com.github.zcmgit:ClearableEditTextWithIcon:v1.1'
maven { url 'https://jitpack.io' }
<com.example.edittext.weigets.ClearableEditTextWithIcon
android:layout_width="match_parent"
android:layout_height="40dp"
app:icon="@mipmap/clean_icon"
android:layout_marginTop="20dp"/>
app:icon设置删除图标,默认为clean_icon
| d74290901aaa8aaa21c882f79af1efc940066b2a | [
"Markdown",
"Java"
] | 2 | Java | zcmgit/ClearableEditTextWithIcon | 64071c36b5835b0c8e465ac2cafad1bf597f07fd | 5835e35e8541f74daa7706a3bfee634cc7125939 |
refs/heads/master | <repo_name>bidutch/SnowflakeSnippets<file_sep>/SetEnv.sql
ALTER ACCOUNT SET TIMEZONE = 'Europe/Amsterdam';<file_sep>/ListAgg.md
# Listagg
Designed to compose a (comma separated) list of values that originate from rows in a query
/var/folders/lj/48nhg0lj3jv8824w17zl3lbw0000gn/T/TemporaryItems/(Document wordt bewaard door screencaptureui 5)/Schermafbeelding 2021-04-14 om 20.42.28.png
<file_sep>/Tasks.sql
-- create the table
CREATE OR REPLACE TABLE DEMO_DB.PUBLIC.CREDITS (
SLEUTEL NUMBER(19,0),
DATE DATE,
SERVICE_TYPE VARCHAR(25),
WAREHOUSE VARCHAR(16777216),
CREDITS_COMPUTE NUMBER(38,9),
CREDITS_CLOUD_SERVICES NUMBER(38,9),
CREDITS_TOTAL NUMBER(38,9)
);
-- compose the source query
SELECT
DATE(START_TIME) AS DATE
,SERVICE_TYPE
,NAME AS WAREHOUSE
,SUM(CREDITS_USED_COMPUTE) AS CREDITS_COMPUTE
,SUM(CREDITS_USED_CLOUD_SERVICES) AS CREDITS_CLOUD_SERVICES
,SUM(CREDITS_USED) AS CREDITS_TOTAL
FROM SNOWFLAKE.ACCOUNT_USAGE.METERING_HISTORY
GROUP BY DATE, SERVICE_TYPE, WAREHOUSE;
-- create the task:
CREATE OR REPLACE TASK DEMO_DB.PUBLIC.TASK_INSERT_METERING
WAREHOUSE = COMPUTE_WH
SCHEDULE = '20 MINUTE'
AS
INSERT INTO DEMO_DB.PUBLIC.Credits
("DATE"
, "SERVICE_TYPE"
, "WAREHOUSE"
, "CREDITS_COMPUTE"
, "CREDITS_CLOUD_SERVICES"
, "CREDITS_TOTAL"
)
SELECT
DATE(START_TIME) AS DATE
,SERVICE_TYPE
,NAME AS WAREHOUSE
,SUM(CREDITS_USED_COMPUTE) AS CREDITS_COMPUTE
,SUM(CREDITS_USED_CLOUD_SERVICES) AS CREDITS_CLOUD_SERVICES
,SUM(CREDITS_USED) AS CREDITS_TOTAL
FROM SNOWFLAKE.ACCOUNT_USAGE.METERING_HISTORY
GROUP BY DATE, SERVICE_TYPE, WAREHOUSE;
-- See what tasks we have in Snowflake
SHOW TASKS;
-- Resume the task
ALTER TASK DEMO_DB.PUBLIC.TASK_INSERT_METERING RESUME;
-- Get the DDL for a task
SELECT GET_DDL('TASK', 'TASK_INSERT_METERING');
-- See the task history
SELECT * FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY());
SELECT * FROM SNOWFLAKE.ACCOUNT_USAGE.TASK_HISTORY;
-- See suspended tasks using SHOW TASKS
SHOW TASKS;
SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())) WHERE "state" = 'suspended';
-- Create a task with 2 queries
CREATE OR REPLACE TASK DEMO_DB.PUBLIC.TASK_SHOW_SUSPENDED
WAREHOUSE = COMPUTE_WH
SCHEDULE = '20 MINUTE'
AS
SHOW TASKS;
SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())) WHERE "state" = 'suspended';
-- Resume this task
ALTER TASK TASK_SHOW_SUSPENDED RESUME;
-- Create a second task with the RESULT_SCAN
CREATE OR REPLACE TASK DEMO_DB.PUBLIC.TASK_RESULT_SCAN
WAREHOUSE = COMPUTE_WH
AFTER TASK_SHOW_SUSPENDED
AS
SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())) WHERE "state" = 'suspended';
-- Suspend a task
ALTER TASK TASK_SHOW_SUSPENDED SUSPEND;
-- Suspend a chain of tasks
ALTER TASK TASK_SHOW_SUSPENDED SUSPEND;
ALTER TASK TASK_RESULT_SCAN SUSPEND;
-- Resume the chain of tasks
ALTER TASK TASK_RESULT_SCAN RESUME;
ALTER TASK TASK_SHOW_SUSPENDED RESUME;<file_sep>/Listagg.sql
select listagg(column_name,',')
from demo_db.information_schema.columns
where table_name = 'xxx';
<file_sep>/GET_DDL.sql
use role public;
use database demo_db;
select get_ddl('schema', '"PUBLIC"', true); | a7fb10cf6ce92935e3a0db34a8645b239d031067 | [
"Markdown",
"SQL"
] | 5 | SQL | bidutch/SnowflakeSnippets | c24bb8aaeea3835d1a99a71b762cae24afae206b | 950b221f2382f40c6061978db9f719985e750d6a |
refs/heads/master | <file_sep>
class ConfigManager:
"""
Proxy class to allow implementations of . Applies ansbile playbooks
as formulas to a local machine.
"""
def __init__(self, cm_class, cfgs, logger):
self.name = 'ConfigManager'
self.cm = cm_class(cfgs, logger)
def apply(self, name, path, hosts):
# lookup and download formula
# then validate the gpg pubkey of the formula from remote
return self.cm.apply(name, path, hosts)
<file_sep>#!/usr/bin/env python
from distutils.core import setup
setup(name='formulas',
version='0.1',
description='Manage and apply Formulas',
author='<NAME>',
author_email='<EMAIL>',
url='http://github.com/herlo/formulas/',
packages=['fedulas', 'plugins'],
scripts=['scripts/formulas'],
)
<file_sep>#!/usr/bin/python
import os
import sys
import time
import shutil
import argparse
import subprocess
from fedulas.formulas import Formulas,FormulasError
debug = True
def main():
cp = argparse.ArgumentParser(
description=u"manage and apply Formulas",
add_help=False
)
cp.add_argument("-c", "--config", help="Path to configuration file",
default='/etc/formulas/formulas.conf:~/.formulas/formulas.conf')
(args, other) = cp.parse_known_args()
# print "args: {0}".format(args)
# print "other: {0}".format(other)
f = Formulas(args.config)
p = argparse.ArgumentParser(
# Inherit options from config_parser
parents=[cp],
# print script description with -h/--help
description=__doc__,
# Don't mess with format of description
formatter_class=argparse.RawDescriptionHelpFormatter,
)
sp = p.add_subparsers()
p_apply = sp.add_parser("apply", help=u"apply a Formula")
p_apply.add_argument("-p", "--path", help="Override default path to formulas")
p_apply.add_argument("-o", "--hosts", default=['localhost'], nargs='+', help="Host(s) to apply formula. Default: localhost")
p_apply.add_argument("name", help=u"Formula name")
p_apply.set_defaults(func=f.apply_formula)
args = p.parse_args()
if debug:
try:
args.func(args)
except Exception as e:
print e
sys.exit(1)
else:
try:
args.func(args)
except Exception as e:
print e
sys.exit(1)
if __name__ == "__main__":
raise SystemExit(main())
<file_sep>import os
import tempfile
from ansible import playbook, callbacks, utils
from fedulas.configmanager import ConfigManager
class AnsibleManager(ConfigManager):
"""
First ConfigManager proxy class. Applies ansbile playbooks
as formulas to a local machine.
"""
def __init__(self, cfgs, logger):
self.name = 'Ansible'
self.cfgs = cfgs
self.logger = logger
def _make_hosts_file(self, tmp_file, hosts=['localhost']):
for host in hosts:
tmp_file.write(host)
tmp_file.flush()
return tmp_file.name
def apply(self, name, path=None, hosts=['localhost']):
"""Apply an ansible playbook"""
pass
tmp_file = tempfile.NamedTemporaryFile(suffix=".tmp")
hosts_file = self._make_hosts_file(tmp_file, hosts)
transport = self.cfgs['formulas']['transport']
if not path:
path = os.path.expanduser(self.cfgs['formulas']['base_path'])
else:
path = os.path.expanduser(path)
if not os.path.exists(path):
os.makedirs(path, 0750)
playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
stats = callbacks.AggregateStats()
runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)
pb = playbook.PlayBook(playbook='{0}/{1}.yml'.format(path, name),
host_list=hosts_file, transport=transport,
callbacks=playbook_cb, runner_callbacks=runner_cb,
stats=stats)
pb.run()
tmp_file.close()
<file_sep># Main class for formulas
import os
import re
import sys
import rpm
import time
import glob
import stat
import shutil
import hashlib
import logging
import tempfile
import argparse
import subprocess
import ConfigParser
from fedulas.configmanager import ConfigManager
class FormulasError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
repr(self.value)
class Formulas:
"""
Support class for Formulas. Provides tooling for managing and applying
Formulas.
"""
def __init__(self, config_file=None):
"""Constructor for Formulas, will create self.cfgs and self.logger
"""
self.cfgs = {}
for path in config_file.split(':'):
expanded_path = "{0}".format(os.path.expanduser(path))
# print "expanded_path: {0}".format(expanded_path)
if os.path.exists(expanded_path):
self._load_config(expanded_path)
# print "self.cfgs: {0}".format(self.cfgs)
self.logger = logging.getLogger('formulas')
self.logger.setLevel(eval(self.cfgs['logger']['loglevel']))
# create file handler which logs even debug messages
fh = logging.FileHandler(self.cfgs['logger']['file'])
fh.setLevel(eval(self.cfgs['logger']['loglevel']))
# create formatter and add it to the handlers
formatter = logging.Formatter(self.cfgs['logger']['format'])
fh.setFormatter(formatter)
# add the handlers to the logger
self.logger.addHandler(fh)
self._load_plugin()
def _load_config(self, path):
"""Will create self.cfgs
:param str path: formulas.conf path
"""
config = ConfigParser.SafeConfigParser()
try:
f = open(path)
config.readfp(f)
f.close()
except ConfigParser.InterpolationSyntaxError as e:
raise FormulasError("Unable to parse configuration file properly: %s" % e)
for section in config.sections():
if not self.cfgs.has_key(section):
self.cfgs[section] = {}
for k, v in config.items(section):
self.cfgs[section][k] = v
def _load_plugin(self):
# print "self.cfgs: {0}".format(self.cfgs)
# config_manager object handles calls for chosen
cmModuleName = self.cfgs['cm']['module']
cmClassName = self.cfgs['cm']['class']
try:
cmModule = __import__('plugins.{0}'.format(cmModuleName),
globals(),
locals(),
[cmClassName])
#print "cmModule: {0}".format(cmModule)
self.config_manager = ConfigManager(cmModule.__dict__[cmClassName], self.cfgs, self.logger)
#print "self.config_manager: {0}".format(self.config_manager)
except ImportError, e:
self.logger.debug("Class %s in module %s not found: %s" % (cmClassName, 'plugins.{0}'.format(cmModuleName), e))
# print "Class {0} in module {1} not found: {2}".format(cmClassName, 'plugins.{0}'.format(cmModuleName), e)
raise FormulasError("Class %s in module %s not found: %s" % (cmClassName, 'plugins.{0}'.format(cmModuleName), e))
def apply_formula(self, args):
"""Apply the named Formula"""
name = args.name
path = None
host = 'localhost'
if args.hosts:
hosts = args.hosts
if args.path:
path=args.path
self.config_manager.apply(name, path, hosts)
pass
<file_sep>**This document is a draft**
Give Credit Where Credit is Due
===============================
The idea was formed around a concept to extend the ability to manage a
local system with configuration management tools. The
`initial idea <https://fedoraproject.org/wiki/Fedora_formulas>`_ was
put forth by `<NAME> <https://fedoraproject.org/wiki/User:Kevin>`_,
Infrastructure Lead at the `Fedora Project <http://fedoraproject.org>`_.
This document and repository is my take on how formulas can be implemented.
What are Formulas
=================
Formulas provide an better way to manage local configurations.
The primary CM tool supported is ansible, but it is possible to support
other CM tools.
A Formula is idempotent, meaning that it can be applied and each time
the resulting configuration is the same. The value of this is that one
or more machines can use the same Formula and expect the same setup.
Consider the following example as a simple Formula::
* Install the Apache Web Server (httpd)
* Add a configuration to create a virtual host
* Drop some basic web data, including configuration for a database
* Install Mysql (mysql-server)
* Start the httpd and mysql services
* Sync the database
It may be clear that some of the steps above can be done by a simple
yum install or adding a simple script to the %post section in a
kickstart. In some cases, however, interactive responses are required,
like the username/password of the database, for example. In these cases
it may be better to have an interactive prompt at first boot.
Additionally, Formulas could be played back after the initial interactive
configuration. Thus providing automation to the process. Answer the questions
once, apply the same rules in several other situations quickly and easily.
Managing Formulas
=================
Simply put, many Formulas will be written. It would seem logical that Formulas
should be shared, but with a control structure of some sort. Therefore, a model
has been put forth to manage 'approved' Formulas, by which a trust can be formed
between the infrastructure provider and those applying Formulas. Formulas will
exist in a git repository which is tightly managed for writes by gitolite. This
will provide a level of assurance that any Formula being applied from the
'approved' set can be applied reliably each time.
Additionally, it would make sense that a read-only form of these git repositories
would exist to provide an easy mechanism for sharing. Because the goal is to
encourage more 'approved' Formulas, as well as provide a means for testing,
expanding and even maintaining a separate set of Formulas, a git forking model
has been adopted.
With the exception of the 'approved' repositories being managed in some form
of review and approval process, likely similar to the Fedora RPM approval
model, git repositories can be forked and modified much like how
they are on github. The fork and pull request model works well because the
control remains with the upstream repository. In this case, it proves valuable
because when any Formula is improved upon, it can be merged back into the
upstream repository at the maintainer's convenience or not at all.
Applying Formulas
=================
Formulas can be applied to any Linux system as long as it is a supported
configuration management system. This currently means that it '''must'''
be ansible, but more are likely to come.
To apply a Formula, it must exist on the local system in an archive. A Formula
is applied as follows::
# formulas apply formula_one
Formulas can be downloaded from remote sources to the local system as part of the apply
command. Remote sources can be configured in the Formulas.conf. Multiple
sources can be searched in the order provided, thus allowing for searching
through 'approved' Formulas before others, for example. An example
configuration may look something like this::
remote_sources:
- git://github.com/herlo/formulas/
- git://github.com/bob/formulas/
- file:///var/lib/formulas/
In this way, if the 'formula_one' Formula existed in both the herlo and bob
repositories, the herlo 'formula_one' Formula would be downloaded and applied.
If the 'formula_two' were to be applied, the same search would occur, but it's
possible that the bob 'formula_two' formula would be the first one found since
the 'herlo' repository didn't have a 'formula_two'. Additionally, locations for
Formulas can be overridden by a config option::
# formulas apply formula_one --remote_source=file:///var/lib/formulas,file://home/herlo/formulas
Eventually, the hope is to have Formulas available in 'FirstBoot'. In Fedora
18, FirstBoot was replaced by anaconda, probably called 'Stage III'. Because
anaconda Stage III now provides this functionality, it is much more flexible
than the old FirstBoot. This makes adding a GUI interface for formulas much
less complex. To that end, the list of 'approved' Formulas may easily be
available and/or configurable at FirstBoot. Having something like this makes
Formulas a 'killer' feature for Fedora 18 and beyond.
| 7f702f5e762d9f9caeda5246063da8801f5ac35c | [
"Python",
"reStructuredText"
] | 6 | Python | manifestation/destiny | 2a27d5080aa07a2cd737b98101c766fa22d699c7 | 16057a33334cc8943eb63fbead398bb6e794ddd3 |
refs/heads/main | <repo_name>Nicolas-albu/test_of_robot_java_2<file_sep>/src/vidapropria2/VidaPropria2.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vidapropria2;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
/**
*
* @author Andressa
*/
public class VidaPropria2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws AWTException {
// TODO code application logic here
Robot robo = new Robot();
robo.delay(5000);
robo.mouseMove(600, 400);
robo.mousePress(InputEvent.BUTTON3_MASK);
robo.mouseRelease(InputEvent.BUTTON3_MASK);
robo.delay(1000);
robo.keyPress(KeyEvent.VK_UP);
robo.delay(100);
robo.keyRelease(KeyEvent.VK_UP);
robo.delay(1000);
robo.keyPress(KeyEvent.VK_UP);
robo.delay(100);
robo.keyRelease(KeyEvent.VK_UP);
robo.delay(1000);
robo.keyPress(KeyEvent.VK_UP);
robo.delay(100);
robo.keyRelease(KeyEvent.VK_UP);
robo.delay(1000);
robo.keyPress(KeyEvent.VK_UP);
robo.delay(100);
robo.keyRelease(KeyEvent.VK_UP);
robo.delay(1000);
robo.keyPress(KeyEvent.VK_RIGHT);
robo.delay(100);
robo.keyRelease(KeyEvent.VK_RIGHT);
robo.delay(1000);
robo.keyPress(KeyEvent.VK_ENTER);
robo.delay(100);
robo.keyRelease(KeyEvent.VK_ENTER);
//Criando pasta = 1
robo.delay(3000);
robo.keyPress(KeyEvent.VK_O);
robo.delay(500);
robo.delay(500);
robo.keyPress(KeyEvent.VK_I);
robo.delay(500);
robo.keyPress(KeyEvent.VK_ENTER);
//Entrando mouse para pasta: oi
robo.keyPress(KeyEvent.VK_ENTER);
robo.delay(5000);
robo.mousePress(InputEvent.BUTTON3_MASK);
robo.mouseRelease(InputEvent.BUTTON3_MASK);
robo.delay(1000);
robo.keyPress(KeyEvent.VK_UP);
robo.delay(100);
robo.keyRelease(KeyEvent.VK_UP);
robo.delay(1000);
robo.keyPress(KeyEvent.VK_UP);
robo.delay(100);
robo.keyRelease(KeyEvent.VK_UP);
robo.delay(1000);
robo.keyPress(KeyEvent.VK_RIGHT);
robo.delay(100);
robo.keyRelease(KeyEvent.VK_RIGHT);
robo.delay(1000);
robo.keyPress(KeyEvent.VK_ENTER);
robo.delay(100);
robo.keyRelease(KeyEvent.VK_ENTER);
//Criando pasta com nome = java
robo.keyPress(KeyEvent.VK_J);
robo.delay(500);
robo.keyPress(KeyEvent.VK_A);
robo.delay(500);
robo.keyPress(KeyEvent.VK_V);
robo.delay(500);
robo.keyPress(KeyEvent.VK_A);
robo.delay(500);
robo.keyPress(KeyEvent.VK_ENTER);
robo.delay(500);
//Entrando na pasta: chato
robo.keyPress(KeyEvent.VK_ENTER);
robo.delay(500);
//Criando pasta: blablablabla
robo.keyPress(KeyEvent.VK_B);
robo.delay(500);
robo.keyPress(KeyEvent.VK_L);
robo.delay(500);
robo.keyPress(KeyEvent.VK_A);
robo.delay(500);
robo.keyPress(KeyEvent.VK_B);
robo.delay(500);
robo.keyPress(KeyEvent.VK_L);
robo.delay(500);
robo.keyPress(KeyEvent.VK_A);
robo.delay(500);
robo.keyPress(KeyEvent.VK_B);
robo.delay(500);
robo.keyPress(KeyEvent.VK_L);
robo.delay(500);
robo.keyPress(KeyEvent.VK_A);
robo.delay(500);
robo.keyPress(KeyEvent.VK_ENTER);
robo.delay(500);
//Entrando na pasta: blablabla
robo.keyPress(KeyEvent.VK_ENTER);
//Criando pasta: oi
robo.delay(3000);
robo.keyPress(KeyEvent.VK_O);
robo.delay(500);
robo.delay(500);
robo.keyPress(KeyEvent.VK_I);
robo.delay(500);
robo.keyPress(KeyEvent.VK_ENTER);
//Entrando na pasta: oi
robo.keyPress(KeyEvent.VK_ENTER);
//Criando pasta: chato
robo.keyPress(KeyEvent.VK_C);
robo.delay(500);
robo.keyPress(KeyEvent.VK_H);
robo.delay(500);
robo.keyPress(KeyEvent.VK_A);
robo.delay(500);
robo.keyPress(KeyEvent.VK_T);
robo.delay(500);
robo.keyPress(KeyEvent.VK_O);
robo.delay(500);
robo.keyPress(KeyEvent.VK_ENTER);
robo.delay(500);
//Entrando na pasta: chato
robo.keyPress(KeyEvent.VK_ENTER);
//Criando pasta: blablabla
robo.keyPress(KeyEvent.VK_B);
robo.delay(500);
robo.keyPress(KeyEvent.VK_L);
robo.delay(500);
robo.keyPress(KeyEvent.VK_A);
robo.delay(500);
robo.keyPress(KeyEvent.VK_B);
robo.delay(500);
robo.keyPress(KeyEvent.VK_L);
robo.delay(500);
robo.keyPress(KeyEvent.VK_A);
robo.delay(500);
robo.keyPress(KeyEvent.VK_B);
robo.delay(500);
robo.keyPress(KeyEvent.VK_L);
robo.delay(500);
robo.keyPress(KeyEvent.VK_A);
robo.delay(500);
robo.keyPress(KeyEvent.VK_ENTER);
robo.delay(500);
//Entrando na pasta: blablabla
robo.keyPress(KeyEvent.VK_ENTER);
//Entrando mouse para pasta: oi
}
}
| 79d433f59436094d21a6dceda67aa17cd72c6578 | [
"Java"
] | 1 | Java | Nicolas-albu/test_of_robot_java_2 | 93199d02557deecbac2f82cf1bb97794a943f3ce | 0a5f59838c4123fc57a2ffddaac0d3b9e4a5653c |
refs/heads/master | <file_sep>package sample;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import java.sql.SQLException;
public class RepeatWordsController {
@FXML
private Button startTestButton;
@FXML
private TextField textFieldLang1;
@FXML
private TextField textFieldLang2;
@FXML
private Button submitWordPairButton;
@FXML
private MenuButton menuButton1;
@FXML
private RadioMenuItem radioMenuItem_ar1;
@FXML
private ToggleGroup toggleGroupLeft;
@FXML
private RadioMenuItem radioMenuItem_de1;
@FXML
private RadioMenuItem radioMenuItem_en1;
@FXML
private RadioMenuItem radioMenuItem_fr1;
@FXML
private RadioMenuItem radioMenuItem_it1;
@FXML
private RadioMenuItem radioMenuItem_es1;
@FXML
private RadioMenuItem radioMenuItem_pl1;
@FXML
private RadioMenuItem radioMenuItem_ru1;
@FXML
private Text textCorrectness;
@FXML
private MenuButton menuButton21;
@FXML
private RadioMenuItem radioMenuItem_ar11;
@FXML
private ToggleGroup toggleGroupRight;
@FXML
private RadioMenuItem radioMenuItem_de11;
@FXML
private RadioMenuItem radioMenuItem_en11;
@FXML
private RadioMenuItem radioMenuItem_fr11;
@FXML
private RadioMenuItem radioMenuItem_it11;
@FXML
private RadioMenuItem radioMenuItem_es11;
@FXML
private RadioMenuItem radioMenuItem_pl11;
@FXML
private RadioMenuItem radioMenuItem_ru11;
@FXML
private Text textLanFrom1;
@FXML
private Text textLanTo1;
@FXML
private TextField textFieldNumberofWords;
@FXML
private Text textNumWords;
@FXML
void initialize() {
startTestButton.setOnAction(event->{
startTestButton.setVisible(false);
menuButton1.setVisible(false);
menuButton21.setVisible(false);
textFieldNumberofWords.setVisible(false);
textNumWords.setVisible(false);
textFieldLang1.setVisible(true);
textFieldLang2.setVisible(true);
submitWordPairButton.setVisible(true);
String langUserTransFrom = getLangToStartFrom();
String langUserTransTo = getLangToStartTo();
textLanFrom1.setText(getFullLanName(langUserTransFrom));
textLanTo1.setText(getFullLanName(langUserTransTo));
textLanFrom1.setVisible(true);
textLanTo1.setVisible(true);
try {
RepeatWordsEngineClass rwengn = new RepeatWordsEngineClass(langUserTransFrom, langUserTransTo,
Integer.parseInt(textFieldNumberofWords.getText().trim()));
rwengn.createWordsSetOfStartLanguage();
if(!rwengn.wordsSetUserTranslFromIsEmpty()){
textFieldLang1.setText(rwengn.wordUserHasToGiveTranslationTo());
}
else{
textFieldLang2.setVisible(false);
textFieldLang1.setVisible(false);
submitWordPairButton.setVisible(false);
textCorrectness.setText("No words in "
+langUserTransFrom+ " - " +langUserTransTo+" language pair!");
textCorrectness.setFill(Color.DARKBLUE);
textLanFrom1.setVisible(false);
textLanTo1.setVisible(false);
}
submitWordPairButton.setOnAction(event1 ->{
if(rwengn.wordsSetUserTranslFromIsEmpty()){
textFieldLang2.setVisible(false);
textFieldLang1.setVisible(false);
submitWordPairButton.setVisible(false);
textCorrectness.setText("Finished all words in "
+langUserTransFrom+ " - " +langUserTransTo+" language pair!");
textCorrectness.setFill(Color.DARKBLUE);
textLanFrom1.setVisible(false);
textLanTo1.setVisible(false);
} else {
String wordToCheck = textFieldLang2.getText();
if (rwengn.userAnswerIsCorrect(wordToCheck)) {
textCorrectness.setText("Correct!");
textCorrectness.setFill(Color.GREEN);
}
else {
textCorrectness.setText("Wrong!");
textCorrectness.setFill(Color.RED);
}
rwengn.removeCheckedWordFromWordsSetStartLang();
if (!rwengn.wordsSetUserTranslFromIsEmpty()) {
textFieldLang1.setText(rwengn.wordUserHasToGiveTranslationTo());
}
else
textFieldLang1.clear();
textFieldLang2.clear();
}
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
});
}
private String getLangToStartTo(){
if(radioMenuItem_ar11.isSelected()){
return "ar";
}
if(radioMenuItem_de11.isSelected()){
return "de";
}
if(radioMenuItem_en11.isSelected()){
return "en";
}
if(radioMenuItem_fr11.isSelected()){
return "fr";
}
if(radioMenuItem_it11.isSelected()){
return "it";
}
if(radioMenuItem_pl11.isSelected()){
return "pl";
}
if(radioMenuItem_es11.isSelected()){
return "es";
}
if(radioMenuItem_ru11.isSelected()){
return "ru";
}
return "pl";
}
private String getLangToStartFrom(){
if(radioMenuItem_ar1.isSelected()){
menuButton1.setText("Arabic");
return "ar";
}
if(radioMenuItem_de1.isSelected()){
menuButton1.setText("German");
return "de";
}
if(radioMenuItem_en1.isSelected()){
menuButton1.setText("English");
return "en";
}
if(radioMenuItem_fr1.isSelected()){
menuButton1.setText("French");
return "fr";
}
if(radioMenuItem_it1.isSelected()){
menuButton1.setText("Italian");
return "it";
}
if(radioMenuItem_pl1.isSelected()){
menuButton1.setText("Polish");
return "pl";
}
if(radioMenuItem_es1.isSelected()){
menuButton1.setText("Spanish");
return "es";
}
if(radioMenuItem_ru1.isSelected()){
menuButton1.setText("Russian");
return "ru";
}
return "en";
}
public String getFullLanName(String lan){
if(lan.equals("ar")){
return "Arabic";
}
if(lan.equals("de")){
return "German";
}
if(lan.equals("en")){
return "English";
}
if(lan.equals("fr")){
return "French";
}
if(lan.equals("it")){
return "Italian";
}
if(lan.equals("pl")){
return "Polish";
}
if(lan.equals("es")){
return "Spanish";
}
if(lan.equals("ru")){
return "Russian";
}
else
return"";
}
}
<file_sep>package sample;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import java.io.IOException;
import java.util.Vector;
public class TranslateWordToMultiLangClass {
private Vector<String> languages;
private String langFrom;
@FXML
private TextField transResult1;
@FXML
private TextField transResult2;
@FXML
private TextField transResult4;
@FXML
private TextField transResult3;
public TranslateWordToMultiLangClass(Vector<String> langs, String lFrom,
TextField transRes1, TextField transRes2, TextField transRes3, TextField transRes4){
languages = langs;
langFrom = lFrom;
transResult1 = transRes1;
transResult2 = transRes2;
transResult3 = transRes3;
transResult4 = transRes4;
}
private String translateWord(String wordToTranslate, String langTo) {
Vector<String> translatedWords;
try {
translatedWords = HttpRequestTranslation.translateHttp(wordToTranslate, langFrom, langTo);
String translatedWordsString = translatedWords.toString();
return translatedWordsString.substring(1, translatedWordsString.length()-1);
} catch (IOException e) {
e.printStackTrace();
}
return "Error: Probably, word not found";
}
public void translateWordMultipleLan(String wordToTranslate){
Runnable task = new Runnable()
{
Vector<String> temp = new Vector<>();
public void run()
{
if (languages.size() > 0) {
temp.add(translateWord(wordToTranslate, languages.elementAt(0)));
if (languages.size() > 1) {
temp.add(translateWord(wordToTranslate, languages.elementAt(1)));
if (languages.size() > 2) {
temp.add(translateWord(wordToTranslate, languages.elementAt(2)));
if (languages.size() > 3) {
temp.add(translateWord(wordToTranslate, languages.elementAt(3)));
}
}
}
}
Platform.runLater(new Runnable()
{
@Override
public void run()
{
if (languages.size() > 0) {
transResult1.setText(temp.elementAt(0));
if (languages.size() > 1) {
transResult2.setText(temp.elementAt(1));
if (languages.size() > 2) {
transResult3.setText(temp.elementAt(2));
if (languages.size() > 3) {
transResult4.setText(temp.elementAt(3));
}
}
}
}
}
});
}
};
// Run the task in a background thread
Thread backgroundThread = new Thread(task);
// Terminate the running thread if the application exits
backgroundThread.setDaemon(true);
// Start the thread
backgroundThread.start();
}
}
<file_sep>package sample;
import java.sql.Connection;
import java.sql.SQLException;
public class AddWordPairClass {
private DatabaseHandlerOwnDictionary dbhandler = DatabaseHandlerOwnDictionarySingleton.getInstance();
private Connection conn = null;
public void addWordsPairToPersonalDictionary(String leftLan, String rightLan, String txFieldAddWordLeft,
String txFieldAddWordRight) throws SQLException, ClassNotFoundException {
dbhandler.checkDBIfExistsandCreate();
conn = dbhandler.getDbConnection();
if(dbhandler.checkTableExistence(conn, "UID")==false){
dbhandler.createUIDTable(conn);
}
if(dbhandler.checkTableExistence(conn, leftLan)==false){
dbhandler.createTableSpecificLan(conn, leftLan);
}
if(dbhandler.checkTableExistence(conn, rightLan)==false){
dbhandler.createTableSpecificLan(conn, rightLan);
}
if(!leftLan.equals(rightLan)){
insertWordPair(leftLan, rightLan, txFieldAddWordLeft, txFieldAddWordRight);
}
conn.close();
}
private void insertWordPair(String leftLan, String rightLan,
String leftWord, String rightWord) throws SQLException, ClassNotFoundException {
int uidl, uidr, uid;
uidl = dbhandler.findUIDforAWord(leftLan, leftWord);
uidr = dbhandler.findUIDforAWord(rightLan, rightWord);
if(uidl == -1 && uidr == -1){
uid = dbhandler.findUIDfromUIDTable();
dbhandler.insertWord(leftLan, leftWord, uid);
dbhandler.insertWord(rightLan, rightWord, uid);
}
else if(uidl == -1 && uidr != -1){
uid = uidr;
dbhandler.insertWord(leftLan, leftWord, uid);
}
else if(uidl != -1 && uidr == -1){
uid = uidl;
dbhandler.insertWord(rightLan, rightWord, uid);
}
}
}
| fe66508bcc7493063cb174deafe1c5446b18a57e | [
"Java"
] | 3 | Java | abulenok/TransLatteProject | b971504ea754dbe3d4d98be72e3a4a07d4b0cfe3 | f3006442a5b60cd7823215a69fa8e21386b1904e |
refs/heads/master | <repo_name>antonyoneill/Antler<file_sep>/src/tech/antonyoneill/antler/utils/TimeUtil.java
package tech.antonyoneill.antler.utils;
import java.time.Duration;
import java.time.Instant;
public class TimeUtil {
private static final String ERROR_THEN_IS_NULL = "Argument then cannot be null";
/**
* Calculates a pretty time string to output
*
* @param then
* @return String
*/
public String timeDifference(Instant then) {
if (then == null) {
throw new IllegalArgumentException(ERROR_THEN_IS_NULL);
}
Duration duration = Duration.between(then, Instant.now());
long time = 0;
String unit = "";
if (duration.toDays() > 0) {
time = duration.toDays();
unit = "day";
} else if (duration.toHours() > 0) {
time = duration.toHours();
unit = "hour";
} else if (duration.toMinutes() > 0) {
time = duration.toMinutes();
unit = "minute";
} else if (duration.getSeconds() > 0) {
time = duration.getSeconds();
unit = "second";
} else {
return "just now";
}
return String.format("%d %s%s ago", time, unit, time > 1 ? "s" : "");
}
}
<file_sep>/test/tech/antonyoneill/antler/tests/StreamBase.java
package tech.antonyoneill.antler.tests;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
public class StreamBase {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
public String[] getOutContent() {
return trimArray(outContent.toString().split("\n"));
}
public String[] getErrContent() {
return trimArray(errContent.toString().split("\n"));
}
private String[] trimArray(String[] input) {
return Arrays.stream(input).map(line -> line.trim()).toArray(size -> new String[size]);
}
@After
public void cleanUpStreams() {
System.setOut(null);
System.setErr(null);
}
}
<file_sep>/src/tech/antonyoneill/antler/AntlerApplication.java
package tech.antonyoneill.antler;
import java.io.Console;
import java.util.ArrayList;
import java.util.List;
import tech.antonyoneill.antler.command.Command;
import tech.antonyoneill.antler.command.FollowCommand;
import tech.antonyoneill.antler.command.PostCommand;
import tech.antonyoneill.antler.command.ReadCommand;
import tech.antonyoneill.antler.command.WallCommand;
import tech.antonyoneill.antler.exceptions.CommandException;
import tech.antonyoneill.antler.exceptions.CommandSyntaxException;
import tech.antonyoneill.antler.utils.PostPrinter;
import tech.antonyoneill.antler.utils.UserManager;
/**
* Antler is a simple Twitter style messaging board.
*
* It assumes that the users all use the same console, and that once the
* application has been closed the users will not want to access the messages
* again. That is to say there's no persistence, concurrency protection, or
* networking.
*
* @author @antonyoneill
*
*/
public class AntlerApplication {
private Console console;
private List<Command> commands;
private UserManager userManager = new UserManager();
private PostPrinter printer = new PostPrinter();
/**
* Create the application and initialise the fields.
*
* @param console
* The system console to read from
*/
public AntlerApplication(Console console) {
this.console = console;
commands = new ArrayList<>();
commands.add(new ReadCommand(this));
commands.add(new PostCommand(this));
commands.add(new FollowCommand(this));
commands.add(new WallCommand(this));
}
public AntlerApplication(Console console, PostPrinter printer) {
this(console);
this.printer = printer;
}
/**
* Run the application! Commands are parsed and executed until an ^C is
* passed into the input.
*/
public void run() {
while (true) {
String input = console.readLine("> ");
for (Command command : commands) {
if (command.isInputValid(input)) {
try {
command.execute(input);
} catch (CommandSyntaxException e) {
// Suppress this exception
} catch (CommandException e) {
getPrinter().printException(e);
}
}
}
}
}
/**
* @return {@link UserManager} Containing the users for this application
*/
public UserManager getUserManager() {
return userManager;
}
/**
* @return {@link PostPrinterImpl} To print to the console
*/
public PostPrinter getPrinter() {
return printer;
}
}
<file_sep>/test/tech/antonyoneill/antler/entity/PostTest.java
package tech.antonyoneill.antler.entity;
import static org.junit.Assert.assertEquals;
import java.time.Instant;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class PostTest {
@Rule
public ExpectedException expectedEx = ExpectedException.none();
User user = new User("Tester");
@Test
public void testPostCreation() {
Instant createdDate = Instant.now();
Post post = new Post(createdDate, user, "Hello");
assertEquals("The message is accessible", "Hello", post.getMessage());
assertEquals("The toString method contains the date", "Hello", post.toString());
}
@Test
public void testNullCreatedDate() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage(Post.ERROR_CREATED_DATE_NULL);
expectedEx.reportMissingExceptionWithMessage("Expected exception with null createdDate");
new Post(null, user, "Hello");
}
@Test
public void testFutureCreatedDate() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage(Post.ERROR_CREATED_DATE_IN_FUTURE);
expectedEx.reportMissingExceptionWithMessage("Expected exception with future createdDate");
new Post(Instant.now().plusSeconds(60), user, "Hello");
}
@Test
public void testNullUser() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage(Post.ERROR_USER_NULL);
expectedEx.reportMissingExceptionWithMessage("Expected exception with null user");
new Post(Instant.now(), null, "Hello");
}
@Test
public void testNullMessage() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage(Post.ERROR_MESSAGE_NULL_OR_EMPTY);
expectedEx.reportMissingExceptionWithMessage("Expected exception with null message");
new Post(Instant.now(), user, null);
}
@Test
public void testEmptyMessage() {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage(Post.ERROR_MESSAGE_NULL_OR_EMPTY);
expectedEx.reportMissingExceptionWithMessage("Expected exception with empty message");
new Post(Instant.now(), user, "");
}
}
<file_sep>/src/tech/antonyoneill/antler/command/PostCommand.java
package tech.antonyoneill.antler.command;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import tech.antonyoneill.antler.AntlerApplication;
import tech.antonyoneill.antler.entity.User;
import tech.antonyoneill.antler.exceptions.CommandSyntaxException;
import tech.antonyoneill.antler.exceptions.UnableToFindUserException;
public class PostCommand implements Command {
private AntlerApplication app;
private Pattern pattern = Pattern.compile("([^\\s]+) -> (.+$)");
public PostCommand(AntlerApplication app) {
this.app = app;
}
@Override
public boolean isInputValid(String input) {
return pattern.matcher(input).matches();
}
@Override
public void execute(String input) throws CommandSyntaxException {
Matcher matcher = pattern.matcher(input);
if (!matcher.matches()) {
throw new CommandSyntaxException(input);
}
String username = matcher.group(1);
User user;
try {
user = app.getUserManager().getUser(username);
} catch (UnableToFindUserException e) {
// It's OK if the user wasn't found.
user = app.getUserManager().addUser(username);
}
String message = matcher.group(2);
try {
app.getUserManager().post(user, message);
} catch (IllegalArgumentException e) {
return;
}
}
}
<file_sep>/test/tech/antonyoneill/antler/command/CommandBase.java
package tech.antonyoneill.antler.command;
import java.util.Collection;
import tech.antonyoneill.antler.AntlerApplication;
import tech.antonyoneill.antler.entity.Post;
import tech.antonyoneill.antler.tests.StreamBase;
import tech.antonyoneill.antler.utils.PostPrinter;
public class CommandBase extends StreamBase {
AntlerApplication app;
MockPostPrinter printer;
public void setupApp() {
printer = new MockPostPrinter();
app = new AntlerApplication(System.console(), printer);
}
//TODO: Use Mockito here
class MockPostPrinter extends PostPrinter {
Collection<Post> posts;
Exception exception;
@Override
public void printPosts(Collection<Post> posts) {
this.posts = posts;
}
@Override
public void printException(Exception exception) {
this.exception = exception;
}
public Post[] getPostsPrinted() {
return posts.toArray(new Post[posts.size()]);
}
public Exception getException() {
return exception;
}
}
}
<file_sep>/test/tech/antonyoneill/antler/utils/ReverseInstantComparatorTest.java
package tech.antonyoneill.antler.utils;
import static org.junit.Assert.assertEquals;
import java.time.Instant;
import org.junit.Test;
import tech.antonyoneill.antler.entity.Post;
import tech.antonyoneill.antler.entity.User;
public class ReverseInstantComparatorTest {
private ReverseInstantComparator comparator = new ReverseInstantComparator();
private User user = new User("Tester");
@Test
public void testLeftEarlier() {
Post left = new Post(Instant.now().minusSeconds(60), user, "left");
Post right = new Post(Instant.now(), user, "right");
assertEquals("Left is greater than right", 1, comparator.compare(left, right));
}
@Test
public void testRightEarlier() {
Post left = new Post(Instant.now(), user, "left");
Post right = new Post(Instant.now().minusSeconds(60), user, "right");
assertEquals("Left is less than right", -1, comparator.compare(left, right));
}
@Test
public void testEqual() {
Instant instant = Instant.now();
Post left = new Post(instant, user, "left");
Post right = new Post(instant, user, "right");
assertEquals("Left is equal to right", 0, comparator.compare(left, right));
}
}
<file_sep>/src/tech/antonyoneill/antler/exceptions/CommandSyntaxException.java
package tech.antonyoneill.antler.exceptions;
/**
* Thrown when the input for a command is invalid.
*
* @author @antonyoneill
*
*/
public class CommandSyntaxException extends CommandException {
private static final long serialVersionUID = -5850583146053623894L;
public CommandSyntaxException(String input) {
super(String.format("Syntax not valid [%s] for command", input));
}
}
<file_sep>/src/tech/antonyoneill/antler/utils/UserManager.java
package tech.antonyoneill.antler.utils;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import tech.antonyoneill.antler.entity.Post;
import tech.antonyoneill.antler.entity.Post;
import tech.antonyoneill.antler.entity.User;
import tech.antonyoneill.antler.entity.User;
import tech.antonyoneill.antler.exceptions.UnableToFindUserException;
/**
* This class is responsible for keeping a list of users.
*
* @author @antonyoneill
*
*/
public class UserManager {
private Map<String, User> users = new HashMap<>();
/**
* Return a user if we have a record of it, or throw an exception otherwise
*
* @param username
*
* @return {@link User} If the user exists
* @throws UnableToFindUserException
* If the user doesn't exist
*/
public User getUser(String username) throws UnableToFindUserException {
User user = users.get(username);
if (user == null) {
throw new UnableToFindUserException(username);
}
return user;
}
/**
* Add a new user to the application
*
* @param username
* @return The new user
*/
public User addUser(String username) {
User user = new User(username);
users.put(username, user);
return user;
}
/**
* Make a user follow another user. If the users are equal nothing will
* happen.
*
* @param follower
* The {@link User} who wants to follow
* @param user
* The {@link User} to be followed
*/
public void follow(User follower, User user) {
if (follower.equals(user)) {
return;
}
follower.getFollows().add(user);
}
/**
* Posts a message on a users timeline
*
* @param user
* @param message
*/
public void post(User user, String message) {
Post post = new Post(Instant.now(), user, message);
user.getTimeline().add(post);
}
}
<file_sep>/README.md
# Antler
A Simple Twitter style social application
## Execution
1. Clone the repo
2. Build the jar `mvn package`
3. Execute the jar `java -jar target/antler-0.0.1.jar`
### Commands
- Posting: `<username> -> <message>`
- Reading: `<username>`
- Following: `<username> follows <otherusername>`
- Wall: `<username> wall`
The Users are first created when they post a message.
Users cannot follow themselves, and their username is what makes them unique.
| 759531c7625e8ec13e300a9ee58556689d05575c | [
"Markdown",
"Java"
] | 10 | Java | antonyoneill/Antler | 1b21deee5e890ae114b06f93481879d3b0897f91 | a393071fd9c8840e3ed1cb6c8f0e149ac17da284 |
refs/heads/master | <file_sep>import turtle
##turtle.shape('turtle')
##square=turtle.clone()
##square.shape('square')
##square.goto(100,0)
##square.goto(100,100)
##square.goto(0,100)
##square.goto(0,0)
##
##triangle=turtle.clone()
##triangle.shape('triangle')
##triangle.penup()
##triangle.goto(-100,0)
##triangle.pendown()
##triangle.goto(-200,0)
##triangle.goto(-150,100)
##triangle.goto(-100,0)
##
##square.penup()
##square.goto(300,300)
##square.pendown()
##square.stamp
turtle.goto(100,100)
UP_ARROW='Up'
LEFT_ARROW='Left'
DOWN_ARROW='Down'
RIGHT_ARROW='Right'
SPACEBAR="space"
UP=0
LEFT=1
DOWN=2
RIGHT=3
direction=UP
def up():
global direction
direction=0
old_pos=turtle.pos()
x,y=old_pos
turtle.goto(x,y+10)
print(turtle.pos())
def down():
global direction
direction=2
old_pos=turtle.pos()
x,y=old_pos
turtle.goto(x,y-10)
print(turtle.pos())
def left():
global direction
direction=1
old_pos=turtle.pos()
x,y=old_pos
turtle.goto(x-10,y)
print(turtle.pos())
def right():
global direction
direction=3
old_pos=turtle.pos()
x,y=old_pos
turtle.goto(x+10,y)
print(turtle.pos())
turtle.onkeypress(up,UP_ARROW)
turtle.onkeypress(down,DOWN_ARROW)
turtle.onkeypress(left,LEFT_ARROW)
turtle.onkeypress(right,RIGHT_ARROW)
turtle.listen()
turtle.mainloop()
| 7ca9af3d31a9f8f54f1f0c44291bd5c479495600 | [
"Python"
] | 1 | Python | orr19-meet/meet2017y1lab6 | 1ed3b4cc6b85674f4ade8540eef524f4be4ae3e7 | 8020f3346432e7b9944a9e68882e8dc69fc1071c |
refs/heads/main | <repo_name>Markhzz/oldpatent_disambiguation<file_sep>/pv/disambiguation/inventor/build_canopies_sql.py
import collections
import pickle
import mysql.connector
from absl import app
from absl import flags
from absl import logging
from pv.disambiguation.core import InventorMention
FLAGS = flags.FLAGS
flags.DEFINE_string('canopy_out', 'data/inventor/canopies', '')
flags.DEFINE_string('source', 'pregranted', 'pregranted or granted')
import os
def first_letter_last_name(im):
fi = im.first_letter()[0] if len(im.first_letter()) > 0 else im.uuid
lastname = im.last_name()[0] if len(im.last_name()) > 0 else im.uuid
res = 'fl:%s_ln:%s' % (fi, lastname)
return res
def build_pregrants():
cnx = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='pregrant_publications')
cursor = cnx.cursor()
query = "SELECT id, name_first, name_last FROM rawinventor;"
cursor.execute(query)
canopy2uuids = collections.defaultdict(list)
idx = 0
for uuid, name_first, name_last in cursor:
im = InventorMention(uuid, '0', '', name_first if name_first else '', name_last if name_last else '', '', '',
'')
canopy2uuids[first_letter_last_name(im)].append(uuid)
idx += 1
logging.log_every_n(logging.INFO, 'Processed %s pregrant records - %s canopies', 10000, idx, len(canopy2uuids))
return canopy2uuids
def build_granted():
cnx = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='patent_20200630')
cursor = cnx.cursor()
query = "SELECT uuid, name_first, name_last FROM rawinventor;"
cursor.execute(query)
canopy2uuids = collections.defaultdict(list)
idx = 0
for uuid, name_first, name_last in cursor:
im = InventorMention(uuid, '0', '', name_first if name_first else '', name_last if name_last else '', '', '',
'')
canopy2uuids[first_letter_last_name(im)].append(uuid)
idx += 1
logging.log_every_n(logging.INFO, 'Processed %s granted records - %s canopies', 10000, idx, len(canopy2uuids))
return canopy2uuids
def main(argv):
logging.info('Building canopies')
if FLAGS.source == 'pregranted':
canopies = build_pregrants()
elif FLAGS.source == 'granted':
canopies = build_granted()
with open(FLAGS.canopy_out + '.%s.pkl' % FLAGS.source, 'wb') as fout:
pickle.dump(canopies, fout)
if __name__ == "__main__":
app.run(main)
<file_sep>/pv/disambiguation/assignee/build_assignee_klc_stcy.py
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 12 15:10:19 2021
@author: <NAME>
Process patent text
"""
## the function to keep the unique full names in a list
import re
import glob
import math
import pandas as pd
import uuid as uuid_gen
import nltk
nltk.download('punkt')
import collections
import pickle
import mysql.connector
from absl import app
from absl import flags
from absl import logging
from pv.disambiguation.core import AssigneeMention, AssigneeNameMention
def symbol_corr(text):
text = re.sub(r'(?<= [A-Z]), ','. ',text)
return text
def revise_short(text,text_copy):
if ' ' in text and len(text)>=7:
return text
else:
text = (',').join(text_copy.split(',')[0:2])
return text
def revise_assignor(text,text_copy):
if len(re.compile('[Aa][Ss][Ss][Ii][Gg][Nn][Oo][A-Za-z]').findall(text))>0:
text_copy = re.sub(r', [Bb][Yy] .*?,','',text_copy)
text_copy = re.sub(r'.*?(?<![A-Za-z])[Tt][Oo](?![A-Za-z])','|||',text_copy)
text_copy = re.sub(r'\|\|\|.','',text_copy)
text = (',').join(text_copy.split(',')[0:1])
text = re.sub(r'[Aa][Ss][Ss][Ii][Gg][Nn][Oo][Rr]','',text)
return text
else:
return text
FLAGS = flags.FLAGS
flags.DEFINE_string('feature_out', '/kellogg/data/patents/output/', '')
flags.DEFINE_string('path', '/kellogg/data/patents/patent_text/', '')
def build_assignee():
path = FLAGS.path
feature_out = FLAGS.feature_out
# read the list of texts
'''
file_list = glob.glob(path+"abbyy/US100/*.txt")
assign = []
add = []
patentid = []
uuid = []
assign_content = []
i = 0
while(i <= len(file_list)-1):
file = file_list[i]
temp_text = open(file,encoding='utf-8').read()
temp_patentid = re.sub(path,'',file)
temp_patentid = re.sub(r'abbyy/US100\\','',temp_patentid)
temp_patentid = re.sub(r'.txt','',temp_patentid)
# capture the sentence begins w/ Assign...
assign_cap = re.compile('[Aa][Ss][Ss][Ii][Gg][Nn].*\n.*\n').findall(temp_text)
assign_cap = assign_cap + re.compile('[Bb]y .*[Aa][Ss][Ss][Ii][Gg][Nn][Ee][Ee]').findall(temp_text)
# split the sentence if the patent is assigned to multiple agents
assign_cap_split = []
for sent in assign_cap:
sent = re.sub(r'ONE-.*? TO ','|| TO ',sent)
if '||' in sent:
assign_cap_split = assign_cap_split + sent.split('||')[1:]
else:
assign_cap_split = assign_cap_split + [sent]
# revise the captured sentence
assign_rev = []
for sent in assign_cap_split:
assign_content.append(sent)
sent = re.sub(r'\n',' ',sent)
# delete the part before the TO
sent = symbol_corr(sent)
sent = re.sub(r'.*? TO ','',sent)
sent_copy = sent+''
sent = sent.split(',')[0]
# revise the extraction if too short
sent = revise_short(sent,sent_copy)
# revise the extraction if “assignor” is in the string
sent = revise_assignor(sent,sent_copy)
# extract the entities
assign_rev = assign_rev + [sent]
k = 1
temp_uuid = []
while(k<=len(assign_rev)):
temp_uuid.append(str(uuid_gen.uuid4()))
k = k+1
temp_patentid = [temp_patentid]*len(assign_rev)
temp_add = [file]*len(assign_rev)
uuid = uuid + temp_uuid
patentid = patentid + temp_patentid
assign = assign + assign_rev
add = add + temp_add
if math.floor((i-1)/1000) != math.floor(i/1000):
print("finished {0}/{1}".format(i,len(file_list)))
i = i+1
'''
extract_assignee = pd.read_csv(path + 'patents_assignee_name_location_long.csv')
extract_assignee['patnum'] = extract_assignee['patnum'].apply(str)
extract_assignee['assignee_name'] = extract_assignee['assignee_name'].apply(str)
extract_assignee['uuid'] = [str(uuid_gen.uuid4()) for i in extract_assignee['patnum']]
extract_assignee['mention_id'] = ['%s-%s' % (extract_assignee['patnum'][i], extract_assignee['uuid'][i]) for i in range(len(extract_assignee))]
print(len(extract_assignee))
# 6750000
with open(FLAGS.feature_out + 'disambiguation_output.pkl', 'wb') as fout:
pickle.dump(extract_assignee, fout)
# check
with open(FLAGS.feature_out + 'disambiguation_output.pkl', 'rb') as fin:
check = pickle.load(fin)
print(len(check))
print("generated uuids for each patent and saved the output")
# | assignee | patentid | uuid |
feature_map = collections.defaultdict(list)
idx = 0
while(idx <= len(extract_assignee)-1):
rec = {'uuid':extract_assignee['uuid'][idx], 'patent_id':extract_assignee['patnum'][idx], 'organization':extract_assignee['assignee_name'][idx],'assignee_state':extract_assignee['assignee_state'][idx],'assignee_country':extract_assignee['assignee_country'][idx]}
am = AssigneeMention.from_doc(rec)
# the key is the organization which is the assignee
# the name_features return the cleaned name string[0] and
# noStopwords[1]
feature_map[am.name_features()[0],am.assignee_state,am.assignee_country].append(am)
idx += 1
logging.log_every_n(logging.INFO, 'Processed %s granted records - %s features', 10000, idx, len(feature_map))
# the feature_map has the cleaned no blankspace name string as the key
# and in each element, there is the unique id for the patent;
return feature_map
def run(source):
if source == 'document':
features = build_assignee()
return features
def main(argv):
logging.info('Building assignee mentions')
feats = [n for n in map(run, ['document'])]
logging.info('finished loading mentions %s', len(feats))
mention_st_country = set(feats[0].keys())
logging.info('number of name mentions %s', len(mention_st_country))
from tqdm import tqdm
records = dict()
from collections import defaultdict
canopies = defaultdict(set)
for nm in tqdm(mention_st_country, 'name_mentions'):
anm = AssigneeNameMention.from_assignee_mentions(nm, feats[0][nm])
for c in anm.canopies:
canopies[c].add(anm.uuid)
records[anm.uuid] = anm
with open(FLAGS.feature_out + 'assignee_mentions.%s.pkl' % 'records', 'wb') as fout:
pickle.dump(records, fout)
with open(FLAGS.feature_out + 'assignee_mentions.%s.pkl' % 'canopies', 'wb') as fout:
pickle.dump(canopies, fout)
if __name__ == "__main__":
app.run(main)
<file_sep>/pv/disambiguation/inventor/build_coinventor_features_sql.py
import collections
import pickle
import mysql.connector
from absl import app
from absl import flags
from absl import logging
from pathos.multiprocessing import ProcessingPool
from pv.disambiguation.core import InventorMention
FLAGS = flags.FLAGS
flags.DEFINE_string('feature_out', 'data/inventor/coinventor_features', '')
import os
def last_name(im):
return im.last_name()[0] if len(im.last_name()) > 0 else im.uuid
def build_pregrants():
cnx = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='pregrant_publications')
cursor = cnx.cursor()
query = "SELECT id, document_number, name_first, name_last FROM rawinventor;"
cursor.execute(query)
feature_map = collections.defaultdict(list)
idx = 0
for uuid, document_number, name_first, name_last in cursor:
im = InventorMention(uuid, None, '', name_first if name_first else '', name_last if name_last else '', '', '',
'', document_number=document_number)
feature_map[im.record_id].append(last_name(im))
idx += 1
logging.log_every_n(logging.INFO, 'Processed %s pregrant records - %s features', 10000, idx, len(feature_map))
return feature_map
def build_granted():
cnx = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='patent_20200630')
cursor = cnx.cursor()
query = "SELECT uuid, patent_id, name_first, name_last FROM rawinventor;"
cursor.execute(query)
feature_map = collections.defaultdict(list)
idx = 0
for uuid, patent_id, name_first, name_last in cursor:
im = InventorMention(uuid, patent_id, '', name_first if name_first else '', name_last if name_last else '', '',
'', '')
feature_map[im.record_id].append(last_name(im))
idx += 1
logging.log_every_n(logging.INFO, 'Processed %s granted records - %s features', 10000, idx, len(feature_map))
return feature_map
def run(source):
if source == 'pregranted':
features = build_pregrants()
elif source == 'granted':
features = build_granted()
return features
def main(argv):
logging.info('Building coinventor features')
feats = [n for n in ProcessingPool().imap(run, ['granted', 'pregranted'])]
features = feats[0]
for i in range(1, len(feats)):
features.update(feats[i])
with open(FLAGS.feature_out + '.%s.pkl' % 'both', 'wb') as fout:
pickle.dump(features, fout)
if __name__ == "__main__":
app.run(main)
<file_sep>/pv/disambiguation/assignee/run_clustering.py
import os
import pickle
import numpy as np
import wandb
from absl import app
from absl import flags
from absl import logging
from grinch.agglom import Agglom
from grinch.model import LinearAndRuleModel
from pv.disambiguation.assignee.load_name_mentions import Loader
from pv.disambiguation.assignee.model import AssigneeModel
from pv.disambiguation.assignee.model import AssigneeModel_nolocation
FLAGS = flags.FLAGS
flags.DEFINE_string('assignee_canopies', 'exp_out/assignee_mentions.canopies.pkl', '')
flags.DEFINE_string('assignee_mentions', 'exp_out/assignee_mentions.records.pkl', '')
# !!! the input that is missing;
flags.DEFINE_string('assignee_name_model','resources/permid_vectorizer.pkl', '')
flags.DEFINE_string('model', 'exp_out/disambiguation-inventor-patentsview/solo/1rib1zt6/model-1000.torch', '')
flags.DEFINE_string('patent_titles', 'data/inventor/title_features.both.pkl', '')
flags.DEFINE_string('coinventors', 'data/inventor/coinventor_features.both.pkl', '')
flags.DEFINE_string('assignees', 'data/inventor/assignee_features.both.pkl', '')
flags.DEFINE_string('title_model', 'exp_out/sent2vec/patents/2020-05-10-15-08-42/model.bin', '')
flags.DEFINE_string('rawinventor', '/iesl/data/patentsview/2020-06-10/rawinventor.tsv', 'data path')
flags.DEFINE_string('outprefix', 'exp_out/', 'data path')
flags.DEFINE_string('run_id', 'run_3', 'data path')
flags.DEFINE_string('dataset_name', 'patentsview', '')
flags.DEFINE_string('exp_name', 'disambiguation-inventor', '')
flags.DEFINE_string('base_id_file', '', '')
flags.DEFINE_integer('chunk_size', 100, '')
flags.DEFINE_integer('chunk_id', 1, '')
flags.DEFINE_integer('min_batch_size', 900, '')
flags.DEFINE_integer('max_canopy_size', 900, '')
flags.DEFINE_float('sim_threshold', 0.80, '')
logging.set_verbosity(logging.INFO)
def batched_canopy_process(datasets, model, encoding_model):
logging.info('running on batch of %s with %s points', len(datasets), sum([len(x[1]) for x in datasets]))
all_pids = []
all_lbls = []
all_records = []
all_canopies = []
for dataset_name, dataset in datasets:
pids, lbls, records = dataset[0], dataset[1], dataset[2]
all_canopies.extend([dataset_name for _ in range(len(pids))])
all_pids.extend(pids)
all_lbls.extend(lbls)
all_records.extend(records)
return run_on_batch(all_pids, all_lbls, all_records, all_canopies, model, encoding_model)
def run_on_batch(all_pids, all_lbls, all_records, all_canopies, model, encoding_model, canopy2predictions):
features = encoding_model.encode(all_records)
grinch = Agglom(model, features, num_points=len(all_pids), min_allowable_sim=0)
grinch.build_dendrogram_hac()
fc = grinch.flat_clustering(model.aux['threshold'])
# import pdb
# pdb.set_trace()
for i in range(len(all_pids)):
if all_canopies[i] not in canopy2predictions:
canopy2predictions[all_canopies[i]] = [[], []]
canopy2predictions[all_canopies[i]][0].append(all_pids[i])
canopy2predictions[all_canopies[i]][1].append('%s-%s' % (all_canopies[i], fc[i]))
return canopy2predictions
def needs_predicting(canopy_list, results, loader):
return [c for c in canopy_list if c not in results]
def batcher(canopy_list, loader, min_batch_size=800):
all_pids = []
all_lbls = []
all_records = []
all_canopies = []
for c in canopy_list:
if len(all_pids) > min_batch_size:
yield all_pids, all_lbls, all_records, all_canopies
all_pids = []
all_lbls = []
all_records = []
all_canopies = []
records = loader.load(c)
pids = [x.uuid for x in records]
lbls = -1 * np.ones(len(records))
all_canopies.extend([c for _ in range(len(pids))])
all_pids.extend(pids)
all_lbls.extend(lbls)
all_records.extend(records)
if len(all_pids) > 0:
yield all_pids, all_lbls, all_records, all_canopies
def run_batch(canopy_list, outdir, loader, job_name='disambig'):
logging.info('need to run on %s canopies = %s ...', len(canopy_list), str(canopy_list[:5]))
os.makedirs(outdir, exist_ok=True)
results = dict()
outfile = os.path.join(outdir, job_name) + '.pkl'
num_mentions_processed = 0
if os.path.exists(outfile):
with open(outfile, 'rb') as fin:
results = pickle.load(fin)
to_run_on = needs_predicting(canopy_list, results, None)
logging.info('had results for %s, running on %s', len(canopy_list) - len(to_run_on), len(to_run_on))
if len(to_run_on) == 0:
logging.info('already had all canopies completed! wrapping up here...')
# !!! place where the missing input was used
encoding_model = AssigneeModel_nolocation.from_flags(FLAGS)
weight_model = LinearAndRuleModel.from_encoding_model(encoding_model)
weight_model.aux['threshold'] = 1 / (1 + FLAGS.sim_threshold)
if to_run_on:
for idx, (all_pids, all_lbls, all_records, all_canopies) in enumerate(
batcher(to_run_on, loader, FLAGS.min_batch_size)):
logging.info('[%s] run_batch %s - %s - processed %s mentions', job_name, idx, len(canopy_list),
num_mentions_processed)
run_on_batch(all_pids, all_lbls, all_records, all_canopies, weight_model, encoding_model, results)
if idx % 10 == 0:
wandb.log({'computed': idx + FLAGS.chunk_id * FLAGS.chunk_size, 'num_mentions': num_mentions_processed})
logging.info('[%s] caching results for job', job_name)
with open(outfile, 'wb') as fin:
pickle.dump(results, fin)
with open(outfile, 'wb') as fin:
pickle.dump(results, fin)
def handle_singletons(canopy2predictions, singleton_canopies, loader):
for s in singleton_canopies:
ments = loader.load(s)
assert len(ments) == 1
canopy2predictions[s] = [[ments[0].uuid], [ments[0].uuid]]
return canopy2predictions
def run_singletons(canopy_list, outdir, loader, job_name='disambig'):
logging.info('need to run on %s canopies = %s ...', len(canopy_list), str(canopy_list[:5]))
os.makedirs(outdir, exist_ok=True)
results = dict()
outfile = os.path.join(outdir, job_name) + '.pkl'
num_mentions_processed = 0
if os.path.exists(outfile):
with open(outfile, 'rb') as fin:
results = pickle.load(fin)
to_run_on = needs_predicting(canopy_list, results, loader)
logging.info('had results for %s, running on %s', len(canopy_list) - len(to_run_on), len(to_run_on))
if len(to_run_on) == 0:
logging.info('already had all canopies completed! wrapping up here...')
if to_run_on:
handle_singletons(results, to_run_on, loader)
with open(outfile, 'wb') as fin:
pickle.dump(results, fin)
def main(argv):
logging.info('Running clustering - %s ', str(argv))
wandb.init(project="%s-%s" % (FLAGS.exp_name, FLAGS.dataset_name))
wandb.config.update(flags.FLAGS)
# load the mention and canopies
loader = Loader.from_flags(FLAGS)
all_canopies = set(loader.assignee_canopies.keys())
all_canopies = set([x for x in all_canopies if loader.num_records(x) < FLAGS.max_canopy_size])
singletons = set([x for x in all_canopies if loader.num_records(x) == 1])
all_canopies_sorted = sorted(list(all_canopies.difference(singletons)), key=lambda x: (loader.num_records(x), x),
reverse=True)
logging.info('Number of canopies %s ', len(all_canopies_sorted))
logging.info('Number of singletons %s ', len(singletons))
logging.info('Largest canopies - ')
for c in all_canopies_sorted[:10]:
logging.info('%s - %s records', c, loader.num_records(c))
outdir = os.path.join(FLAGS.outprefix, 'assignee', FLAGS.run_id)
logging.info('%s len(all_canopies_sorted)', len(all_canopies_sorted))
num_chunks = int(len(all_canopies_sorted) / FLAGS.chunk_size)
logging.info('%s num_chunks', num_chunks)
logging.info('%s chunk_size', FLAGS.chunk_size)
logging.info('%s chunk_id', FLAGS.chunk_id)
chunks = [[] for _ in range(num_chunks)]
for idx, c in enumerate(all_canopies_sorted):
chunks[idx % num_chunks].append(c)
if FLAGS.chunk_id == 0:
logging.info('Running singletons!!')
run_singletons(list(singletons), outdir, job_name='job-singletons', loader=loader)
logging.info('%s chunk_len', len(chunks))
run_batch(chunks[FLAGS.chunk_id], outdir, loader, job_name='job-%s' % FLAGS.chunk_id)
if __name__ == "__main__":
app.run(main)
<file_sep>/pv/disambiguation/assignee/canonicalize.py
import os
import matplotlib.pyplot as plt
import pandas as pd
import mysql.connector
import collections
from tqdm import tqdm
import pymysql
from pv.disambiguation.util.qc_utils import get_dataframe_from_pymysql_cursor, generate_comparitive_violin_plot
from pv.disambiguation.assignee.model import EntityKBFeatures
from pv.disambiguation.assignee.names import normalize_name
def main():
granted_db = pymysql.connect(read_default_file="~/.mylogin.cnf", database='patent_20200630')
old_disambig_data_query = """
select count(1) as cluster_size, assignee_id
from rawassignee
group by assignee_id;
"""
old_disambig_data = get_dataframe_from_pymysql_cursor(granted_db, old_disambig_data_query)
mention_query = """
SELECT rawassignee.uuid, disambiguated_id, organization, name_first, name_last
from rawassignee INNER JOIN tmp_assignee_disambiguation_granted ON rawassignee.uuid=tmp_assignee_disambiguation_granted.uuid;
"""
mention_data = get_dataframe_from_pymysql_cursor(granted_db, mention_query).to_numpy()
entity_id_query = """
SELECT DISTINCT(disambiguated_id)
from tmp_assignee_disambiguation_granted;
"""
entity_data = get_dataframe_from_pymysql_cursor(granted_db, entity_id_query).to_numpy()
entity2namecount = collections.defaultdict(dict)
for i in tqdm(range(mention_data.shape[0]), 'counting', mention_data.shape[0]):
name = mention_data[i][2] if mention_data[i][2] else '%s %s' % (mention_data[i][3], mention_data[i][4])
if name not in entity2namecount[mention_data[i][1]]:
entity2namecount[mention_data[i][1]][name] = 1
else:
entity2namecount[mention_data[i][1]][name] += 1
# Algorithm:
# If linked, use name of PermID entity
# Otherwise pick most frequently appearing name in the cluster (i.e. largest number of patents determines frequency)
# Normalize characters not displayed in html
# TODO: Normalize & Tie-break!
entity_kb = EntityKBFeatures('data/assignee/permid/permid_entity_info.pkl', None, None)
canonical_names = dict()
for entity,name2count in tqdm(entity2namecount.items(), 'canonicalizing'):
sorted_pairs = sorted([(n,c) for n,c in name2count.items()], key=lambda x:x[1], reverse=True)
for n,c in sorted_pairs:
if normalize_name(n) in entity_kb.emap:
canonical_names[entity] = n
break
if entity in canonical_names:
continue
else:
canonical_names[entity] = sorted_pairs[0][0]
with open('assignee_canonical.pkl', 'wb') as fout:
import pickle
pickle.dump(canonical_names,fout)
if __name__ == "__main__":
main()<file_sep>/wandb/run-20210419_094027-2zg2e80x/files/requirements.txt
-cipy==1.1.0
-umpy==1.15.4
absl-py==0.11.0
alabaster==0.7.10
anaconda-client==1.6.14
anaconda-navigator==1.8.7
anaconda-project==0.8.2
appdirs==1.4.4
argcomplete==1.12.2
asn1crypto==0.24.0
astroid==1.6.3
astropy==3.0.2
atomicwrites==1.4.0
attrs==18.1.0
automat==20.2.0
babel==2.5.3
backcall==0.1.0
backoff==1.10.0
backports.shutil-get-terminal-size==1.0.0
bagit==1.8.1
bcrypt==3.2.0
beautifulsoup4==4.6.0
bitarray==0.8.1
bkcharts==0.2
blaze==0.11.3
bleach==2.1.3
blis==0.7.4
bokeh==0.12.16
boto==2.48.0
bottleneck==1.2.1
cachecontrol==0.11.7
cachetools==4.2.1
catalogue==1.0.0
certifi==2020.12.5
cffi==1.11.5
chardet==3.0.4
click==7.1.2
cloudpickle==0.5.3
clyent==1.2.2
colorama==0.3.9
coloredlogs==15.0
comtypes==1.1.4
conda-build==3.10.5
conda-package-handling==1.7.2
conda-verify==2.0.0
conda==4.10.0
configparser==4.0.2
constantly==15.1.0
contextlib2==0.5.5
cryptography==3.3.1
cycler==0.10.0
cymem==2.0.5
cython==0.28.2
cytoolz==0.9.0.1
dask==0.17.5
dataclasses==0.8
datashape==0.5.4
decorator==4.3.0
defusedxml==0.6.0
dill==0.3.3
dispatcher==1.0
distributed==1.21.8
docker-pycreds==0.4.0
docutils==0.14
en-core-web-sm==2.3.1
entrypoints==0.2.3
et-xmlfile==1.0.1
fastcache==1.0.2
filelock==3.0.4
flask-cors==3.0.4
flask==1.0.2
future==0.18.2
geotext==0.4.0
gevent==1.3.0
gitdb==4.0.5
gitpython==3.1.12
glob2==0.6
google-auth==1.28.0
googlemaps==3.1.3
greenlet==0.4.13
grinch==0.2
h3==3.7.0
h5py==2.7.1
heapdict==1.0.0
html5lib==1.0.1
humanfriendly==9.1
hyperlink==21.0.0
idna==2.6
imageio==2.3.0
imagesize==1.0.0
importlib-metadata==3.4.0
incremental==17.5.0
ipykernel==4.8.2
ipython-genutils==0.2.0
ipython==6.4.0
ipywidgets==7.2.1
isodate==0.6.0
isort==4.3.4
itsdangerous==0.24
jdcal==1.4
jedi==0.12.0
jinja2==2.10
joblib==1.0.1
jsonschema==2.6.0
jupyter-client==5.2.3
jupyter-console==5.2.0
jupyter-core==4.4.0
jupyter==1.0.0
jupyterlab-launcher==0.10.5
jupyterlab==0.32.1
keyring==22.0.1
kiwisolver==1.0.1
lazy-object-proxy==1.3.1
llvmlite==0.23.1
locket==0.2.0
lockfile==0.12.2
lxml==4.2.1
mailmerge==2.0.0
markdown==3.1.1
markupsafe==1.0
matplotlib==2.2.2
mccabe==0.6.1
menuinst==1.4.14
mistune==0.8.3
mkl-fft==1.0.6
mkl-random==1.0.1
more-itertools==4.1.0
mpmath==1.0.0
msgpack-python==0.5.6
multipledispatch==0.5.0
multiprocess==0.70.11.1
murmurhash==1.0.5
mypy-extensions==0.4.3
mysql-connector-python==8.0.23
mysql==0.0.2
mysqlclient==2.0.3
navigator-updater==0.2.1
nbconvert==5.3.1
nbformat==4.4.0
networkx==2.1
nltk==3.3
nose==1.3.7
notebook==5.5.0
numba==0.38.0
numexpr==2.6.5
numpy==1.19.5
numpydoc==0.8.0
oauthlib==3.1.0
odo==0.5.1
olefile==0.45.1
openpyxl==2.5.3
packaging==17.1
pandas==0.23.0
pandocfilters==1.4.2
parso==0.2.0
partd==0.3.8
path.py==11.0.1
pathlib2==2.3.2
pathos==0.2.7
pathtools==0.1.2
patsy==0.5.0
pep8==1.7.1
pickleshare==0.7.4
pillow==5.1.0
pip==21.0
pkginfo==1.4.2
plac==1.1.3
placekey==0.0.9
pluggy==0.6.0
ply==3.11
pox==0.2.9
ppft==1.6.6.3
preshed==3.0.5
prometheus-client==0.9.0
promise==2.3
prompt-toolkit==1.0.15
protobuf==3.14.0
prov==1.5.1
psutil==5.4.5
py==1.5.3
pyasn1-modules==0.2.8
pyasn1==0.4.8
pycodestyle==2.4.0
pycosat==0.6.3
pycparser==2.18
pycrypto==2.6.1
pycurl==7.43.0.6
pydot==1.4.2
pyflakes==1.6.0
pygments==2.2.0
pyhamcrest==2.0.2
pylint==1.8.4
pynare==0.1.5
pyodbc==4.0.23
pyopenssl==18.0.0
pyparsing==2.2.0
pyreadline==2.1
pysocks==1.6.8
pytest-arraydiff==0.2
pytest-astropy==0.3.0
pytest-doctestplus==0.1.3
pytest-openfiles==0.3.0
pytest-remotedata==0.2.1
pytest==3.5.1
python-dateutil==2.7.3
python-google-places==1.4.1
pytz==2018.4
pywavelets==0.5.2
pywin32-ctypes==0.2.0
pywin32==223
pywinpty==0.5.1
pyyaml==3.12
pyzmq==17.0.0
qtawesome==0.4.4
qtconsole==4.3.1
qtpy==1.4.1
ratelimit==2.2.1
rdflib-jsonld==0.5.0
rdflib==5.0.0
requests-oauthlib==1.3.0
requests==2.22.0
rope==0.10.7
rsa==4.7.2
ruamel-yaml==0.15.35
schema-salad==7.1.20210316164414
scikit-image==0.13.1
scikit-learn==0.19.1
scipy==1.4.1
seaborn==0.8.1
selenium==3.14.0
send2trash==1.5.0
sentry-sdk==0.19.5
service-identity==18.1.0
setuptools==54.2.0
sh==1.12.14
shapely==1.7.1
shellescape==3.4.1
shortuuid==1.0.1
simplegeneric==0.8.1
singledispatch==3.4.0.3
six==1.15.0
smmap==3.0.5
snowballstemmer==1.2.1
sortedcollections==0.6.1
sortedcontainers==1.5.10
spacy==2.3.5
sphinx==1.7.4
sphinxcontrib-websupport==1.0.1
spyder-kernels==1.4.0
spyder==3.2.8
sqlalchemy==1.2.7
srsly==1.0.5
statsmodels==0.9.0
subprocess32==3.5.4
sympy==1.1.1
tables==3.4.3
tbb==0.1
tblib==1.3.2
tensorboard-plugin-wit==1.8.0
terminado==0.8.1
testpath==0.3.1
thinc==7.4.5
toolz==0.9.0
torch==1.7.1
torchvision==0.4.0
tornado==5.0.2
tqdm==4.54.1
traitlets==4.3.2
twisted==20.3.0
typed-ast==1.4.2
typing-extensions==3.7.4.3
typing==3.6.4
unicodecsv==0.14.1
urllib3==1.22
wandb==0.10.15
wasabi==0.8.0
watchdog==0.10.4
wcwidth==0.1.7
webencodings==0.5.1
weibull==0.1.3
werkzeug==0.14.1
wheel==0.36.2
widgetsnbextension==3.2.1
win-inet-pton==1.0.1
win-unicode-console==0.5
wincertstore==0.2
wrapt==1.10.11
xlrd==1.1.0
xlsxwriter==1.0.4
xlwings==0.11.8
xlwt==1.3.0
zict==0.1.3
zipp==3.4.0
zope.interface==5.2.0<file_sep>/pv/disambiguation/inventor/upload.py
import os
import mysql
import mysql.connector
from absl import app
from absl import flags
from absl import logging
from tqdm import tqdm
from pv.disambiguation.inventor import load_mysql
FLAGS = flags.FLAGS
flags.DEFINE_string('input', 'exp_out/inventor/run_24/disambiguation.tsv', '')
flags.DEFINE_string('uuidmap', 'data/inventor/uuid2mentionid.tsv', '')
flags.DEFINE_string('output', 'exp_out/inventor/run_24/disambiguation.tsv.toScore', '')
flags.DEFINE_string('pregranted_canopies', 'data/inventor/canopies.pregranted.pkl', '')
flags.DEFINE_string('granted_canopies', 'data/inventor/canopies.granted.pkl', '')
flags.DEFINE_boolean('create_tables', False, '')
logging.set_verbosity(logging.INFO)
def create_tables():
cnx_g = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='patent_20200630')
cnx_pg = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='pregrant_publications')
g_cursor = cnx_g.cursor()
g_cursor.execute(
"CREATE TABLE tmp_inventor_disambiguation_granted (uuid VARCHAR(255), disambiguated_id VARCHAR(255))")
pg_cursor = cnx_pg.cursor()
pg_cursor.execute(
"CREATE TABLE tmp_inventor_disambiguation_pregranted (uuid VARCHAR(255), disambiguated_id VARCHAR(255))")
g_cursor.close()
pg_cursor.close()
def upload():
loader = load_mysql.Loader.from_flags(FLAGS)
pregranted_ids = set([y for x in loader.pregranted_canopies.values() for y in x])
granted_ids = set([y for x in loader.granted_canopies.values() for y in x])
pairs_pregranted = []
pairs_granted = []
with open(FLAGS.input, 'r') as fin:
for line in fin:
splt = line.strip().split('\t')
if splt[0] in pregranted_ids:
pairs_pregranted.append((splt[0], splt[1]))
elif splt[0] in granted_ids:
pairs_granted.append((splt[0], splt[1]))
cnx_g = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='patent_20200630')
cnx_pg = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='pregrant_publications')
g_cursor = cnx_g.cursor()
batch_size = 100000
offsets = [x for x in range(0, len(pairs_granted), batch_size)]
for idx in tqdm(range(len(offsets)), 'adding granted', total=len(offsets)):
sidx = offsets[idx]
eidx = min(len(pairs_granted), offsets[idx] + batch_size)
sql = "INSERT INTO tmp_inventor_disambiguation_granted (uuid, disambiguated_id) VALUES " + ', '.join(
['("%s", "%s")' % x for x in pairs_granted[sidx:eidx]])
# logging.log_first_n(logging.INFO, '%s', 1, sql)
g_cursor.execute(sql)
cnx_g.commit()
g_cursor.execute('alter table tmp_inventor_disambiguation_granted add primary key (uuid)')
cnx_g.close()
pg_cursor = cnx_pg.cursor()
batch_size = 100000
offsets = [x for x in range(0, len(pairs_pregranted), batch_size)]
for idx in tqdm(range(len(offsets)), 'adding pregranted', total=len(offsets)):
sidx = offsets[idx]
eidx = min(len(pairs_pregranted), offsets[idx] + batch_size)
sql = "INSERT INTO tmp_inventor_disambiguation_pregranted (uuid, disambiguated_id) VALUES " + ', '.join(
['("%s", "%s")' % x for x in pairs_pregranted[sidx:eidx]])
# logging.log_first_n(logging.INFO, '%s', 1, sql)
pg_cursor.execute(sql)
cnx_pg.commit()
pg_cursor.execute('alter table tmp_inventor_disambiguation_pregranted add primary key (uuid)')
cnx_pg.close()
def main(argv):
if FLAGS.create_tables:
create_tables()
upload()
if __name__ == "__main__":
app.run(main)
<file_sep>/pv/disambiguation/process/build_uuid2mention_id.py
import collections
import mysql.connector
from er.patents.core import InventorMention
from absl import logging
import pickle
from tqdm import tqdm
from absl import app
from absl import flags
FLAGS = flags.FLAGS
flags.DEFINE_string('output', 'data/inventor/uuid2mentionid.tsv', '')
flags.DEFINE_string('source', 'pregranted', 'pregranted or granted')
import os
def build_granted(fout):
cnx = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'],'.mylogin.cnf'), database='patent_20200630')
cursor = cnx.cursor()
query = "SELECT uuid, patent_id, sequence FROM rawinventor;"
cursor.execute(query)
for uuid, patent_id, sequence in tqdm(cursor, 'process', total=17000000):
fout.write('%s\t%s-%s\n' % (uuid, patent_id, sequence))
def main(argv):
logging.info('Building uuid2mid')
with open(FLAGS.output, 'w') as fout:
build_granted(fout)
if __name__ == "__main__":
app.run(main)<file_sep>/pv/disambiguation/inventor/run_clustering.py
import os
import pickle
import numpy as np
import torch
import wandb
from absl import app
from absl import flags
from absl import logging
from grinch.agglom import Agglom
from pv.disambiguation.inventor.load_mysql import Loader
from pv.disambiguation.inventor.model import InventorModel
FLAGS = flags.FLAGS
flags.DEFINE_string('pregranted_canopies', 'data/inventor/canopies.pregranted.pkl', '')
flags.DEFINE_string('granted_canopies', 'data/inventor/canopies.granted.pkl', '')
# !!! missing input
flags.DEFINE_string('model', 'exp_out/disambiguation-inventor-patentsview/solo/1gylsq4m/model-1000.torch', '')
flags.DEFINE_string('patent_titles', 'data/inventor/title_features.both.pkl', '')
flags.DEFINE_string('coinventors', 'data/inventor/coinventor_features.both.pkl', '')
flags.DEFINE_string('assignees', 'data/inventor/assignee_features.both.pkl', '')
# !!! missing input
flags.DEFINE_string('title_model', 'exp_out/sent2vec/patents/2020-05-10-15-08-42/model.bin', '')
flags.DEFINE_string('rawinventor', '/iesl/data/patentsview/2020-06-10/rawinventor.tsv', 'data path')
flags.DEFINE_string('outprefix', 'exp_out', 'data path')
flags.DEFINE_string('run_id', 'run_3', 'data path')
flags.DEFINE_string('dataset_name', 'patentsview', '')
flags.DEFINE_string('exp_name', 'disambiguation-inventor', '')
flags.DEFINE_string('base_id_file', '', '')
flags.DEFINE_integer('chunk_size', 10000, '')
flags.DEFINE_integer('chunk_id', 1000, '')
flags.DEFINE_integer('min_batch_size', 900, '')
logging.set_verbosity(logging.INFO)
def handle_singletons(canopy2predictions, singleton_canopies, loader):
for s in singleton_canopies:
pgids, gids = loader.pregranted_canopies[s], loader.granted_canopies[s]
assert len(pgids) == 1 or len(gids) == 1
if gids:
canopy2predictions[s] = [[gids[0]], [gids[0]]]
else:
canopy2predictions[s] = [[pgids[0]], [pgids[0]]]
return canopy2predictions
def run_on_batch(all_pids, all_lbls, all_records, all_canopies, model, encoding_model, canopy2predictions):
features = encoding_model.encode(all_records)
# grinch = WeightedMultiFeatureGrinch(model, features, num_points=len(all_pids), max_nodes=3 * len(all_pids))
grinch = Agglom(model, features, num_points=len(all_pids))
grinch.build_dendrogram_hac()
# grinch.get_score_batch(grinch.all_valid_internal_nodes())
fc = grinch.flat_clustering(model.aux['threshold'])
for i in range(len(all_pids)):
if all_canopies[i] not in canopy2predictions:
canopy2predictions[all_canopies[i]] = [[], []]
canopy2predictions[all_canopies[i]][0].append(all_pids[i])
canopy2predictions[all_canopies[i]][1].append('%s-%s' % (all_canopies[i], fc[i]))
return canopy2predictions
def needs_predicting(canopy_list, results, loader):
res = []
for c in canopy_list:
if c not in results or (c in canopy_list and len(results[c]) != loader.num_records(c)):
res.append(c)
return res
def form_canopy_groups(canopy_list, loader, min_batch_size=800):
size_pairs = [(c, loader.num_records(c)) for c in canopy_list]
batches = [[]]
batch_sizes = [0]
batch_id = 0
for c, s in size_pairs:
if batch_sizes[-1] < min_batch_size:
batch_sizes[-1] += s
batches[-1].append(c)
else:
batches.append([c])
batch_sizes.append(s)
return batches, batch_sizes, dict(size_pairs)
def batch(canopy_list, loader, min_batch_size=800):
batches, batch_sizes, sizes = form_canopy_groups(canopy_list, loader, min_batch_size)
for batch, batch_size in zip(batches, batch_sizes):
if batch_size > 0:
all_records = loader.load_canopies(batch)
all_pids = [x.uuid for x in all_records]
all_lbls = -1 * np.ones(len(all_records))
all_canopies = []
for c in batch:
all_canopies.extend([c for _ in range(sizes[c])])
yield all_pids, all_lbls, all_records, all_canopies
def run_batch(canopy_list, outdir, job_name='disambig', singletons=None):
logging.info('need to run on %s canopies = %s ...', len(canopy_list), str(canopy_list[:5]))
os.makedirs(outdir, exist_ok=True)
results = dict()
outfile = os.path.join(outdir, job_name) + '.pkl'
num_mentions_processed = 0
num_canopies_processed = 0
if os.path.exists(outfile):
with open(outfile, 'rb') as fin:
results = pickle.load(fin)
loader = Loader.from_flags(FLAGS)
to_run_on = needs_predicting(canopy_list, results, loader)
logging.info('had results for %s, running on %s', len(canopy_list) - len(to_run_on), len(to_run_on))
if len(to_run_on) == 0:
logging.info('already had all canopies completed! wrapping up here...')
encoding_model = InventorModel.from_flags(FLAGS)
weight_model = torch.load(FLAGS.model).eval()
if to_run_on:
for idx, (all_pids, all_lbls, all_records, all_canopies) in enumerate(
batch(to_run_on, loader, FLAGS.min_batch_size)):
logging.info('[%s] run_batch %s - %s of %s - processed %s mentions', job_name, idx, num_canopies_processed,
len(canopy_list),
num_mentions_processed)
run_on_batch(all_pids, all_lbls, all_records, all_canopies, weight_model, encoding_model, results)
num_mentions_processed += len(all_pids)
num_canopies_processed += np.unique(all_canopies).shape[0]
if idx % 10 == 0:
wandb.log({'computed': idx + FLAGS.chunk_id * FLAGS.chunk_size, 'num_mentions': num_mentions_processed,
'num_canopies_processed': num_canopies_processed})
logging.info('[%s] caching results for job', job_name)
with open(outfile, 'wb') as fin:
pickle.dump(results, fin)
with open(outfile, 'wb') as fin:
pickle.dump(results, fin)
def run_singletons(canopy_list, outdir, job_name='disambig'):
logging.info('need to run on %s canopies = %s ...', len(canopy_list), str(canopy_list[:5]))
os.makedirs(outdir, exist_ok=True)
results = dict()
outfile = os.path.join(outdir, job_name) + '.pkl'
num_mentions_processed = 0
if os.path.exists(outfile):
with open(outfile, 'rb') as fin:
results = pickle.load(fin)
loader = Loader.from_flags(FLAGS)
to_run_on = needs_predicting(canopy_list, results, loader)
logging.info('had results for %s, running on %s', len(canopy_list) - len(to_run_on), len(to_run_on))
if len(to_run_on) == 0:
logging.info('already had all canopies completed! wrapping up here...')
if to_run_on:
handle_singletons(results, to_run_on, loader)
with open(outfile, 'wb') as fin:
pickle.dump(results, fin)
def main(argv):
logging.info('Running clustering - %s ', str(argv))
wandb.init(project="%s-%s" % (FLAGS.exp_name, FLAGS.dataset_name))
wandb.config.update(flags.FLAGS)
loader = Loader.from_flags(FLAGS)
all_canopies = set(loader.pregranted_canopies.keys()).union(set(loader.granted_canopies.keys()))
singletons = set([x for x in all_canopies if loader.num_records(x) == 1])
all_canopies_sorted = sorted(list(all_canopies.difference(singletons)), key=lambda x: (loader.num_records(x), x),
reverse=True)
logging.info('Number of canopies %s ', len(all_canopies_sorted))
logging.info('Number of singletons %s ', len(singletons))
logging.info('Largest canopies - ')
for c in all_canopies_sorted[:10]:
logging.info('%s - %s records', c, loader.num_records(c))
outdir = os.path.join(FLAGS.outprefix, 'inventor', FLAGS.run_id)
num_chunks = int(len(all_canopies_sorted) / FLAGS.chunk_size)
logging.info('%s num_chunks', num_chunks)
logging.info('%s chunk_size', FLAGS.chunk_size)
logging.info('%s chunk_id', FLAGS.chunk_id)
chunks = [[] for _ in range(num_chunks)]
for idx, c in enumerate(all_canopies_sorted):
chunks[idx % num_chunks].append(c)
if FLAGS.chunk_id == 0:
logging.info('Running singletons!!')
run_singletons(list(singletons), outdir, job_name='job-singletons')
run_batch(chunks[FLAGS.chunk_id], outdir, job_name='job-%s' % FLAGS.chunk_id)
if __name__ == "__main__":
app.run(main)
<file_sep>/pv/disambiguation/inventor/load_mysql.py
import os
import pickle
import mysql.connector
from absl import logging
from pv.disambiguation.core import InventorMention
class Loader(object):
def __init__(self, pregranted_canopies, granted_canopies):
self.pregranted_canopies = pregranted_canopies
self.granted_canopies = granted_canopies
self.cnx_g = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='patent_20200630')
self.cnx_pg = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='pregrant_publications')
def load(self, canopy):
return load_canopy(canopy,
self.pregranted_canopies[canopy] if canopy in self.pregranted_canopies else [],
self.granted_canopies[canopy] if canopy in self.granted_canopies else [],
self.cnx_pg, self.cnx_g)
def ids_for(self, canopies):
return [x for canopy in canopies for x in
(self.pregranted_canopies[canopy] if canopy in self.pregranted_canopies else [])], \
[x for canopy in canopies for x in
(self.granted_canopies[canopy] if canopy in self.granted_canopies else [])]
def load_canopies(self, canopies):
return load_canopy('batch of %s' % len(canopies),
[x for canopy in canopies for x in
(self.pregranted_canopies[canopy] if canopy in self.pregranted_canopies else [])],
[x for canopy in canopies for x in
(self.granted_canopies[canopy] if canopy in self.granted_canopies else [])],
self.cnx_pg, self.cnx_g)
def num_records(self, canopy):
return len(self.pregranted_canopies[canopy] if canopy in self.pregranted_canopies else []) + len(
self.granted_canopies[canopy] if canopy in self.granted_canopies else [])
@staticmethod
def from_flags(flgs):
with open(flgs.pregranted_canopies, 'rb') as fin:
pregranted_canopies = pickle.load(fin)
with open(flgs.granted_canopies, 'rb') as fin:
granted_canopies = pickle.load(fin)
l = Loader(pregranted_canopies, granted_canopies)
return l
def load_canopy(canopy_name, pregrant_ids, granted_ids, cnx_pg, cnx_g):
logging.info('Loading data from canopy %s, %s pregranted, %s granted', canopy_name, len(pregrant_ids),
len(granted_ids))
rec = (get_pregrants(pregrant_ids, cnx_pg) if pregrant_ids else []) + (
get_granted(granted_ids, cnx_g) if granted_ids else [])
return rec
def get_granted(ids, cnx, max_query_size=300000):
# | uuid | patent_id | assignee_id | rawlocation_id | type | name_first | name_last | organization | sequence |
# cnx = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'],'.mylogin.cnf'), database='patent_20200630')
cursor = cnx.cursor()
feature_map = dict()
for idx in range(0, len(ids), max_query_size):
id_str = ", ".join(['"%s"' % x for x in ids[idx:idx + max_query_size]])
query = "SELECT * FROM rawinventor WHERE uuid in (%s);" % id_str
cursor.execute(query)
for rec in cursor:
am = InventorMention.from_granted_sql_record(rec)
feature_map[am.uuid] = am
missed = [x for x in ids if x not in feature_map]
logging.warning('[get_granted] missing %s ids: %s', len(missed), str(missed))
return [feature_map[x] for x in ids if x in feature_map] # sorted order.
def get_pregrants(ids, cnx, max_query_size=300000):
# | id | document_number | sequence | name_first | name_last | organization | type | rawlocation_id | city | state | country | filename | created_date | updated_date |
# cnx = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'],'.mylogin.cnf'), database='pregrant_publications')
cursor = cnx.cursor()
feature_map = dict()
for idx in range(0, len(ids), max_query_size):
id_str = ", ".join(['"%s"' % x for x in ids[idx:idx + max_query_size]])
query = "SELECT * FROM rawinventor WHERE id in (%s);" % id_str
cursor.execute(query)
for rec in cursor:
am = InventorMention.from_application_sql_record(rec)
feature_map[am.uuid] = am
idx += 1
missed = [x for x in ids if x not in feature_map]
logging.warning('[get_pregrants] missing %s ids: %s', len(missed), str(missed))
return [feature_map[x] for x in ids if x in feature_map] # sorted order.
<file_sep>/pv/disambiguation/core.py
import uuid as uuid_gen
import numpy as np
from absl import logging
import pv.disambiguation.inventor.names as names
from pv.disambiguation.assignee.names import assignee_name_features_and_canopies
from pv.disambiguation.assignee.names import normalize_name
from pv.disambiguation.location.reparser import LOCATIONS
def clean_name(name_str):
return name_str.replace('\"', '')
class AssigneeMention(object):
def __init__(self, uuid, patent_id, organization,assignee_state, assignee_country):
self.uuid = uuid.replace('\"', '')
self.patent_id = patent_id.replace('\"', '') if patent_id is not None else None
self.organization = organization.replace('\"', '') if organization else ''
self._name_features = None
self._canopies = None
self.mention_id = '%s-%s' % (self.patent_id, self.uuid)
self.assignee_state = assignee_state
self.assignee_country = assignee_country
def canopies(self):
if self._canopies is None:
self._name_features, self._canopies = assignee_name_features_and_canopies(self.assignee_name())
return self._canopies
def name_features(self):
if self._name_features is None:
self._name_features, self._canopies = assignee_name_features_and_canopies(self.assignee_name())
return self._name_features
def assignee_name(self):
return self.organization
@staticmethod
def from_doc(rec):
uuid = rec['uuid']
patent_id = rec['patent_id']
organization = rec['organization']
assignee_state = rec['assignee_state']
assignee_country = rec['assignee_country']
return AssigneeMention(uuid, patent_id, organization,assignee_state,assignee_country)
@staticmethod
def from_master(rec):
uuid = rec['uuid']
# patent_id = rec['patent_id']
organization = rec['organization']
return AssigneeMention(uuid, None, organization)
class AssigneeMention_2stage(object):
def __init__(self, uuid, patent_id, organization):
self.uuid = uuid.replace('\"', '')
self.patent_id = patent_id.replace('\"', '') if patent_id is not None else None
self.organization = organization.replace('\"', '') if organization else ''
self._name_features = None
self._canopies = None
self.mention_id = '%s-%s' % (self.patent_id, self.uuid)
def canopies(self):
if self._canopies is None:
self._name_features, self._canopies = assignee_name_features_and_canopies(self.assignee_name())
return self._canopies
def name_features(self):
if self._name_features is None:
self._name_features, self._canopies = assignee_name_features_and_canopies(self.assignee_name())
return self._name_features
def assignee_name(self):
return self.organization
@staticmethod
def from_doc(rec):
uuid = rec['uuid']
patent_id = rec['patent_id']
organization = rec['organization']
return AssigneeMention_2stage(uuid, patent_id, organization)
@staticmethod
def from_master(rec):
uuid = rec['uuid']
# patent_id = rec['patent_id']
organization = rec['organization']
return AssigneeMention_2stage(uuid, None, organization)
class AssigneeNameMention(object):
def __init__(self, uuid, name_hash, canopies, name_features,
unique_exact_strings,mention_ids,assignee_state, assignee_country):
self.uuid = uuid
self.name_hash = name_hash
self.name_features = name_features
self.canopies = canopies
self.mention_ids = mention_ids
self.unique_exact_strings = unique_exact_strings
self.normalized_most_frequent = normalize_name(max(self.unique_exact_strings.items(), key=lambda x: x[1])[0])
self.assignee_state = assignee_state
self.assignee_country = assignee_country
@staticmethod
def from_assignee_mentions(mention_st_country, assignee_mentions):
anm_id = str(uuid_gen.uuid4())
name_features = set()
canopies = set()
unique_exact_strings = dict()
mention_ids = set()
assignee_state = mention_st_country[1]
assignee_country = mention_st_country[2]
name_hash = mention_st_country[0]
for m in assignee_mentions:
name_features.update(m.name_features())
canopies.update(m.canopies())
mention_ids.add(m.mention_id)
if m.assignee_name() not in unique_exact_strings:
unique_exact_strings[m.assignee_name()] = 0
unique_exact_strings[m.assignee_name()] += 1
return AssigneeNameMention(anm_id, name_hash, canopies, name_features, unique_exact_strings,mention_ids,assignee_state, assignee_country)
class AssigneeNameMention_2stage(object):
def __init__(self, uuid, name_hash, canopies, name_features,
unique_exact_strings,mention_ids):
self.uuid = uuid
self.name_hash = name_hash
self.name_features = name_features
self.canopies = canopies
self.mention_ids = mention_ids
self.unique_exact_strings = unique_exact_strings
self.normalized_most_frequent = normalize_name(max(self.unique_exact_strings.items(), key=lambda x: x[1])[0])
@staticmethod
def from_assignee_mentions(name_hash, assignee_mentions):
anm_id = str(uuid_gen.uuid4())
name_features = set()
canopies = set()
unique_exact_strings = dict()
mention_ids = set()
for m in assignee_mentions:
name_features.update(m.name_features())
canopies.update(m.canopies())
mention_ids.add(m.mention_id)
if m.assignee_name() not in unique_exact_strings:
unique_exact_strings[m.assignee_name()] = 0
unique_exact_strings[m.assignee_name()] += 1
return AssigneeNameMention_2stage(anm_id, name_hash, canopies, name_features, unique_exact_strings,mention_ids)
def load_assignee_mentions(filename, st=0, N=np.Inf, skip_first_line=True):
logging.info('Loading assignee mentions from %s', filename)
with open(filename, 'r') as fin:
for idx, line in enumerate(fin):
if idx == 0 and skip_first_line:
continue
logging.log_every_n(logging.INFO, 'Loaded %s lines of %s', 1000, idx, filename)
if idx > N:
logging.info('Loaded %s lines of %s', idx, filename)
return
elif idx >= st:
yield AssigneeMention.from_line(line)
class LawyerMention(object):
def __init__(self, uuid, patent_id, raw_first, raw_last, organization, country, sequence):
self.uuid = uuid.replace('\"', '')
self.patent_id = patent_id.replace('\"', '')
self.country = country.replace('\"', '')
self.raw_first = raw_first.replace('\"', '')
self.raw_last = raw_last.replace('\"', '')
self.organization = organization.replace('\"', '')
self.sequence = sequence.replace('\"', '')
self.is_organization = len(organization) > 0
def lawyer_name(self):
if self.is_organization:
return self.organization
else:
fn = self.first_name()
ln = self.last_name()
return 'fn:%s_ln:%s' % (fn[0] if fn else self.uuid, ln[0] if ln else self.uuid)
def first_name(self):
if self._first_name is None:
self.compute_name_features()
return self._first_name
def first_initial(self):
if self._first_initial is None:
self.compute_name_features()
return self._first_initial
def middle_initial(self):
if self._middle_initial is None:
self.compute_name_features()
return self._middle_initial
def middle_name(self):
if self._middle_name is None:
self.compute_name_features()
return self._middle_name
def last_name(self):
if self._last_name is None:
self.compute_name_features()
return self._last_name
def suffixes(self):
if self._suffixes is None:
self.compute_name_features()
return self._suffixes
def compute_name_features(self):
self._first_name = names.first_name(self.raw_first)
self._first_initial = names.first_initial(self.raw_first)
self._middle_name = names.middle_name(self.raw_first)
self._middle_initial = names.middle_initial(self.raw_first)
self._suffixes = names.suffixes(self.raw_last)
self._last_name = names.last_name(self.raw_last)
@staticmethod
def from_line(line):
"uuid" "lawyer_id" "patent_id" "name_first" "name_last" "organization" "country" "sequence"
splt = line.strip().split("\t")
if len(splt) != 8:
logging.warning('Error processing line %s', line)
return None
else:
return LawyerMention(splt[0], splt[1], splt[3], splt[4], splt[5], splt[6], splt[7])
def load_lawyer_mentions(filename, st=0, N=np.Inf, skip_first_line=True):
logging.info('Loading lawyer mentions from %s', filename)
with open(filename, 'r') as fin:
for idx, line in enumerate(fin):
if idx == 0 and skip_first_line:
continue
logging.log_every_n(logging.INFO, 'Loaded %s lines of %s', 1000, idx, filename)
if idx > N:
logging.info('Loaded %s lines of %s', idx, filename)
return
elif idx >= st:
yield LawyerMention.from_line(line)
class LocationMention(object):
def __init__(self, uuid, city, state, country, latlong):
self.uuid = uuid.replace('\"', '')
self.city = city.replace('\"', '')
self.country = country.replace('\"', '')
self.state = state.replace('\"', '')
self.latlong = latlong.replace('\"', '')
self._location_string = '%s|%s|%s' % (self.city, self.state, self.country)
self._reparsed = LOCATIONS.reparse(self.location_string())
self._canonical_city = self._reparsed[0]
self._canonical_state = self._reparsed[1]
self._canonical_country = self._reparsed[2]
self._canonical_string = '%s|%s|%s' % (self._canonical_city, self._canonical_state, self._canonical_country)
def location_string(self):
return self._location_string
def canonical_string(self):
return self._canonical_string
@staticmethod
def from_line(line):
# "id" "location_id" "city" "state" "country" "latlong"
splt = line.strip().split("\t")
if len(splt) != 6:
logging.warning('Error processing line %s', line)
return None
else:
return LocationMention(splt[0], splt[1], splt[3], splt[4], splt[5])
@staticmethod
def from_application_sql_record(rec):
# | id | city | state | country | lattitude | longitude | filename | created_date | updated_date |
uuid = rec[0]
city = rec[1] if rec[1] else ''
state = rec[2] if rec[2] else ''
country = rec[3] if rec[3] else ''
lattitude = rec[4]
longitude = rec[5]
filename = rec[6]
created_date = rec[7]
updated_date = rec[8]
return LocationMention(uuid, city, state, country, '')
@staticmethod
def from_granted_sql_record(rec):
# | id | location_id | city | state | country | country_transformed | location_id_transformed |
uuid = rec[0]
location_id = rec[1]
city = rec[2] if rec[2] else ''
state = rec[3] if rec[3] else ''
country = rec[4] if rec[4] else ''
country_transformed = rec[5]
return LocationMention(uuid, city, state, country, '')
class LocationNameMention(object):
def __init__(self, uuid, city, state, country, record_ids, mention_ids):
self.uuid = uuid.replace('\"', '')
self.city = city.replace('\"', '')
self.country = country.replace('\"', '')
self.state = state.replace('\"', '')
self._location_string = '%s|%s|%s' % (self.city, self.state, self.country)
self._in_database = None
self.num_records = len(mention_ids)
self.record_ids = record_ids
self.mention_ids = mention_ids
self._reparsed = LOCATIONS.reparse(self.location_string())
self._canonical_city = self._reparsed[0]
self._canonical_state = self._reparsed[1]
self._canonical_country = self._reparsed[2]
self._canonical_string = '%s|%s|%s' % (self._canonical_city, self._canonical_state, self._canonical_country)
def canonical_city(self):
return self._canonical_city
def canonical_state(self):
return self._canonical_state
def canonical_country(self):
return self._canonical_country
def canonical_string(self):
return self._canonical_string
def location_string(self):
return self._location_string
@staticmethod
def from_mentions(locationMentions):
record_ids = set()
mention_ids = set()
for m in locationMentions:
mention_ids.add(m.uuid)
return LocationNameMention(str(uuid_gen.uuid4()), locationMentions[0]._canonical_city,
locationMentions[0]._canonical_state,
locationMentions[0]._canonical_country, record_ids, mention_ids)
def load_location_mentions(filename, st=0, N=np.Inf, skip_first_line=True):
logging.info('Loading location mentions from %s', filename)
with open(filename, 'r') as fin:
for idx, line in enumerate(fin):
if idx == 0 and skip_first_line:
continue
logging.log_every_n(logging.INFO, 'Loaded %s lines of %s', 1000, idx, filename)
if idx > N:
logging.info('Loaded %s lines of %s', idx, filename)
return
elif idx >= st:
yield LocationMention.from_line(line)
<file_sep>/README.md
# Running clustering on KLC
## 1.
```
module load python-anaconda3
conda create -n patent python==3.9
# conda install pytorch==1.2.0 torchvision==0.4.0 cudatoolkit=9.2 -c pytorch
source activate patent
pip install git+https://github.com/iesl/grinch.git --user
pip install -r /kellogg/data/patents/code/assignee_clustering/requirements.txt --user
conda install -c conda-forge wandb
pip install torch --user
# build the mentions
cd /kellogg/data/patents/code/assignee_clustering_stcy/
export PYTHONPATH=$PYTHONPATH:/kellogg/data/patents/code/assignee_clustering_stcy
python -m pv.disambiguation.assignee.build_assignee_klc_stcy
# run the clustering
wandb sweep bin/assignee/run_all_klc.yaml
wandb agent markhe/assignee_disambiguation/z9xsixiw
# finalize
python -m pv.disambiguation.assignee.finalize_klc_stcy
# extract a random sample to examine
python
import pandas as pd
full= pd.read_csv('/kellogg/data/patents/output/disambiguation_output.csv')
sample = full[:100000]
sample.to_csv('/kellogg/data/patents/output/disambiguation_output_sample.csv')
# 2nd stage build the mentions
python -m pv.disambiguation.assignee.build_assignee_klc_stcy_2stage
# 2nd stage run the clustering
wandb sweep bin/assignee/run_all_klc_2stage.yaml
wandb agent markhe/assignee_disambiguation/z9xsixiw
# 2nd stage finalize
python -m pv.disambiguation.assignee.finalize_klc_stcy_2stage
python
import pandas as pd
full= pd.read_csv('/kellogg/data/patents/output/disambiguation_output_2stage.csv')
sample = full[:100000]
sample.to_csv('/kellogg/data/patents/output/disambiguation_output_2stage_sample.csv')
```
<file_sep>/pv/disambiguation/assignee/upload.py
import os
import pickle
import mysql
import mysql.connector
from absl import app
from absl import flags
from absl import logging
from tqdm import tqdm
FLAGS = flags.FLAGS
flags.DEFINE_string('input', 'exp_out/assignee/run_22/disambiguation.tsv', '')
flags.DEFINE_string('uuidmap', 'data/assignee/uuid.pkl', '')
flags.DEFINE_boolean('create_tables', False, '')
flags.DEFINE_boolean('drop_tables', False, '')
logging.set_verbosity(logging.INFO)
def create_tables():
cnx_g = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='patent_20200630')
cnx_pg = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='pregrant_publications')
g_cursor = cnx_g.cursor()
g_cursor.execute(
"CREATE TABLE tmp_assignee_disambiguation_granted (uuid VARCHAR(255), disambiguated_id VARCHAR(255))")
pg_cursor = cnx_pg.cursor()
pg_cursor.execute(
"CREATE TABLE tmp_assignee_disambiguation_pregranted (uuid VARCHAR(255), disambiguated_id VARCHAR(255))")
g_cursor.close()
pg_cursor.close()
def drop_tables():
cnx_g = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='patent_20200630')
cnx_pg = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='pregrant_publications')
g_cursor = cnx_g.cursor()
g_cursor.execute("DROP TABLE tmp_assignee_disambiguation_granted")
pg_cursor = cnx_pg.cursor()
pg_cursor.execute("DROP TABLE tmp_assignee_disambiguation_pregranted")
g_cursor.close()
pg_cursor.close()
def create_uuid_map():
cnx_g = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='patent_20200630')
cnx_pg = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='pregrant_publications')
g_cursor = cnx_g.cursor()
g_cursor.execute("SELECT uuid, patent_id, sequence FROM rawassignee;")
granted_uuids = dict()
for uuid, patent_id, seq in tqdm(g_cursor, 'granted uuids'):
granted_uuids['%s-%s' % (patent_id, seq)] = uuid
pg_cursor = cnx_pg.cursor()
pg_cursor.execute("SELECT id, document_number, sequence FROM rawassignee;")
pgranted_uuids = dict()
for uuid, doc_id, seq in tqdm(pg_cursor, 'pregranted uuids'):
pgranted_uuids['pg-%s-%s' % (doc_id, seq)] = uuid
return granted_uuids, pgranted_uuids
def upload(granted_ids, pregranted_ids):
pairs_pregranted = []
pairs_granted = []
with open(FLAGS.input, 'r') as fin:
for line in fin:
splt = line.strip().split('\t')
if splt[0] in pregranted_ids:
pairs_pregranted.append((pregranted_ids[splt[0]], splt[1]))
elif splt[0] in granted_ids:
pairs_granted.append((granted_ids[splt[0]], splt[1]))
cnx_g = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='patent_20200630')
cnx_pg = mysql.connector.connect(option_files=os.path.join(os.environ['HOME'], '.mylogin.cnf'),
database='pregrant_publications')
g_cursor = cnx_g.cursor()
batch_size = 100000
offsets = [x for x in range(0, len(pairs_granted), batch_size)]
for idx in tqdm(range(len(offsets)), 'adding granted', total=len(offsets)):
sidx = offsets[idx]
eidx = min(len(pairs_granted), offsets[idx] + batch_size)
sql = "INSERT INTO tmp_assignee_disambiguation_granted (uuid, disambiguated_id) VALUES " + ', '.join(
['("%s", "%s")' % x for x in pairs_granted[sidx:eidx]])
# logging.log_first_n(logging.INFO, '%s', 1, sql)
g_cursor.execute(sql)
cnx_g.commit()
g_cursor.execute('alter table tmp_assignee_disambiguation_granted add primary key (uuid)')
cnx_g.close()
pg_cursor = cnx_pg.cursor()
batch_size = 100000
offsets = [x for x in range(0, len(pairs_pregranted), batch_size)]
for idx in tqdm(range(len(offsets)), 'adding pregranted', total=len(offsets)):
sidx = offsets[idx]
eidx = min(len(pairs_pregranted), offsets[idx] + batch_size)
sql = "INSERT INTO tmp_assignee_disambiguation_pregranted (uuid, disambiguated_id) VALUES " + ', '.join(
['("%s", "%s")' % x for x in pairs_pregranted[sidx:eidx]])
# logging.log_first_n(logging.INFO, '%s', 1, sql)
pg_cursor.execute(sql)
cnx_pg.commit()
pg_cursor.execute('alter table tmp_assignee_disambiguation_pregranted add primary key (uuid)')
cnx_pg.close()
def main(argv):
# if FLAGS.drop_tables:
# drop_tables()
if FLAGS.create_tables:
create_tables()
if not os.path.exists(FLAGS.uuidmap):
granted_uuids, pgranted_uuids = create_uuid_map()
with open(FLAGS.uuidmap, 'wb') as fout:
pickle.dump([granted_uuids, pgranted_uuids], fout)
else:
granted_uuids, pgranted_uuids = pickle.load(open(FLAGS.uuidmap, 'rb'))
upload(granted_uuids, pgranted_uuids)
if __name__ == "__main__":
app.run(main)
| 83988f4243dbdd20b2ddc8394cfae22752280a12 | [
"Markdown",
"Python",
"Text"
] | 13 | Python | Markhzz/oldpatent_disambiguation | 8cfa6e8a7f54285f0b812757a2e6ab4097e22729 | 09634b85615d6238168b66c416359badcd9cdb27 |
refs/heads/master | <repo_name>jasonhellwig/Sketch-App<file_sep>/Dockerfile
FROM node:8
WORKDIR /usr/src/app
# install global packages
RUN apt-get update && apt-get install -y bash && \
apt-get clean && \
npm install -g serve && npm cache clean --force
# npm install
COPY package.json /tmp
RUN cd /tmp && npm install && npm cache clean --force && \
cp -R /tmp/node_modules /usr/src/app && \
rm -rf /tmp/node_modules
COPY . /usr/src/app
# Build for production.
RUN npm run build --production
# Set the command to start the node server.
CMD serve -s build
# Tell Docker about the port we'll run on.
EXPOSE 5000<file_sep>/src/components/text-pad.js
import React, { Component } from 'react';
class TextPad extends Component {
constructor(props){
super(props);
this.onTextChanged = props.onTextChanged;
this.state = {text: props.text};
}
render() {
return (
<div className={"container"}>
<div className={"row justify-content-center"}>
<div className={"col-md-10"}>
<div className="form-group">
<label htmlFor={"textArea"}>Example textarea</label>
<textarea className="form-control" id="textArea" rows="3" defaultValue={this.state.text} onChange={this.onTextChanged}/>
</div>
</div>
</div>
</div>
);
}
}
export default TextPad;
<file_sep>/src/components/trace-pad.js
import React, { Component } from 'react';
import {PaperScope} from 'paper';
import q from 'q';
import request from "request";
class TracePad extends Component {
constructor(props){
super(props);
const {refresh = true, preview = true, category = 'Auto'} = props;
//set up drawing tool
const paper = new PaperScope();
const tool = new paper.Tool();
tool.onMouseDown = this.onMouseDown.bind(this);
tool.onMouseDrag = this.onMouseDrag.bind(this);
tool.onMouseUp = this.onMouseUp.bind(this);
tool.activate();
this.clear = this.clear.bind(this);
this.done = this.done.bind(this);
this.load = this.load.bind(this);
this.setBackground = this.setBackground.bind(this);
this.setRaster = this.setRaster.bind(this);
this.state = {paths: [], tool, paper, refresh, preview, category};
}
componentDidMount(){
// init paperJs;
let canvas = document.getElementById('traceArea');
q.when(canvas)
.then(() => {
this.setState({canvas: canvas});
this.state.paper.setup(canvas);
this.load()
});
}
componentDidUpdate(){
//wait for canvas drawing events to render
if(this.state.waitForLoading){
window.requestAnimationFrame(() =>{
this.setState({waitForLoading: false});
this.done(true)
})
}
}
onMouseDown(event) {
this.path = new this.state.paper.Path();
this.path.strokeColor = '#ffffff';
this.path.strokeWidth = 5;
this.state.paths.push(this.path);
}
onMouseDrag(event) {
this.path.add(event.point);
}
onMouseUp(event) {
// const circle = new Path.Circle({
// center: event.point,
// radius: 10
// });
// circle.strokeColor = 'black';
// circle.fillColor = 'blue';
}
setRaster(imageUrl) {
// set the new background image
let raster = new this.state.paper.Raster(imageUrl);
raster.scale(2);
raster.position = this.state.paper.view.center;
raster.sendToBack();
// remove any existing background image
if (this.state.currentRaster)
this.state.currentRaster.remove();
//update the state
this.setState({currentRaster: raster})
}
clear(){
this.state.paths.forEach(path => path.remove());
this.setState({paths: []})
}
done(reset){
if(!reset) {
//set up final image
this.state.paths.forEach(p => p.strokeColor = 'black');
this.state.currentRaster.remove();
this.setBackground();
this.setState({waitForLoading: true});
return;
}
let dataUrl = this.state.canvas.toDataURL();
this.setState({result: dataUrl});
request({method: 'POST', url: 'http://localhost:5000/trace?token=<KEY>', body: dataUrl},
(error, response, body) => {
if(error) {
console.log(error);
return;
}
this.load()
})
}
load(){
this.state.background && this.state.background.remove();
this.clear();
request({method: 'GET', url: 'http://localhost:5000/trace?token=<KEY>'},
(error, response, body) => {
if(error) {
console.log(error);
return;
}
this.setRaster(body)
})
}
setBackground() {
let rect = new this.state.paper.Path.Rectangle({
point: [0, 0],
size: [this.state.paper.view.size.width, this.state.paper.view.size.height],
strokeColor: 'white'
});
rect.sendToBack();
rect.fillColor = '#ffffff';
this.setState({background: rect})
}
render() {
return (
<div>
<div className={"container"}>
<div className={"row justify-content-center"}>
<div className={"col-md-6"}>
<div className="form-group">
<label htmlFor={"traceArea"}>Sketch Area</label>
<canvas id="traceArea" className={"form-control"} style={{padding: 0, height: "512px", width: "512px"}}/>
</div>
</div>
<div className={"col-md-6"}>
<div className="form-group">
<label htmlFor={"resultsArea"}>Results Area</label>
<img id="resultsArea" src={this.state.result} alt={""}/>
</div>
</div>
</div>
</div>
<div className={"btn btn-primary float-right"} onClick={this.load}>Next</div>
<div className={"btn btn-primary float-right"} onClick={this.clear}>Clear</div>
<div className={"btn btn-primary float-right"} onClick={() => this.done()}>Submit</div>
</div>
);
}
}
export default TracePad;
<file_sep>/src/components/sketch-pad.js
import React, { Component } from 'react';
import {PaperScope} from 'paper';
import q from 'q';
import request from "request";
import _ from 'lodash';
class SketchPad extends Component {
constructor(props){
super(props);
this.props = props;
//set up drawing tool
const paper = new PaperScope();
const tool = new paper.Tool();
paper.tools.push(tool);
paper.tool = tool;
tool.onMouseDown = this.onMouseDown.bind(this);
tool.onMouseDrag = this.onMouseDrag.bind(this);
tool.onMouseUp = this.onMouseUp.bind(this);
this.clear = this.clear.bind(this);
this.predict = _.throttle(this.predict.bind(this), 1000 * 2); //throttle predictions to at most once every 2 seconds
this.state = {paths: [], tool, paper};
}
componentDidMount(){
// init paperJs
let canvas = document.getElementById('sketchArea');
q.when(canvas)
.then(() => {
this.setState({canvas: canvas});
this.state.paper.setup(canvas);
this.props.overlay? this.setOverlay() : this.setBackground();
});
}
componentDidUpdate({overlay, category}){
if(overlay !== this.props.overlay){
console.log('overlay set');
if(overlay) {
this.setOverlay();
}
else {
this.setBackground();
}
}
if(category !== this.props.category){
console.log('category set');
this.predict();
}
//wait for canvas drawing events to render
if(this.state.waitForLoading){
window.requestAnimationFrame(() =>{
let cb = this.state.loadingCallback;
this.setState({waitForLoading: false, loadingCallback: null});
this.createImageUrl(true, cb)
})
}
}
onMouseDown(event) {
this.path = new this.state.paper.Path();
this.path.strokeColor = '#000000';
this.path.strokeWidth = 5;
this.state.paths.push(this.path);
}
onMouseDrag(event) {
this.path.add(event.point);
}
onMouseUp(event) {
if(this.props.refresh) {
this.predict()
}
}
setOverlay() {
if(!this.state.prediction)
return this.setBackground();
let raster = new this.state.paper.Raster(this.state.prediction);
raster.scale(2);
raster.position = this.state.paper.view.center;
raster.sendToBack();
// remove any existing background image
if (this.state.currentBackground)
this.state.currentBackground.remove();
//update the state
this.setState({currentBackground: raster})
}
setBackground() {
let rect = new this.state.paper.Path.Rectangle({
point: [0, 0],
size: [this.state.paper.view.size.width, this.state.paper.view.size.height],
strokeColor: 'white'
});
rect.sendToBack();
rect.fillColor = '#ffffff';
if (this.state.currentBackground)
this.state.currentBackground.remove();
this.setState({currentBackground: rect});
}
clear(){
this.state.paths.forEach(path => path.remove());
this.setState({paths: []})
}
predict(){
this.createImageUrl(false, (imageUrl) => {
this.requestPrediction(imageUrl)
});
}
requestPrediction(imageUrl, drawingType){
drawingType = drawingType || this.props.category.toLowerCase();
//get the image type using the classifier if set to auto
if(drawingType === 'auto'){
request({method: 'POST', url: `http://localhost:5000/classify?token=<KEY>`, body: imageUrl},
(error, response, body) => {
if(error) {
console.log(error);
return;
}
console.log(body);
return this.requestPrediction(imageUrl, body)
});
return;
}
request({method: 'POST', url: `http://localhost:5000/predict/${drawingType}?token=<KEY>`, body: imageUrl},
(error, response, body) => {
if(error) {
console.log(error);
return;
}
this.setState({prediction: body});
if(this.props.overlay)
this.setOverlay();
})
}
createImageUrl(reset, cb){
if(!reset) {
this.setBackground();
this.setState({waitForLoading: true, loadingCallback: cb});
return;
}
let drawingUrl = this.state.canvas.toDataURL();
this.setState({drawing: drawingUrl});
if(cb)
cb(drawingUrl);
}
render() {
return (
<div>
<div className={"container"}>
<div className={"row justify-content-center"}>
<div className={"col-md-6"}>
<div className="form-group">
<label htmlFor={"sketchArea"}>Sketch Area</label>
<canvas id="sketchArea" className={"form-control"} style={{padding: 0, height: "512px", width: "512px"}}/>
</div>
</div>
<div className={"col-md-6"}>
<div className="form-group">
<label htmlFor={"resultsArea"}>Results Area</label>
<div>
<img id="resultsArea" src={this.state.prediction} alt={""} style={{height: "512px", width: '512px'}}/>
</div>
</div>
</div>
</div>
</div>
<div className={"btn btn-primary float-right"} onClick={this.clear}>Clear</div>
<div className={"btn btn-primary float-right"} onClick={this.predict}>Draw</div>
</div>
);
}
}
export default SketchPad;
<file_sep>/src/components/classification-result.js
import React from 'react';
function ClassificationResult({text}){
const tags = text.split(',').map(item => item.trim());
return (
<div className={"row"}>
<div className={"col-md-12 text-center"}>
{tags.map((tag, idx) => <span key={idx} className="mr-3 badge badge-info">{tag}</span>)}
</div>
</div>
);
}
export default ClassificationResult
| 366b07c0da70d1bdacc5c80a89e46d9260f01a33 | [
"JavaScript",
"Dockerfile"
] | 5 | Dockerfile | jasonhellwig/Sketch-App | 8c255579cdf52240264144e8e1a0657b892b8766 | 64df76c52ae1fd105b430a30ab0bfb75a388d855 |
refs/heads/master | <repo_name>campjefferson/netlify-cms<file_sep>/website/site/content/docs/widgets/list.md
---
label: "List"
target: "list"
type: "widget"
---
### List
The list widget allows you to create a repeatable item in the UI which saves as a list of widget values. map a user-provided string with a comma delimiter into a list. You can choose any widget as a child of a list widget—even other lists.
- **Name:** `list`
- **UI:**
- if `fields` is specified, field containing a repeatable child widget, with controls for adding, deleting, and re-ordering the repeated widgets; if unspecified, a text input for entering comma-separated values
- if `types` is specified, it is a list of widgets (modular content types) available to the user from the modular content dropdown. User selects a (or multiple) widgets to add to a list. Child widget is added to the list, with controls for adding, deleting, and re-ordering the child widgets;
- **Data type:** list of widget values
- **Options:**
- `default`: if `fields` is specified, declare defaults on the child widgets; if not, you may specify a list of strings to populate the text field
- `allow_add`: if added and labeled `false`, button to add additional widgets disapears
- `field`: a single widget field to be repeated
- `fields`: a nested list of multiple widget fields to be included in each repeatable iteration
- `types`: a one-dimensional list of multiple widget types to be included in the dropdown
- **Example** (`field`/`fields` not specified):
```yaml
- label: "Tags"
name: "tags"
widget: "list"
default: ["news"]
```
- **Example** (`allow_add` marked `false`):
```yaml
- label: "Tags"
name: "tags"
widget: "list"
allow_add: false
default: ["news"]
```
- **Example** (with `field`):
```yaml
- label: "Gallery"
name: "galleryImages"
widget: "list"
field:
- {label: Image, name: image, widget: image}
```
- **Example** (with `fields`):
```yaml
- label: "Testimonials"
name: "testimonials"
widget: "list"
fields:
- {label: Quote, name: quote, widget: string, default: "Everything is awesome!"}
- label: Author
name: author
widget: object
fields:
- {label: Name, name: name, widget: string, default: "Emmet"}
- {label: Avatar, name: avatar, widget: image, default: "/img/emmet.jpg"}
```
- **Example** (with `types`)
```yaml
- label: "Modular Content Chunks"
label_singular: "Modular Content Chunk"
name: "chunk"
widget: "modular"
types:
- {label: "Text", name: "text", widget: "text"}
- {label: "String", name: "string", widget: "string"}
- {label: "Boolean", name: "boolean", widget: "boolean"}
- {label: "Number", name: "number", widget: "number"}
- {label: "Markdown", name: "markdown", widget: "markdown"}
- {label: "Datetime", name: "datetime", widget: "datetime"}
- {label: "Date", name: "date", widget: "date"}
- {label: "Image", name: "image", widget: "image"}
- {label: "File", name: "file", widget: "file"}
- {label: "Select", name: "select", widget: "select", options: ["a", "b", "c"]}
- {label: "Select (Object)", name: "select_object", widget: "select", options: [{ label: "Chicago", value: "ORD" },{ label: "Paris", value: "CDG" },{ label: "Tokyo", value: "HND" }]}
- {label: "Related Post", name: "relation", widget: "relationKitchenSinkPost", collection: "posts", searchFields: ["title", "body"], valueField: "title"}
- label: "Profile"
name: "profile"
widget: "object"
fields:
- {label: "Public", name: "public", widget: "boolean", default: true}
- {label: "Name", name: "name", widget: "string"}
- label: "Birthdate"
name: "birthdate"
widget: "date"
- label: "List"
name: "list"
widget: "list"
fields:
- {label: "String", name: "string", widget: "string"}
- {label: "Boolean", name: "boolean", widget: "boolean"}
- {label: "Text", name: "text", widget: "text"}
```<file_sep>/README.md
# Netlify CMS
[](#contributors)
[](https://www.codetriage.com/netlify/netlify-cms)
[](https://gitter.im/netlify/netlifycms)
A CMS for static site generators. Give non-technical users a simple way to edit
and add content to any site built with a static site generator.
## How it works
Netlify CMS is a single-page app that you pull into the `/admin` part of your site.
It presents a clean UI for editing content stored in a Git repository.
You setup a YAML config to describe the content model of your site, and typically
tweak the main layout of the CMS a bit to fit your own site.
When a user navigates to `/admin` they'll be prompted to login, and once authenticated
they'll be able to create new content or edit existing content.
Read more about Netlify CMS [Core Concepts](https://www.netlifycms.org/docs/intro/).
# Installation and Configuration
The Netlify CMS can be used in two different ways.
* A Quick and easy install, that just requires you to create a single HTML file and a configuration file. All the CMS Javascript and CSS are loaded from a CDN.
To learn more about this installation method, refer to the [Quick Start Guide](https://www.netlifycms.org/docs/quick-start/)
* A complete, more complex install, that gives you more flexibility but requires that you use a static site builder with a build system that supports npm packages.
# Community
Netlify CMS has a [Gitter community](https://gitter.im/netlify/netlifycms) where members of the community hang out and share things about the project, as well as give and receive support.
# Change Log
This project adheres to [Semantic Versioning](http://semver.org/).
Every release is documented on the Github [Releases](https://github.com/netlify/netlify-cms/releases) page.
# License
Netlify CMS is released under the [MIT License](LICENSE).
Please make sure you understand its [implications and guarantees](https://writing.kemitchell.com/2016/09/21/MIT-License-Line-by-Line.html).
## Contributors
Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind welcome!
<file_sep>/src/components/EditorWidgets/Object/ObjectPreview.js
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { List } from 'immutable';
import { resolveWidget } from 'Lib/registry';
class PreviewErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) {
return (
<div style={{ display: `inline-block`, verticalAlign: `text-top` }}>
{this.props.value ? this.props.value.toString() : ''}
</div>
);
}
return <div style={{ display: `inline-block`, verticalAlign: `text-top` }}>{this.props.children}</div>;
}
}
PreviewErrorBoundary.propTypes = {
value: PropTypes.any,
children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]).isRequired,
};
const renderObject = (field, value, result, getAsset, index = 0) => {
const fields = value.get('fields').toArray();
const resultToJS = result.toJS();
if (resultToJS) {
const values = List(
fields.map((childField) => {
const key = childField.get('name');
let renderedField = childField.merge({ [key]: result.get(key) || '' });
if (key === 'name') {
renderedField = renderedField.merge({ ___name: result.get(key) });
}
return renderedField || null;
})
);
return (
<ObjectPreview key={`${ field.get('name') }-${ index }`} field={field} value={values} getAsset={getAsset} nested />
);
}
return null;
};
const renderValue = (field, value, getAsset) => {
const widget = value.get('widget');
let result = value.get('___name') || value.get(value.get('name'));
const PreviewComponent = resolveWidget(widget).preview;
let valuePreview;
switch (widget) {
case 'boolean':
result = result || 'false';
break;
case 'date':
result = Object(result);
break;
case 'datetime':
result = new Date(result);
break;
case 'list':
if (result && result.size) {
valuePreview = (
<div className="list">{result.map((r, idx) => renderObject(field, value, r, getAsset, idx))}</div>
);
}
break;
case 'object':
valuePreview = renderObject(field, value, result, getAsset);
break;
default:
valuePreview = PreviewComponent ? (
<PreviewErrorBoundary value={result}>
<PreviewComponent value={result} getAsset={getAsset} />
</PreviewErrorBoundary>
) : (
result
);
break;
}
if (valuePreview) {
return valuePreview;
}
return result ? result.toString() : null;
};
const ObjectPreview = ({ field, value, getAsset, nested }) => (
<div className="nc-widgetPreview">
{(field && field.get('fields')) ||
(value && (
<div className="nc-widgetPreview" style={{ marginBottom: 20, marginTop: nested ? 5 : 0 }}>
{!nested && <h3 style={{ marginTop: 0, marginBottom: 10 }}>Modular Content -- {field.get('label')}</h3>}
{!nested && <hr />}
{value &&
value.size &&
value.map((val, index) => (
<div
key={`${ val.get('name') }-${ index }`}
className="nc-widgetPreview"
style={{
marginBottom: nested ? 2 : 5,
marginLeft: nested ? 10 : 0,
}}
>
<h4
style={{
display: `inline-block`,
margin: 0,
marginRight: 5,
}}
>
{val.get('label')}:
</h4>
{renderValue(field, val, getAsset)}
</div>
))}
{!nested && <hr />}
</div>
))}
</div>
);
ObjectPreview.propTypes = {
field: PropTypes.any,
value: PropTypes.map,
getAsset: PropTypes.func,
nested: PropTypes.bool,
};
export default ObjectPreview;
| 679d2bfc2ae0f82c1a8580b9b6eb4cb97aefdff8 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | campjefferson/netlify-cms | 3abf66ac398252ab0931ec70c66318550cacf8bc | 0ad55c66b4d4f686ab2657a8fe5f1451aa2f5317 |
refs/heads/master | <file_sep># parsehttpdate · [](https://github.com/Pimm/parseHttpDate/blob/master/copying.txt) [](https://www.npmjs.com/package/parsehttpdate) [](https://github.com/Pimm/parseHttpDate/actions/workflows/test.yaml) [](https://coveralls.io/github/Pimm/parseHttpDate?branch=master)
Parses the value of the `Date` header in HTTP responses.
## Description
Parses date-times from HTTP headers such as _Date_, _Last-Modified_, and _Expires_. An example of such a date-time is:
> Tue, 15 Nov 1994 08:12:31 GMT
The format [is defined by HTTP/1.1][http-1.1] (and [HTTP/1.0][http-1.0]) and is a subset of the specification used by the [Internet Message Format][imf].
# Installation
Install `parsehttpdate` using npm or Yarn and import the function:
```javascript
import parseHttpDate from 'parsehttpdate';
```
Alternatively, include `parsehttpdate` through unpkg:
```html
<script src="https://unpkg.com/parsehttpdate@^1.0.10"></script>
```
This alternative makes the function available at `window.parseHttpDate`.
# Usage
```javascript
parseHttpDate('Wed, 21 Oct 2015 07:28:00 GMT');
```
### Combined with [fetch][mdn-fetch]
This is how you can determine the time according to your server:
```javascript
fetch('/')
.then(({ headers }) => headers.get('Date'))
.then(parseHttpDate)
.then(date => {
console.log(date.toTimeString());
});
```
This is the same example using an [async function][mdn-async-function]:
```javascript
async function getServerDate() {
const { headers } = await fetch('/');
return parseHttpDate(headers.get('Date'));
}
getServerDate()
.then(date => {
console.log(date.toTimeString());
});
```
### Advanced usage
If you are fairly certain the input is formatted correctly, you can squeeze out some extra performance by turning off validation.
```javascript
parseHttpDate('Wed, 21 Oct 2015 07:28:00 GMT', false);
```
## Other formats
Does your date-time look nothing like the example above, but rather something like this?
> 1994-11-06T08:49:37Z
Congratulations: your date-time is formatted [according to ISO 8601][ecmascript-10-date-time]. _You don't need this library_. You don't need any library:
```javascript
new Date('1994-11-06T08:49:37Z');
```
The HTTP/1.1 specification defines two obsolete formats besides the preferred format of the examples above:
> Sunday, 06-Nov-94 08:49:37 GMT
> Sun Nov 6 08:49:37 1994
This library does not support those; the supported format has been the preferred one since 1996. [Please create an issue][issues] if your use case requires the others.
# License (X11/MIT)
Copyright (c) 2018-2021 Pimm "<NAME>" Hogeling
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
**The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the Software.**
[http-1.1]: https://tools.ietf.org/html/rfc7231#section-7.1.1.1
[http-1.0]: https://tools.ietf.org/html/rfc1945#section-3.3
[imf]: https://tools.ietf.org/html/rfc5322
[ecmascript-10-date-time]: http://www.ecma-international.org/ecma-262/10.0/#sec-date-time-string-format
[mdn-fetch]: https://developer.mozilla.org/docs/Web/API/Fetch_API
[mdn-async-function]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/async_function
[issues]: https://github.com/Pimm/parseHttpDate/issues<file_sep>### 1.0.0
* Initial version.
### 1.0.1
(No changes)
### 1.0.2
* Now rolling up the library as a CommonJS module, an ES module, and an IIFE.
### 1.0.3 - 1.0.10
(No changes)<file_sep>import parseHttpDate from '..';
// This file is used to test the type definitions in `index.d.ts`.
export function basics(): Array<Date> {
return [
parseHttpDate(
'Wed, 21 Oct 2015 07:28:00 GMT',
),
parseHttpDate(
'Wed, 21 Oct 2015 07:28:00 GMT',
true
),
parseHttpDate(
'Wed, 21 Oct 2015 07:28:00 GMT',
false
)
];
}<file_sep># parsehttpdate · [](https://github.com/Pimm/parseHttpDate/blob/master/copying.txt) [](https://www.npmjs.com/package/parsehttpdate) [](https://github.com/Pimm/parseHttpDate/actions/workflows/test.yaml) [](https://coveralls.io/github/Pimm/parseHttpDate?branch=master)
Ontleedt de waarde van de `Date` header in HTTP antwoorden.
## Omschrijving
Ontleedt datum-tijdstippen van HTTP-headers zoals _Date_, _Last-Modified_, en _Expires_. Een voorbeeld van zo een datum-tijdstip is:
> Tue, 15 Nov 1994 08:12:31 GMT
Het formaat is [gedefinieerd door HTTP/1.1][http-1.1] (en [HTTP/1.0][http-1.0]) en is een subgroep van de specificatie die wordt gebruikt door in het [Internet Message Format][imf].
# Installatie
Installeer `parsehttpdate` met npm of Yarn en importeer de functie:
```javascript
import parseHttpDate from 'parsehttpdate';
```
Als alternatief kan `parsehttpdate` ook worden binnengehaald met unpkg:
```html
<script src="https://unpkg.com/parsehttpdate@^1.0.10"></script>
```
Met deze aanpak wordt de functie beschikbaar als `window.parseHttpDate`.
# Gebruik
```javascript
parseHttpDate('Wed, 21 Oct 2015 07:28:00 GMT');
```
### In combinatie met [fetch][mdn-fetch]
Op deze manier vind je de tijd volgens jouw server:
```javascript
import parseHttpDate from 'parsehttpdate';
fetch('/')
.then(({ headers }) => headers.get('Date'))
.then(parseHttpDate)
.then(date => {
console.log(date.toTimeString());
});
```
Dit is hetzelfde voorbeeld met een [async-functie][mdn-async-function]:
```javascript
import parseHttpDate from 'parsehttpdate';
async function getServerDate() {
const { headers } = await fetch('/');
return parseHttpDate(headers.get('Date'));
}
getServerDate()
.then(date => {
console.log(date.toTimeString());
});
```
### Geavanceerd gebruik
Als je er vrij zeker van bent dat de invoer is opgeschreven in het correcte formaat, kun je de prestaties nog iets verbeteren door validatie uit te zetten.
```javascript
parseHttpDate('Wed, 21 Oct 2015 07:28:00 GMT', false);
```
## Andere formaten
Ziet jouw datum-tijdstip er niet uit zoals het voorbeeld hierboven, maar meer zo?
> 1994-11-06T08:49:37Z
Gefeliciteerd: jouw datum-tijdstip is opgeschreven in het [ISO 8601][ecmascript-10-date-time]-formaat. _Je hebt deze bibliotheek niet nodig_. Je hebt geen enkele bibliotheek nodig:
```javascript
new Date('1994-11-06T08:49:37Z');
```
De HTTP/1.1-specificatie definieert ook twee verouderde formaten naast het aangerade formaat van de bovengenoemde voorbeelden:
> Sunday, 06-Nov-94 08:49:37 GMT
> Sun Nov 6 08:49:37 1994
Deze bibliotheek ondersteunt deze niet; sinds 1996 is het gebruik van het ondersteunde formaat aanbevolen. [Maak alsjeblieft een issue aan][issues] als je de overige toch nodig hebt.
## Licentie (X11/MIT)
Copyright (c) 2018-2021 Pimm "<NAME>" Hogeling
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
**The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the Software.**
[http-1.1]: https://tools.ietf.org/html/rfc7231#section-7.1.1.1
[http-1.0]: https://tools.ietf.org/html/rfc1945#section-3.3
[imf]: https://tools.ietf.org/html/rfc5322
[ecmascript-10-date-time]: http://www.ecma-international.org/ecma-262/10.0/#sec-date-time-string-format
[mdn-fetch]: https://developer.mozilla.org/docs/Web/API/Fetch_API
[mdn-async-function]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/async_function
[issues]: https://github.com/Pimm/parseHttpDate/issues<file_sep>/**
* @jest-environment node
*/
const parseHttpDate = require('..');
test('parsing', () => {
expect(parseHttpDate('Sun, 06 Nov 1994 08:49:37 GMT').toISOString()).toBe('1994-11-06T08:49:37.000Z');
expect(parseHttpDate('Wed, 21 Oct 2015 07:28:00 GMT').toISOString()).toBe('2015-10-21T07:28:00.000Z');
// Ensure every month is correctly parsed.
expect(parseHttpDate('Thu, 04 Jan 2018 13:01:35 GMT').toISOString()).toBe('2018-01-04T13:01:35.000Z');
expect(parseHttpDate('Sun, 04 Feb 2018 13:01:35 GMT').toISOString()).toBe('2018-02-04T13:01:35.000Z');
expect(parseHttpDate('Sun, 04 Mar 2018 13:01:35 GMT').toISOString()).toBe('2018-03-04T13:01:35.000Z');
expect(parseHttpDate('Wed, 04 Apr 2018 13:01:35 GMT').toISOString()).toBe('2018-04-04T13:01:35.000Z');
expect(parseHttpDate('Fri, 04 May 2018 13:01:35 GMT').toISOString()).toBe('2018-05-04T13:01:35.000Z');
expect(parseHttpDate('Mon, 04 Jun 2018 13:01:35 GMT').toISOString()).toBe('2018-06-04T13:01:35.000Z');
expect(parseHttpDate('Wed, 04 Jul 2018 13:01:35 GMT').toISOString()).toBe('2018-07-04T13:01:35.000Z');
expect(parseHttpDate('Sat, 04 Aug 2018 13:01:35 GMT').toISOString()).toBe('2018-08-04T13:01:35.000Z');
expect(parseHttpDate('Tue, 04 Sep 2018 13:01:35 GMT').toISOString()).toBe('2018-09-04T13:01:35.000Z');
expect(parseHttpDate('Thu, 04 Oct 2018 13:01:35 GMT').toISOString()).toBe('2018-10-04T13:01:35.000Z');
expect(parseHttpDate('Sun, 04 Nov 2018 13:01:35 GMT').toISOString()).toBe('2018-11-04T13:01:35.000Z');
expect(parseHttpDate('Tue, 04 Dec 2018 13:01:35 GMT').toISOString()).toBe('2018-12-04T13:01:35.000Z');
});<file_sep>// (The number of seconds may start with a 6 because of leap seconds.)
const pattern = /^[F-W][a-u]{2}, [0-3]\d (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} [0-2]\d:[0-5]\d:[0-6]\d GMT$/;
// ⎣day o' week⎦ ⎣date ⎦ ⎣ month ⎦ ⎣yr ⎦ ⎣hour ⎦ ⎣ min ⎦ ⎣ sec ⎦
// J F M A M J J A S O N D
const monthsNames = 'anebarprayunulugepctovec';
// u r c i e y u t o e e
// a u h l s e b m m
// r a t m e b b
// y r b r e e
// y e r r
// r
/**
* Parses the passed date-time which has the preferred format as defined by HTTP/1.1. An example of such a date-time
* is:
*
* > Tue, 15 Nov 1994 08:12:31 GMT
*
* The second argument determines whether the passed date-time should be validated before being parsed. Not validating
* (`false`) is faster, but behaviour is undefined if the passed date-time is not formatted correctly. Validating
* (`true`, default) causes an error to be thrown if the passed date-time is not formatted correctly.
*/
export default function parseHttpDate(value, validate) {
if (false != validate) {
if (false == pattern.test(value)) {
throw new Error('The passed value has an unexpected format');
}
}
const substring = value.substring.bind(value);
return new Date(Date.UTC(
parseInt(substring(12, 16), 10),
// (Skip over the first character of the month abbreviation, as we can safely detect the name by the second and
// third character only.)
monthsNames.indexOf(substring(9, 11)) >> 1,
parseInt(substring(5, 7), 10),
parseInt(substring(17, 19), 10),
parseInt(substring(20, 22), 10),
parseInt(substring(23, 25), 10)
));
}
<file_sep>/**
* Parses the passed date-time which has the preferred format as defined by HTTP/1.1. An example of such a date-time
* is:
*
* > Tue, 15 Nov 1994 08:12:31 GMT
*
* The second argument determines whether the passed date-time should be validated before being parsed. Not validating
* (`false`) is faster, but behaviour is undefined if the passed date-time is not formatted correctly. Validating
* (`true`, default) causes an error to be thrown if the passed date-time is not formatted correctly.
*/
declare function parseHttpDate(value: string, validate?: boolean): Date;
export default parseHttpDate; | 33420054979f65ce0f6502e8e82c200d08c69f30 | [
"Markdown",
"TypeScript",
"JavaScript"
] | 7 | Markdown | Pimm/parseHttpDate | 4b4589af9d3fe451e250cb4ee5aa72be63960607 | 426f0e6e36eac62bbd1544fdaf5fa1f9362c4bf0 |
refs/heads/master | <repo_name>mnoskoski/scripts-template-python<file_sep>/loop_for.py
"""
Loop for
Loop -> estrutura de repeticacao
For -> uma das estruturas
for item in interavel:
//execucao do loop
Utilizamos loop para iterar sobre sequencia ou sobre valores iteraveis()
String
nome = 'Marcelo'
Lista
list = [1,2,3,4]
Range
numero
nome = 'Marcelo'
lista = [1, 3, 4, 5, 7]
numeros = range(1,10)
# Exemplo iterando sobre uma string
for letra in nome:
print(letra)
# Exemplo iterando sobre uma lista
for numero in lista:
print(numero)
# Exemplo iterando sobre range
for numero in range(1,10):
print(numero)
"""
# nome = 'Marcelo'
# lista = [1, 3, 4, 5, 7]
# numeros = range(1,10)
# for indice, letra in enumerate(nome):
# print(nome[indice])
# for indice, letra in enumerate(nome):
# print(letra)
# for valor in enumerate(nome):
# print(valor)
# qtd = int(input('Quantas vezes esse loop deve rodar?'))
# for n in range(1, qtd):
# print(f'imprimindo {n}')
#Original: U+1F60D
#Modificado: U0001F60D
num_range=10
emoji = "U0001F60D"
for num in range(num_range):
for num in range(1,11):
print('\U0001F60D' * num)
for num in range(4):
print('\U0001F60D' * num)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)<file_sep>/05exercicio.py
#/usr/bin/python
"""
Estrutura Logica e Condicionais - if, else, elif
elif é possivel ter varios no codigo
"""
idade = 20
if idade < 18:
print('menor de idade')
elif idade == 18:
print("tem 18 anos")
else:
print('Maior de idade')
<file_sep>/testa-senha.py
import os
import sys
import requests
import string
from itertools import combinations_with_replacement
#file_path=sys.argv[1]
def generatePassword():
password = string.ascii_lowercase + string.digits
comb = combinations_with_replacement(password, 10)
print(list(comb))
if __name__ == "__main__":
generatePassword()<file_sep>/type-conversion.py
#/usr/bin/python
#entrada de dados com o input e conversao dos tipos de dados
## Example:
##leg_a = float(input("Input first leg length: "))
##leg_b = float(input("Input second leg length: "))
##print("Hypotenuse length is " + str((leg_a**2 + leg_b**2) ** .5))
# input a float value for variable a here
varA = float((input("digite um valor:")))
# input a float value for variable b here
varB = float((input("digite um valor:")))
# output the result of addition here
print("Soma: " + str(varA + varB))
# output the result of subtraction here
print("Subtracao: " + str(varA - varB))
# output the result of multiplication here
print("Multiplicacao: " + str(varA * varB))
# output the result of division here
print("Divisao: " + str(varA / varB))
print("\nThat's all, folks!")
<file_sep>/06exercicio.py
"""
Estruturas logiscas
and (e)
or (ou)
not (nao)
operadores unarios
- not
operadores binarios
- and, or, is
Para o and ambos valores precisam ser True
Para o or um ou outro valor precisa ser True
Para o not o valor do booleano é invertido, se for True vira false e for false vira True
Para o is o valor é comparado com o segundo valor
"""
ativo = True
logado = False
if ativo and logado:
print('Bem vindo usuario!')
else:
print('Voces precisa ativar sua conta!')
#Ativo é verdadeiro?
print(ativo is True)
<file_sep>/01exercicio.py
#/usr/bin/python
#teste da funcao 'len' para pegar a quantidade de caracter de uma string
import sys
import requests
s = len(sys.argv[1])
def right_justify(s):
print('tamanho da string:', +s )
if __name__ == "__main__":
right_justify(s)<file_sep>/python-calculator.py
#/usr/bin/python3
"""
Python with operations calculator
/ division
* multiplication
+ sum
-
// divions get only value integer
** elevado (3 ** 3 ) = 275
comando round(variable_name, 2) #define a quantidade de numeros que vao aparecer depois da virgula
"""
kilometers = 12.25
miles = 7.38
miles_to_kilometers = miles * 1.61
kilometers_to_miles = kilometers / 1.61
print(miles, "miles is", round(miles_to_kilometers, 2), "kilometers")
print(kilometers, "kilometers is", round(kilometers_to_miles, 2), "miles")
a = '1'
b = "1"
print(a + b) #o print sera 11
<file_sep>/replicacation-exercicio.py
#/usr/bin/python3
# no python posso ter uma multiplicacao inclusive de string
print("Marcelo " * 5)
print(("|" + " 3 " * 10 + "|\n") * 5, end="")<file_sep>/02exercicio.py
#/usr/bin/python
#usando and 'trunegacao no python
#False and True deve ser escrito em maiusculo
ativo = True
print(ativo)
logado = True
def validacaUsuarioConectado():
if logado == False:
print ("usuario desconectado")
else:
print("usuario conectado")
if __name__ == "__main__":
validacaUsuarioConectado()<file_sep>/function-print-string.py
print("hello, world!".upper()) # set all text to upper
print("The itsy bitsy spider\nclimbed up the waterspout.")
print("My", "name", "is", "Monty", "Python.", sep="-")
print("Monty", "Python.", sep="*", end="*\n")
print("Programming","Essentials","in",sep="***",end="...")<file_sep>/using_replication_string.py
numer = input("Digite um numero: ")
#using replication operation string
for i in numer:
print("+" + i * "-" + "+")
print(("|" + " " * 10 + "|\n") * 5, end="")
print("+" + i * "-" + "+")
<file_sep>/04exercicio.py
"""
Escopo de variaveis
Dois casos
1- Globais
- sao reconhecidas, ou seja, o escopo é todo o programa
2- Locais
- sao reconhecidas apenas no bloco onde foram declaradas
Para declarar variaveis:
nome_variavel = valor_variavel
"""
numero = 10
print(numero)
print(type(numero))
numero = "10"
print(numero)
print(type(numero))
#novo =0
numero = 11
if numero > 10:
novo = numero +5
print(novo)
#print(novo)<file_sep>/get-date.py
#!/usr/bin/python
import subprocess
import sys
command = subprocess.Popen(['date'])
print("Hello World", command)<file_sep>/pep8.py
"""
Comentarios no python 3 aspas duplas coemcandos 3 o final "
PEP8 - Python Enhancement proposal
São propostas de melhorias para a linguagem Python
The Zen of Python
import this
A ideia da PEP8 é que possamos escrever codigos Python de forma Pythonica
[1] Utilize Camel Case para nomes de classes;
class Calculadora:
pass
class CalculadoraCientifica:
pass
[2] Utilize nomes em minusculos, separados por underline para funcoes e variaves;
def soma():
pass
def soma_dois():
pass
numero = 4
[3] Utilize 4 espacoes para identacao
if 'a' in 'banana':
print('tem')
[4] Linhas em branco
- separar funcoes e definicoes com duas linhas em branco
- metodos dentro de uma classe devem ser separados com uma unica linha em branco
[5] Imports
- Imports devem ser seprados feitos em linhas separadas
class Classe:
pass
class Outra:
pass
# Import Errado
import sys, os
#Import Certo
import sys
import os
# Nao tem problemas em utilizar:
from types import StringType, ListType
#Caso tenha muitos imports de um mesmo pacote, recomenda se fazer:
from types import(
StringType,
ListType,
SetType,
OutroType
)
# imports devem ser colocados no topo do arquivo, logo depois de qualquer
# comentario ou docstrings e antes de constantes ou variaveis globais
# imports vao na primeira linha
#
[6] Espacos em expressoes e instrucoes
Nao faca:
funcao_algo( algo[ 1 ], { outro: 2 } )
faca:
funcao(algo[1], {outro: 2})
nao faca:
algo (1)
faca:
algo(1)
nao faca:
dict ['chave'] = lista [indice]
faca:
dict['chave'] = lista[indice]
nao fazer:
x = 1
y = 2
variavel_longa = 4
Python=
- string em python
- dir e help
- funcao
- classes
"""
from random import randrange, uniform
print(randrange(1, 60))
<file_sep>/03exercicio.py
"""
Tipo String
EM python, um dado é considerado do tipo string sempre que:
- Estive entre aspas, simples ou duplas -> "a" , 'a'
- Estiver entre aspas simples triplas -> '''a'''
nome = '<NAME>'
print(nome)
print(type(nome))
nome = "Marcelu's"
print(nome)
print(type(nome))
nome = 'Angelina \nJolie'
print(nome)
print(type(nome))
nome = "Marcelo"
print(nome.upper())
print(type(nome))
nome = "Marcelo"
print(nome.lower())
print(type(nome))
## transforma em uma lista de string
nome = '''Marcelo'''
print(nome.split())
print(nome[0:4]) #Slice de string
#transformo em uma lista de strings separados pelo espaco
nome = '<NAME>'
print(nome.split()[1])
# Uso pra escrever a string ao contrario - inversao da string
nome = 'Marcelo'
print(nome[::-1])
# Substituo a letra M por L
nome = 'Marcelo'
print(nome.replace('M' , 'L'))
# Substituo a letra M por L
texto = 'socorram me subino onibus em marrocos' #palindromo
print(texto)
print(texto[::-1])
"""
<file_sep>/07exercicio-loop_for.py
"""
Loop -> estrutura de repeticao
for é uma dessas estrutura
C ou Java
for (i=0; i <10; i++){
//instrucao
}
Python
for item in interavel:
//execucao do loop
Utilizamos loops para criar lacos de repeticao
Exemplo de iteraveis:
- string
nome = 'geek univesity'
- Lista:
list = [11, 12]
- Range
numero = range[1, 10]
"""
nome = '<NAME>'
lista = [1, 3, 5, 7, 9]
numeros = range(1, 10) #deve ser transformado em uma lista
#exemplo de for 1
for letra in nome:
print(letra)
#exemplo de for 2
for numero in lista:
print(numero)
#exemplo de for 3
for numero in range(1, 10):
print(numero) <file_sep>/using_input.py
name = input("Qual seu nome?")
print("Seu nome é:", name)
#quando quero usar meu dado que deram input na var para uma operaao que n user string preciso definir o tipo do dado
anything = float(input("Enter a number: "))
something = anything ** 2.0
print(anything, "to the power of 2 is", something) | 1b9dd2ff056e80734b8d5cd0d6f4d2c5b39fb8da | [
"Python"
] | 17 | Python | mnoskoski/scripts-template-python | 1a61f04276cc26e4602113fe37e482d9841378be | 95ba20f2571513893e0dc2b65288dc8e929bd9d7 |
refs/heads/master | <repo_name>thorerik/ets2mp_homepage<file_sep>/en/user.php
<?php
$lang = array(
'password' => array(
'reset_and_view' => 'Reset password and display it',
'reset_and_send' => 'Reset password and send it to the user',
'submit' => 'Submit',
'password_reset' => <PASSWORD>'s <PASSWORD>!",
'password_display' => 'Password has been reset, copy it from below. Remember to reset and send the password when done testing, DO NOT share the password',
'password_sent_to' => 'Password has been reset and sent to :email',
),
);
return $lang;<file_sep>/en/welcome.php
<?php
$lang = array(
// ---- Sliders ----
// Create Account Button Text
'slider_create_account' => 'Create Account',
// Points of text on second slider
'second_slider_point_1' => 'Thousands of players',
'second_slider_point_2' => 'Strong and Fair Administration Team',
'second_slider_point_3' => 'Dedicated Servers',
'second_slider_point_4' => 'Great Community',
'second_slider_point_5' => 'All that is missing is you!',
// ----
// ---- Download ----
// 'Get The Mod'
'download_header' => 'Get the mod',
// 'Mod Description'
'download_content' => "Installation is quick and easy. Register an account with us and link your steam account that has Euro Truck Simulator 2. Download, install, play. It's as easy as that! Within minutes you'll be trucking alongside thousands of other enthusiasts.",
// Download Button Text
'download_button' => 'Download Now',
// ----
// ---- Advantages ----
//Community Header
'community_header' => 'Great Community',
// Community Content
'community_content' => 'Join a very close-knit community that takes simulation to a whole other level.',
// Administration Header
'administration_header' => 'Dedicated Administration Team',
// Administration Content
'administration_content' => 'We have a strong team of 50+ members that help keep ets2mp running smoothly. There is always somebody online to assist with troubles you may have.',
// Features Header
'features_header' => 'Advanced Features',
// Features Content
'features_content' => "When we say multiplayer, we mean it! Avatars, Nicknames, Ingame Chat and more. We're always adding new features to improve the game experience.",
// ----
// ---- Testomonials ----
// Testomonial Header
'testomonial_header' => 'Hear what other players have to say!',
// Testomonial Content
'testomonial_content' => 'We get a lot of input from our players. And we listen! Here are a few of our favorite words sent to us.',
// ----
);
return $lang;
<file_sep>/README.md
Up to date informations about localization
===================
http://forum.ets2mp.com/index.php?/topic/132-localization-of-homepage/
ETS2MP Localization
===================
ETS2MP php files that contains translations to many languages. You can contribute your own language.
When my localization will be added to website?
===================
As soon as possible - I don't have time to check github every minute and update all localizations real time.
How to translate?
===================
1. Create a new branch and check it out
2. **Copy** the ```en``` folder to your ISO 639-1 shortcode (eg. Polish is pl, Norwegian Bokmål is nb, English is en, etc. these can be found on eg. wikipedia in the infobox on the side)
3. Translate all messages to your langauge keep this format:
```
'key' => 'message',
```
Sometimes you will encounter something like this:
```
'ban_too_new' => 'Please wait until :date UTC to create an appeal.',
```
In this case you should translate everything except ```:date``` this is a special keyword.
Other times you might encounter
```
'registration_body' => array(
'pre_link' => 'Already signed up? Click ',
'link' => 'Sign in',
'post_link' => 'to login to your account.',
),
```
this is used when there's a link in a sentence, you should only change the message in the pre_link, link and post_link parts, these appears before, inside and after the link.
Remember: Do not change key. Change only "message".
If you have more questions feel free to ask send them to me:
Have fun.
<file_sep>/en/auth.php
<?php
$lang = array(
/*
|--------------------------------------------------------------------------
| Auth Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the Authentication module
|
*/
'username' => 'Username',
'email' => 'Email',
'password' => '<PASSWORD>',
'confirm_password' => '<PASSWORD>',
'remember_me' => 'Remember Me',
'login_button' => 'Login',
'errors' => 'Registration failed',
'reset_password' => 'Send Password Reset Link',
'reset_button' => 'Reset Password',
'reset_header' => 'Password reset',
'registration' => 'Registration',
'registration_header' => 'Register a new account',
'registration_body' => array(
'pre_link' => 'Already signed up? Click ',
'link' => 'Sign in',
'post_link' => 'to login to your account.',
),
'register_button' => 'Register',
'login_head' => 'Login to your account',
'login_forgot_head' => 'Forgot your password?',
'login_forgot_body' => array(
'pre_link' => 'No worries, ',
'link' => 'click here',
'post_link' => ' to reset your password.'
),
);
return $lang;
<file_sep>/en/navbar.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Navigation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the navbar
|
*/
'search' => 'Search for a player…',
'home' => 'Home',
'forum' => 'Forum',
'admin' => 'Admin',
'reports' => 'Reports',
'appeals' => 'Appeals',
'me' => 'Me',
'profile' => 'Profile',
'settings' => 'Settings',
'login' => 'Login',
'logout' => 'Logout',
'register' => 'Register',
];<file_sep>/en/shared.php
<?php
$lang = array(
'errors' => 'Fix the below errors and try again',
);
return $lang;
<file_sep>/en/admin.php
<?php
$lang = array(
'group' => array(
'deleted' => 'Group deleted successfully!',
'name_header' => 'Group',
'member_count' => 'Member count',
'new_group_button' => 'New Group',
'group_not_empty_delete_button_tooltip' => 'You have to assign all members to another group before deleting',
'delete_button' => 'Delete',
'edit_button' => 'Edit',
'view_button' => 'View',
'modal_delete_header' => 'Are you sure?',
'modal_delete_body' => 'Are you sure you want to delete this group?',
'modal_cancel_button' => 'Cancel',
'modal_delete_button' => 'Delete',
'create_group_name' => 'Group Name',
'create_color' => 'Color',
'create_group_title' => 'Group Title',
'create_permission_level' => 'Permission Level',
'create_developer' => 'Developer',
'create_super_admin' => 'Super Admin',
'create_admin' => 'Admin',
'create_manager' => 'Manager',
'create_game_admin' => 'Game Admin',
'create_moderator' => 'Moderator',
'create_support' => 'Support',
'create_save_button' => 'Save',
'not_empty_error' => 'Group is not empty',
'edited' => 'Group successfully edited',
'view_user' => 'Username',
'back' => 'Back',
),
'index' => array(
'group_settings' => 'Group settings',
'system_logs' => 'System logs',
'reports' => 'Reports',
'appeals' => 'Appeals',
'find_user' => 'Find User',
),
'users' => array(
'username' => 'Username',
'group' => 'Group',
'view_link' => 'View'
),
);
return $lang;<file_sep>/en/ban.php
<?php
$lang = array(
'no_steam_id_header' => 'No Steam ID associated with account',
'no_steam_id_body' => 'You can\'t ban this user because they have not associated a steam account yet',
'steam_id' => 'Steam ID',
'expire' => 'Expiration time',
'save_button' => 'Save',
'permanent' => 'Permanent',
'timelimited' => 'Time Limited',
'reason' => 'Reason',
'active' => 'Active',
'user_banned' => 'User has been banned',
'ban_updated' => 'Ban has been updated',
'ban_deleted' => 'Ban has been deleted',
'modal_delete_header' => 'Are you sure?',
'modal_delete_body' => 'Are you sure you want to delete this ban?',
'modal_delete_button' => 'Delete',
'modal_cancel_button' => 'Cancel',
'ban_in_the_past_error' => 'Ban can not be in the past!',
'ban_reason_empty' => 'Ban reason can not be empty',
);
return $lang;<file_sep>/en/profile.php
<?php
$lang = array(
// Top of Profile page
'profile_header' => 'Profile options',
// Appears after successfully connecting a ETS 2:MP account with a steam account
'steam_association_success' => 'You have successfully associated a steam account!',
// Header of message displayed if you haven't attach a steam account to your ETS 2:MP account
'no_steam_id_header' => 'You have not associated a Steam ID, please click the button below to associate one now.',
// Body of message displayed if you haven't attach a steam account to your ETS 2:MP account
'no_steam_id_body' => 'You will not be able to play online without completing this step',
// Button in message displayed if you haven't attach a steam account to your ETS 2:MP account
'associate_steam_id_button' => 'Associate Steam ID now',
// Error message used when steam don't return any ETS 2 on an account attempted to be associated
'ets2_not_found' => 'We where unable to find Euro Truck Simulator 2 on your account, please ensure your profile is set to public',
// Error message if the steam account has been associated with another ETS 2:MP account
'already_associated' => 'Steam ID is already associated with an account',
// Appears on settings page above input field for changing username
'username' => 'Username',
// Appears on settings page, required for changing anything
'current_password' => '<PASSWORD> (<PASSWORD>)',
// Appears on settings page, only required if changing
'new_password' => '<PASSWORD> (leave blank if not changing)',
// Appears on settings page, only required if changing
'repeat_new_password' => '<PASSWORD> Password (leave blank if not changing)',
// Appears on settings page, saves settings
'save_button' => 'Save',
// Error message on settings page, wrong password
'incorrect_password' => '<PASSWORD>',
// Error message on settings page, Username taken
'username_taken' => 'Username taken, please choose a different username',
// Success message on settings page, changes saved
'changes_saved' => 'Changes saved',
// Appears above dropdown for theme
'theme' => 'Theme',
// Appears in dropdown for item Light theme
'light' => 'Light',
// Appears in dropdown for item Dark theme
'dark' => 'Dark',
);
return $lang;<file_sep>/en/appeals.php
<?php
$lang = array(
// Error message to user if they are banned from the system
'access_denied' => 'You have been banned from using the appeals system, please contact a Project Manager for more information',
// Error message if appeal has been decided upon and user attempts to submit a message to appeal
'closed' => 'Appeal has been closed and you can not comment on it anymore',
// Confirmation message to admin when accepting an appeal
'accepted' => 'Appeal accepted!',
// Confirmation message to admin when declining an appeal
'declined' => 'Appeal declined!',
// Header of page when editing a ban in response to appeal, place :reason where reason should appear and :username where the user's name should appear
'modified' => "Editing ban :reason for :username's appeal",
// Confirmation to admin when disabling appeals module access for a user
'disabled' => 'Appeals disabled for user',
// Confirmation to admin when enabling appeals module access for a user
'enabled' => 'Appeals enabled for user',
// Button for disabling appeals system for user
'disable_access' => 'Disable appeals system for user',
// Button for accepting appeal
'accept' => 'Accept',
// Button for modifying ban from appeal
'modify' => 'Modify',
// Button for declining appeal
'decline' => 'Decline',
// Label above comment box
'comment' => 'Comment',
// Label for dropdown for selecting comment visibility
'visibility' => 'Visibility of comment',
// Label for dropdown element
'public' => 'Public',
// Label for dropdown element
'private' => 'Private',
// Button for submitting comment
'submit_comment' => 'Submit comment',
// table header listing appeals
'ban_reason' => 'Ban Reason',
// table header listing appeals
'user' => 'User',
// table header listing appeals
'status' => 'Status',
// table header listing appeals
'updated' => 'Updated',
// Link for viewing appeal
'view_appeal' => 'View Appeal',
// Appears on top when user first creates an appeal
'ban_details' => 'Ban details',
// Appears during appealing a ban
'reason' => 'Reason',
// Appears during appealing a ban
'admin' => 'Admin',
// Appears during appealing a ban
'expires' => 'Expires',
// Label above comment field during appealing a ban
'explain' => 'Explain for us why you should be unbanned?',
// Button for submitting appeal
'submit' => 'Submit appeal',
// Link for creating appeal
'new_appeal' => 'Appeal this ban',
// Text if ban is too recent, don't change :date and include Timezone denotation UTC where appropriate
'ban_too_new' => 'Please wait until :date UTC to create an appeal.',
// Text if no bans present
'no_active_bans' => 'You got no active bans',
);
return $lang; | 0c843f7aea0e177d35ea3f4976f75ebe1986d8f5 | [
"Markdown",
"PHP"
] | 10 | PHP | thorerik/ets2mp_homepage | 9020368fc8b813b4c21fa1069115674873b8cbd6 | 3e05f0af24b6b30188c07349a08763f6bdd6354c |
refs/heads/master | <repo_name>NetalNandita/MyActitime<file_sep>/src/script/verifyInvalidLogin.java
package script;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import generic.BaseTest;
import pom.LoginPage;
public class verifyInvalidLogin extends BaseTest
{
@Test
public void testVerifyInvalidLogin()
{
SoftAssert s= new SoftAssert();
LoginPage l= new LoginPage(driver);
l.setUsername("abc");
l.setPassword("xyz");
l.clickOnLogin();
l.verifyErrIsPresent(s);
s.assertAll();
}
}
| 35b0fda24b6183548451c8cc4929ccbbd13e447f | [
"Java"
] | 1 | Java | NetalNandita/MyActitime | 671c00114a277c318d8914ea3bb2aac98101e992 | de97539888889fd4d61baa1efc9d511c29740faa |
refs/heads/master | <repo_name>hubject/winston-amazon-ses<file_sep>/lib/winston-amazon-ses.js
/*
* winston-amazon-ses.js: Transport for outputting logs to email using Amazon Simple Email Service (SES)
*
* (C) 2010 <NAME>
* MIT LICENCE
*/
var util = require('util');
var os = require('os');
var AmazonSES = require('amazon-ses');
var winston = require('winston');
var _ = require('underscore');
// Set Underscore to Mustache style templates
function template(text, obj) {
return _.template(text, obj, {
interpolate: /\{\{(.+?)\}\}/g
});
}
/**
* @constructs SES
* @param {object} options hash of options
*/
var SES = exports.SES = function(options) {
winston.Transport.call(this, options);
options = options || {};
if (!options.to) {
throw "winston-amazon-ses requires 'to' property";
}
if (!options.accessKey) {
throw "winston-amazon-ses requires 'accessKey' property";
}
if (!options.secretKey) {
throw "winston-amazon-ses requires 'secretKey' property";
}
this.name = 'ses';
this.to = _.flatten([options.to]);
this.from = options.from || "winston@" + os.hostname();
this.silent = options.silent || false;
this.label = options.label || 'winston';
this.subject = options.subject ? template(options.subject) : template(this.label + ": {{subject}}");
this.handleExceptions = options.handleExceptions || false;
this.server = new AmazonSES(options.accessKey, options.secretKey);
this.waitUntilSend = options.waitUntilSend || 0;
this.messageQueueLimit = options.messageQueueLimit || 500;
this.messageQueue = [];
};
/** @extends winston.Transport */
util.inherits(SES, winston.Transport);
/**
* Define a getter so that `winston.transports.MongoDB`
* is available and thus backwards compatible.
*/
winston.transports.SES = SES;
/**
* Core logging method exposed to Winston. Metadata is optional.
* @function log
* @member SES
* @param level {string} Level at which to log the message
* @param msg {string} Message to log
* @param [meta] {Object} **Optional** Additional metadata to attach
* @param [callback] {function} Continuation to respond to when complete.
*/
SES.prototype.log = function(level, msg, meta, callback) {
if (this.silent) return callback && callback(null, true);
this._push(msg, meta);
this._initSending();
this.emit('logged');
callback && callback(null, true);
};
/**
* Pushes logging message to queue
* @param level {string} Level at which to log the message
* @param msg {string} Message to log
* @param meta {Object} **Optional** Additional metadata to attach
* @private
*/
SES.prototype._push = function(level, msg, meta) {
this.messageQueue.push({level: level, msg: msg, meta: meta});
};
/**
* Clears message queue
* @private
*/
SES.prototype._clear = function() {
this.messageQueue.length = 0;
};
/**
* Sends all messages of the queue after specified delay (waitUntilSend) unless
* _initSending is called again
* @private
*/
SES.prototype._initSending = function() {
var self = this;
// send immediately if limit is reached
var waitUntilSend = this._isMessageQueueLimitReached() ? 0 : this.waitUntilSend;
clearTimeout(this.timeoutId);
this.timeoutId = setTimeout(function() {
var message = self._getFormattedMessages();
self.server.send({
from: this.from,
to: this.to,
subject: self.subject(message),
body: {
html: message.body
}
}, function(err) {
if(err) {
console.error(err);
self.emit('mail.error');
}
});
self._clear();
self.emit('mail.sending');
}, waitUntilSend);
};
/**
* Formats messages of queue to one subject and one body string
* @returns {{subject: string, body: string}}
* @private
*/
SES.prototype._getFormattedMessages = function() {
var preSubject = {};
var body = '';
this.messageQueue.forEach(function(message) {
var msg = message.msg;
var level = message.level;
var meta = message.meta;
body += msg + "<br />";
if (meta) {
body += ('<h3>Metadata</h3><p>' + util.inspect(meta, true, null) + '</p>');
if (meta.stack) {
meta.stack = (typeof meta.stack == 'object') ? util.inspect(meta.stack, true, null) : meta.stack;
body += ('<h3>Stack trace</h3><p>' + meta.stack.replace(/\n/g, '<br/>').replace(/\s/g, ' ') + '</p>');
}
}
body += '<br>---------------------------<br><br>';
var _subject = '(' + level + ') ' + msg;
preSubject[_subject] = (preSubject[_subject] || 0) + 1;
});
var subject = Object
.keys(preSubject)
.map(function(_subject) { return _subject + ' (' + preSubject[_subject] + ')' })
.join(', ')
;
return {subject: subject, body: body};
};
/**
* Returns true if message queue limit is reached
* @returns {boolean}
* @private
*/
SES.prototype._isMessageQueueLimitReached = function() {
return this.messageQueueLimit <= this.messageQueue.length;
};
<file_sep>/lib/winston-amazon-ses.d.ts
import {NPMLoggingLevel, TransportInstance} from "winston";
export const SES: SESTransportStatic;
export interface SESTransportStatic {
new(options: SESTransportOptions): TransportInstance
}
export interface SESTransportOptions {
to: string[];
from: string;
level?: NPMLoggingLevel;
silent?: boolean;
label?: string;
subject?: string;
accessKey: string;
secretKey: string;
waitUntilSend?: number;
messageQueueLimit?: number;
}<file_sep>/readme.md
# winston-amazon-ses [](http://travis-ci.org/jpgarcia/winston-amazon-ses) [ ](https://www.codeship.io/projects/1546)
A email transport for [winston][0] using Amazon Simple Email Service (SES) inspired in [winston-mail](https://github.com/wavded/winston-mail).
## Installation
### Installing npm (node package manager)
``` sh
$ curl http://npmjs.org/install.sh | sh
```
### Installing winston-amazon-ses
``` sh
$ npm install winston
$ npm install winston-amazon-ses
```
## Usage
``` js
var winston = require('winston');
//
// Requiring `winston-amazon-ses` will expose
// `winston.transports.SES`
//
require('winston-amazon-ses').SES;
winston.add(winston.transports.SES, options);
```
The SES transport uses [node-amazon-ses](https://github.com/jjenkins/node-amazon-ses.git) behind the scenes. Options are the following:
* __to:__ The address(es) you want to send to. *[required]*
* __accessKey__: AWS SES access key. *[required]*
* __secretKey__: AWS SES secret key. *[required]*
* __from:__ The address you want to send from. (default: `winston@[server-host-name]`)
* __subject__ Subject for email (default: winston: {{level}} {{msg}})
* __level:__ Level of messages that this transport should log.
* __silent:__ Boolean flag indicating whether to suppress output.
[0]: https://github.com/flatiron/winston<file_sep>/changelog.md
0.1.4 / 2013-02-19
==================
* show err.stack as string when typeof is object
0.1.3 / 2013-02-17
==================
* improved message formatting for errors in err object is provided as metadata
0.1.2 / 2013-02-17
==================
* fixed the missing body issue
0.0.1 / 2012-11-17
==================
* initial release
| ebc65085fc08c4be365c82b542d18f0d25effbbb | [
"JavaScript",
"TypeScript",
"Markdown"
] | 4 | JavaScript | hubject/winston-amazon-ses | f416da5ea14c04c85c206d9a9e85ccf17f556586 | 9f4b5c4ccfc9f6a537559e950c049a0abfe3f987 |
refs/heads/master | <file_sep>#include<stdio.h>
#include<stdlib.h>
static void malicious() __attribute__((constructor));
void malicious() {
system("some command");
}
// gcc -shared -o attack.so -fPIC attack.c
// go get github.com/qweraqq/CVE-2018-6574
| a82fbedc150e03032af9e4d12cce7a779d743939 | [
"C"
] | 1 | C | qweraqq/CVE-2018-6574 | eecf9bc9bbc743c9442da971e9e822d1897a8cce | def90853b048269839ce6fa5c7ba6c658cdd9347 |
refs/heads/master | <repo_name>jjdredd/obj_detect<file_sep>/paths_import.sh
#! /bin/bash
export PYTHONPATH=$PYTHONPATH:"/home/ragim/source/models/research/":"/home/ragim/source/models/research"/slim
<file_sep>/main.py_odl
#! /usr/bin/env python3
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from object_detection.utils import ops as utils_ops
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
MODEL_NAME = 'ssd_mobilenet_v1_coco_2018_01_28'
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')
NUM_CLASSES = 90
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(
label_map, max_num_classes = NUM_CLASSES, use_display_name = True)
category_index = label_map_util.create_category_index(categories)
# Load the Tensorflow model into memory.
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name ='')
sess = tf.Session(graph = detection_graph)
# Define input and output tensors (i.e. data) for the object detection classifier
# Input tensor is the image
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Output tensors are the detection boxes, scores, and classes
# Each box represents a part of the image where a particular object was detected
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represents level of confidence for each of the objects.
# The score is shown on the result image, together with the class label.
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
# Number of objects detected
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
image = Image.open(image_path)
image_expanded = load_image_into_numpy_array(image)
# Perform the actual detection by running the model with the image as input
(boxes, scores, classes, num) = sess.run(
[detection_boxes, detection_scores, detection_classes, num_detections],
feed_dict ={image_tensor: image_expanded})
# Draw the results of the detection (aka 'visualize the results')
vis_util.visualize_boxes_and_labels_on_image_array(
image,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
category_index,
use_normalized_coordinates = True,
line_thickness = 8,
min_score_thresh = 0.60)
plt.figure(figsize=IMAGE_SIZE)
plt.imshow(image_np)
<file_sep>/main.py
#! /usr/bin/env python3
# https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from object_detection.utils import ops as utils_ops
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
# patch tf1 into `utils.ops`
utils_ops.tf = tf.compat.v1
# Patch the location of gfile
tf.gfile = tf.io.gfile
def run_inference_for_single_image(model, image):
image = np.asarray(image)
# The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
input_tensor = tf.convert_to_tensor(image)
# The model expects a batch of images, so add an axis with `tf.newaxis`.
input_tensor = input_tensor[tf.newaxis,...]
# Run inference
output_dict = model(input_tensor)
# All outputs are batches tensors.
# Convert to numpy arrays, and take index [0] to remove the batch dimension.
# We're only interested in the first num_detections.
num_detections = int(output_dict.pop('num_detections'))
output_dict = {key:value[0, :num_detections].numpy()
for key,value in output_dict.items()}
output_dict['num_detections'] = num_detections
# detection_classes should be ints.
output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)
# Handle models with masks:
if 'detection_masks' in output_dict:
# Reframe the the bbox mask to the image size.
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
output_dict['detection_masks'], output_dict['detection_boxes'],
image.shape[0], image.shape[1])
detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5,
tf.uint8)
output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy()
return output_dict
def show_inference(model, image_path):
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = np.array(Image.open(image_path))
# Actual detection.
output_dict = run_inference_for_single_image(model, image_np)
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
output_dict['detection_boxes'],
output_dict['detection_classes'],
output_dict['detection_scores'],
category_index,
instance_masks=output_dict.get('detection_masks_reframed', None),
use_normalized_coordinates=True,
line_thickness=8)
plt.figure()
plt.imsave(image_path + '_det_1.png', image_np)
# plt.imshow(image_np)
MODEL_NAME = 'ssd_mobilenet_v1_coco_2018_01_28'
MODEL_NAME = 'faster_rcnn_inception_v2_coco_2018_01_28'
MODEL_NAME = 'faster_rcnn_resnet50_coco_2018_01_28'
PATH_TO_MODELF = MODEL_NAME + '/saved_model'
PATH_TO_LABELS = ("/home/ragim/source/models/"
"research/object_detection/data/mscoco_label_map.pbtxt")
NUM_CLASSES = 90
print ("loading model ", MODEL_NAME)
model = tf.saved_model.load(PATH_TO_MODELF)
model = model.signatures['serving_default']
detection_model = model
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS,
use_display_name=True)
PATH_TO_TEST_IMAGES_DIR = "/home/ragim/progs/python/obj_detect/test_images/"
TEST_IMAGE_PATHS = [
PATH_TO_TEST_IMAGES_DIR + 'image1.jpg',
PATH_TO_TEST_IMAGES_DIR + 'image2.jpg'
]
for image_path in TEST_IMAGE_PATHS:
print ("infering ", image_path)
show_inference(detection_model, image_path)
<file_sep>/create_trecord.py
#! /usr/bin/env python3
from xml.etree import cElementTree as ElementTree
import glob
import tensorflow as tf
from object_detection.utils import dataset_util
import os
import io
from PIL import Image
annotations_dir = 'prepare_data'
image_dir = 'prepare_data'
output_dir = 'prepare_data'
output_path = os.path.join(output_dir, 'train.tfrecord')
def create_tfrecord(data_dict):
"""creating tfrecord from a dict with all needed data"""
with tf.io.gfile.GFile(os.path.join(image_dir, data_dict['image']), 'rb') as fid:
encoded_jpg = fid.read()
encoded_jpg_io = io.BytesIO(encoded_jpg)
image = Image.open(encoded_jpg_io)
width, height = image.size
filename = data_dict['image'].encode('utf8')
image_format = b'png'
xmins = []
xmaxs = []
ymins = []
ymaxs = []
for i in range(len(data_dict['names'])):
xmins.append(data_dict['xmins'][i] / width)
xmaxs.append(data_dict['xmaxs'][i] / width)
ymins.append(data_dict['ymins'][i] / height)
ymaxs.append(data_dict['ymaxs'][i] / height)
tf_example = tf.train.Example(features=tf.train.Features(feature={
'image/height': dataset_util.int64_feature(height),
'image/width': dataset_util.int64_feature(width),
'image/filename': dataset_util.bytes_feature(filename),
'image/source_id': dataset_util.bytes_feature(filename),
'image/encoded': dataset_util.bytes_feature(encoded_jpg),
'image/format': dataset_util.bytes_feature(image_format),
'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
'image/object/class/text': dataset_util.bytes_list_feature(data_dict['names']),
'image/object/class/label': dataset_util.int64_list_feature(data_dict['labels']),
}))
return tf_example
def parse_pascal_xml(fname, labelmap):
"""parse xml annotation in pascal format"""
data_dict = {}
root = ElementTree.parse(fname).getroot()
data_dict['image'] = root.find('filename').text
data_dict['width'] = int(root.find('size').find('width').text)
data_dict['height'] = int(root.find('size').find('height').text)
data_dict['depth'] = int(root.find('size').find('depth').text)
data_dict['names'] = []
data_dict['labels'] = []
data_dict['xmins'] = []
data_dict['ymins'] = []
data_dict['xmaxs'] = []
data_dict['ymaxs'] = []
for obj in root.findall('object'):
data_dict['names'].append(obj.find('name').text.encode('utf8'))
data_dict['labels'].append(labelmap[obj.find('name').text])
data_dict['xmins'].append(int(obj.find('bndbox').find('xmin').text))
data_dict['ymins'].append(int(obj.find('bndbox').find('ymin').text))
data_dict['xmaxs'].append(int(obj.find('bndbox').find('xmax').text))
data_dict['ymaxs'].append(int(obj.find('bndbox').find('ymax').text))
return(data_dict)
def main():
labelmap = {'mexpr' : 1}
writer = tf.io.TFRecordWriter(output_path)
for fname in glob.iglob(os.path.join(annotations_dir, '*.xml')):
print("adding", fname)
tfr = create_tfrecord(parse_pascal_xml(fname, labelmap))
writer.write(tfr.SerializeToString())
writer.close()
if __name__ == '__main__':
main()
| 77e05844fc49ad804340e2be301602e818ae4a6b | [
"Python",
"Shell"
] | 4 | Shell | jjdredd/obj_detect | 55abc063339f5cc97263cea02773ef189f47c4f2 | d2c497e38280d9fa7b2bb5a8b9f7871dbdcc0d56 |
refs/heads/master | <file_sep>#!/bin/bash -e
moboot=uImage.moboot_0.3.8
kernel=uImage.Fedora
cat <<EOF
This script installs moboot and kernel. The moboot src can be had at:
git://github.com/jcsullins/moboot.git
And the kernel:
git://github.com/freedreno/kernel-msm.git
branch: hp-tenderloin-3.0
use tenderloin_rob_defconfig
Note that kernel uImage is not a normal uImage, but has has ramdisk
embedded. It can be created with mkimage:
mkimage -A arm -O linux -T multi -a 0x40208000 -e 0x40208000 -C none -n "multi image" -d arch/arm/boot/uImage:uRamdisk uImage.Fedora
EOF
# Put the files we'll need in /tmp
novacom put file:///tmp/$moboot < boot/$moboot
novacom put file:///tmp/$kernel < boot/$kernel
novacom put file:///tmp/moboot.background.tga < boot/moboot.background.tga
# we can't very easily do interactive cmds w/ novacom, so instead we
# build up a shell script to run to do what we want on the device:
novacom put file:///tmp/do-setup-boot.sh <<EOF
#!/bin/sh -e
echo "Mount boot writable."
mount -o rw,remount /boot
echo "Install moboot."
mv /tmp/$moboot /boot/uImage.moboot
cd /boot
rm uImage
ln -s uImage.moboot uImage
# setup symlink so moboot gives user a boot-to-webos option:
rm -f uImage.webOS
ln -s uImage-2.6.35-palm-tenderloin uImage.webOS
# install moboot theme/background:
mv /tmp/moboot.background.tga /boot/moboot.background.tga
mv /tmp/$kernel /boot/$kernel
echo "yes" > moboot.verbose.${kernel##uImage\.} sync
cd /tmp
sync
echo "Mount boot read-only."
mount -o ro,remount /boot
echo "Done!"
EOF
novacom run file:///bin/chmod 755 /tmp/do-setup-boot.sh
novacom run file:///tmp/do-setup-boot.sh
<file_sep># Installing Fedora F18 on HP Touchpad
1. Put device in developer mode (if not done already), by typing **webos20090606** or **upupdowndownleftrightleftrightbastart** in the "Just Type" text box, and launch the developer-mode app. You turn it on and your device should be in developer mode. If it requests a password you may just press submit.
2. Install novacom on your host desktop/laptop:
* if your host is fedora, `sudo yum install novacom`.. and then `sudo novacomd` to launch the server.
* From there, you can use `novaterm` command to connect to the device or `novacom` to transfer files.
3. Install adb on your host.. you will need this later
* for fedora, `sudo yum install android-tools`
* if you get permission errors when adb tries to spawn the server, `adb kill-server` and then `sudo adb start-server`
3. run: ./create-partition.sh _size_
* for example on a 32GB device if you want to create a 20GB linux partition:
`./create-partition.sh 20480`
* this step can take quite a while
4. run: ./install-boot.sh
this will install moboot bootloader and kernel
5. run: ./install-rootfs.sh
this will install the root filesystem, and then reboot.
6. At the moboot screen, use the volume rocker switch to select whether to boot webOS or fedora
7. Once fedora has booted, you can use `adb shell` to connect to the device.
* `export TERM=xterm` and `/usr/bin/resize` to get a semi-sane console
8. rndis is enabled, so you should see a new wired connection in network manager. To allow network access over usb/adb, in network manager IPv4 settings, select: Method: Shared to other computers
* at this point, you could enable sshd in order to connect to the touchpad over ssh
## TODO:
- [ ] wifi patch: https://github.com/TouchpadCM/compat-wireless-3.3-rc1-2/commit/4f92acb42c210e08ff20853d82afdacf7da28354
- [x] touchscreen
- [ ] gnome-shell
- [ ] re-enable android ram-console in kernel config.. it is quite useful for debugging crashes, but seems to be causing some memory corruption itself
## Teh Codez
* kernel: git://github.com/freedreno/kernel-msm.git
* branch: hp-tenderloin-3.0
* use tenderloin_rob_defconfig
* ts_srv: git://github.com/freedreno/ts_srv_tenderloin.git
<file_sep>#!/bin/bash
echo "Mount rootfs."
novacom run "file:///bin/mkdir -p /tmp/linux"
novacom run "file:///bin/mount /dev/store/fedora-root /tmp/linux"
for f in rootfs/*.tar.gz; do
echo "Extracting: $f"
novacom run "file:///bin/tar -C /tmp/linux -xvzf -" < $f
done
echo "Unmounting rootfs."
novacom run "file:///bin/sync"
novacom run "file:///bin/umount /tmp/linux"
echo "Rebooting."
novacom run "file:///bin/reboot"
<file_sep>#!/bin/bash -e
partition_size=$1
if [ "x" = "x$partition_size" ] || ! [[ "$partition_size" =~ ^[0-9]+$ ]]; then
echo "usage: $0 <partition_size>"
echo "creates a <partition_size>MB partition"
exit 1
fi
# we can't very easily do interactive cmds w/ novacom, so instead we
# build up a shell script to run to do what we want on the device:
novacom put file:///tmp/do-resize-partition.sh <<EOF
#!/bin/sh -e
PARTITION=$partition_size
echo "Creating \${PARTITION}MB partition"
CURRENTSIZE=\$(lvm.static lvdisplay -c store/media | awk -F: '{print \$7/2048}')
NEWSIZE=\$((\$CURRENTSIZE - \$PARTITION))
echo "Your new partition layout will include a \${PARTITION}MB ext3 partition and a \${NEWSIZE}MB media partition."
echo "Does this seem correct? If so, type y, if not, type n."
read OK
if [ \$OK == "y" ];
then echo "Ok, continuing."
else
echo "Goodbye."
exit
fi
echo "Repartition to create ext3 volume for Fedora."
pkill -SIGUSR1 cryptofs
umount /media/internal
echo "Now resizing your media partition and creating the ext3 partition for Fedora"
resizefat /dev/store/media \${NEWSIZE}M
lvresize -f -L -\${PARTITION}M /dev/store/media
lvcreate -L \${PARTITION}M -n fedora-root store
mkfs.ext3 /dev/store/fedora-root
sync
# Possibly we don't actually have to reboot here..
echo "Rebooting..."
reboot
EOF
novacom run file:///bin/chmod 755 /tmp/do-resize-partition.sh
novacom run file:///tmp/do-resize-partition.sh
| 79d8b79616c9e2e255a096ea391aaa68c4df7da3 | [
"Markdown",
"Shell"
] | 4 | Shell | freedreno-zz/touchpad-fedora | ce8506c8632a054b51156548dc74ed500dad237b | 1aa7d8efb6a8863df69f1328658c4b81e3983fee |
refs/heads/master | <repo_name>Godvolf/Asystent<file_sep>/Asystent/src/ChatModule.jsx
import React, { useState, useEffect } from 'react';
import ChatBox from 'react-chat-plugin';
import axios from 'axios';
import './styles.css';
export default function ChatModule () {
const [user, setUser] = useState({token: undefined, user_id: undefined})
const [messages, setMessages] = useState([
{
text: 'Połączyłeś się z Asystentem Żywieniowym',
timestamp: 1578366389250,
type: 'notification',
}
]);
const handleRequestCard = (res) => {
setMessages( m =>
m.concat({
author: { username: 'Digital Assistant', id: 2, avatarUrl: 'https://image.flaticon.com/icons/svg/2446/2446032.svg' },
text: createCardContent(res.data[0].body),
type: 'text',
timestamp: +new Date(),
})
)
}
const createCardContent = (data) => {
return (
<div>
<div className="card-title">{data.title_id}</div>
<div className="card-desc">{data.description}</div>
<div className="card-link">Recipe: <a href={data.link}>{data.link}</a></div>
<img src={data.img} alt={data.title_id}></img>
</div>
)
}
const handleRequestMessage = (res) => {
setMessages( m =>
m.concat({
author: { username: 'Digital Assistant', id: 2, avatarUrl: 'https://image.flaticon.com/icons/svg/2446/2446032.svg' },
text: res.data[0].body.message,
type: 'text',
timestamp: +new Date(),
})
)
}
useEffect(() => {
let config = {
header: 'Content-Type: application/json'
}
let data = {}
axios.post(`http://192.168.3.11:8080/auth`, data, config).then(res => {
setUser(res.data);
});
}, []);
useEffect(() => {
if (user.token) {
let config = {
headers: {
'Authorization': 'Bearer ' + user.token,
'Content-Type': 'application/json'
}
}
let data = {
"type": "message",
"body": {
"message": "init request"
}
}
axios.post(`http://192.168.3.11:8080/add_event`, data, config)
.then(res => {
setMessages( m =>
m.concat({
author: { username: 'Digital Assistant', id: 2, avatarUrl: 'https://image.flaticon.com/icons/svg/2446/2446032.svg' },
text: res.data[0].body.message,
type: 'text',
timestamp: +new Date(),
})
)
})
}
}, [user])
const handleOnSendMessage = (message) => {
setMessages( m =>
m.concat({
author: {
username: 'User',
id: 1,
},
text: message,
timestamp: +new Date(),
type: 'text',
})
);
if (user.token) {
let config = {
headers: {
'Authorization': 'Bearer ' + user.token,
'Content-Type': 'application/json'
}
}
let data = {
"type": "message",
"body": {
"message": message
}
}
axios.post(`http://192.168.3.11:8080/add_event`, data, config)
.then(res => {
if (res.data[0].type === 'message') {
handleRequestMessage(res);
} else if (res.data[0].type === 'card') {
handleRequestCard(res);
}
})
}
};
return (
<div className="main-container">
<div className="chatbox-container">
<ChatBox
messages={messages}
userId={1}
onSendMessage={handleOnSendMessage}
width={'800px'}
height={'89vh'}
/>
</div>
</div>
);
} | 8ffe9fb2a3477ad2c2ad75f176cf8f4cc70ea3ba | [
"JavaScript"
] | 1 | JavaScript | Godvolf/Asystent | 9e9bb4be64a7d55d8e17cb203aaa28fee07ad66f | 551ebad27d141867a9f0d5ee6448dd04c42e37fb |
refs/heads/master | <repo_name>aclemons/photographers-notebook<file_sep>/Photographers/src/unisiegen/photographers/model/Camera.java
package unisiegen.photographers.model;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* Created by aboden on 16.07.14.
*/
@XStreamAlias("camera")
public class Camera {
public String name;
public int value;
public int def;
public Camera(String name, int value, int def) {
this.name = name;
this.value = value;
this.def = def;
}
public Camera() {
// Empty constructor needed for XStream Library.
}
}
<file_sep>/Photographers/docs/Datamodel-2.sql
/* Drop Tables */
DROP TABLE [CameraLensCombination];
DROP TABLE [Photo];
DROP TABLE [Filmroll];
DROP TABLE [Setting];
DROP TABLE [GearSet];
/* Create Tables */
CREATE TABLE [CameraLensCombination]
(
[ID] integer NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT,
[CameraID] integer,
[LensID] integer
);
-- For every roll of film, that a user loads into a camera, he can add one of those. Filmrolls will be displayed in the FilmSelectActivity. A Filmroll consists of details as ASA, Make, Name, Load and unload date and development information. Related to a Filmroll are several Pictures.
CREATE TABLE [Filmroll]
(
[ID] integer NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT,
-- War "Titel"
[Title] text,
-- Date of creation of this entry
--
-- Datatype: Date
--
--
[CreatedDate] text,
[InsertedInCamera] text,
[RemovedFromCamera] text,
-- TODO: Should we create a link to an equipemt table or copy the camera namefrom there. (Second solution is better, if a camera was deleted; first reduces data doubling).
--
-- Was: "Kamera"
--
[Camera] text,
-- A user defined field to enter maker and type of the roll of film.
--
-- Was: "Filmbezeichnung"
[FilmMakerType] text,
-- Type of Film and emulsion: e.g. slide, negativ, b/w, color...
[FilmType] text,
-- Format/size of the film (e.g. 24x36mm, 6x6, 6x9)
--
[FilmFormat] text,
-- ASA/ISO of this roll of film
[ASA] text,
[SpecialDevelopment1] text,
[SpecialDevelopment2] text
);
CREATE TABLE [GearSet]
(
[ID] integer NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT,
[SetName] text,
[SetDescription] text
);
-- Every Filmroll is a container for several Pictures. Each Picture contains information such as the Date of the exposure, Shutterspeed and Aperture, Fokus and Measureing Method and maybe a Note do describe the Picture or scene.
CREATE TABLE [Photo]
(
[ID] integer NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT,
[FilmRollID] integer NOT NULL UNIQUE,
[PhotoNumber] integer,
-- Date: When was this picture taken?
--
[ExposureDate] text,
[Lens] text,
[Aperture] text,
[ShutterSpeed] text,
[FocusDistance] text,
[Filter] text,
[Makro] text,
-- TODO: Rename
--
[FilterVF] text,
-- TODO: rename
[MakroVF] text,
[Flash] text,
[FlashCorrection] text,
[ExposureMeasureMethod] text,
[ExporuseMeasureCorrection] text,
[Note] text,
[longitude] text,
[latitude] text,
FOREIGN KEY ([FilmRollID])
REFERENCES [Filmroll] ([ID])
);
CREATE TABLE [Setting]
(
[ID] integer NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT,
[GearSetID] integer NOT NULL UNIQUE,
-- Examples for a Type are: Camera, Lens, Fokus, etc. Basically, everything type of setting, we had a single table for, previously.
[SettingType] text,
[SettingName] text,
[IsDisplayed] integer,
[IsDefaultSelection] integer,
[ID] integer NOT NULL UNIQUE,
FOREIGN KEY ([GearSetID])
REFERENCES [GearSet] ([ID]),
FOREIGN KEY ([ID])
REFERENCES [Setting] ([ID])
);
<file_sep>/Photographers/src/unisiegen/photographers/helper/DefaultLocationListener.java
/* Copyright (C) 2012 <NAME>, <NAME>, <NAME> (Committers)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unisiegen.photographers.helper;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
public class DefaultLocationListener implements LocationListener {
Location last;
public void onLocationChanged(Location location) {
last = location;
Log.v("GPS", "New Location: " + location);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public Location getLast() {
return last;
}
public void setLast(Location last){
this.last = last;
}
}<file_sep>/Photographers/src/unisiegen/photographers/database/DataSource.java
package unisiegen.photographers.database;
import java.util.ArrayList;
import unisiegen.photographers.model.Bild;
import unisiegen.photographers.model.Film;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class DataSource {
private SQLiteDatabase database;
private PnDatabaseOpenHelper dbHelper;
private static DataSource instance;
private DataSource(Context context) {
// for debugging purposes
/*
if (context.deleteDatabase("pn_data")) {
Log.v("DB", "Old pn_data database removed.");
} else {
Log.v("DB", "ATTENTION: Old pn_data database could not be removed.");
}
*/
// for debugging purposes
if (dbHelper == null) {
dbHelper = new PnDatabaseOpenHelper(context);
}
if (database == null) {
database = dbHelper.getWritableDatabase();
}
}
public static DataSource getInst(Context context) {
if (instance == null) {
instance = new DataSource(context);
}
return instance;
}
public void close() {
if (database != null) {
database.close();
}
dbHelper.close();
}
// TODO: Move to List instead of ArrayList?
public ArrayList<Film> getFilms() {
Cursor filmC = database.query(PnDatabaseOpenHelper.TABLE_FILMROLL,
null, null, null, null, null, null);
ArrayList<Film> result = parseFilmsFromCursor(filmC);
return result;
}
public Film getFilm(String title) {
Cursor cursor = database.query(PnDatabaseOpenHelper.TABLE_FILMROLL, null, PnDatabaseOpenHelper.COLUMN_TITLE + " == ?",
new String[]{title}, null, null, null);
ArrayList<Film> result = parseFilmsFromCursor(cursor);
if(result.size() != 1){
// TODO: There is a Problem...
Log.v("DATA_SOURCE", "While Querying for a FilmRoll Title, more than one element was returned: There are duplicates in the Database.");
return null;
}
return result.get(0);
}
private ArrayList<Film> parseFilmsFromCursor(Cursor c) {
ArrayList<Film> result = new ArrayList<Film>();
if (c != null && c.moveToFirst()) {
do {
Film film = new Film();
film.Bilder = new ArrayList<Bild>();
film.ID = c.getInt(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_ID));
film.Titel = c.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_TITLE));
film.Datum = c
.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_CREATEDDATE));
film.Empfindlichkeit = c.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_ASA));
film.Filmbezeichnung = c
.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_FILMMAKERTYPE));
film.Filmformat = c
.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_FILMFORMAT));
film.Filmtyp = c.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_FILMTYPE));
film.Kamera = c.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_CAMERA));
film.Pics = "0"; // TODO: Count that manually
film.Sonderentwicklung1 = c
.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_SPECIALDEVELOPMENT1));
film.Sonderentwicklung2 = c
.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_SPECIALDEVELOPMENT2));
result.add(film);
int filmRollID = c.getInt(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_ID));
film.Bilder = getPhotosForFilm(filmRollID);
film.Pics = String.valueOf(film.Bilder.size());
} while (c.moveToNext());
}
return result;
}
private ArrayList<Bild> getPhotosForFilm(int filmRollID) {
Cursor c = database.query(PnDatabaseOpenHelper.TABLE_PHOTO, null,
PnDatabaseOpenHelper.COLUMN_FILMROLLID + " == ?",
new String[] { String.valueOf(filmRollID) }, null, null, null);
ArrayList<Bild> result = new ArrayList<Bild>();
if (c.moveToFirst()) {
do {
Bild bild = new Bild();
bild.ID = c.getInt(c.getColumnIndex(PnDatabaseOpenHelper.COLUMN_ID));
bild.Bildnummer = c
.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_PHOTONUMBER));
bild.Belichtungskorrektur = c
.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_EXPORUSEMEASURECORRECTION));
bild.Blende = c.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_APERTURE));
bild.Blitz = c.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_FLASH));
bild.Blitzkorrektur = c
.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_FLASHCORRECTION));
bild.Filter = c.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_FILTER));
bild.FilterVF = c.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_FILTERVF));
bild.Fokus = c
.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_FOCUSDISTANCE));
bild.GeoTag = ""; // TODO!!!!
// bild.KameraNotiz =
// c.getString(c.getColumnIndex(PnDatabaseOpenHelper.COLUMN_));
bild.Makro = c.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_MAKRO));
bild.MakroVF = c.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_MAKROVF));
bild.Messmethode = c
.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_EXPOSUREMEASUREMETHOD));
bild.Notiz = c.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_NOTE));
bild.Objektiv = c.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_LENS));
bild.Zeit = c
.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_SHUTTERSPEED));
bild.Zeitstempel = c
.getString(c
.getColumnIndex(PnDatabaseOpenHelper.COLUMN_EXPOSUREDATE));
result.add(bild);
} while (c.moveToNext());
}
return result;
}
public void updateFilm(Film film){
ContentValues updateValues = new ContentValues();
updateValues.put(PnDatabaseOpenHelper.COLUMN_FILMMAKERTYPE, film.Filmbezeichnung);
updateValues.put(PnDatabaseOpenHelper.COLUMN_CAMERA, film.Kamera);
updateValues.put(PnDatabaseOpenHelper.COLUMN_FILMFORMAT, film.Filmformat);
updateValues.put(PnDatabaseOpenHelper.COLUMN_ASA, film.Empfindlichkeit);
updateValues.put(PnDatabaseOpenHelper.COLUMN_FILMTYPE, film.Filmtyp);
updateValues.put(PnDatabaseOpenHelper.COLUMN_SPECIALDEVELOPMENT1, film.Sonderentwicklung1);
updateValues.put(PnDatabaseOpenHelper.COLUMN_SPECIALDEVELOPMENT2, film.Sonderentwicklung2);
database.update(PnDatabaseOpenHelper.TABLE_FILMROLL, updateValues, PnDatabaseOpenHelper.COLUMN_ID + "=" + film.ID, null);
}
public void deleteFilm(String titel) {
Film tempFilm = getFilm(titel);
if(tempFilm == null){
// Log an error
return;
}
int deletedPhotos = database.delete(PnDatabaseOpenHelper.TABLE_PHOTO, PnDatabaseOpenHelper.COLUMN_FILMROLLID + " == ?", new String []{ String.valueOf(tempFilm.ID)});
int deletedFilms = database.delete(PnDatabaseOpenHelper.TABLE_FILMROLL, PnDatabaseOpenHelper.COLUMN_ID + " == ?", new String []{ String.valueOf(tempFilm.ID)});
Log.v("DB", String.format("Deleted film: %s from database. %d Photos were remove, %d Films were removed.",
tempFilm.Titel, deletedPhotos, deletedFilms));
}
public void deletePhoto(Bild photo) {
int deletedPhotos =
database.delete(PnDatabaseOpenHelper.TABLE_PHOTO,
PnDatabaseOpenHelper.COLUMN_ID + " == ?",
new String []{ String.valueOf(photo.ID)});
Log.v("DB", String.format("Deleted photo: %d from database. %d photos deleted", photo.ID, deletedPhotos));
}
public boolean isFilmTitleTaken(String titleToTest){
return getFilm(titleToTest) != null ? true : false;
}
private ContentValues convertPhotoToContentValues(Film film, Bild photo){
ContentValues contentValues = new ContentValues();
contentValues.put(PnDatabaseOpenHelper.COLUMN_FILMROLLID, film.ID);
contentValues.put(PnDatabaseOpenHelper.COLUMN_PHOTONUMBER, photo.Bildnummer);
contentValues.put(PnDatabaseOpenHelper.COLUMN_EXPORUSEMEASURECORRECTION, photo.Belichtungskorrektur);
contentValues.put(PnDatabaseOpenHelper.COLUMN_APERTURE, photo.Blende);
contentValues.put(PnDatabaseOpenHelper.COLUMN_FLASH, photo.Blitz);
contentValues.put(PnDatabaseOpenHelper.COLUMN_FLASHCORRECTION, photo.Blitzkorrektur);
contentValues.put(PnDatabaseOpenHelper.COLUMN_FILTER, photo.Filter);
contentValues.put(PnDatabaseOpenHelper.COLUMN_FILTERVF, photo.FilterVF);
contentValues.put(PnDatabaseOpenHelper.COLUMN_FOCUSDISTANCE, photo.Fokus);
// Geotag
contentValues.put(PnDatabaseOpenHelper.COLUMN_MAKRO, photo.Makro);
contentValues.put(PnDatabaseOpenHelper.COLUMN_MAKROVF, photo.MakroVF);
contentValues.put(PnDatabaseOpenHelper.COLUMN_EXPOSUREMEASUREMETHOD, photo.Messmethode);
contentValues.put(PnDatabaseOpenHelper.COLUMN_NOTE, photo.Notiz);
contentValues.put(PnDatabaseOpenHelper.COLUMN_LENS, photo.Objektiv);
contentValues.put(PnDatabaseOpenHelper.COLUMN_SHUTTERSPEED, photo.Zeit);
contentValues.put(PnDatabaseOpenHelper.COLUMN_EXPOSUREDATE, photo.Zeitstempel);
return contentValues;
}
public void addPhoto(Film film, Bild photo){
long rowID = database.insert(PnDatabaseOpenHelper.TABLE_PHOTO, null, convertPhotoToContentValues(film, photo));
Log.v("DB", String.format("Added a new photo. ID of the new row is %d.", rowID));
}
public void updatePhoto(Film film, Bild photo){
if(photo.ID == 0){
Log.v("DB", String.format("Trying to update a photo that has no ID. Will probably break."));
}
int updatedRows = database.update(PnDatabaseOpenHelper.TABLE_PHOTO, convertPhotoToContentValues(film, photo),
PnDatabaseOpenHelper.COLUMN_ID + "=?", new String[] {String.valueOf(photo.ID)});
Log.v("DB", String.format("Updated photo " + photo.ID + ". %d rows updated.", updatedRows));
}
public long addFilm(Film film) {
// check if film does exist already
if(isFilmTitleTaken(film.Titel)){
return -1;
}
ContentValues values = new ContentValues();
//values.put(PnDatabaseOpenHelper.COLUMN_FILMROLLID, film.ID);
values.put(PnDatabaseOpenHelper.COLUMN_TITLE, film.Titel);
values.put(PnDatabaseOpenHelper.COLUMN_CREATEDDATE, film.Datum);
values.put(PnDatabaseOpenHelper.COLUMN_INSERTEDINCAMERA, "");
values.put(PnDatabaseOpenHelper.COLUMN_REMOVEDFROMCAMERA, "");
values.put(PnDatabaseOpenHelper.COLUMN_CAMERA, film.Kamera);
values.put(PnDatabaseOpenHelper.COLUMN_FILMMAKERTYPE, film.Filmbezeichnung); // check if this is what you expect it to be
values.put(PnDatabaseOpenHelper.COLUMN_FILMTYPE, film.Filmtyp);
values.put(PnDatabaseOpenHelper.COLUMN_FILMFORMAT, film.Filmformat);
values.put(PnDatabaseOpenHelper.COLUMN_ASA, film.Empfindlichkeit);
values.put(PnDatabaseOpenHelper.COLUMN_SPECIALDEVELOPMENT1, film.Sonderentwicklung1);
values.put(PnDatabaseOpenHelper.COLUMN_SPECIALDEVELOPMENT2, film.Sonderentwicklung2);
long rowID = database.insert(PnDatabaseOpenHelper.TABLE_FILMROLL, null, values);
Log.v("DB", String.format("Added a new photo. ID of the new row is %d.", rowID));
return rowID;
}
/**
* @deprecated
* @return
*/
public ArrayList<Integer> getGearSets(){
Cursor c = database.query(PnDatabaseOpenHelper.TABLE_GEARSET, null, null, null, null, null, null);
ArrayList<Integer> result = new ArrayList<Integer>();
if (c != null && c.moveToFirst()) {
do {
result.add(c.getInt(c.getColumnIndex(PnDatabaseOpenHelper.COLUMN_ID)));
} while (c.moveToNext());
}
return result;
}
}
<file_sep>/Photographers/src/unisiegen/photographers/settings/SettingsViewPart.java
/* Copyright (C) 2012 <NAME>, <NAME>
* Copyright (C) 2012 <NAME>, <NAME>, <NAME> (Committers)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unisiegen.photographers.settings;
import java.util.ArrayList;
import unisiegen.photographers.activity.R;
import unisiegen.photographers.database.DB;
import unisiegen.photographers.model.Setting;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* This is a hack... as I seem to be too stupid to subclass from View in a
* usable way...
*
* @author sdraxler
*/
public class SettingsViewPart {
private LayoutInflater inflater;
private View view;
private TextView title;
private TableLayout layout;
private ListView list;
private ArrayList<Setting> values;
private SettingsArrayAdapter listAdapter;
public View getView() {
return view;
}
public SettingsViewPart(final Context context, int titleID,
final String settingName) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.settingsauswahl, null, false);
title = (TextView) view.findViewById(R.id.freecell);
title.setText(context.getString(titleID));
layout = (TableLayout) view.findViewById(R.id.tablor);
Button buttonAdd = (Button) view.findViewById(R.id.addkamera);
final EditText textNewItem = ((EditText) view
.findViewById(R.id.kameramodell));
list = (ListView) view.findViewById(android.R.id.list);
// layout.setBackgroundResource(R.drawable.shaperedtable);
values = DB.getDB().getAllSettings(context, settingName);
listAdapter = new SettingsArrayAdapter(context, values);
list.setAdapter(listAdapter);
layout.setPadding(4, 0, -2, 0);
list.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0,
final View arg1, final int arg2, long arg3) {
View layoutOwn = inflater.inflate(R.layout.longclick,
(ViewGroup) view.findViewById(R.id.testen), false);
Button deleteButton = (Button) layoutOwn
.findViewById(R.id.deletebutton);
Button cancelButton = (Button) layoutOwn
.findViewById(R.id.cancelbutton);
Button setDefaultButton = (Button) layoutOwn
.findViewById(R.id.editbutton);
deleteButton.setText(context.getString(R.string.delete_entry));
setDefaultButton.setText(context
.getString(R.string.make_default));
setDefaultButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LinearLayout lins = (LinearLayout) arg1;
TextView texti = (TextView) lins.getChildAt(0);
DB.getDB().setDefaultVal(context, settingName,
texti.getText().toString());
listAdapter.clear();
values = DB.getDB()
.getAllSettings(context, settingName);
for (Setting s : values) {
listAdapter.add(s);
}
Toast.makeText(context,
context.getString(R.string.default_saved),
Toast.LENGTH_SHORT).show();
Object o = v.getTag();
if (o instanceof PopupWindow) {
PopupWindow pw = (PopupWindow) o;
pw.dismiss();
}
}
});
deleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LinearLayout lins = (LinearLayout) arg1;
TextView texti = (TextView) lins.getChildAt(0);
DB.getDB().deleteSetting(context, settingName,
texti.getText().toString());
listAdapter.clear();
// activity.readDB(); // TODO: Die zeile muss später
// raus...
values = DB.getDB()
.getAllSettings(context, settingName);
for (Setting s : values) {
listAdapter.add(s);
}
Toast.makeText(context,
context.getString(R.string.deleted),
Toast.LENGTH_SHORT).show();
Object o = v.getTag();
if (o instanceof PopupWindow) {
PopupWindow pw = (PopupWindow) o;
pw.dismiss();
}
}
});
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Object o = v.getTag();
if (o instanceof PopupWindow) {
PopupWindow pw = (PopupWindow) o;
pw.dismiss();
}
}
});
PopupWindow pw = new PopupWindow(layoutOwn,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
pw.setAnimationStyle(7);
pw.setBackgroundDrawable(new ColorDrawable());
pw.showAtLocation(layoutOwn, Gravity.CENTER, 0, 0);
setDefaultButton.setTag(pw);
deleteButton.setTag(pw);
cancelButton.setTag(pw);
return true;
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean vorhanden = false;
String newVal = textNewItem.getText().toString();
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
textNewItem.getApplicationWindowToken(), 0);
for (Setting s : values) {
vorhanden = s.getValue().equals(newVal);
break;
}
if (vorhanden || newVal.length() == 0
|| newVal.trim().length() == 0) {
Toast.makeText(
context,
context.getString(R.string.empty_or_existing_entry),
Toast.LENGTH_SHORT).show();
} else {
DB.getDB().addSetting(context, settingName, newVal, 1);
listAdapter.clear();
values = DB.getDB().getAllSettings(context, settingName);
for (Setting s : values) {
listAdapter.add(s);
}
textNewItem.setText("");
Toast.makeText(context,
context.getString(R.string.entry_saved),
Toast.LENGTH_SHORT).show();
}
}
});
textNewItem.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
textNewItem.getApplicationWindowToken(), 0);
return true;
}
return false;
}
});
}
}<file_sep>/Photographers/src/unisiegen/photographers/database/PnDatabaseOpenHelper.java
package unisiegen.photographers.database;
import java.io.File;
import java.util.ArrayList;
import unisiegen.photographers.model.Bild;
import unisiegen.photographers.model.Film;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class PnDatabaseOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "pn_data";
private static final int DATABASE_VERSION = 1;
public static final String COLUMN_ID = "ID";
public static final String TABLE_FILMROLL = "Filmroll";
public static final String COLUMN_TITLE = "Title";
public static final String COLUMN_CREATEDDATE = "CreatedDate";
public static final String COLUMN_INSERTEDINCAMERA = "InsertedInCamera";
public static final String COLUMN_REMOVEDFROMCAMERA = "RemovedFromCamera";
public static final String COLUMN_CAMERA = "Camera";
public static final String COLUMN_FILMMAKERTYPE = "FilmMakerType";
public static final String COLUMN_FILMTYPE = "FilmType";
public static final String COLUMN_FILMFORMAT = "FilmFormat";
public static final String COLUMN_ASA = "ASA";
public static final String COLUMN_SPECIALDEVELOPMENT1 = "SpecialDevelopment1";
public static final String COLUMN_SPECIALDEVELOPMENT2 = "SpecialDevelopment2";
public static final String TABLE_PHOTO = "Photo";
public static final String COLUMN_FILMROLLID = "FilmRollID";
public static final String COLUMN_PHOTONUMBER = "PhotoNumber";
public static final String COLUMN_EXPOSUREDATE = "ExposureDate";
public static final String COLUMN_LENS = "Lens";
public static final String COLUMN_APERTURE = "Aperture";
public static final String COLUMN_SHUTTERSPEED = "ShutterSpeed";
public static final String COLUMN_FOCUSDISTANCE = "FocusDistance";
public static final String COLUMN_FILTER = "Filter";
public static final String COLUMN_MAKRO = "Makro";
public static final String COLUMN_FILTERVF = "FilterVF";
public static final String COLUMN_MAKROVF = "MakroVF";
public static final String COLUMN_FLASH = "Flash";
public static final String COLUMN_FLASHCORRECTION = "FlashCorrection";
public static final String COLUMN_EXPOSUREMEASUREMETHOD = "ExposureMeasureMethod";
public static final String COLUMN_EXPORUSEMEASURECORRECTION = "ExporuseMeasureCorrection";
public static final String COLUMN_NOTE = "Note";
public static final String COLUMN_LONGITUDE = "longitude";
public static final String COLUMN_LATITUDE = "latitude";
public static final String TABLE_SETTING = "Setting";
public static final String COLUMN_GEARSETID = "GearSetID";
public static final String COLUMN_SETTINGTYPE = "SettingType";
public static final String COLUMN_SETTINGNAME = "SettingName";
public static final String COLUMN_ISDISPLAYED = "IsDisplayed";
public static final String COLUMN_ISDEFAULTSELECTION = "IsDefaultSelection";
public static final String TABLE_GEARSET = "GearSet";
public static final String COLUMN_SETNAME = "SetName";
public static final String COLUMN_SETDESCRIPTION = "SetDescription";
public static final String TABLE_CAMERALENSCOMBINATION = "CameraLensCombination";
// ID
public static final String COLUMN_CAMERAID = "CameraID";
public static final String COLUMN_LENSID = "LensID";
// GearSetID
private static final String SETTING_TABLE_CREATE = "CREATE TABLE "
+ TABLE_SETTING + " (" + COLUMN_ID
+ " integer NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_GEARSETID + " integer NOT NULL, " + COLUMN_SETTINGTYPE
+ " text, " + COLUMN_SETTINGNAME + " text, " + COLUMN_ISDISPLAYED
+ " integer, " + COLUMN_ISDEFAULTSELECTION + " integer, "
+ "FOREIGN KEY (" + COLUMN_GEARSETID + ") " + "REFERENCES "
+ TABLE_GEARSET + " (" + COLUMN_ID + ")" + ");";
private static final String GEARSET_TABLE_CREATE = "CREATE TABLE "
+ TABLE_GEARSET + " (" + COLUMN_ID
+ " integer NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_SETNAME + " text, " + COLUMN_SETDESCRIPTION + " text);";
private static final String CAMLENS_TABLE_CREATE = "CREATE TABLE "
+ TABLE_CAMERALENSCOMBINATION + " (" + COLUMN_ID
+ " integer NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_CAMERAID + " integer, " + COLUMN_LENSID + " integer, "
+ COLUMN_GEARSETID + " integer NOT NULL, " + "FOREIGN KEY ("
+ COLUMN_GEARSETID + ") " + "REFERENCES " + TABLE_GEARSET + "("
+ COLUMN_ID + "), " + "FOREIGN KEY (" + COLUMN_CAMERAID + ") "
+ "REFERENCES " + TABLE_SETTING + "(" + COLUMN_ID + "), "
+ "FOREIGN KEY (" + COLUMN_LENSID + ") " + "REFERENCES "
+ TABLE_SETTING + "(" + COLUMN_ID + ")" + ");";
private static final String FILMROLL_TABLE_CREATE = "CREATE TABLE "
+ TABLE_FILMROLL + " (" + COLUMN_ID
+ " integer NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_TITLE + " text, " + COLUMN_CREATEDDATE + " text, "
+ COLUMN_INSERTEDINCAMERA + " text, " + COLUMN_REMOVEDFROMCAMERA
+ " text, " + COLUMN_CAMERA + " text, " + COLUMN_FILMMAKERTYPE
+ " text, " + COLUMN_FILMTYPE + " text, " + COLUMN_FILMFORMAT
+ " text, " + COLUMN_ASA + " text, " + COLUMN_SPECIALDEVELOPMENT1
+ " text, " + COLUMN_SPECIALDEVELOPMENT2 + " text);";
private static final String PHOTO_TABLE_CREATE = "CREATE TABLE "
+ TABLE_PHOTO + " (" + COLUMN_ID
+ " integer NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_FILMROLLID + " integer NOT NULL, " + COLUMN_PHOTONUMBER
+ " integer, " + COLUMN_EXPOSUREDATE + " text, " + COLUMN_LENS
+ " text, " + COLUMN_APERTURE + " text, " + COLUMN_SHUTTERSPEED
+ " text, " + COLUMN_FOCUSDISTANCE + " text, " + COLUMN_FILTER
+ " text, " + COLUMN_MAKRO + " text, " + COLUMN_FILTERVF
+ " text, " + COLUMN_MAKROVF + " text, " + COLUMN_FLASH + " text, "
+ COLUMN_FLASHCORRECTION + " text, " + COLUMN_EXPOSUREMEASUREMETHOD
+ " text, " + COLUMN_EXPORUSEMEASURECORRECTION + " text, "
+ COLUMN_NOTE + " text, " + COLUMN_LONGITUDE + " text, "
+ COLUMN_LATITUDE + " text, " + "FOREIGN KEY (" + COLUMN_FILMROLLID
+ ") REFERENCES " + TABLE_FILMROLL + " (" + COLUMN_ID + "));";
private static final String logFile = "importLegacyDB.log";
private Context context;
private SQLiteDatabase db;
private boolean log = false;
private DatabaseImportLogger logger;
public PnDatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
this.db = db;
File file = new File(context.getFilesDir(), logFile);
logger = new DatabaseImportLogger(file, true);
log = logger.open();
long t1 = System.currentTimeMillis();
db.execSQL(GEARSET_TABLE_CREATE);
if (log)
logger.log(String
.format("OK: Created new Table: %s", TABLE_GEARSET));
db.execSQL(SETTING_TABLE_CREATE);
if (log)
logger.log(String
.format("OK: Created new Table: %s", TABLE_SETTING));
db.execSQL(CAMLENS_TABLE_CREATE);
if (log)
logger.log(String.format("OK: Created new Table: %s",
TABLE_CAMERALENSCOMBINATION));
db.execSQL(PHOTO_TABLE_CREATE);
if (log)
logger.log(String.format("OK: Created new Table: %s", TABLE_PHOTO));
db.execSQL(FILMROLL_TABLE_CREATE);
if (log)
logger.log(String.format("OK: Created new Table: %s",
TABLE_FILMROLL));
if (legacyDataExist()) {
importLegacyData();
// remove old database
} else {
// establish new default data for settings
}
long t2 = System.currentTimeMillis();
double importTime = (double) t2 - (double) t1;
if (log)
logger.log(String.format(
"Legacy Database import finished. Duration: %d ms",
(int) importTime));
logger.close();
}
private void importLegacyData() {
// import all data from different tables into a new one
String[] gearSets = new String[] { DB.MY_DB_SET, DB.MY_DB_SET1,
DB.MY_DB_SET2, DB.MY_DB_SET3 };
for (String set : gearSets) {
createSet(set);
importSettingsForSet(set);
createCamLensConnection(set);
}
importFilmRolls();
}
/**
* @deprecated This is old DB API and will be removed.
*/
private ArrayList<Film> getFilmeOldAPI() {
ArrayList<Film> filme = new ArrayList<Film>();
try {
SQLiteDatabase myDBNummer = context.openOrCreateDatabase(
DB.MY_DB_NUMMER, Context.MODE_PRIVATE, null);
SQLiteDatabase myDBFilm = context.openOrCreateDatabase(
DB.MY_DB_FILM, Context.MODE_PRIVATE, null);
Cursor c = myDBNummer.rawQuery(
"SELECT title,camera,datum,bilder,pic FROM "
+ DB.MY_DB_TABLE_NUMMER + " ORDER BY datum DESC",
null);
if (c != null) {
if (c.moveToFirst()) {
do {
Film film = new Film();
filme.add(film);
film.Titel = c.getString(c.getColumnIndex("title"));
film.Kamera = c.getString(c.getColumnIndex("camera"));
film.Datum = c.getString(c.getColumnIndex("datum"));
film.Pics = c.getString(c.getColumnIndex("bilder"));
film.setIcon(c.getString(c.getColumnIndex("pic")));
Cursor c1 = myDBFilm
.rawQuery(
"SELECT _id,filmtitle,filmnotiz,picuhrzeit,picnummer, picobjektiv, filmformat, filmtyp, filmempfindlichkeit, filmsonder, filmsonders FROM "
+ DB.MY_DB_FILM_TABLE
+ " WHERE filmtitle = '"
+ film.Titel + "'", null);
if (c1 != null) {
if (c1.moveToFirst()) {
film.Filmbezeichnung = c1.getString(c1
.getColumnIndex("filmnotiz"));
film.Filmformat = c1.getString(c1
.getColumnIndex("filmformat"));
film.Filmtyp = c1.getString(c1
.getColumnIndex("filmtyp"));
film.Empfindlichkeit = c1.getString(c1
.getColumnIndex("filmempfindlichkeit"));
film.Sonderentwicklung1 = c1.getString(c1
.getColumnIndex("filmsonder"));
film.Sonderentwicklung2 = c1.getString(c1
.getColumnIndex("filmsonders"));
}
}
c1.close();
// Bilder holen
film.Bilder = getBilderOldAPI(film.Titel, null);
} while (c.moveToNext());
}
}
c.close();
myDBNummer.close();
myDBFilm.close();
} catch (Exception e) {
}
return filme;
}
/**
* @deprecated This is old DB API and will be removed.
*/
private ArrayList<Bild> getBilderOldAPI(String title, String bildNummer) {
SQLiteDatabase myDBFilm = context.openOrCreateDatabase(DB.MY_DB_FILM,
Context.MODE_PRIVATE, null);
StringBuilder sql = new StringBuilder();
sql.append("SELECT _id,picfokus,picuhrzeit,piclat,piclong,filmdatum,picobjektiv, picblende,piczeit,picmessung, picnummer, pickorr,picmakro,picmakrovf,picfilter,picfiltervf,picblitz,picblitzkorr,picnotiz,pickameranotiz FROM ");
sql.append(DB.MY_DB_FILM_TABLE);
sql.append(" WHERE filmtitle = '");
sql.append(title);
if (bildNummer == null) {
sql.append("' AND picnummer != 'Bild 0';"); // Ignore the dummy pic
// "Bild 0"
} else {
sql.append("' AND picnummer = '");
sql.append(bildNummer);
sql.append("';");
}
Cursor c2 = myDBFilm.rawQuery(new String(sql), null);
ArrayList<Bild> bilder = new ArrayList<Bild>();
if (c2 != null) {
if (c2.moveToFirst()) {
do {
bilder.add(new Bild(
c2.getString(c2.getColumnIndex("picnummer")),
c2.getString(c2.getColumnIndex("picobjektiv")),
c2.getString(c2.getColumnIndex("picblende")),
c2.getString(c2.getColumnIndex("piczeit")),
c2.getString(c2.getColumnIndex("picfokus")),
c2.getString(c2.getColumnIndex("picfilter")),
c2.getString(c2.getColumnIndex("picmakro")),
c2.getString(c2.getColumnIndex("picfiltervf")),
c2.getString(c2.getColumnIndex("picmakrovf")),
c2.getString(c2.getColumnIndex("picmessung")),
c2.getString(c2.getColumnIndex("pickorr")),
c2.getString(c2.getColumnIndex("picblitz")),
c2.getString(c2.getColumnIndex("picblitzkorr")),
c2.getString(c2.getColumnIndex("picuhrzeit"))
+ " - "
+ c2.getString(c2
.getColumnIndex("filmdatum")),
"Lat : "
+ c2.getString(c2.getColumnIndex("piclat"))
+ " - Long : "
+ c2.getString(c2.getColumnIndex("piclong")),
c2.getString(c2.getColumnIndex("picnotiz")), c2
.getString(c2
.getColumnIndex("pickameranotiz"))));
} while (c2.moveToNext());
}
}
c2.close();
myDBFilm.close();
return bilder;
}
private void importFilmRolls() {
ArrayList<Film> filme = getFilmeOldAPI();
for (Film film : filme) {
// Create a Filmroll
ContentValues cvFilm = new ContentValues();
// cv.put("ID", "");
cvFilm.put(COLUMN_TITLE, film.Titel);
cvFilm.put(COLUMN_CREATEDDATE, film.Datum);
cvFilm.put(COLUMN_INSERTEDINCAMERA, "");
cvFilm.put(COLUMN_REMOVEDFROMCAMERA, "");
cvFilm.put(COLUMN_CAMERA, film.Kamera);
cvFilm.put(COLUMN_FILMMAKERTYPE, film.Filmbezeichnung);
cvFilm.put(COLUMN_FILMTYPE, film.Filmtyp);
cvFilm.put(COLUMN_FILMFORMAT, film.Filmformat);
cvFilm.put(COLUMN_ASA, film.Empfindlichkeit);
cvFilm.put(COLUMN_SPECIALDEVELOPMENT1, film.Sonderentwicklung1);
cvFilm.put(COLUMN_SPECIALDEVELOPMENT2, film.Sonderentwicklung2);
long result = db.insert(TABLE_FILMROLL, null, cvFilm);
if (result == -1) {
if (log)
logger.log(String
.format("FAILED: to create Filmroll: %s, %s %s from legacy data",
film.Titel, film.Filmtyp, film.Kamera));
} else {
if (log)
logger.log(String.format(
"OK: Created Filmroll: %s, %s %s from legacy data",
film.Titel, film.Filmtyp, film.Kamera));
}
Cursor filmRollC = db.query(TABLE_FILMROLL, null, COLUMN_TITLE
+ " like ?", new String[] { film.Titel }, null, null, null);
filmRollC.moveToFirst();
int newFilmrollID = filmRollC.getInt(0);
for (Bild bild : film.Bilder) {
// Create a Photo
ContentValues cvPhoto = new ContentValues();
// cv.put("ID", "");
cvPhoto.put(COLUMN_FILMROLLID, newFilmrollID);
cvPhoto.put(COLUMN_PHOTONUMBER, bild.Bildnummer);
cvPhoto.put(COLUMN_EXPOSUREDATE, bild.Zeitstempel);
cvPhoto.put(COLUMN_LENS, bild.Objektiv);
cvPhoto.put(COLUMN_APERTURE, bild.Blende);
cvPhoto.put(COLUMN_SHUTTERSPEED, bild.Zeit);
cvPhoto.put(COLUMN_FOCUSDISTANCE, bild.Fokus);
cvPhoto.put(COLUMN_FILTER, bild.Filter);
cvPhoto.put(COLUMN_MAKRO, bild.Makro);
cvPhoto.put(COLUMN_FILTERVF, bild.FilterVF);
cvPhoto.put(COLUMN_MAKROVF, bild.MakroVF);
cvPhoto.put(COLUMN_FLASH, bild.Blitz);
cvPhoto.put(COLUMN_FLASHCORRECTION, bild.Blitzkorrektur);
cvPhoto.put(COLUMN_EXPOSUREMEASUREMETHOD, bild.Messmethode);
cvPhoto.put(COLUMN_EXPORUSEMEASURECORRECTION, "");
cvPhoto.put(COLUMN_NOTE, bild.Notiz);
String[] latlon = bild.GeoTag.split(" - ");
String lat = latlon[0].substring("Lat : ".length());
String lon = latlon[1].substring("Long : ".length());
cvPhoto.put(COLUMN_LONGITUDE, lat);
cvPhoto.put(COLUMN_LATITUDE, lon);
long result2 = db.insert(TABLE_PHOTO, null, cvPhoto);
if (result2 == -1) {
if (log)
logger.log(String
.format("FAILED: to create Photo: %s, %s from legacy data",
bild.Bildnummer, bild.Objektiv));
} else {
if (log)
logger.log(String.format(
"OK: Created Photo: %s, %s from legacy data",
bild.Bildnummer, bild.Objektiv));
}
}
}
}
private void createCamLensConnection(String myDbSet) {
Cursor gearset = db.query(TABLE_GEARSET, null, COLUMN_SETNAME
+ " like ?", new String[] { myDbSet }, null, null, null);
gearset.moveToFirst();
int gearSetID = gearset.getInt(0);
SQLiteDatabase legacyDB = context.openOrCreateDatabase(myDbSet,
Context.MODE_PRIVATE, null);
Cursor c = legacyDB.rawQuery("SELECT cam, bw FROM "
+ DB.MY_DB_TABLE_SETCAMBW, null);
if (c != null) {
if (c.moveToFirst()) {
do {
// get id of the set
// gearSetID
// get id of a camera
String camName = c.getString(c.getColumnIndex("cam"));
Cursor cams = db
.query(TABLE_SETTING, new String[] { COLUMN_ID },
COLUMN_GEARSETID + " == ? AND "
+ COLUMN_SETTINGNAME + " like ?",
new String[] { String.valueOf(gearSetID),
camName }, null, null, null);
cams.moveToFirst();
int camID = cams.getInt(0);
// get id of a lens
String lensName = c.getString(c.getColumnIndex("bw"));
Cursor lenses = db
.query(TABLE_SETTING, new String[] { COLUMN_ID },
COLUMN_GEARSETID + " == ? AND "
+ COLUMN_SETTINGNAME + " like ?",
new String[] { String.valueOf(gearSetID),
lensName }, null, null, null);
lenses.moveToFirst();
int lensID = lenses.getInt(0);
ContentValues cv = new ContentValues();
// cv.put("ID", "");
cv.put(COLUMN_CAMERAID, camID);
cv.put(COLUMN_LENSID, lensID);
cv.put(COLUMN_GEARSETID, gearSetID);
long result = db.insert(TABLE_CAMERALENSCOMBINATION, null,
cv);
if (result == -1) {
if (log)
logger.log(String
.format("FAILED: to create CameraLensCombination: %s, %s from legacy data",
camName, lensName));
} else {
if (log)
logger.log(String
.format("OK: Created CameraLensCombination: %s, %s from legacy data",
camName, lensName));
}
} while (c.moveToNext());
}
}
c.close();
legacyDB.close();
}
private void createSet(String myDbSet) {
ContentValues cv = new ContentValues();
// cv.put("ID", "");
cv.put(COLUMN_SETNAME, myDbSet);
cv.put(COLUMN_SETDESCRIPTION,
"Imported Set. Change this to your liking.");
long result = db.insert(TABLE_GEARSET, null, cv);
if (result == -1) {
if (log)
logger.log(String.format(
"FAILED: to create GearSet: %s from legacy data",
myDbSet));
} else {
if (log)
logger.log(String.format(
"OK: Created GearSet: %s from legacy data", myDbSet));
}
}
private void importSettingsForSet(String myDbSet) {
Cursor gearset = db.query(TABLE_GEARSET, null, COLUMN_SETNAME
+ " like ?", new String[] { myDbSet }, null, null, null);
gearset.moveToFirst();
int gearSetID = gearset.getInt(0);
SQLiteDatabase legacyDB = context.openOrCreateDatabase(myDbSet,
Context.MODE_PRIVATE, null);
for (String tableName : DB.tableNames) {
Cursor c = legacyDB.rawQuery("SELECT name, value, def FROM "
+ tableName, null);
if (c != null) {
if (c.moveToFirst()) {
do {
ContentValues cv = new ContentValues();
// cv.put("ID", "");
cv.put(COLUMN_GEARSETID, gearSetID);
cv.put(COLUMN_SETTINGTYPE, tableName);
cv.put(COLUMN_SETTINGNAME,
c.getString(c.getColumnIndex("name")));
cv.put(COLUMN_ISDISPLAYED,
c.getInt(c.getColumnIndex("value")));
cv.put(COLUMN_ISDEFAULTSELECTION,
c.getInt(c.getColumnIndex("def")));
long result = db.insert(TABLE_SETTING, null, cv);
if (result == -1) {
if (log)
logger.log(String
.format("FAILED: to create Setting: %s, %s from legacy data",
tableName,
c.getString(c
.getColumnIndex("name"))));
} else {
if (log)
logger.log(String
.format("OK: Created Setting: %s, %s from legacy data",
tableName,
c.getString(c
.getColumnIndex("name"))));
}
} while (c.moveToNext());
}
}
c.close();
}
legacyDB.close();
}
private boolean legacyDataExist() {
SQLiteDatabase myDBSet = null;
try {
myDBSet = context.openOrCreateDatabase(DB.MY_DB_SET,
Context.MODE_PRIVATE, null);
if (myDBSet != null) {
Cursor c = myDBSet.rawQuery("SELECT * FROM "
+ DB.MY_DB_TABLE_SETZEI + ";", null);
if (c != null && c.getCount() > 0) {
c.close();
return true;
}
}
} catch (Exception e) {
return false;
} finally {
if (myDBSet != null)
myDBSet.close();
}
return false;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
<file_sep>/Photographers/src/unisiegen/photographers/helper/FilmIconFactory.java
/* Copyright (C) 2012 <NAME>, <NAME>, <NAME> (Committers)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unisiegen.photographers.helper;
import unisiegen.photographers.model.Film;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
public class FilmIconFactory {
public Bitmap createBitmap(Film film) {
// Size of the Bitmap in pixels
int x = 200;
int y = 200;
// Get the values we want to display
String iso = film.Empfindlichkeit;
String type = film.Filmformat;
String brand = film.Filmtyp;
// Define the default variables for the design. Each icon consists of
// three stripes
// with individual colors, heights, and texts they can display (apart of
// the top stripe
// which is only decoration).
//
// In the current version, all stripes are displayed in the same pastel
// color.
int heightTop = 30;
String colorTop = "#04B431";
int heightMiddle = 80;
String colorMiddle = "#04B431";
String colorMiddleText = "white";
String colorBottom = "#04B431";
String colorBottomText = "white";
int marginText = 5; // Margin for the text on the bottom stripe
int textSize = 40; // Standard text size
// Variables for the text to be displayed on the icon (will be modified
// later)
String middleText = "Film";
String bottomLeftText = "";
String bottomRightText = "";
// Define different styles for different film types. We also set the
// text on the badge according to the kind of film.
// final String color_red = "#DD597D";
final String color_cyan = "#44B4D5";
// final String color_violet = "#9588EC";
final String color_orange = "#FFAC62";
final String color_green = "#93BF96";
final String color_lgray = "#999999";
final String color_dgray = "#555555";
if (brand != null) {
if (brand.contains("I: CR")) { // TODO: read these from the string
// resources.
middleText = "CR";
heightTop = 30;
colorTop = color_green;
heightMiddle = 80;
colorMiddle = color_green;
colorMiddleText = "white";
colorBottom = color_green;
colorBottomText = "white";
} else if (brand.contains("I: CT")) {
middleText = "CT";
heightTop = 30;
colorTop = color_cyan;
heightMiddle = 80;
colorMiddle = color_cyan;
colorMiddleText = "white";
colorBottom = color_cyan;
colorBottomText = "white";
} else if (brand.contains("I: CN")) {
middleText = "CN";
heightTop = 30;
colorTop = color_orange;
heightMiddle = 80;
colorMiddle = color_orange;
colorMiddleText = "white";
colorBottom = color_orange;
colorBottomText = "white";
} else if (brand.contains("I: SWR")) {
middleText = "SWR";
heightTop = 30;
colorTop = color_lgray;
heightMiddle = 80;
colorMiddle = color_lgray;
colorMiddleText = "white";
colorBottom = color_lgray;
colorBottomText = "white";
} else if (brand.contains("I: SW")) {
middleText = "SW";
heightTop = 30;
colorTop = color_dgray;
heightMiddle = 80;
colorMiddle = color_dgray;
colorMiddleText = "white";
colorBottom = color_dgray;
colorBottomText = "white";
}
}
// Some re-formatting of the database defaults...
// if (name.length() == 0) { name = badgeName; }
if (iso.contains("/")) {
iso = iso.substring(0, iso.indexOf("/"));
}
if (iso.contains("ISO ")) {
iso = iso.replace("ISO ", "");
}
if (iso.length() > 4) {
iso = iso.substring(0, 5);
} // As iso can be set by the user in the settings we should make sure
// the text does not get too long...
bottomLeftText = iso;
if (type.contains("24x36")) {
bottomRightText = "135";
} // Here we define only two values right now ... 135er or 120er film.
// If the user has entered something other than the defaults here,
// we display nothing.
if (type.contains("4,5x6") || type.contains("6x6")
|| type.contains("6x7") || type.contains("6x9")) {
bottomRightText = "120";
}
// Finally, we create the Bitmap ...
Bitmap returnedBitmap = Bitmap.createBitmap(x, y,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
// Top stripe
canvas.drawPaint(paint);
paint.setColor(Color.parseColor(colorTop));
canvas.drawRect(0, 0, x, heightTop, paint);
// Middle stripe
paint.setColor(Color.parseColor(colorMiddle));
canvas.drawRect(0, heightTop, x, (heightTop + heightMiddle), paint);
// Bottom stripe
paint.setColor(Color.parseColor(colorBottom));
canvas.drawRect(0, (heightTop + heightMiddle), x, y, paint);
// Text middle stripe
paint.setTextSize(textSize + 50);
Rect bounds = new Rect(); // Trick to center text vertically ...
paint.getTextBounds("A", 0, 1, bounds);
paint.setColor(Color.parseColor(colorMiddleText));
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(middleText, x >> 1,
(heightTop + (heightMiddle >> 1) + (bounds.height() >> 1)),
paint);
// Text bottom stripe
paint.setTextSize(textSize);
paint.setColor(Color.parseColor(colorBottomText));
paint.setTextAlign(Paint.Align.RIGHT);
canvas.drawText(bottomRightText, (x - marginText), (y - marginText),
paint);
paint.setTextAlign(Paint.Align.LEFT);
canvas.drawText(bottomLeftText, (0 + marginText), (y - marginText),
paint);
return returnedBitmap;
}
}
<file_sep>/Photographers/src/unisiegen/photographers/settings/SettingsArrayAdapter.java
/* Copyright (C) 2012 <NAME>, <NAME>
* Copyright (C) 2012 <NAME>, <NAME>, <NAME> (Committers)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unisiegen.photographers.settings;
import java.util.List;
import unisiegen.photographers.activity.R;
import unisiegen.photographers.database.DB;
import unisiegen.photographers.model.Setting;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
public class SettingsArrayAdapter extends ArrayAdapter<Setting> {
private LayoutInflater inflater;
public SettingsArrayAdapter(Context context, List<Setting> settings) {
super(context, R.layout.list_item, R.id.listItemText, settings);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Planet to display
Setting planet = (Setting) this.getItem(position);
// The child views in each row.
CheckBox checkBox;
TextView textView;
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
// Find the child views.
textView = (TextView) convertView.findViewById(R.id.listItemText);
checkBox = (CheckBox) convertView.findViewById(R.id.check);
// Optimization: Tag the row with it's child views, so we don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new SettingsViewHolder(textView, checkBox));
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Setting planet = (Setting) cb.getTag();
planet.setDisplay(cb.isChecked());
int value = 0;
if (cb.isChecked() == true) {
value = 1;
}
DB.getDB().updateSetting(getContext(), planet.getType(),
planet.getValue(), value);
}
});
}
// Reuse existing row view
else {
// Because we use a ViewHolder, we avoid having to call
// findViewById().
SettingsViewHolder viewHolder = (SettingsViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the Planet it is displaying, so that we can
// access the planet in onClick() when the CheckBox is toggled.
checkBox.setTag(planet);
// Display planet data
if (planet.shouldBeDisplayed() == 1) {
checkBox.setChecked(true);
} else if (planet.shouldBeDisplayed() == 0) {
checkBox.setChecked(false);
}
textView.setText(planet.getValue());
if (planet.isDefaultValueB()) {
textView.setTextColor(0xFF0000AA);
} else {
textView.setTextColor(0xFF000000);
}
return convertView;
}
}<file_sep>/Photographers/src/unisiegen/photographers/model/Lens.java
package unisiegen.photographers.model;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* Created by aboden on 16.07.14.
*/
@XStreamAlias("lens")
public class Lens {
public String name;
public String camera;
public Lens(String name, String camera) {
this.name = name;
this.camera = camera;
}
public Lens() {
// Empty constructor needed for XStream Library.
}
}
<file_sep>/Photographers/src/unisiegen/photographers/model/Bild.java
/* Copyright (C) 2012 <NAME>, <NAME>, <NAME> (Committers)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unisiegen.photographers.model;
public class Bild implements Comparable<Bild> {
public int ID;
public String Bildnummer;
public String Objektiv;
public String Blende;
public String Zeit;
public String Fokus;
public String Filter;
public String Makro;
public String FilterVF;
public String MakroVF;
public String Messmethode;
public String Belichtungskorrektur;
public String Blitz;
public String Blitzkorrektur;
public String Zeitstempel;
public String GeoTag;
public String Notiz;
public String KameraNotiz;
public Bild(String _bildnummer, String _objektiv, String _blende,
String _zeit, String _fokus, String _filter, String _makro,
String _filterVF, String _makroVF, String _messmethode,
String _belichtungskorrektur, String _blitz,
String _blitzkorrektur, String _zeitstempel, String _geoTag,
String _notiz, String _kameraNotiz) {
Bildnummer = _bildnummer;
Objektiv = _objektiv;
Blende = _blende;
Zeit = _zeit;
Fokus = _fokus;
Filter = _filter;
Makro = _makro;
FilterVF = _filterVF;
MakroVF = _makroVF;
Messmethode = _messmethode;
Belichtungskorrektur = _belichtungskorrektur;
Blitz = _blitz;
Blitzkorrektur = _blitzkorrektur;
Zeitstempel = _zeitstempel;
GeoTag = _geoTag;
Notiz = _notiz;
KameraNotiz = _kameraNotiz;
}
public Bild() {
}
public String toString() {
StringBuilder sr = new StringBuilder();
sr.append(Bildnummer);
sr.append(" ");
sr.append(Objektiv);
sr.append(" ");
sr.append(Blende);
sr.append(" ");
sr.append(Zeit);
return sr.toString();
}
@Override
public int compareTo(Bild otherBild) {
Integer bildNummerAsInt = Integer.valueOf(this.Bildnummer
.replaceAll("[\\D]", ""));
Integer otherBildNummerAsInt = Integer.valueOf(otherBild.Bildnummer
.replaceAll("[\\D]", ""));
return bildNummerAsInt.compareTo(otherBildNummerAsInt);
}
}<file_sep>/Photographers/src/unisiegen/photographers/helper/EquipmentImportTask.java
package unisiegen.photographers.helper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import unisiegen.photographers.activity.EditSettingsActivity;
import unisiegen.photographers.activity.R;
import unisiegen.photographers.database.DB;
import unisiegen.photographers.model.Camera;
import unisiegen.photographers.model.Equipment;
import unisiegen.photographers.model.Lens;
import unisiegen.photographers.model.Setting;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import com.thoughtworks.xstream.XStream;
/**
* Created by aboden on 16.07.14.
*/
public class EquipmentImportTask extends AsyncTask<String, Void, Boolean> {
EditSettingsActivity myActivity;
File file;
Equipment equipment = new Equipment();
private ProgressDialog dialog;
Context context;
Boolean import_success = true;
public EquipmentImportTask(Context context, File file, EditSettingsActivity myActivity) {
this.context = context;
this.file = file;
this.myActivity = myActivity;
dialog = new ProgressDialog(context);
}
protected void onPreExecute() {
this.dialog.setMessage(context.getString(R.string.import_data));
this.dialog.show();
Log.v("Check", "Bereite Import von Equipment vor");
}
@Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
AlertDialog alert = new AlertDialog.Builder(context).create();
alert.setTitle(context.getString(R.string.info_title));
if (import_success) {
alert.setMessage(context.getString(R.string.info_backup_success));
} else {
alert.setMessage(context.getString(R.string.info_backup_failed));
}
alert.setButton(DialogInterface.BUTTON_POSITIVE, context.getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
myActivity.finish();
return;
}
});
alert.show();
}
protected Boolean doInBackground(final String... args) {
FileInputStream input = null;
try {
input = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
import_success = false;
}
XStream xs = new XStream();
xs.processAnnotations(Equipment.class);
xs.processAnnotations(Lens.class);
xs.processAnnotations(Camera.class);
xs.processAnnotations(Setting.class);
if (input != null) {
try {
equipment = (Equipment) xs.fromXML(input);
Log.v("Check", "Equipment importiert aus Datei: " + file.getAbsolutePath());
} catch (Exception e) {
Log.v("Check", "Import von Datei fehlgeschlagen: " + e.toString());
import_success = false;
}
if (import_success) {
try {
DB.getDB().createSettingsTableFromEquipmentImport(context, equipment);
} catch (Exception e) {
Log.v("Check", e.toString());
import_success = false;
}
}
}
return null;
}
}
<file_sep>/Photographers/src/unisiegen/photographers/helper/FilmsViewHolder.java
/* Copyright (C) 2012 <NAME>, <NAME>
* Copyright (C) 2012 <NAME>, <NAME>, <NAME> (Committers)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unisiegen.photographers.helper;
import android.widget.ImageView;
import android.widget.TextView;
public class FilmsViewHolder {
private TextView textViewTime;
private TextView textViewName;
private TextView textViewCam;
private TextView textViewPics;
private ImageView imageViewBild;
public FilmsViewHolder(TextView textViewname, TextView textViewtime,
TextView textViewcam, TextView textViewpics, ImageView Bilds) {
this.textViewTime = textViewtime;
this.textViewName = textViewname;
this.textViewCam = textViewcam;
this.textViewPics = textViewpics;
this.imageViewBild = Bilds;
}
public TextView getTextViewName() {
return textViewName;
}
public TextView getTextViewTime() {
return textViewTime;
}
public TextView getTextViewCam() {
return textViewCam;
}
public TextView getTextViewPics() {
return textViewPics;
}
public ImageView getBildView() {
return imageViewBild;
}
}<file_sep>/Photographers/src/unisiegen/photographers/activity/PhotographersNotebookActivity.java
/* Copyright (C) 2012 <NAME>, <NAME>
* Copyright (C) 2012 <NAME>, <NAME>, <NAME> (Committers)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unisiegen.photographers.activity;
import java.util.ArrayList;
import unisiegen.photographers.database.DataSource;
import unisiegen.photographers.helper.DefaultLocationListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class PhotographersNotebookActivity extends Activity {
public static final String ACTIVEGEARSET = "ActiveGearSet";
private LocationManager locManager;
private DefaultLocationListener locListener;
protected void onResume() {
super.onResume();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getString(EditSettingsActivity.GEO_TAG, "nein").equals("ja")) {
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locListener = new DefaultLocationListener();
locListener.setLast(locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 20000, 5, locListener);
}
int activegearSetId = settings.getInt(ACTIVEGEARSET, -1);
if(activegearSetId == -1){
// Log this also
ArrayList<Integer> setIds = DataSource.getInst(this).getGearSets();
if(setIds != null && setIds.size() != 0){
activegearSetId = setIds.get(0).intValue();
settings.edit().putInt(ACTIVEGEARSET, activegearSetId);
} else {
// Do some logging
}
}
// check if this exists
// if not, pick the first one, so nothing breaks.
// in other activities, make use of this setting.
}
public void onPause() {
super.onPause();
if(locManager != null && locListener != null){
locManager.removeUpdates(locListener);
}
}
protected DefaultLocationListener getLocListener(){
return locListener;
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.generic_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.opt_openSettings) {
Intent openSettings = new Intent(getApplicationContext(),
EditSettingsActivity.class);
startActivityForResult(openSettings, 0);
return true;
} else if (item.getItemId() == R.id.opt_backToMenu) {
finish();
startActivity(new Intent(getApplicationContext(),
FilmSelectionActivity.class));
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
}
<file_sep>/Photographers/src/unisiegen/photographers/model/Setting.java
/* Copyright (C) 2012 <NAME>, <NAME>, <NAME> (Committers)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unisiegen.photographers.model;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("setting")
public class Setting {
// corresponds with the database table
private String type;
// The value (of a certain type), as displayed in the UI
private String value;
// true if selected in settings dialog = should be displayed as possible
// value in the UI.
private boolean shouldBeDisplayed = false;
// true, if this specific value is mark as the default value
private boolean defaultValue = false;
public Setting() {
// Empty Constructor needed for XStream Library.
}
public Setting(String type, String value, int shouldBeDisplayed,
int defaultValue) {
this.type = type;
this.value = value;
if (shouldBeDisplayed == 1) {
this.shouldBeDisplayed = true;
} else
this.shouldBeDisplayed = false;
if (defaultValue == 1) {
this.defaultValue = true;
} else
this.defaultValue = false;
}
public String getType() {
return type;
}
public String getValue() {
return value;
}
public int shouldBeDisplayed() {
if (shouldBeDisplayed) {
return 1;
} else
return 0;
}
public int isDefaultValue() {
if (defaultValue) {
return 1;
} else
return 0;
}
public boolean isDefaultValueB() {
return defaultValue;
}
public void setDisplay(boolean checked) {
this.shouldBeDisplayed = checked;
}
public String toString() {
if (shouldBeDisplayed) {
return type + "::" + value + "::1";
} else
return type + "::" + value + "::0";
}
}<file_sep>/Photographers/src/unisiegen/photographers/activity/FotoContentActivity.java
/* Copyright (C) 2012 <NAME>, <NAME>
* Copyright (C) 2012 <NAME>, <NAME>, <NAME> (Committers)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package unisiegen.photographers.activity;
import unisiegen.photographers.database.DB;
import unisiegen.photographers.database.DataSource;
import unisiegen.photographers.helper.FilmIconFactory;
import unisiegen.photographers.model.Bild;
import unisiegen.photographers.model.Film;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.viewpagerindicator.TitlePageIndicator;
import com.viewpagerindicator.TitleProvider;
public class FotoContentActivity extends PhotographersNotebookActivity {
private TitlePageIndicator mIndicator;
private MyPagerAdapter adapter;
private ViewPager viewPager;
private Film film;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slidi);
}
@SuppressLint("NewApi")
public void onResume() {
super.onResume();
String filmID = "";
filmID = getIntent().getExtras().getString("ID");
int selectedItem = 0;
selectedItem = getIntent().getExtras().getInt("selectedItem");
film = new Film();
if (filmID.length() > 0) {
film = DataSource.getInst(getApplicationContext()).getFilm(filmID);
}
else { finish(); }
Bitmap b = new FilmIconFactory().createBitmap(film);
Drawable drawable = new BitmapDrawable(getResources(), b);
if (android.os.Build.VERSION.SDK_INT >= 14) {
try {
getActionBar().setIcon(drawable);
} catch (Exception e) {
Log.v("check", e.toString());
}
}
viewPager = (ViewPager) findViewById(R.id.viewPager);
adapter = new MyPagerAdapter(getApplicationContext(), film);
viewPager.setAdapter(adapter);
viewPager.getAdapter().setPrimaryItem(viewPager, 2, null);
mIndicator = (TitlePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(viewPager);
mIndicator.setFooterColor(0xFF000000);
viewPager.setCurrentItem(selectedItem);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.fotomenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.opt_openSettings) {
Intent openSettings = new Intent(getApplicationContext(),
EditSettingsActivity.class);
startActivityForResult(openSettings, 0);
return true;
} else if (item.getItemId() == R.id.opt_editfoto) {
Intent editFoto = new Intent(getApplicationContext(), NewPictureActivity.class);
editFoto.putExtra("picToEdit", adapter.getTitle(viewPager.getCurrentItem()));
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString("Title", film.Titel);
editor.putBoolean("EditMode", true);
editor.commit();
startActivity(editFoto);
return true;
} else if (item.getItemId() == R.id.opt_deletefoto) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.question_delete));
builder.setCancelable(false);
builder.setPositiveButton(getString(R.string.yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final String bildToDelete = adapter.getTitle(viewPager.getCurrentItem());
int lastBild = 0;
for (Bild bild : film.Bilder) {
if (bild.Bildnummer.equals(bildToDelete)) {
DataSource.getInst(getApplicationContext()).deletePhoto(bild);
film.Bilder.remove(bild);
break;
}
lastBild = film.Bilder.indexOf(bild);
}
finish();
if (!film.Bilder.isEmpty()) {
Intent reload = new Intent(getApplicationContext(), FotoContentActivity.class);
reload.putExtra("ID", film.Titel);
reload.putExtra("selectedItem", lastBild);
startActivity(reload);
}
}
});
builder.setNegativeButton(getString(R.string.no),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
/*
* Pageadapter f�r das hin- und herwischen zwischen den Bildenr. W�hlt
* man ein Bild aus, wird ein "Popup" ge�ffnet in der alle Informationen
* zu dem Bild vorhanden sind in dieser Ansicht l�sst sich dann auch
* zwischen den Bildern hin- und herwechseln. Es wird einfach eine
* ArrayList<Views> gef�llt. Quasi fertige Views in eine Liste, die beim
* Wischen durchgegangen wird.
*/
private class MyPagerAdapter extends PagerAdapter implements TitleProvider {
private LayoutInflater inflater;
private Film film;
public MyPagerAdapter(Context context, Film film) {
inflater = getLayoutInflater();
this.film = film;
}
private View createView(Bild bild) {
View v = inflater.inflate(R.layout.filminfobox, null, false);
final TextView zeitStempel = (TextView) v
.findViewById(R.id.zeitStempel);
zeitStempel.setText(bild.Zeitstempel);
final TextView zeitGeo = (TextView) v.findViewById(R.id.geoTag);
zeitGeo.setText(bild.GeoTag);
final TextView objektiv = (TextView) v
.findViewById(R.id.showobjektiv);
objektiv.setText(bild.Objektiv);
final TextView filtervf = (TextView) v
.findViewById(R.id.showfiltervf);
filtervf.setText(bild.FilterVF);
final TextView picfocus = (TextView) v
.findViewById(R.id.showfokus);
picfocus.setText(bild.Fokus);
final TextView picblende = (TextView) v
.findViewById(R.id.showblende);
picblende.setText(bild.Blende);
final TextView piczeit = (TextView) v
.findViewById(R.id.showzeit);
piczeit.setText(bild.Zeit);
final TextView picmessung = (TextView) v
.findViewById(R.id.showmessung);
picmessung.setText(bild.Messmethode);
final TextView picplus = (TextView) v
.findViewById(R.id.showbelichtung);
picplus.setText(bild.Belichtungskorrektur);
final TextView picmakro = (TextView) v
.findViewById(R.id.showmakro);
picmakro.setText(bild.Makro);
final TextView picmakrovf = (TextView) v
.findViewById(R.id.showmakrovf);
picmakrovf.setText(bild.MakroVF);
final TextView picfilter = (TextView) v
.findViewById(R.id.showfilter);
picfilter.setText(bild.Filter);
final TextView picblitz = (TextView) v
.findViewById(R.id.showblitz);
picblitz.setText(bild.Blitz);
final TextView picblitzkorr = (TextView) v
.findViewById(R.id.showblitzkorr);
picblitzkorr.setText(bild.Blitzkorrektur);
final TextView picnotiz = (TextView) v
.findViewById(R.id.shownotiz);
picnotiz.setText(bild.Notiz);
final TextView picnotizcam = (TextView) v
.findViewById(R.id.shownotizkam);
picnotizcam.setText(bild.KameraNotiz);
// final TextView picTitle = (TextView) v
// .findViewById(R.id.pictitle);
// picTitle.setText(bild.Bildnummer);
return v;
}
@Override
public void destroyItem(View view, int arg1, Object object) {
// Es werden immer nur die 2 nächsten und die 2 letzten Views
// "gespeichert" bzw. berechnet, der Rest wird erstmal gelöscht.
((ViewPager) view).removeView((LinearLayout) object);
}
@Override
public void finishUpdate(View arg0) {
}
@Override
public int getCount() {
return film.Bilder.size(); // Wieviele Views zum Wischen
}
@Override
public Object instantiateItem(View view, int position) {
// Das vorpuffern, wenn die View bald drankommt... s.o.
Bild bild = film.Bilder.get(position);
View myView = createView(bild);
((ViewPager) view).addView(myView);
return myView;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {
}
@Override
public String getTitle(int position) { // Kommt vom TitleProvider um den
// Titel einer View festzulegen
return film.Bilder.get(position).Bildnummer;
}
}
}
| d42ea5347e40365b3b0108048048db37b8d2931a | [
"Java",
"SQL"
] | 15 | Java | aclemons/photographers-notebook | 702b82b53b44ecb6c8ecc994ced4b736723f4c77 | 2b634c0be2a621382eeb5b129082437b34608f7e |
refs/heads/master | <file_sep>#!/usr/bin/env python
"""This is a DBGp xdebug protocol proxy started by phpsh. It accepts a
connection from xdebug, connects to an IDE debug client and
communicates with its parent phpsh over a pair of pipes."""
from select import poll, POLLIN, POLLHUP
from subprocess import Popen, PIPE
from phpsh import PhpshConfig
import xml.dom.minidom
import signal
import socket
import shlex
import time
import sys
import re
import os
__version__ = "1.0"
__author__ = "<EMAIL>"
__date__ = "Nov 05, 2008"
usage = "dbgp.py <4-pipe-fds>"
client_init_error_msg = """
Timed out while waiting for debug client for %ds. Make sure the client is
configured for PHP debugging and expects xdebug connections on port
%d. Client command was: %s"""
logfile = None
def debug_log(s):
global tracing_enabled
global logfile
if not tracing_enabled:
return
if not logfile:
logfile = open("dbgp.log", "a", 1)
logfile.write('\n>>>>>>>>>>>>>>>>>>>>>>>\n\n')
logfile.write(s + '\n\n')
logfile.flush()
def dbgp_get_filename(dbgp_response):
"""If dbgp_response is a dbgp <response> message with status='break' and
'filename' attribute set, return the value of filename. Otherwise
return None"""
doc = xml.dom.minidom.parseString(dbgp_response)
res = doc.getElementsByTagName("response")
if res and res[0].getAttribute('status') == "break":
msg = doc.getElementsByTagName("xdebug:message")
if msg and msg[0].hasAttribute('filename'):
return msg[0].getAttribute('filename')
def dbgp_get_txid(dbgp_response):
doc = xml.dom.minidom.parseString(dbgp_response)
res = doc.getElementsByTagName("response")
if res:
return res[0].getAttribute('transaction_id')
def dbgp_get_bpid(dbgp_response):
"""If dbgp_response is a response to 'breakpoint_set' with
transaction_id=txid, return the value of id attribute as a string.
Otherwise return None"""
doc = xml.dom.minidom.parseString(dbgp_response)
res = doc.getElementsByTagName("response")
if res and res[0].getAttribute('command') == 'breakpoint_set':
return res[0].getAttribute('id')
def xdebug_is_stopping(dbgp_response):
doc = xml.dom.minidom.parseString(dbgp_response)
res = doc.getElementsByTagName("response")
return res and res[0].getAttribute("status") == "stopping"
def parse_port(portstr):
if not portstr:
return None
try:
port = int(portstr)
if port < 0:
raise ValueError, "Invalid port: " + portstr
elif port == 0:
port = None
except ValueError:
raise ValueError, "Invalid port: " + portstr
return port
def parse_timeout(timeoutstr):
if not timeoutstr:
return None
try:
timeout = int(timeoutstr)
if timeout <= 0:
return None
except ValueError:
raise ValueError, "Invalid timeout: " + timeoutstr
return timeout
def get_emacs_version():
vline = Popen("emacs --version | head -n 1", shell=True,
stdout=PIPE, stderr=PIPE).communicate()[0]
if not vline:
raise OSError, "emacs not found. Make sure it's in your PATH."
m = re.compile("GNU Emacs ([0-9.]+)").match(vline)
if not m:
raise ValueError, "could not parse emacs version: " + vline + \
"\nexpected GNU Emacs [0-9.]+"
try:
return [int(s) for s in m.group(1).strip('.').split('.')]
except ValueError:
raise ValueError, "invalid Emacs version format: " + m.group(1)
def get_debugclient_version(debugclient_path):
vline = Popen(debugclient_path + " -v | head -n 1", shell=True,
stdout=PIPE, stderr=PIPE).communicate()[0]
if not vline:
raise OSError, "debugclient not found\nThis is a simple xdebug " \
"protocol client distributed with xdebug\n" \
"Make sure it's in your PATH."
m = re.compile("Xdebug Simple DBGp client \(([0-9.]+)\)").match(vline)
if not m:
raise ValueError, "could not parse debugclient version: " + vline + \
"\nexpected Xdebug Simple DBGp client ([0-9.]+)"
try:
return [int(s) for s in m.group(1).strip('.').split('.')]
except ValueError:
raise ValueError, "invalid debugclient version format: " + m.group(1)
class DebugClient:
"""Objects of this class are interfaces to debug IDE clients.
A DebugClient object may exist even if the underlying IDE process is no longer running.
"""
def __init__(self, config_, port):
self.p_client = None # Popen to client
self.conn = None # DBGpConn to client
self.lasttxid = None # last txid seen from this client
self.lastdbgpcmd = None # name of last command read from client
self.stopped = True # never sent anything to this client, or
# last message was "stopped"
self.config = config_ # RawConfigParser
self.port = port
self.host = config_.get_option("Debugging", "ClientHost")
self.timeout = parse_timeout(config_.get_option("Debugging", "ClientTimeout"))
self.auto_close = False # client exits after each debugging session
# self.emacs_command() may set this to True
debug_log("creating DebugClient object")
if config_.get_option("Debugging", "X11").startswith("require") \
and not os.getenv('DISPLAY'):
debug_log("X11 is required and DISPLAY is not set")
raise Exception, "X11 is required and DISPLAY is not set"
cmd = config_.get_option("Debugging", "DebugClient")
if cmd.startswith("emacs"):
emacs_version = get_emacs_version()
if emacs_version < [22, 1]:
raise Exception, "emacs version " + str(emacs_version) + \
" is too low, 22.1 or above required"
debugclient_path = config_.get_option("Emacs", "XdebugClientPath")
debugclient_version = get_debugclient_version(debugclient_path)
if debugclient_version < [0, 10, 0]:
raise Exception, "debugclient (xdebug client) version " + \
str(debugclient_version) + " is too low. 0.10.0 or " \
"above required"
self.cmd = self.emacs_command(config_)
else:
self.cmd = shlex.split(cmd)
def connect(self):
"""Try to connect to self.host:self.port (if host is an empty string,
connect to localhost). If can't connect and host is localhost,
execute cmd and try to connect again until timeout. Raises
socket.timeout if client is not up until timeout, OSError if
client could not be started"""
global config
if self.conn:
if self.conn.isconnected():
# check if the client is still connected by reading
# everything that the client sent us since the end of
# last session (if any) and checking for HUP
client_set = poll()
client_set.register(self.conn.get_sockfd(), POLLIN)
events = client_set.poll(0)
try:
while events:
fd, e = events[0]
if e & POLLHUP:
self.conn.close()
self.conn = None
raise EOFError
else:
self.recv_cmd()
events = client_set.poll(0)
return # still connected
except (socket.error, EOFError):
pass
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((self.host, self.port))
except socket.error, msg_:
if self.host != '' and self.host != 'localhost' \
and self.host != '127.0.0.1' or not self.cmd:
# could not connect and client is not local or no command
# to start a client. Propagate exception.
raise socket.error, msg_
# client is local, X display is set, try to start it
debug_log("Starting client: " + " ".join(self.cmd))
self.p_client = Popen(self.cmd, close_fds=True)
sock.settimeout(self.timeout)
t_start = time.time()
while True:
try:
debug_log("Connecting to client")
sock.connect(('', self.port))
sock.settimeout(None)
debug_log("Connected to client")
break
except socket.error:
# failed to connect, likely client is not up yet
# keep trying
if self.timeout and time.time() - t_start > self.timeout:
debug_log("Timed out while waiting "
"for debug client to come up")
self.close()
raise socket.timeout, "Timed out while waiting " \
"for debug client to come up"
time.sleep(1)
self.conn = DBGpConn(sock)
def send_msg(self, msg_):
self.conn.send_msg(msg_)
self.stopped = False
def recv_cmd(self):
cmd = self.conn.recv_cmd()
try:
lcmd = cmd.split()
i = lcmd.index("-i")
self.lasttxid = lcmd[i + 1]
self.lastdbgpcmd = lcmd[0]
except Exception:
debug_log("ERROR: did not find txid in command read from client: "
+ cmd)
return cmd
def get_sockfd(self):
return self.conn.get_sockfd()
def stop(self):
if self.stopped or not self.lasttxid or not self.lastdbgpcmd or \
not self.conn.isconnected():
# client is already stopped or hasn't run a debug session
return False
stopped = (
'<?xml version="1.0" encoding="iso-8859-1"?>\n<response '
'xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" '
'command="{cmd}" transaction_id="{id}" status="stopped" reason="ok"></response>'
).format(cmd=self.lastdbgpcmd, id=self.lasttxid)
self.send_msg(stopped)
self.stopped = True
# If our client is emacs that we started and it is
# running without X11, phpsh.el will make it exit at the
# end of debug session. We must wait for that event before
# allowing php to run and phpsh to try to print to terminal.
# Emacs uses tcsetpgrp() to effectively place all other
# processes in its pgroup (including phpsh) in the background.
# Allowing phpsh to print to terminal before emacs reverts the
# terminal pgroup will result in SIGTTOU sent to phpsh
# and dbgp, suspending them. Even if we wignored the signals,
# anything phpsh prints to terminal before emacs resets it
# will be lost or unreadable.
if self.auto_close:
debug_log("waiting for client to exit")
self.wait()
def wait(self):
if self.p_client:
os.waitpid(self.p_client.pid, 0)
def close(self):
"""Close connection to debug client and kill it if we started it"""
if self.conn and self.conn.isconnected():
self.stop()
self.conn.close()
if self.p_client:
try:
os.kill(self.p_client.pid, signal.SIGKILL)
self.wait() # collect zombie
except OSError:
pass
self.p_client = None
def emacs_command(self, config_):
"""Returns a list containing a shell command to start and
configure emacs according to the settings in phpsh config file"""
phpsh_root = os.path.dirname(os.path.realpath(__file__))
elisp_root = os.path.join(phpsh_root, "xdebug-clients/geben")
geben_elc = os.path.join(elisp_root, "geben.elc")
phpsh_el = os.path.join(phpsh_root, "phpsh.el")
help = os.path.join(elisp_root, "help")
debugclient_path = config_.get_option("Emacs", "XdebugClientPath")
use_x = os.getenv('DISPLAY') and \
config_.get_option("Debugging", "X11") != "no"
if use_x:
fg = config_.get_option("Emacs", "ForegroundColor")
bg = config_.get_option("Emacs", "BackgroundColor")
ina = config_.get_option("Emacs", "InactiveColor")
family = config_.get_option("Emacs", "FontFamily")
size = config_.get_option("Emacs", "FontSize")
elisp = (
"(progn (set-face-foreground 'default \"{fg}\") (setq active-bg \"{bg}\") "
"(setq inactive-bg \"{ina}\") (setq geben-dbgp-command-line \"{path} -p {port}\") "
).format(fg=fg, bg=bg, ina=ina, path=debugclient_path, port=self.port)
if family or size:
elisp += "(set-face-attribute 'default nil"
if family:
elisp += " :family \"" + family + "\""
if size:
elisp += " :height " + size
elisp += ") "
if config_.get_option("Emacs", "InactiveMinimize") == "yes":
elisp += (
"(add-hook 'geben-session-finished-hook 'iconify-frame) "
"(add-hook 'geben-session-starting-hook 'make-all-frames-visible) ")
else:
# no X
self.auto_close = True
elisp = "(progn (setq geben-dbgp-command-line \"" + debugclient_path + \
" -p " + str(self.port) + "\") " \
"(setq geben-dbgp-redirect-stdout-current :intercept) " \
"(setq geben-dbgp-redirect-stderr-current :intercept) "
# in terminal mode we set php stdout/err redirection mode
# to "intercept" in geben. this will make xdebug forward
# php stdout/err to geben over the TCP connection instead
# of writing to the parent pipe. This prevents phpsh from
# printing the output to terminal while emacs is running,
# which could mess up display and generate a SIGTTOU.
if config_.get_option("Debugging", "Help") == "yes":
elisp += "(split-window) " \
"(find-file-read-only \"" + help + "\") " \
"(other-window 1) "
else:
elisp += "(find-file-read-only \"" + help + "\") " \
"(switch-to-buffer \"*scratch*\") "
elisp += ")"
if use_x:
return ["emacs", "--name", "phpsh-emacs", "-Q", "-l", geben_elc,
"-l", phpsh_el, "--eval", elisp, "-f", "geben"]
else:
return ["emacs", "-nw", "-Q", "-l", geben_elc,
"-l", phpsh_el, "--eval", elisp, "-f", "geben"]
class XDebug:
"""Encapsulates XDebug connection and communication"""
def __init__(self, s_accept):
sock, addr = s_accept.accept()
self.conn = DBGpConn(sock) # xdebug DBGp connection
self.dbgp_init = self.conn.recv_msg()
self.txid = 1000000 # use high txids to avoid clashes with clients
self.run()
def isconnected(self):
return self.conn and self.conn.isconnected()
def get_dbgp_init(self):
return self.dbgp_init
def set_breakpoint(self, function):
"""Attempt to set a breakpoint at the beginning of _function_.
Return breakpoint id on success, None if breakpoint could not be set"""
self.txid += 1
cmd = "breakpoint_set -i " + str(self.txid) + " -t call -m " + function
self.send_cmd(cmd)
reply = self.recv_reply()
bpid = dbgp_get_bpid(reply)
return bpid
def remove_breakpoint(self, bpid):
self.txid += 1
cmd = "breakpoint_remove -i " + str(self.txid) + " -d " + bpid
self.send_cmd(cmd)
self.recv_reply() # discard reply
def remove_all_breakpoints(self):
self.txid += 1
cmd = "breakpoint_list -i " + str(self.txid)
self.send_cmd(cmd)
response = self.recv_reply()
doc = xml.dom.minidom.parseString(response)
bps = doc.getElementsByTagName("breakpoint")
for bp in bps:
if bp.hasAttribute("id"):
self.remove_breakpoint(bp.getAttribute("id"))
def run(self):
self.txid += 1
cmd = "run -i " + str(self.txid)
self.send_cmd(cmd)
def stop(self):
self.txid += 1
cmd = "stop -i " + str(self.txid)
self.send_cmd(cmd)
def recv_msg(self):
msg = self.conn.recv_msg()
if xdebug_is_stopping(msg):
self.stop()
self.disconnect()
raise EOFError("xdebug is stopping")
else:
return msg
def recv_reply(self, txid=None):
if not txid:
txid = self.txid
while True:
msg = self.recv_msg()
rtxid = dbgp_get_txid(msg)
if rtxid and str(txid) == str(rtxid):
return msg
def send_cmd(self, cmd):
return self.conn.send_cmd(cmd)
def get_sockfd(self):
return self.conn.get_sockfd()
def disconnect(self):
self.conn.close()
class DebugSession:
"""This class encapsulates the process of debugging a single
function"""
def __init__(self, function, client, xdebug, p_in):
self.client = client
self.xdebug = xdebug
self.function = function
self.p_in = p_in # file encapsulating "from parent" pipe end
def setup(self):
"""This function must be called when php just executed the initial xdebug_break()
call that starts a new debugging session and the initial <break> message has been received
from xdebug. setup() verifies that the function call being debugged is valid. If it is, a
debug client is started and its view is set to display the first line of function.
If the function call is invalid, for example, the function name cannot be found, setup()
throws an Exception."""
# set a breakpoint on the function being debugged and on
# ___phpsh___eval_completed(), which phpsh.php will execute
# right after the eval(), continue PHP execution
debug_log("setting up debug session")
funbp = self.xdebug.set_breakpoint(self.function)
donebp = self.xdebug.set_breakpoint('___phpsh___eval_completed')
self.xdebug.run()
filename = None
while not filename:
reply = self.xdebug.recv_msg()
filename = dbgp_get_filename(reply)
if not filename.startswith("file://") or \
filename.endswith("/phpsh.php"):
# Execution stopped at ___phpsh___eval_completed() or in the
# eval(). Abort the session.
self.client = None
raise Exception, "Invalid PHP function call"
# at this point reply and filename are initialized. Delete
# breakpoint at self.function, then send <init> to client with
# fileuri attr set to filename (followed by the break message
# itself?)
self.xdebug.remove_breakpoint(funbp)
r = re.compile(' fileuri="([^"]*)"', re.M)
client_init = r.sub(' fileuri="' + filename + '"',
self.xdebug.get_dbgp_init())
self.client.connect()
self.client.send_msg(client_init)
#self.client.send_msg(reply) --this breaks geben, so disabling for now
# but vim seems to need id
def run(self):
"""forward messages between client and xdebug until xdebug stops in
phpsh.php, client closes connection or parent closes stdin"""
debug_log("running debug session")
session_set = poll()
session_set.register(self.client.get_sockfd(), POLLIN)
session_set.register(self.xdebug.get_sockfd(), POLLIN)
session_set.register(self.p_in.fileno(), POLLIN | POLLHUP)
while True:
events = session_set.poll()
for fd, e in events:
if fd == self.p_in.fileno():
phpsh_cmd = self.p_in.readline().strip()
if phpsh_cmd == 'run php':
# phpsh wants to restart php
# if php is blocked in xdebug, send a run command
raise EOFError # TODO: handle this gracefully
else:
raise EOFError
elif fd == self.client.get_sockfd():
dbgp_cmd = self.client.recv_cmd()
self.xdebug.send_cmd(dbgp_cmd)
elif fd == self.xdebug.get_sockfd():
reply = self.xdebug.recv_msg()
filename = dbgp_get_filename(reply)
if filename and filename.endswith("/phpsh.php"):
return
self.client.send_msg(reply)
def stop(self):
"""Do our best to clean up if we got to the end of a session
or if client or xdebug connection had an exception. This
function does not throw any IO exceptions."""
if self.client:
try:
# Send client a stop message at end of session.
self.client.stop()
except (socket.error, EOFError):
pass
if self.xdebug and self.xdebug.isconnected():
try:
# remove all bps we set in xdebug so that php will not
# get stuck on them when phpsh issues non-debug evals
debug_log("removing all breakpoints")
self.xdebug.remove_all_breakpoints()
debug_log("unblocking script")
self.xdebug.run()
except (socket.error, EOFError):
pass
class PhpshDebugProxy:
"""This is a DBGp filtering proxy for phpsh. It sits between xdebug.so
extension in PHP interpreter and a GUI debug client such as
Geben/Emacs and alters the conversation in a way that makes the
debugger and client begin debugging on a function specified through
commands that the proxy reads from g_in"""
# if doing dynamic port assignment, pick ports from this range:
min_port = 9002
max_port = 9998
def __init__(self, config, p_in, p_out):
self.config = config # RawConfigParser
self.cmd = None # Popen command list to start client if local
self.client = None # DebugClient
self.xdebug = None # XDebug
self.session = None # DebugSession
self.s_accept = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.p_in = p_in # file encapsulating a pipe from parent
self.p_out = p_out # file encapsulating a pipe to parent
# host on which client runs:
client_host = config.get_option("Debugging", "ClientHost")
# client listens on this port
client_port = parse_port(config.get_option("Debugging", "ClientPort"))
if not client_port and client_host and client_host != "localhost" and \
not client_host.startswith("127.0.0."):
raise Exception(
"configuration error: remote ClientHost with no ClientPort")
listen_port = parse_port(config.get_option("Debugging", "ProxyPort"))
if listen_port:
self.s_accept.bind(('', listen_port))
else:
listen_port = self.bind_to_port()
if not client_port:
client_port = listen_port + 1
try:
self.client = DebugClient(config, client_port)
self.s_accept.listen(1)
self.s_accept.settimeout(1)
except Exception:
self.s_accept.close()
raise
# tell parent we have initialized
debug_log("initialized, bound to port " + str(listen_port))
self.tell_parent('initialized port=' + str(listen_port))
def parent_closed(self):
"""Return True if 'from parent' pipe has HUP condition"""
evset = poll()
evset.register(self.p_in.fileno(), POLLIN | POLLHUP)
events = evset.poll(0)
if events:
fd, e = events[0]
if e & POLLHUP:
debug_log("parent_closed(): detected HUP")
return True
return False
def tell_parent(self, str):
self.p_out.write(str + '\n')
self.p_out.flush()
def bind_to_port(self):
"""Find an unused pair of adjacent ports (n,n+1) where n is
between PhpshDebugProxy.min_port and max_port. Bind .s_accept to
n and return n. Throw socket.exception if suitable pair was
available."""
for n in xrange(PhpshDebugProxy.min_port, PhpshDebugProxy.max_port + 2, 2):
try:
self.s_accept.bind(('', n))
except socket.error:
continue
# check if client port is also available
trysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
trysock.bind(('', n + 1))
trysock.close()
return n
except socket.error:
trysock.close()
self.s_accept.close()
self.s_accept = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
raise socket.error, "No ports available"
def run(self):
"""main loop of dbgp proxy"""
while True:
if self.xdebug is None or not self.xdebug.isconnected():
# if we do not have an xdebug connection, accept one
# keep an eye on phpsh, exit if it closes our stdin
self.xdebug = None
while not self.xdebug:
try:
debug_log("creating XDebug object")
self.xdebug = XDebug(self.s_accept)
except (socket.error, socket.timeout, EOFError):
if self.parent_closed():
debug_log("parent closed its end of pipe")
return
time.sleep(1)
# at this point self.xdebug is initialized
# block waiting for a command from phpsh, if xdebug disconnects
# because PHP was restarted, start over
phpsh_cmd = None
try:
cmd_pollset = poll()
cmd_pollset.register(self.p_in.fileno(), POLLIN | POLLHUP)
cmd_pollset.register(self.xdebug.get_sockfd(), POLLIN | POLLHUP)
while not phpsh_cmd:
# wait for a command from phpsh
# keep an eye on PHP, handle restarts
events = cmd_pollset.poll()
for fd, e in events:
if fd == self.p_in.fileno():
phpsh_cmd = self.p_in.readline().strip()
debug_log("Got command: >>" + phpsh_cmd + "<<")
break
elif fd == self.xdebug.get_sockfd():
# xdebug disconnected or sent us something
# after <init> or after previous client
# session ended. This cannot be the
# initial <break> of next session because
# phpsh only evals xdebug_break() after it
# gets a "ready" from dbgp, and we haven't
# sent it yet.
res = self.xdebug.recv_msg()
filename = dbgp_get_filename(res)
if filename and filename.endswith("/phpsh.php"):
# there is a bug in xdebug where it breaks
# on ___phpsh___eval_completed() after the
# breakpoint on that function was removed. This
# happens only if we reach the function via
# a "step out" command. Compensate by sending
# a run command.
debug_log("ERROR: xdebug stopped in phpsh.php "
"after breakpoint was removed.")
self.xdebug.run()
except (socket.error, EOFError), msg:
debug_log("Exception while waiting for command: " + str(msg))
if self.parent_closed():
return # phpsh went away
if not self.xdebug.isconnected():
continue # xdebug disconnected
else:
debug_log("Error: unexpected exception " + str(msg))
# at this point phpsh_cmd has a new command from phpsh
if phpsh_cmd.startswith("x "):
function = phpsh_cmd[2:].strip()
# in the future we will be checking here if debugging
# can be started, for now we create a session object
# unconditionally and tell phpsh to go on. If later we
# fail to start a debug client, we just continue
# execution without debugging.
session = DebugSession(function, self.client,
self.xdebug, self.p_in)
debug_log("sending 'ready' to parent")
self.tell_parent("ready")
try:
# wait for an initial break message issued by
# xdebug_break() that phpsh is going to execute
# right before the target function
debug_log("waiting for inital 'break'")
self.xdebug.recv_msg()
# php is stopped in xdebug after executing xdebug_break()
session.setup()
session.run()
except Exception, msg:
# client, PHP, or phpsh exited, session.stop() will
# clean up
debug_log("Exception while setting up or running debug "
"session: " + str(msg))
pass
session.stop()
if self.parent_closed():
return
elif phpsh_cmd == "run php":
# phpsh sends this when it needs to restart PHP
# Since PHP is not blocked in debugger there
# is nothing to do. Ignore.
debug_log("got 'run php' from phpsh while waiting "
"for x command")
else:
self.tell_parent("ERROR: invalid command: " + phpsh_cmd)
# Based on debugger.py for Vim. Closes underlying socket on all exceptions.
#
# Authors:
# <NAME> <segv <at> sayclub.com>
# <NAME> <sam <at> box.net>
class DBGpConn:
"""DBGp Connection class."""
def __init__(self, sock):
self.sock = sock
def isconnected(self):
return not self.sock is None
def close(self):
if not self.sock is None:
self.sock.close()
self.sock = None
def _recv_length(self):
length = ''
while 1:
c = self.sock.recv(1)
if c == '':
self.close()
raise EOFError('Socket Closed')
if c == '\0':
return int(length)
if c.isdigit():
length = length + c
def _recv_null(self):
while 1:
c = self.sock.recv(1)
if c == '':
self.close()
raise EOFError('Socket Closed')
if c == '\0':
return
def _recv_body(self, to_recv):
body = ''
while to_recv > 0:
buf = self.sock.recv(to_recv)
if buf == '':
self.close()
raise EOFError('Socket Closed')
to_recv -= len(buf)
body = body + buf
return body
def recv_msg(self):
try:
length = self._recv_length()
body = self._recv_body(length)
self._recv_null()
debug_log("received from " + str(self.sock.fileno()) + ": " + body)
return body
except:
self.close()
raise
def recv_cmd(self):
try:
cmd = ''
while True:
c = self.sock.recv(1)
if c == '':
self.close()
raise EOFError('Socket Closed')
elif c == '\0':
debug_log("received from " + str(self.sock.fileno()) + ": " +
cmd)
return cmd
else:
cmd += c
except:
self.close()
raise
def send_cmd(self, cmd):
try:
self.sock.send(cmd + '\0')
debug_log("sent to " + str(self.sock.fileno()) + ": " + cmd)
except:
self.close()
raise
def send_msg(self, msg):
try:
self.sock.send(str(len(msg)) + '\0' + msg + '\0')
debug_log("sent to " + str(self.sock.fileno()) + ": " + msg)
except:
self.close()
raise
def get_sockfd(self):
if self.sock:
return self.sock.fileno()
config = PhpshConfig()
try:
config.read()
except Exception, msg:
pass
tracing_enabled = (config.get_option("Debugging", "LogDBGp") == "yes")
if len(sys.argv) < 5:
debug_log("dbgp called with %d arguments, 4 required, exiting..." %
(len(sys.argv) - 1))
sys.exit(1)
try:
p_in = os.fdopen(int(sys.argv[1]), "r", 0) # read end of pipe from parent
try:
os.close(int(sys.argv[2])) # write end of "in" pipe
except OSError:
pass
try:
os.close(int(sys.argv[3])) # read end of "out" pipe
except OSError:
pass
p_out = os.fdopen(int(sys.argv[4]), "w", 0) # write end of pipe to parent
except Exception, msg:
debug_log("Caught an exception while parsing arguments, exiting: " +
str(msg))
sys.exit(1)
# do not die on SIGINT, SIGPIPE
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGPIPE, signal.SIG_IGN)
try:
proxy = PhpshDebugProxy(config, p_in, p_out)
except Exception, msg:
debug_log("failed to initialize: " + str(msg))
p_out.write("failed to initialize: " + str(msg))
sys.exit(1)
proxy.run()
if proxy.client:
debug_log("Closing client")
proxy.client.close()
else:
debug_log("No client to close")
<file_sep>__version__ = "1.3"
__author__ = "<EMAIL>"
__date__ = "Nov 20, 2008"
from subprocess import Popen, PIPE, call
from threading import Thread
from bisect import bisect
import ansicolor as clr
import cmd_util as cu
import ctags
import ConfigParser
import os
import re
import readline
import select
import signal
import sys
import tempfile
import time
comm_poll_timeout = 0.01
PHP_RESERVED_WORDS = [
# Include reserved words from
# http://us3.php.net/manual/en/reserved.keywords.php
"abstract",
"and",
"array",
"as",
"break",
"case",
"catch",
"cfunction",
"class",
"clone",
"const",
"else",
"continue",
"declare",
"default",
"do",
"else",
"elseif",
"enddeclare",
"endfor",
"endforeach",
"endif",
"endswitch",
"endwhile",
"extends",
"final",
"for",
"foreach",
"function",
"global",
"goto", # (!)
"if",
"implements",
"interface",
"instanceof",
"namespace",
"new",
"old_function",
"or",
"private",
"protected",
"public",
"static",
"switch",
"throw",
"try",
"use",
"var",
"while",
"xor",
"__CLASS__",
"__DIR__",
"__FILE__",
"__FUNCTION__",
"__METHOD__",
"__NAMESPACE__",
"die",
"echo",
"empty",
"exit",
"eval",
"include",
"include_once",
"isset",
"list",
"require",
"require_once",
"return",
"print",
"unset",
]
def help_message():
return """\
-- Help --
Type php commands and they will be evaluted each time you hit enter. Ex:
php> $msg = "hello world"
Put = at the beginning of a line as syntactic sugar for return. Ex:
php> = 2 + 2
4
phpsh will print any returned value (in yellow) and also assign the last
returned value to the variable $_. Anything printed to stdout shows up blue,
and anything sent to stderr shows up red.
You can enter multiline input, such as a multiline if statement. phpsh will
accept further lines until you complete a full statement, or it will error if
your partial statement has no syntactic completion. You may also use ^C to
cancel a partial statement.
You can use tab to autocomplete function names, global variable names,
constants, classes, and interfaces. If you are using ctags, then you can hit
tab again after you've entered the name of a function, and it will show you
the signature for that function. phpsh also supports all the normal
readline features, like ctrl-e, ctrl-a, and history (up, down arrows).
Note that stdout and stderr from the underlying php process are line-buffered;
so php> for ($i = 0; $i < 3; $i++) {echo "."; sleep(1);}
will print the three dots all at once after three seconds.
(echo ".\n" would print one a second.)
See phpsh -h for invocation options.
-- phpsh quick command list --
h Display this help text.
r Reload (e.g. after a code change). args to r append to add
includes, like: php> r ../lib/username.php
(use absolute paths or relative paths from where you start phpsh)
R Like 'r', but change includes instead of appending.
d Get documentation for a function or other identifier.
ex: php> d my_function
D Like 'd', but gives more extensive documentation for builtins.
v Open vim read-only where a function or other identifer is defined.
ex: php> v some_function
V Open vim (not read-only) and reload (r) upon return to phpsh.
e Open emacs where a function or other identifer is defined.
ex: php> e some_function
x [=]function([args]) Execute function() with args under debugger
c Append new includes without restarting; display includes.
C Change includes without restarting; display includes.
! Execute a shell command.
ex: php> ! pwd
q Quit (ctrl-D also quits)
"""
def do_sugar(line):
line = line.lstrip()
if line.startswith("="):
line = "return " + line[1:]
if line:
line += ";"
return line
def line_encode(line):
return cu.multi_sub({"\n": "\\n", "\\": "\\\\"}, line) + "\n"
def inc_args(s):
"""process a string of includes to a set of them"""
return set([inc.strip() for inc in s.split(" ") if inc.strip()])
def xdebug_loaded():
"""checks if Xdebug is already loaded"""
try:
retcode = call("php -m | grep Xdebug &> /dev/null", shell=True)
return retcode == 0
except OSError:
return False
def get_php_ext_path():
extension_dir = Popen(
"php-config | grep extension-dir", shell=True, stdout=PIPE, stderr=PIPE).communicate()[0]
if extension_dir:
lbr = extension_dir.find("[")
rbr = extension_dir.find("]")
if 0 < lbr < rbr:
return extension_dir[lbr + 1:rbr]
def sigalrm_handler(sig, frame):
raise OSError("Alarm")
class PhpMultiliner:
"""This encapsulates the process and state of intaking multiple input lines
until a complete php expression is formed, or detecting a syntax error.
Note: this is not perfectly encapsulated while the parser has global state
"""
complete = "complete"
incomplete = "incomplete"
syntax_error = "syntax_error"
def __init__(self):
self.partial = ""
def check_syntax(self, line):
p = Popen(["php", "-r", "return;" + line], stdout=PIPE, stderr=PIPE)
p.wait()
# "php -r" lint errors seem to only use stdout, but it might (idk)
# depend on configuration or change later, so just grab everything.
ls = p.stdout.readlines() + p.stderr.readlines()
# hack so that missing extensions etc don't halt all phpsh use.
# these php startup errors will still show at phpsh start up.
ls = [l for l in ls if l.find("PHP Startup:") == -1]
l = "".join(ls)
if l:
if l.find("unexpected end") != -1 or l.find("unexpected $end") != -1:
return self.incomplete, ""
return self.syntax_error, l
return self.complete, ""
def input_line(self, line):
if self.partial:
self.partial += "\n"
self.partial += line
partial_mod = do_sugar(self.partial)
if not partial_mod:
return self.complete, ""
(syntax_info, _) = self.check_syntax(partial_mod)
if syntax_info == self.complete:
# Multiline inputs are encoded to one line.
partial_mod = line_encode(partial_mod)
self.clear()
return syntax_info, partial_mod
# We need to pull off the syntactic sugar ; to see if the line failed
# the syntax check because of syntax_error, or because of incomplete.
return self.check_syntax(partial_mod[:-1])
def clear(self):
self.partial = ""
class ProblemStartingPhp(Exception):
def __init__(self, file_name=None, line_num=None, stdout_lines=None, stderr_lines=None):
self.file_name = file_name
self.line_num = line_num
self.stdout_lines = stdout_lines
self.stderr_lines = stderr_lines
class PhpshConfig:
def __init__(self):
self.config = ConfigParser.RawConfigParser({
"UndefinedFunctionCheck": "yes",
"Xdebug": None,
"DebugClient": "emacs",
"ClientTimeout": 60,
"ClientHost": "localhost",
"ClientPort": None,
"ProxyPort": None,
"Help": "no",
"LogDBGp": "no",
"ForegroundColor": "black",
"BackgroundColor": "white",
"InactiveColor": "grey75",
"InactiveMinimize": "yes",
"FontFamily": None,
"FontSize": None,
"XdebugClientPath": "debugclient",
"X11": "yes"})
self.config.add_section("General")
self.config.add_section("Debugging")
self.config.add_section("Emacs")
def read(self):
config_files = ["/etc/phpsh/config"]
home = os.getenv("HOME")
if home:
homestr = home.strip()
if homestr:
config_files.append(os.path.join(homestr, ".phpsh/config"))
self.config.read(config_files)
return self.config
def get_option(self, s, o):
if self.config.has_option(s, o):
return self.config.get(s, o)
else:
return None
def until_paren_close_balanced(s):
lparens = 1
for i in range(len(s)):
if s[i] == "(":
lparens += 1
elif s[i] == ")":
lparens -= 1
if lparens == 0:
return s[:i]
return s
class LoadCtags(Thread):
def __init__(self, phpsh_state):
Thread.__init__(self)
self.phpsh_state = phpsh_state
self.phpsh_state.function_signatures = {}
def run(self):
tags_file_path = None
try:
try:
tags_file_path = ctags.find_tags_file()
except ctags.CantFindTagsFile, e:
return
print self.phpsh_state.clr_cmd + \
"Loading ctags (in background)" + \
self.phpsh_state.clr_default
self.phpsh_state.ctags = ctags.Ctags(tags_file_path)
try:
self.phpsh_state.function_signatures = \
ctags.CtagsFunctionSignatures().function_signatures
except Exception, e:
print self.phpsh_state.clr_err + \
"Problem loading function signatures" + \
self.phpsh_state.clr_default
except Exception, e:
if tags_file_path:
path = tags_file_path
else:
path = ""
print self.phpsh_state.clr_err + \
"Problem loading ctags %(path)s\n(%(e)s)\n" % locals() + \
self.phpsh_state.clr_default
class PhpshState:
"""This doesn't perfectly encapsulate state (e.g. the readline module has
global state), but it is a step in the
right direction and it already fulfills its primary objective of
simplifying the notion of throwing a line of input (possibly only part of a
full php line) at phpsh.
"""
php_prompt = "php> "
php_more_prompt = " ... "
no_command = "no_command"
yes_command = "yes_command"
quit_command = "quit_command"
debug_command = "x "
def __init__(self, cmd_incs, do_color, do_echo, codebase_mode,
do_autocomplete, do_ctags, interactive, with_xdebug, verbose):
"""start phpsh.php and do other preparations (colors, ctags)
"""
self.phpsh_root = os.path.dirname(os.path.realpath(__file__))
self.do_echo = do_echo
self.p_dbgp = None # debugging proxy
self.dbgp_port = 9000 # default port on which dbgp proxy listens
self.temp_file_name = tempfile.mkstemp()[1]
self.output_tempfile = None # tempfile to buffer php output
self.with_xdebug = with_xdebug
self.verbose = verbose
self.xdebug_path = None # path to xdebug.so read from config file
self.xdebug_disabled_reason = None # why debugging was disabled
self.to_dbgp = None # fds of pipe endpoints for writing commands
self.from_dbgp = None # to dbgp proxy and reading replies
# so many colors, so much awesome
if not do_color:
self.clr_cmd = ""
self.clr_err = ""
self.clr_help = ""
self.clr_announce = ""
self.clr_default = ""
else:
self.clr_cmd = clr.Green
self.clr_err = clr.Red
self.clr_help = clr.Green
self.clr_announce = clr.Magenta
self.clr_default = clr.Default
self.config = PhpshConfig()
try:
self.config.read()
except Exception, msg:
self.print_error("Failed to load config file, using default settings: " + str(msg))
if self.with_xdebug:
xdebug = self.config.get_option("Debugging", "Xdebug")
if xdebug and xdebug != "yes":
if xdebug == "no":
self.with_xdebug = False
self.xdebug_disabled_reason = "Xdebug is set to 'no' in config file"
else:
self.xdebug_path = xdebug
self.comm_base = ["php"]
if self.with_xdebug:
xdebug_comm_base = self.comm_base[:]
if not xdebug_loaded():
php_ext_dir = get_php_ext_path()
if php_ext_dir:
if not self.xdebug_path:
self.xdebug_path = php_ext_dir + "/xdebug.so"
try:
os.stat(self.xdebug_path)
xdebug_comm_base += ["-d"]
extension = "zend_extension"
if php_ext_dir.find("php/extensions/debug") >= 0:
extension += "_debug"
extension += "=\"" + self.xdebug_path + "\""
xdebug_comm_base += [extension]
# The following is a workaround if role.ini is overly
# restrictive. role.ini currently sets max nesting
# level to 50 at facebook.
xdebug_comm_base += ["-d",
"xdebug.max_nesting_level=500"]
try:
xdebug_version = self.get_xdebug_version(
xdebug_comm_base)
if xdebug_version < [2, 0, 3]:
self.xdebug_disabled_reason = (
"Xdebug version %s is too low. xdebug-2.0.3 or above required."
% xdebug_version)
self.with_xdebug = False
except Exception, msg:
self.xdebug_disabled_reason = (
self.xdebug_path + " is incompatible with your php build")
self.with_xdebug = False
except OSError:
self.xdebug_disabled_reason = \
"xdebug.so not found, tried " + self.xdebug_path
self.with_xdebug = False
self.xdebug_path = None
else:
self.xdebug_disabled_reason = """\
Could not identify PHP extensions directory.
Make sure php-config is in your PATH."""
self.with_xdebug = False
self.xdebug_path = None
if self.verbose and not self.with_xdebug and \
self.xdebug_disabled_reason:
self.print_warning("PHP debugging will be disabled:\n" +
self.xdebug_disabled_reason)
if self.with_xdebug:
self.comm_base = xdebug_comm_base
self.start_xdebug_proxy()
self.comm_base += [self.phpsh_root + "/phpsh.php",
self.temp_file_name,
codebase_mode]
if not do_color:
self.comm_base += ["-c"]
if not do_autocomplete:
self.comm_base += ["-A"]
if self.config.get_option("General", "UndefinedFunctionCheck") == "no":
self.comm_base += ["-u"]
if not self.with_xdebug:
self.comm_base += ["-f"]
self.cmd_incs = cmd_incs
# ctags integration
self.ctags = None
if do_ctags:
LoadCtags(self).start()
else:
self.function_signatures = {}
input_rc_file = os.path.join(os.environ["HOME"], ".inputrc")
if os.path.isfile(input_rc_file):
readline.parse_and_bind(open(input_rc_file).read())
readline.parse_and_bind("tab: complete")
# persistent readline history
# we set the history length to be something reasonable
# so that we don't write a ridiculously huge file every time
# someone executes a command
home_phpsh_dir = os.path.join(os.environ["HOME"], ".phpsh")
if not os.path.exists(home_phpsh_dir):
os.mkdir(home_phpsh_dir)
self.history_file = os.path.join(home_phpsh_dir, "history")
readline.set_history_length(1000)
try:
readline.read_history_file(self.history_file)
except IOError:
# couldn't read history (probably one hasn't been created yet)
pass
self.autocomplete_identifiers = sorted(PHP_RESERVED_WORDS)
self.autocomplete_cache = None
self.autocomplete_match = None
self.autocomplete_signature = None
self.show_incs(start=True)
self.php_open_and_check()
def tab_complete(text, state):
"""The completer function is called as function(text, state),
for state in 0, 1, 2, ..., until it returns a non-string value."""
if not text:
# currently there is a segfault in readline when you complete
# on nothing. so just don't allow completing on that for now.
# in the long term, we may use ipython's prompt code instead
# of readline
return None
if state == 0:
self.autocomplete_cache = []
pos = bisect(self.autocomplete_identifiers, text)
while self.autocomplete_identifiers[pos].startswith(text):
identifier = self.autocomplete_identifiers[pos]
self.autocomplete_cache.append(identifier)
pos += 1
if self.function_signatures.has_key(text):
for sig in self.function_signatures[text]:
func_str = sig[1]
if func_str[-1] == ",":
file_contents = "".join(
l[:-1] for l in file(sig[0]).readlines())
# this is not perfect but it should be good enough
look_for = "function " + text + "("
i = file_contents.find(look_for)
if i != -1:
i_paren = func_str.find("(")
if i_paren != -1:
func_str = func_str[:i_paren + 1]
i_end = i + len(look_for)
s = until_paren_close_balanced(
file_contents[i_end:])
s = re.sub(", +", ", ", s, 1000)
func_str += s + ")"
self.autocomplete_cache.append(func_str)
try:
return self.autocomplete_cache[state]
except IndexError:
return None
readline.set_completer(tab_complete)
# print welcome message
if interactive:
print self.clr_help + \
"type 'h' or 'help' to see instructions & features" + \
self.clr_default
def get_xdebug_version(self, comm_base):
p = Popen(comm_base + ["-r", "phpinfo();"], stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
if p.returncode is not 0:
raise Exception("Failed to load Xdebug\n" + err)
m = re.compile(" *with Xdebug v([0-9.]+)").search(out)
if not m:
raise Exception("Could not find xdebug version number in phpinfo() output")
try:
return [int(s) for s in m.group(1).strip(".").split(".")]
except ValueError:
raise ValueError("invalid Xdebug version format: " + m.group(1))
def start_xdebug_proxy(self):
try:
to_r, to_w = os.pipe()
from_r, from_w = os.pipe()
dbgp_py = ["dbgp-phpsh.py",
str(to_r), str(to_w), str(from_r), str(from_w)]
self.p_dbgp = Popen(dbgp_py)
os.close(to_r)
os.close(from_w)
self.to_dbgp = os.fdopen(to_w, "w", 0)
self.from_dbgp = os.fdopen(from_r, "r", 0)
try:
dbgp_status = self.from_dbgp.readline()
if dbgp_status.startswith("initialized"):
r = re.compile(".*port=([0-9]+).*")
m = r.match(dbgp_status)
if m:
self.dbgp_port = m.group(1)
else:
self.to_dbgp.close()
self.from_dbgp.close()
self.p_dbgp = None
self.with_xdebug = False
self.xdebug_disabled_reason = "xdebug proxy " + dbgp_status
except Exception, msg:
self.print_error("\
Could not obtain initialization status from xdebug proxy: %s" % msg)
self.to_dbgp.close()
self.from_dbgp.close()
self.p_dbgp = None
self.with_xdebug = False
except Exception, msg:
self.print_error("Failed to start xdebug proxy: " + str(msg))
self.with_xdebug = False
if self.verbose and not self.with_xdebug and \
self.xdebug_disabled_reason:
self.print_warning("PHP debugging will be disabled:\n" +
self.xdebug_disabled_reason)
def print_error(self, msg):
print self.clr_err + msg + self.clr_default
def print_warning(self, msg):
print self.clr_announce + msg + self.clr_default
# pass expr to php for evaluation, wait for completion
# if debug_funcall is True, the expression is being run under
# debugger.
def do_expr(self, expr, debug_funcall=False):
defer_output = debug_funcall and (
not os.getenv("DISPLAY") or self.config.get_option("Debugging", "X11") == "no")
# if we are executing a function call under debugger and debug
# client is running in the same terminal as phpsh, do not print
# the output we get from php in terminal until evaluation is done
# and debug client exits, so that we do not mess up the debug
# client UI.
self.p.stdin.write(expr)
self.wait_for_comm_finish(defer_output)
return self.result
def wait_on_ready(self):
while True:
a = self.comm_file.readline()
if a:
break
time.sleep(comm_poll_timeout)
def php_open_and_check(self):
self.p = None
while not self.p:
try:
self.php_open()
except ProblemStartingPhp, e:
self.end_process()
print(self.clr_cmd + """\
phpsh failed to initialize PHP.
Fix the problem and hit enter to reload or ctrl-C to quit.""")
print self.clr_err
print "".join(e.stdout_lines + e.stderr_lines)
if e.line_num:
print("\
Type 'e' to open emacs or 'V' to open vim to %s: %s" %
(e.file_name, e.line_num))
print self.clr_default
response = raw_input()
if response == "V":
editor = "vim"
elif response == "e":
editor = "emacs -nw"
else:
editor = ""
if editor != "":
Popen(editor + " +" + str(e.line_num) + " " +
e.file_name, shell=True).wait()
else:
print self.clr_default
raw_input()
# this file is how phpsh.php tells us it is done with a command
self.comm_file = open(self.temp_file_name)
self.wait_on_ready()
self.wait_for_comm_finish()
def php_restart(self):
if self.with_xdebug and self.p_dbgp:
self.to_dbgp.write("run php\n")
self.initialized_successfully = False
self.end_process()
return self.php_open_and_check()
def php_open(self):
self.autocomplete_identifiers = sorted(PHP_RESERVED_WORDS)
cmd = self.comm_base + list(self.cmd_incs)
env = os.environ.copy()
if self.with_xdebug:
env["XDEBUG_CONFIG"] = \
"remote_port=%(port)s remote_enable=1" % {"port": self.dbgp_port}
self.p = Popen(cmd, env=env, stdin=PIPE, stdout=PIPE, stderr=PIPE,
preexec_fn=os.setsid)
if self.with_xdebug:
# disable remote debugging for other instances of php started by
# this script, such as the multiline syntax verifier
os.putenv("XDEBUG_CONFIG", "remote_enable=0")
p_line = self.p.stdout.readline().rstrip()
if p_line != "#start_autocomplete_identifiers":
err_lines = self.p.stderr.readlines()
out_lines = self.p.stdout.readlines()
parse_error_re = re.compile(
"PHP Parse error: .* in (.*) on line ([0-9]*)")
for line in reversed(err_lines):
m = parse_error_re.match(line)
if m:
file_name, line_num = m.groups()
raise ProblemStartingPhp(file_name,
line_num,
stdout_lines=out_lines,
stderr_lines=err_lines)
raise ProblemStartingPhp(stdout_lines=out_lines,
stderr_lines=err_lines)
while True:
p_line = self.p.stdout.readline().rstrip()
if p_line == "#end_autocomplete_identifiers":
break
self.autocomplete_identifiers.append(p_line)
self.autocomplete_identifiers.sort()
def wait_for_comm_finish(self, defer_output=False):
try:
if defer_output:
if self.output_tempfile:
self.output_tempfile.truncate(0)
else:
self.output_tempfile = tempfile.TemporaryFile()
out = self.output_tempfile
err = self.output_tempfile
else:
out = sys.stdout
err = sys.stderr
# wait for signal that php command is done
# keep checking for death
out_buff = ["", ""]
buffer_size = 4096
self.result = ""
died = False
debug = False
#debug = True
while True:
if debug:
print "polling"
ret_code = self.p.poll()
if debug:
print "ret_code: " + str(ret_code)
if ret_code not in (None, 0):
if debug:
print "NOOOOO"
print "subprocess died with return code: " + repr(ret_code)
died = True
break
while not died:
# line-buffer stdout and stderr
if debug:
print "start loop"
s = select.select([self.p.stdout, self.p.stderr], [], [],
comm_poll_timeout)
if s == ([], [], []):
if debug:
print "empty"
break
if debug:
print s[0]
for r in s[0]:
if r is self.p.stdout:
out_buff_i = 0
else:
out_buff_i = 1
buff = os.read(r.fileno(), buffer_size)
if not buff:
died = True
break
out_buff[out_buff_i] += buff
last_nl_pos = out_buff[out_buff_i].rfind("\n")
if last_nl_pos != -1:
l = out_buff[out_buff_i][:last_nl_pos + 1]
self.result += l
if self.do_echo:
if r is self.p.stdout:
out.write(l)
else:
l = self.clr_err + l + self.clr_default
err.write(l)
out_buff[out_buff_i] = \
out_buff[out_buff_i][last_nl_pos + 1:]
# at this point either:
# the php instance died
# select timed out
# read till the end of the file
l = self.comm_file.readline()
lastline = l
while l.strip() != "":
l = self.comm_file.readline()
if l.strip() != "":
lastline = l
l = lastline
if l.startswith("child"):
self.p.poll()
os.kill(self.p.pid, signal.SIGHUP)
self.p.pid = int(l.split()[1])
elif l.startswith("ready"):
break
time.sleep(comm_poll_timeout)
if defer_output and self.output_tempfile.tell() > 0:
self.output_tempfile.seek(0, os.SEEK_SET)
for line in self.output_tempfile:
print line
if died:
self.show_incs("PHP died. ")
self.php_open_and_check()
except KeyboardInterrupt:
self.show_incs("Interrupt! ")
if defer_output and self.output_tempfile.tell() > 0:
self.output_tempfile.seek(0, os.SEEK_SET)
for line in self.output_tempfile: print line
self.php_restart()
def show_incs(self, pre_str="", restart=True, start=False):
s = self.clr_cmd + pre_str
inc_str = str(list(self.cmd_incs))
if start or restart:
if start:
start_word = "Starting"
else:
start_word = "Restarting"
if self.cmd_incs:
s += start_word + " php with extra includes: " + inc_str
else:
s += start_word + " php"
else:
s += "Extra includes are: " + inc_str
print s + self.clr_default
def try_command(self, line):
if line == "r" or line.startswith("r "):
# add args to phpsh.php (includes), reload
self.cmd_incs = self.cmd_incs.union(inc_args(line[2:]))
self.show_incs()
self.php_restart()
elif line == "R" or line.startswith("R "):
# change args to phpsh.php (includes), reload
self.cmd_incs = inc_args(line[2:])
self.show_incs()
self.php_restart()
elif line == "c" or line.startswith("c "):
# add args to phpsh.php (includes)
self.cmd_incs = self.cmd_incs.union(inc_args(line[2:]))
self.show_incs(restart=False)
self.p.stdin.write("\n")
elif line == "C" or line.startswith("C "):
# change args to phpsh.php (includes)
self.cmd_incs = inc_args(line[2:])
self.show_incs(restart=False)
self.p.stdin.write("\n")
elif line.startswith("d ") or line.startswith("D "):
identifier = line[2:]
if identifier.startswith("$"):
identifier = identifier[1:]
print self.clr_help
lookup_tag = False
ctags_error = "ctags not enabled"
try:
if self.ctags:
tags = self.ctags.py_tags[identifier]
ctags_error = None
lookup_tag = True
except KeyError:
ctags_error = "no ctag info found for '" + identifier + "'"
if lookup_tag:
print repr(tags)
for t in tags:
try:
file_ = self.ctags.tags_root + os.path.sep + t["file"]
doc = ""
append = False
line_num = 0
for line in open(file_):
line_num += 1
if not append:
if line.find("/*") != -1:
append = True
doc_start_line = line_num
if append:
if line.find(t["context"]) != -1:
print ("%s, lines %d-%d:" %
(file_, doc_start_line, line_num))
print doc
break
if line.find("*") == -1:
append = False
doc = ""
else:
doc += line
except:
pass
import manual
manual_ret = manual.get_documentation_for_identifier(identifier,
short=line.startswith("d "))
if manual_ret:
print manual_ret
if not manual_ret and ctags_error:
print "could not find in php manual and " + ctags_error
print self.clr_default
elif line.startswith("v "):
self.editor_tag(line[2:], "vim", read_only=True)
elif line.startswith("V "):
self.editor_tag(line[2:], "vim")
elif line.startswith("e "):
self.editor_tag(line[2:], "emacs")
elif line.startswith("x "):
if self.with_xdebug and self.p_dbgp:
return PhpshState.debug_command
else:
self.print_warning("PHP debugging is disabled")
if self.xdebug_disabled_reason:
self.print_warning(self.xdebug_disabled_reason)
return PhpshState.yes_command
elif line.startswith("!"):
# shell command
Popen(line[1:], shell=True).wait()
elif line == "h" or line == "help":
print self.clr_help + help_message() + self.clr_default
elif line == "q" or line == "exit" or line == "exit;":
return self.quit_command
else:
return self.no_command
return self.yes_command
# check if line is of the form "=?<function-name>(<args>?)"
# if it is, send it to the DBGp proxy and if the proxy reports
# that it is ready to start debugging, return True. Otherwise
# return False.
def setup_debug_client(self, funcall):
# extract function name and optional leading "=" from line
if funcall.startswith("return "):
funcall = funcall[6:].lstrip()
m = re.compile(" *([A-Za-z_][A-Za-z0-9_]*) *[(]").match(funcall)
if not m:
self.print_error("Invalid function call syntax")
return False
dbgp_cmd = "x " + m.group(1)
try:
self.to_dbgp.write(dbgp_cmd + "\n")
# TODO: put a timeout on this:
dbgp_reply = self.from_dbgp.readline()
if dbgp_reply != "ready\n":
self.print_error("xdebug proxy error: " + dbgp_reply)
return False
except Exception, msg:
self.print_error("Failed to communicate with xdebug proxy, "
"disabling PHP debugging: " + str(msg))
self.to_dbgp.close()
self.from_dbgp.close()
self.p_dbgp = None
self.with_xdebug = False
return False
# return PHP code to pass to PHP for eval
return True
def editor_tag(self, tag, editor, read_only=False):
if tag.startswith("$"):
tag = tag[1:]
def not_found():
print self.clr_cmd + "no tag '" + tag + "' found" + self.clr_default
self.p.stdin.write("\n")
if not self.ctags.py_tags.has_key(tag):
not_found()
return
if editor == "emacs":
t = self.ctags.py_tags[tag][0]
# get line number (or is there a way to start emacs at a
# particular tag location?)
found_tag = False
try:
file_ = self.ctags.tags_root + os.path.sep + t["file"]
line_num = 1
for line in open(file_):
line_num += 1
if line.find(t["context"]) != -1:
emacs_line = line_num
found_tag = True
break
except:
pass
if found_tag:
# -nw opens it in the terminal instead of using X
cmd = "emacs -nw +%d %s" % (emacs_line, file_)
p_emacs = Popen(cmd, shell=True)
p_emacs.wait()
self.p.stdin.write("\n")
else:
not_found()
return
else:
if read_only:
vim = "vim -R"
else:
vim = "vim"
vim += ' -c "set tags=' + self.ctags.tags_file + '" -t '
p_vim = Popen(vim + tag, shell=True)
p_vim.wait()
self.p.stdin.write("\n")
if not read_only:
self.show_incs()
self.php_open_and_check()
def write(self):
try:
readline.write_history_file(self.history_file)
except IOError, e:
print >> sys.stderr, \
"Could not write history file %s: %s" % \
(self.history_file, e)
def close(self):
self.write()
print self.clr_default
os.remove(self.temp_file_name)
self.end_process(True)
def end_process(self, alarm=False):
# shutdown php, if it doesn't exit in 5s, kill -9
if alarm:
signal.signal(signal.SIGALRM, sigalrm_handler)
# if we have fatal-restart prevention, the child process can't be waited
# on since it's no longer a child of this process
try:
self.p.stdout.close()
self.p.stderr.close()
self.p.stdin.close()
if alarm:
signal.alarm(5)
os.waitpid(self.p.pid, 0)
except (IOError, OSError, KeyboardInterrupt):
os.kill(self.p.pid, signal.SIGKILL)
# collect the zombie
try:
os.waitpid(self.p.pid, 0)
except OSError:
pass
self.p = None
<file_sep>#!/usr/bin/env python
from optparse import OptionParser
from phpsh import PhpshState, PhpMultiliner, do_sugar, line_encode, __version__
import sys
import os
usage = """~/www> phpsh [options] [extra-includes]
phpsh is an interactive shell into a php codebase."""
p = OptionParser(usage=usage, version="%prog " + __version__)
p.add_option("-c", "--codebase-mode", help="""Use "-c none" to load no codebase.
See /etc/phpsh/rc.php for other codebase modes.""")
p.add_option("-t", "--test-file", help="""Run a saved-phpsh-session unit test file.
See test/ in the phpsh distribution for examples.""")
p.add_option(
"-v", "--verbose", action="store_true",
help="Be more verbose, do not defer warnings about missing extensions.")
# are we cool with these negated opts?
# at least they indicate the defaults..
p.add_option("-A", "--no-autocomplete", action="store_true")
p.add_option("-C", "--no-color", action="store_true")
p.add_option("-M", "--no-multiline", action="store_true")
p.add_option("-T", "--no-ctags", action="store_true")
p.add_option("-N", "--no-nice", action="store_true")
p.add_option("-X", "--xdebug", action="store_true",
help="Enable PHP debugging with xdebug (this also disable" +
" forking to save state on fatals)")
(opts, cmd_incs) = p.parse_args()
# default codebase_mode is "" (don't want None)
if not opts.codebase_mode:
opts.codebase_mode = ""
if not opts.no_nice:
os.nice(10)
do_multiline = not opts.no_multiline
s = PhpshState(
cmd_incs=set(cmd_incs),
do_color=not opts.no_color and not opts.test_file,
do_echo=not opts.test_file, codebase_mode=opts.codebase_mode,
do_autocomplete=not opts.no_autocomplete, do_ctags=not opts.no_ctags,
interactive=not opts.test_file, with_xdebug=opts.xdebug,
verbose=opts.verbose)
if opts.test_file:
# TODO support multiline in test-mode
# TODO? test-mode shouldn't support r/c/i etc should it? maybs r?
# but q?
# parse test file
# this is not perfect since output lines could start with "php> " (!!)
test_f = file(opts.test_file)
in_line = None
in_line_n = None
out_lines = []
test_pairs = []
line_n = 1
while True:
l = test_f.readline()
if not l:
break
l = l[:-1]
if l.startswith(s.php_prompt):
if in_line:
test_pairs.append((in_line, out_lines, in_line_n))
out_lines = []
in_line = l[len(s.php_prompt):]
in_line_n = line_n
elif in_line:
out_lines.append(l)
line_n += 1
if in_line:
test_pairs.append((in_line, out_lines, in_line_n))
test_f.close()
test_pairs_iter = test_pairs.__iter__()
test_cur = None
# run through test pairs
error_num = 0
for in_line, out_lines, in_line_n in test_pairs:
out_lines = "\n".join(out_lines)
out_lines_now = s.do_expr(line_encode(do_sugar(in_line)))[:-1]
if out_lines_now != out_lines:
error_num += 1
print s.clr_err + "ERROR Line " + str(in_line_n) + " mismatch:"
print "---Command:---"
print in_line
print "---Expected:---"
print out_lines
print "---Got:---"
print out_lines_now
print "----------" + s.clr_default
s.close()
if error_num:
print "%d of %d tests failed." % (error_num, len(test_pairs))
sys.exit(-1)
else:
print "All %d tests passed." % len(test_pairs)
sys.exit(0)
if do_multiline:
m = PhpMultiliner()
# main loop
new_expr = True
debug_funcall = False
while True:
if new_expr:
prompt = s.php_prompt
else:
prompt = s.php_more_prompt
try:
line = raw_input(prompt)
except EOFError:
break
except KeyboardInterrupt:
print
if do_multiline:
m.clear()
new_expr = True
continue
if new_expr:
t_c_ret = s.try_command(line)
if t_c_ret == PhpshState.quit_command:
break
elif t_c_ret == PhpshState.yes_command:
continue
elif t_c_ret == PhpshState.debug_command:
debug_funcall = True
line = line[len(PhpshState.debug_command):].lstrip()
line_ready = None
if do_multiline:
(m_res, m_str) = m.input_line(line)
if m_res == PhpMultiliner.complete:
line_ready = m_str
elif m_res == PhpMultiliner.syntax_error:
print s.clr_err + \
"Multiline input has no syntactic completion:"
print m_str + s.clr_default
m.clear()
line_ready = ""
else:
line_ready = line_encode(do_sugar(line))
if not line_ready is None:
if line_ready:
s.write()
if debug_funcall:
if s.setup_debug_client(line_ready):
s.do_expr("xdebug_break();\n")
s.do_expr(line_ready, True)
else:
s.do_expr(line_ready)
new_expr = True
debug_funcall = False
else:
new_expr = False
s.close()
<file_sep>#!/usr/bin/env php
<?php
// Copyright 2004-2007 Facebook. All Rights Reserved.
// this is used by phpsh.py to exec php commands and maintain state
// @author ccheever
// @author dcorson
// @author warman (added multiline input support \ing)
// @date Thu Jun 15 22:27:46 PDT 2006
//
// usage: this is only called from phpsh (the python end), as:
// phpsh.php <comm-file> <codebase-mode> [-c]
//
// use '' for default codebase-mode, define others in /etc/phpsh/rc.php
// -c turns off color
namespace __phpsh__;
// This function is here just so that the debug proxy can set a
// breakpoint on something that executes right after the function being
// debugged has been evaluated. Hitting this breakpoint makes debug
// proxy remove the breakpoint it previously set on the function under
// debugging.
function ___phpsh___eval_completed() {
}
/**
* An instance of a phpsh interactive loop
*
* @author ccheever
* @author dcorson
*
* This class mostly exists as a proxy for a namespace
*/
class ___Phpsh___ {
var $_handle = STDIN;
var $_comm_handle;
var $_MAX_LINE_SIZE = 262144;
/**
* Constructor - actually runs the interactive loop so that all we have to do
* is construct it to run
* @param string $output_from_includes
* @param $do_color
* @param $do_autocomplete
* @param $do_undefined_function_check
* @param $fork_every_command
* @param $comm_filename
* @internal param \__phpsh__\list $extra_include Extra files that we want to include
*
* @author ccheever
* @author dcorson
*/
public function __construct(
$output_from_includes='', $do_color, $do_autocomplete,
$do_undefined_function_check, $fork_every_command, $comm_filename
) {
$this->_comm_handle = fopen($comm_filename, 'w');
$this->__send_autocomplete_identifiers($do_autocomplete);
$this->do_color = $do_color;
$this->do_undefined_function_check = $do_undefined_function_check;
if (!PCNTL_EXISTS && $fork_every_command) {
$fork_every_command = false;
fwrite(STDERR,
"Install pcntl to enable forking on every command.\n");
}
$this->fork_every_command = $fork_every_command;
// now it's safe to send any output the includes generated
echo $output_from_includes;
fwrite($this->_comm_handle, "ready\n");
}
/**
* Destructor - just closes the handle to STDIN
*
* @author ccheever
*/
function __destruct() {
fclose($this->_handle);
}
/**
* Sends the list of identifiers that phpsh should know to tab-complete to
* python
*
* @author ccheever
*/
function __send_autocomplete_identifiers($do_autocomplete) {
// send special string to signal that we're sending the autocomplete
// identifiers
echo "#start_autocomplete_identifiers\n";
if ($do_autocomplete) {
// send function names -- both user defined and built-in
// globals, constants, classes, interfaces
$defined_functions = get_defined_functions();
$methods = array();
foreach (($classes = get_declared_classes()) as $class) {
foreach (get_class_methods($class) as $class_method) {
$methods[] = $class_method;
}
}
foreach (array_merge($defined_functions['user'],
$defined_functions['internal'],
array_keys($GLOBALS),
array_keys(get_defined_constants()),
$classes,
get_declared_interfaces(),
$methods,
array('instanceof')) as $identifier) {
// exclude the phpsh internal variables from the autocomplete list
if (strtolower(substr($identifier, 0, 11)) != '___phpsh___') {
echo "$identifier\n";
} else {
unset($$identifier);
}
}
}
// string signalling the end of autocmplete identifiers
echo "#end_autocomplete_identifiers\n";
}
/**
* @param string $buffer phpsh input to check function calls in
* @return string name of first undefined function,
* or '' if all functions exist
*/
function undefined_function_check($buffer) {
$toks = token_get_all('<?php '.$buffer);
$cur_func = null;
$ignore_next_func = false;
foreach ($toks as $tok) {
if (is_string($tok)) {
if ($tok === '(') {
if ($cur_func !== null) {
if (!function_exists($cur_func)) {
return $cur_func;
}
}
}
$cur_func = null;
} elseif (is_array($tok)) {
list($tok_type, $tok_val, $tok_line) = $tok;
if ($tok_type === T_STRING) {
if ($ignore_next_func) {
$cur_func = null;
$ignore_next_func = false;
} else {
$cur_func = $tok_val;
}
} else if (
$tok_type === T_FUNCTION ||
$tok_type === T_NEW ||
$tok_type === T_OBJECT_OPERATOR ||
$tok_type === T_DOUBLE_COLON) {
$ignore_next_func = true;
} else if (
$tok_type !== T_WHITESPACE &&
$tok_type !== T_COMMENT) {
$cur_func = null;
$ignore_next_func = false;
}
}
}
return '';
}
/**
* The main interactive loop
*
* @author ccheever
* @author dcorson
*/
public function interactive_loop() {
extract($GLOBALS);
if (PCNTL_EXISTS) {
// python spawned-processes ignore SIGPIPE by default, this makes sure
// the php process exits when the terminal is closed
pcntl_signal(SIGPIPE, SIG_DFL);
}
while (!feof($this->_handle)) {
// indicate to phpsh (parent process) that we are ready for more input
fwrite($this->_comm_handle, "ready\n");
// multiline inputs are encoded to one line
$buffer_enc = fgets($this->_handle, $this->_MAX_LINE_SIZE);
$buffer = stripcslashes($buffer_enc);
$err_msg = '';
if ($this->do_undefined_function_check) {
$undefd_func = $this->undefined_function_check($buffer);
if ($undefd_func) {
$err_msg = 'Not executing input: Possible call to undefined function ' .
$undefd_func . "()\n" .
'See /etc/phpsh/config.sample to disable UndefinedFunctionCheck.';
}
}
if ($err_msg) {
if ($this->do_color) {
echo "\033[31m"; // red
}
echo $err_msg;
if ($this->do_color) {
echo "\033[0m"; // reset color
}
echo "\n";
continue;
}
// evaluate what the user entered
if ($this->do_color) {
echo "\033[33m"; // yellow
}
if ($this->fork_every_command) {
$pid = pcntl_fork();
$evalue = null;
if ($pid) {
pcntl_wait($status);
} else {
try {
$evalue = eval($buffer);
} catch (\Exception $e) {
// unfortunately, almost all exceptions that aren't explicitly
// thrown by users are uncatchable :(
fwrite(STDERR, 'Uncaught exception: ' . get_class($e) . ': ' .
$e->getMessage() . "\n" . $e->getTraceAsString() . "\n");
$evalue = null;
}
// if we are still alive..
$childpid = getmypid();
fwrite($this->_comm_handle, "child $childpid\n");
}
} else {
try {
$evalue = eval($buffer);
} catch (\Exception $e) {
// unfortunately, almost all exceptions that aren't explicitly thrown
// by users are uncatchable :(
fwrite(STDERR, 'Uncaught exception: ' . get_class($e) . ': ' .
$e->getMessage() . "\n" . $e->getTraceAsString() . "\n");
$evalue = null;
}
}
if ($buffer != "xdebug_break();\n") {
___phpsh___eval_completed();
}
// if any value was returned by the evaluated code, echo it
if (isset($evalue)) {
if ($this->do_color) {
echo "\033[36m"; // cyan
}
echo pretty_print($evalue);
}
// set $_ to be the value of the last evaluated expression
$_ = $evalue;
// back to normal for prompt
if ($this->do_color) {
echo "\033[0m";
}
// newline so we end cleanly
echo "\n";
}
}
}
$__init__ = function () {
// set the TFBENV to script
$_SERVER['TFBENV'] = 16777216;
$argv = $GLOBALS['argv'];
// FIXME: www/lib/thrift/packages/falcon/falcon.php is huge
// this is probably not the right fix, but we need it for now
$memory_limit = ini_get('memory_limit');
switch(strtolower($memory_limit[strlen($memory_limit) - 1])) {
case 'g':
$memory_limit *= 1024;
case 'm':
$memory_limit *= 1024;
case 'k':
$memory_limit *= 1024;
}
ini_set('memory_limit', $memory_limit * 2);
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
fwrite(STDERR, 'Fatal error: phpsh requires PHP 5.4 or greater');
exit;
}
$missing = array_diff(['pcre','tokenizer'], get_loaded_extensions());
if ($missing) {
fwrite(
STDERR,
'Fatal error: phpsh requires the following extensions: '.implode(', ', $missing));
exit;
}
define('PCNTL_EXISTS', in_array('pcntl', get_loaded_extensions()));
// we buffer the output on includes so that output that gets generated by
// includes doesn't interfere with the secret messages we pass between php and
// python we'll capture any output and show it when we construct the shell
// object
ob_start();
$___phpsh___codebase_mode = $argv[2];
$homerc = getenv('HOME').'/.phpsh/rc.php';
if (file_exists($homerc)) {
require_once $homerc;
} else {
require_once '/etc/phpsh/rc.php';
}
$do_color = true;
$do_autocomplete = true;
$do_undefined_function_check = true;
$options_possible = true;
$fork_every_command = false;
foreach (array_slice($GLOBALS['argv'], 3) as $arg) {
$did_arg = true;
if ($options_possible) {
switch ($arg) {
case '-c':
$do_color = false;
break;
case '-A':
$do_autocomplete = false;
break;
case '-u':
$do_undefined_function_check = false;
break;
case '-f':
$fork_every_command = true;
break;
case '--':
$options_possible = false;
break;
default:
$did_arg = false;
}
if ($did_arg) {
continue;
}
}
include_once $arg;
}
$output_from_includes = ob_get_contents();
ob_end_clean();
// We make our pretty-printer override-able in rc.php just in case anyone cares
// enough to tweak it.
if (!function_exists('\__phpsh__\pretty_print')) {
if (function_exists('xdebug_var_dump')) {
function pretty_print($x) {
xdebug_var_dump($x);
}
} else {
require_once __DIR__ . '/php/pretty_print.php';
}
}
return new ___Phpsh___(
$output_from_includes, $do_color, $do_autocomplete, $do_undefined_function_check,
$fork_every_command, $argv[1]);
};
/** @var ___Phpsh___ $___phpsh___ */
$___phpsh___ = $__init__();
unset($__init__);
$___phpsh___->interactive_loop();
<file_sep><?php
namespace __phpsh__;
class Exception extends \Exception {}
function pretty_print($x) {
return _parse_dump($x, _var_dump_cap($x));
}
function _var_dump_cap($x) {
ob_start();
var_dump($x);
$str = ob_get_contents();
ob_end_clean();
return rtrim($str);
}
function _str_lit($str) {
static $str_lit_esc_chars =
"\\\"\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037";
// todo?: addcslashes makes weird control chars in octal instead of hex.
// is hex kwlr in general? if so might want our own escaper here
return '"'.addcslashes($str, $str_lit_esc_chars).'"';
}
function _parse_dump($x, $dump, &$pos=0, $normal_end_check=true, $_depth=0) {
static $indent_str = ' ';
$depth_str = str_repeat($indent_str, $_depth);
// ad hoc parsing not very fun.. use lemon or something? or is that overkill
switch ($dump[$pos]) {
case 'N':
_parse_dump_assert($dump, $pos, 'NULL');
return 'null';
case '&':
$pos++;
return '&' . _parse_dump(
$x, $dump, $pos, $normal_end_check,$_depth);
case 'a':
_parse_dump_assert($dump, $pos, 'array');
$arr_len = (int)_parse_dump_delim_grab($dump, $pos, false);
_parse_dump_assert($dump, $pos, " {\n");
$arr_lines = _parse_dump_arr_lines(
$x, $dump, $pos, $arr_len, $_depth, $depth_str, $indent_str);
_parse_dump_assert(
$dump, $pos, $depth_str."}", $normal_end_check);
return implode("\n", array_merge(['array('], $arr_lines, [$depth_str.')']));
case 'o':
_parse_dump_assert($dump, $pos, 'object');
$obj_type_str = _parse_dump_delim_grab($dump, $pos);
$obj_num_str = _parse_dump_delim_grab($dump, $pos, false, '# ');
$obj_len = (int)_parse_dump_delim_grab($dump, $pos);
_parse_dump_assert($dump, $pos, " {\n");
$obj_lines = _parse_dump_obj_lines(
$x, $dump, $pos, $obj_len, $_depth, $depth_str, $indent_str);
_parse_dump_assert(
$dump, $pos, $depth_str.'}', $normal_end_check);
return implode("\n", array_merge(
["<object #{$obj_num_str} of type {$obj_type_str}> \{"],
$obj_lines,
[$depth_str.'}']
));
case 'b':
_parse_dump_assert($dump, $pos, 'bool(');
switch ($dump[$pos]) {
case 'f':
_parse_dump_assert($dump, $pos, 'false)', $normal_end_check);
return 'false';
case 't':
_parse_dump_assert($dump, $pos, 'true)', $normal_end_check);
return 'true';
}
case 'f':
_parse_dump_assert($dump, $pos, 'float');
return _parse_dump_delim_grab($dump, $pos, $normal_end_check);
case 'd':
_parse_dump_assert($dump, $pos, 'double');
return _parse_dump_delim_grab($dump, $pos, $normal_end_check);
case 'i':
_parse_dump_assert($dump, $pos, 'int');
return _parse_dump_delim_grab($dump, $pos, $normal_end_check);
case 'r':
_parse_dump_assert($dump, $pos, 'resource');
$rsrc_num_str = _parse_dump_delim_grab($dump, $pos);
_parse_dump_assert($dump, $pos, ' of type ');
$rsrc_type_str =
_parse_dump_delim_grab($dump, $pos, $normal_end_check);
return '<resource #'.$rsrc_num_str.' of type '.$rsrc_type_str.'>';
case 's':
_parse_dump_assert($dump, $pos, 'string');
$str_len = (int)_parse_dump_delim_grab($dump, $pos);
_parse_dump_assert($dump, $pos, ' "');
$str = substr($dump, $pos, $str_len);
$pos += $str_len;
_parse_dump_assert($dump, $pos, '"', $normal_end_check);
return _str_lit($str);
default:
if (ini_get('xdebug.cli_color') == '2') {
echo $dump;
} else {
throw new Exception(
"parse error unrecognized type at position {$pos}: ".substr($dump, $pos));
}
}
}
function _parse_dump_arr_lines($x, $dump, &$pos, $arr_len, $depth, $depth_str, $indent_str) {
$arr_lines = [];
foreach (array_keys($x) as $key) {
if (is_int($key)) {
$key_str_php = (string)$key;
$key_str_correct = $key_str_php;
} else {
$key_str_php = '"'.$key.'"';
$key_str_correct = _str_lit($key);
}
_parse_dump_assert(
$dump, $pos,
"{$depth_str}{$indent_str}[{$key_str_php}]=>\n{$depth_str}{$indent_str}");
if ($dump[$pos] == '*') {
_parse_dump_assert($dump, $pos, '*RECURSION*');
$val = '*RECURSION*';
} else {
$val = _parse_dump($x[$key], $dump, $pos, false, $depth + 1);
}
_parse_dump_assert($dump, $pos, "\n");
$arr_lines[] = $depth_str.$indent_str.$key_str_correct.' => '.$val.',';
}
return $arr_lines;
}
function _parse_dump_obj_lines($x, $dump, &$pos, $arr_len, $depth, $depth_str, $indent_str) {
$arr_lines = array();
// this exposes private/protected members (a hack within a hack)
$x_arr = _obj_to_arr($x);
for ($i = 0; $i < $arr_len; $i++) {
_parse_dump_assert($dump, $pos, $depth_str.$indent_str.'[');
$key = _parse_dump_delim_grab($dump, $pos, false, '""');
if ($dump[$pos] == ':') {
$key .= ':'._parse_dump_delim_grab($dump, $pos, false, ':]');
$pos--;
}
_parse_dump_assert($dump, $pos, "]=>\n".$depth_str.$indent_str);
if ($dump[$pos] == '*') {
_parse_dump_assert($dump, $pos, '*RECURSION*');
$val = '*RECURSION*';
} else {
$colon_pos = strpos($key, ':');
if ($colon_pos === false) {
$key_unannotated = $key;
} else {
$key_unannotated = substr($key, 0, $colon_pos);
}
$val = _parse_dump($x_arr[$key_unannotated], $dump, $pos,
false, $depth + 1);
}
_parse_dump_assert($dump, $pos, "\n");
$arr_lines[] = $depth_str.$indent_str.$key.' => '.$val.',';
}
return $arr_lines;
}
function _obj_to_arr($x) {
if (is_object($x)) {
$raw_array = (array)$x;
$result = array();
foreach ($raw_array as $key => $value) {
$key = preg_replace('/\\000.*\\000/', '', $key);
$result[$key] = $value;
}
return $result;
}
return (array)$x;
}
function _parse_dump_assert($dump, &$pos, $str, $end=false) {
$len = strlen($str);
if ($str !== '' && substr($dump, $pos, $len) !== $str) {
throw new Exception(
"parse error looking for '{$str}' at position {$pos}; found instead: "
.substr($dump, $pos));
}
$pos += $len;
if ($end && strlen($dump) > $pos) {
throw new Exception('parse error unexpected input after position '.$pos);
}
return true;
}
function _parse_dump_delim_grab($dump, &$pos, $end=false, $delims='()') {
assert(strlen($delims) === 2);
$pos_open_paren = $pos;
_parse_dump_assert($dump, $pos, $delims[0]);
$pos_close_paren = strpos($dump, $delims[1], $pos_open_paren + 1);
if ($pos_close_paren === false) {
throw new Exception(
"parse error expecting '{$delims[1]}' after position {$pos}");
}
$pos = $pos_close_paren + 1;
if ($end) {
_parse_dump_assert($dump, $pos, '', true);
}
return substr($dump, $pos_open_paren + 1, $pos_close_paren - $pos_open_paren - 1);
}
| 45e213c86020b3dad98c64d13562b72212c394a9 | [
"Python",
"PHP"
] | 5 | Python | VladimirKuzmin/phpsh | ae0a964ce1a6dee38e9f9d9099819c5a5557e0aa | a51a84ecb83173fdd529f96187fc451578d02169 |
refs/heads/master | <file_sep>const express=require('express');
const todoController = require('./Controller/control');
const app=express();
//const bodyParser= require('body-parser');
app.set('view engine','ejs');
app.use(express.static('./assets'));
todoController(app);
app.listen(3000);
console.log('Listening on port 3000 ');<file_sep>A simple to Do App that is made using node.js, express.js, ejs(template engine)
and much more just to begin with node and its frameworks
| 7fa9530910b14f95b9637fba166ebcc4a0f86edf | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Ankitanvesh/Simple-To-Do-App | c30fbec628083068ca341038637ce707f259594c | a38c76258c2cf46c618b577cb1a8dc3c76cbd458 |
refs/heads/master | <file_sep>import java.util.Arrays;
public class Queue {
String[] queueArray;
int back = -1;
int queueSize;
public Queue(int size) {
this.queueSize = size;
queueArray = new String[size];
Arrays.fill(queueArray, "-1");
}
public void enqueue(String item) throws IndexOutOfBoundsException {
if (back+1 >= queueSize) {
throw new IndexOutOfBoundsException("Sorry, Queue is full");
}
back++;
queueArray[back] = item;
System.out.println(item + " enqueued at index " + back);
}
public String dequeue() {
if (back == -1) {
return null;
} else {
String dequeuedItem = queueArray[0];
//shift all the elements over
for (int i = 0; i < back; i++) {
queueArray[i] = queueArray[i+1];
}
back--;
return dequeuedItem;
}
}
public int getItemCount() {
return back+1;
}
public void displayQueue() {
if (back == -1) {
System.out.println("Empty queue");
return;
}
System.out.println("--FRONT--");
for (int i = 0; i < back+1; i++) {
System.out.println(queueArray[i]);
}
System.out.println("--BACK--");
}
public int getQueueCapacity() {
return queueSize;
}
public int getBackIndex() {
return back;
}
}
<file_sep>import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class HashMapTest {
HashMap testHashMap;
@Before
public void setUp() {
testHashMap = new HashMap();
}
@After
public void tearDown() {
testHashMap = null;
}
@Test
public void testGet() {
testHashMap.put(0, "zero");
assertEquals("zero", testHashMap.get(null));
testHashMap.put(1, "one");
assertEquals("one", testHashMap.get(1));
testHashMap.put(17, "seventeen");
assertEquals("seventeen", testHashMap.get(17));
}
@Test
public void testPut() {
}
}<file_sep>import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CircularQueueTest {
CircularQueue testQueue;
@Before
public void setUp() {
testQueue = new CircularQueue();
}
@After
public void tearDown() {
testQueue = null;
}
@Test
public void testIsFull() {
testQueue.enqueue("A");
assertFalse(testQueue.isFull());
fillQueue();
assertTrue(testQueue.isFull());
testQueue.dequeue();
assertFalse(testQueue.isFull());
}
@Test
public void testDisplayQueue() {
try {
testQueue.displayQueue();
} catch (QueueEmptyException e) {
assertEquals("Sorry, Queue is empty", e.getMessage());
}
}
@Test
public void testEnqueue() {
testQueue.enqueue("A");
assertEquals(1, testQueue.size());
fillQueue();
assertEquals(testQueue.capacity(), testQueue.size());
try {
testQueue.enqueue("Z");
} catch (QueueFullException e) {
assertEquals("Sorry, Queue is full", e.getMessage());
}
}
@Test
public void testDequeue() {
try {
testQueue.dequeue();
} catch (QueueEmptyException e) {
assertEquals("Sorry, Queue is empty", e.getMessage());
} finally {
testQueue.enqueue("A");
assertEquals("A", testQueue.dequeue());
assertEquals(0, testQueue.size());
}
}
private void fillQueue() {
for (int i = 0; testQueue.size() < testQueue.capacity(); i++) {
testQueue.enqueue(Integer.toString(i));
}
}
}<file_sep>import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class QueueTest {
private Queue testQueue;
@Before
public void setUp() {
testQueue = new Queue(5);
}
@After
public void tearDown() {
testQueue = null;
}
@Test
public void testEnqueue() {
testQueue.enqueue("zero");
assertEquals(1, testQueue.getItemCount());
testQueue.enqueue("one");
assertEquals(2, testQueue.getItemCount());
}
@Test
public void testDequeue() {
testQueue.enqueue("zero");
assertEquals("zero", testQueue.dequeue());
assertEquals(0, testQueue.getItemCount());
}
@Test
public void testDequeueFirstItem() {
testQueue.enqueue("zero");
testQueue.enqueue("one");
assertEquals("zero", testQueue.dequeue());
assertEquals(1, testQueue.getItemCount());
}
@Test
public void testFillQueue() {
fillQueue();
assertEquals(5, testQueue.getItemCount());
}
@Test
public void testFullQueue() {
try {
fillQueue();
testQueue.enqueue("6");
} catch (IndexOutOfBoundsException e) {
assertEquals("Sorry, Queue is full", e.getMessage());
} finally {
assertEquals(5, testQueue.getItemCount());
}
}
private void fillQueue() {
while (testQueue.getItemCount() < testQueue.getQueueCapacity()) {
testQueue.enqueue((Integer.toString(testQueue.getBackIndex() + 1)));
}
testQueue.displayQueue();
}
} | 590c4f0f5a1f262e406aacb34d16864715826a5a | [
"Java"
] | 4 | Java | dmatis/data-structures | 6be9f79a116412277da565d88e8284f70d2cb325 | 642301b2164caa94dd829102c39c5fa91b8816b9 |
refs/heads/master | <file_sep>const gulp = require('gulp');
// for BrowserSync
const browserSync = require('browser-sync');
// for Webpack
const webpack = require('gulp-webpack');
const _webpack = require('webpack');
// for Stylus
const watch = require('gulp-watch');
const plumber = require('gulp-plumber');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const postcss = require('gulp-postcss');
const cssnext = require('postcss-cssnext');
// for Pug
const pug = require('gulp-pug');
gulp.task('browsersync', () => {
browserSync.init(null, {
server: {
baseDir: './docs'
},
port: 43002,
open: 'external',
notify: false,
});
});
gulp.task('pug', () => {
gulp.src('./src/pug/**/!(_)*.pug', { base: './src/pug' })
.pipe(pug())
.pipe(gulp.dest('./docs'));
});
gulp.task('webpack', () => {
gulp.src('')
.pipe(webpack({
entry: {
bundle: './src/scripts/entry.js'
},
output: {
path: `${__dirname}/public/js`,
filename: '[name].js'
},
module: {
loaders: [
{
test: /\.js$|\.tag$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015'],
cacheDirectory: true
}
}
]
},
resolve: {
extensions: ['', '.js']
},
plugins: [
new _webpack.optimize.UglifyJsPlugin()
],
devtool: 'inline-source-map',
watch: true
}))
.pipe(gulp.dest('./docs/js'));
});
gulp.task('sass', () => {
gulp.src('./src/sass/!(_)*.styl')
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(postcss([ cssnext({ browsers: ['last 1 version'] }) ]))
.pipe(sourcemaps.write())
.pipe(gulp.dest('./docs/css'));
});
gulp.task('dev', ['browsersync', 'webpack', 'sass'], () => {
watch(['./src/sass/**/*.sass'], () => {
gulp.start('sass');
});
watch(['./src/pug/**/*.pug'], () => {
gulp.start('pug');
});
watch(['./docs/**/*'], () => {
browserSync.reload();
});
});
| 6a726b2ae2aa137ab996265101c1bf659bfb6e7e | [
"JavaScript"
] | 1 | JavaScript | simochee/ppark-admin.prototype.v2 | 58ea23b9307efbb3a5d12033cec2e7b63dda7f09 | c9207e61ddac77aaa7cb647b176c7119a31cc892 |
refs/heads/master | <repo_name>LucasGithub123/Difference-between-two-bell-curves<file_sep>/src/mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <limits>
#include <cmath>
#include <algorithm>
#include <cassert>
#include <QString>
#include <QFont>
#include <iostream>
using namespace std;
// GLOBAL CONSTANTS ///////////////////////////////////////////////////////////////////////////
#define CONST_AXES
const static int numPoints = 100; // Number of points per curve. Decrease for better performance.
const static double pMax = 0.0005; // The fraction of the maximum value of the PDF at which this plot will stop. 0 < p < 1
const static double eps = 0.00001; // Acceptable floating point round off error
// NON-MEMBER FUNCTIONS ///////////////////////////////////////////////////////////////////////////
/**
* Get the maximum x and y values in a vector of points.
*/
void getMax(double& maxX, double& maxY, const QVector<QPointF> vec){
maxX = std::numeric_limits<double>::lowest();
maxY = std::numeric_limits<double>::lowest();
for(QPointF pt : vec){
if(pt.x() > maxX) maxX = pt.x();
if(pt.y() > maxY) maxY = pt.y();
}
}
/**
* Get the minimum x and y values in a vector of points.
*/
void getMin(double& minX, double& minY, const QVector<QPointF> vec){
minX = std::numeric_limits<double>::max();
minY = std::numeric_limits<double>::max();
for(QPointF pt : vec){
if(pt.x() < minX) minX = pt.x();
if(pt.y() < minY) minY = pt.y();
}
}
/**
* Get the maximum and minimum x values in a vector of points.
*/
void getMinMax(double& min, double& max, const QVector<QPointF> vec){
min = std::numeric_limits<double>::max();
max = std::numeric_limits<double>::lowest();
for(QPointF pt : vec){
if(pt.x() < min) min = pt.x();
if(pt.x() > max) max = pt.x();
}
}
double gaussian(const double x, const double u, const double sigma){
if(sigma <= 0.0) throw std::domain_error("Error: Standard deviation of " + to_string(sigma) + " is invalid.");
return exp(-(x-u)*(x-u)/(2.0*sigma*sigma)) / sqrt(2.0*M_PI*sigma*sigma);
}
/**
* I'm only displaying a portion of a gaussian, because mathematiclaly they go on forever.
* Given mean and std. dev, compute the interval that I'm plotting, based on the
* fraction of the maximum value of the PDF at which this plot will stop.
*/
void maxInterval(double& xmin, double& xmax, double u, double sigma){
if(sigma <= 0.0) throw std::domain_error("Error: Standard deviation of " + to_string(sigma) + " is invalid.");
xmin = u - sqrt(-2.0*sigma*sigma*log(pMax));
xmax = u + sqrt(-2.0*sigma*sigma*log(pMax));
}
/**
* Given minimum and maximum values for the mean and std. dev. of distributions in this application,
* compute the highest and lowest x and y values that will ever be displayed.
*/
void maxIntervals(double& xmin, double& xmax, double& ymin, double& ymax,
double umin, double umax, double sigmin, double sigmax)
{
if(sigmin <= 0.0) throw std::domain_error("Error: Standard deviation of " + to_string(sigmin) + " is invalid.");
if(sigmax <= 0.0) throw std::domain_error("Error: Standard deviation of " + to_string(sigmax) + " is invalid.");
if(umin > umax) std::swap(umin, umax);
if(sigmin > sigmax) std::swap(sigmin, sigmax);
xmin = umin - sqrt(-2.0*sigmax*sigmax*log(pMax));
xmax = umax + sqrt(-2.0*sigmax*sigmax*log(pMax));
ymin = 0.0; // Obviously minimum value of a gaussian is 0.
ymax = gaussian(umin, umin, sigmin); // Maximum value of a gaussian occurs at the mean, and smallest sigma implies largest maximum value.
}
QAreaSeries* addGaussianToChart(QChart *chart, double u, double sigma, QString title="", QColor colour=0x3cc63c){
if(sigma <= 0.0) throw std::domain_error("Error: Standard deviation of " + to_string(sigma) + " is invalid.");
QLineSeries *series0 = new QLineSeries();
QLineSeries *series1 = new QLineSeries();
double xmin, xmax;
maxInterval(xmin, xmax, u, sigma);
double dx = (xmax - xmin) / static_cast<double>(numPoints);
for(double x = xmin; x <= xmax + eps ; x += dx){
*series0 << QPointF(x, gaussian(x, u, sigma));
*series1 << QPointF(x, 0.0);
}
QAreaSeries *series = new QAreaSeries(series0, series1);
series->setName(title);
QColor border(0, 0, 0);
QPen pen(border);
pen.setWidth(3);
series->setPen(pen);
QLinearGradient gradient(QPointF(0, 0), QPointF(0, 1));
gradient.setColorAt(0.0, colour);
gradient.setColorAt(1.0, colour); // Bottom color
gradient.setCoordinateMode(QGradient::ObjectBoundingMode);
series->setBrush(gradient);
chart->addSeries(series);
return series;
}
/**
* Re-compute the distribution and update all the points in the series.
* Assume sigma > 0.0 since I only call this function from the slots connected to the sliders, and
* the Mainwindow constructor checks the validity of the sliders' range.
*/
void updateSeries(QLineSeries *series, double u, double sigma){
series->clear();
double xmin, xmax;
maxInterval(xmin, xmax, u, sigma);
double dx = (xmax - xmin) / static_cast<double>(numPoints);
for(double x = xmin; x <= xmax + eps ; x += dx){
*series << QPointF(x, gaussian(x, u, sigma));
}
}
/**
* Numerically compute the integral of a line series from (see note) x1 to x2 using trapezoids.
*
* Note: If x1 and x2 do not exist in the series exactly, then this function will search for the
* x-values closest to x1 and x2 and use those as integration limits instead.
* If x1 is lower than the minimum value in the series, the minimum is used as the lower limit instead.
* If x2 is higher than the maximum value in the series, the maximum is used as the upper limit instead.
*/
double area(QLineSeries *series, double x1, double x2){
if(x2 < x1) std::swap(x1, x2);
QVector<QPointF> points = series->pointsVector();
double area = 0.0;
for(int i = 1; i < points.size(); i++){
// If (xi-1 > x1 or x1 is closer to xi-1 than xi) and (xi-1 < x2 and x2 is closer to xi than xi-1)
if( ( points[i-1].x() > x1 || fabs(x1 - points[i-1].x()) < fabs(x1 - points[i].x()) )
&& ( points[i-1].x() < x2 && fabs(x2 - points[i].x()) < fabs(x2 - points[i-1].x()) )
){
area += 0.5*(points[i].y() + points[i-1].y())*(points[i].x() - points[i-1].x());
}
}
return area;
}
/**
* Compute the x-value(s) at which two gaussians meet.
* If the standard deviations and means are the same,
* the distributions are identical, and there are infinitely many intesection points.
* If the standard deviations are the same but the means are different,
* the distributions cross once exactly in the middle of their respective means.
* If the standard deviations are different, they cross at two different places.
*
* Return: Number of intersection points, or -1 if infinitely many.
* If infinitely many intersection points, x1, x2 are unchanged.
* If one intersection point, x1 and x2 will be set to the same value.
* If two intersection points, x1 and x2 will be different, and x1 < x2 will be ensured to be true.
*/
int intersection(double& x1, double& x2, double u0, double sigma0, double u1, double sigma1){
if(sigma0 <= 0.0) throw std::domain_error("Error: Standard deviation of " + to_string(sigma0) + " is invalid.");
if(sigma1 <= 0.0) throw std::domain_error("Error: Standard deviation of " + to_string(sigma1) + " is invalid.");
if(sigma0 == sigma1 && u0 == u1) return -1;
if(sigma0 == sigma1){ // One solution
x1 = 0.5*(u0 + u1);
x2 = x1;
return 1;
}else{ // Two solutions
double a = (1.0/(2.0*sigma1*sigma1)) - (1.0/(2.0*sigma0*sigma0));
double b = (-u1/(sigma1*sigma1)) + (-u0/(sigma0*sigma0));
double c = (-u0*u0/(2.0*sigma0*sigma0)) + log(sqrt(2.0*M_PI*sigma1*sigma1))
+ (u1*u1/(2.0*sigma1*sigma1)) - log(sqrt(2.0*M_PI*sigma0*sigma0));
x1 = (-b - sqrt(b*b - 4.0*a*c)) / (2.0*a);
x2 = (-b + sqrt(b*b - 4.0*a*c)) / (2.0*a);
if(x1 > x2) std::swap(x1, x2);
return 2;
}
}
// MEMBER FUNCTIONS ///////////////////////////////////////////////////////////////////////////
/**
* Re-compute the areas in the three regions: red, blue, and purple.
* Then update the labels with the new values.
*/
void MainWindow::updateAreas(){
double x1 = 0.0, x2 = 0.0;
int numPts = intersection(x1, x2, u0, sigma0, u1, sigma1);
// Can't use std::numeric_limits:: max or lowest. because of floating point round off error.
double min0, max0, min1, max1;
getMinMax(min0, max0, series0->upperSeries()->pointsVector());
getMinMax(min1, max1, series1->upperSeries()->pointsVector());
double lowest = std::min(min0, min1);
double highest = std::max(max0, max1);
if(numPts <= 0){
// If the two gaussians are identical, the only area is the middle area, and it is equal to 1 by definition.
ui->labelLeftVal->setText("0");
ui->labelMiddleVal->setText("1");
ui->labelRightVal->setText("0");
return;
}
double areaLeft = 0.0, areaMiddle = 0.0, areaRight = 0.0;
if(numPts == 2){
// If there are two intersection points, the left and right areas are the same colour.
// This code works because x1 < x2 is enforced by the intersection() function.
QLineSeries *seriesWide = sigma0 > sigma1 ? series0->upperSeries() : series1->upperSeries();
QLineSeries *seriesNarrow = sigma0 > sigma1 ? series1->upperSeries() : series0->upperSeries();
areaLeft = area(seriesWide, lowest, x1) - area(seriesNarrow, lowest, x1);
areaMiddle = area(seriesNarrow, lowest, x1) + area(seriesWide, x1, x2) + area(seriesNarrow, x2, highest);
areaRight = area(seriesWide, x2, highest) - area(seriesNarrow, x2, highest);
}else if(numPts == 1){
// If there is one intersection point, the left and right areas are different colours.
QLineSeries *seriesLeft = u0 < u1 ? series0->upperSeries() : series1->upperSeries();
QLineSeries *seriesRight = u0 < u1 ? series1->upperSeries() : series0->upperSeries();
areaLeft = area(seriesLeft, lowest, x1) - area(seriesRight, lowest, x1);
areaMiddle = area(seriesRight, lowest, x1) + area(seriesLeft, x1, highest);
areaRight = area(seriesRight, x1, highest) - area(seriesLeft, x1, highest);
}
ui->labelLeftVal->setText(QString("%1").arg(areaLeft));
ui->labelMiddleVal->setText(QString("%1").arg(areaMiddle));
ui->labelRightVal->setText(QString("%1").arg(areaRight));
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Axis range calculations are based on the assumption that the sliders have the same range.
if( ui->hSlidMean1->maximum() != ui->hSlidMean2->maximum()
|| ui->hSlidMean1->minimum() != ui->hSlidMean2->minimum()
|| ui->hSlidDev1->maximum() != ui->hSlidDev2->maximum()
|| ui->hSlidDev1->minimum() != ui->hSlidDev2->minimum()
){
throw std::domain_error("Error: Maximum and minimum values of the sliders for the mean of both "
"distributions must be respectively equal. Same goes for the standard deviations.");
}
if(ui->hSlidDev1->minimum() < 0 || ui->hSlidDev1->minimum() < 0){
throw std::domain_error("Error: Standard deviation sliders go below 0. Standard deviations less than or equal to 0 are impossible.");
}
connect(ui->hSlidMean1, SIGNAL(valueChanged(int)), this, SLOT(updateMean0(int)));
connect(ui->hSlidDev1, SIGNAL(valueChanged(int)), this, SLOT(updateStddev0(int)));
connect(ui->hSlidMean2, SIGNAL(valueChanged(int)), this, SLOT(updateMean1(int)));
connect(ui->hSlidDev2, SIGNAL(valueChanged(int)), this, SLOT(updateStddev1(int)));
connect(ui->btnZoomin, SIGNAL(clicked()), this, SLOT(zoomIn()));
connect(ui->btnZoomout, SIGNAL(clicked()), this, SLOT(zoomOut()));
chart = new QChart();
chart->setTitle("Difference between two bell curves");
chart->setTitleFont(QFont("Liberation Sans", 18));
chart->legend()->setFont(QFont("Liberation Sans", 14));
series0 = addGaussianToChart(chart, u0, sigma0,
QString("Distribution 1"), QColor(255, 0, 0, 100));
series1 = addGaussianToChart(chart, u1, sigma0,
QString("Distribution 2"), QColor(0, 0, 255, 100));
chart->createDefaultAxes(); // Adds axes of type QAbstractAxis.
updateAxes();
chart->axisX()->setLabelsFont(QFont("Liberation Sans", 14)); // Can't do this until axes are created, otherwise segfault.
chart->axisY()->setLabelsFont(QFont("Liberation Sans", 14));
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
const int fromRow = 4, fromColumn = 0, rowSpan = 3, columnSpan = 3;
ui->gridLayout_2->addWidget(chartView, fromRow, fromColumn, rowSpan, columnSpan);
ui->hSlidMean1->setValue( (ui->hSlidMean1->maximum() + ui->hSlidMean1->minimum()) / 2);
ui->hSlidDev1->setValue(ui->hSlidDev1->maximum() / 4);
ui->hSlidMean2->setValue(ui->hSlidMean2->maximum() / 4);
ui->hSlidDev2->setValue(ui->hSlidDev2->maximum() / 4);
// setValue() emits valueChanged(), which is connected to slots
// which are defined below and set member variables u0, u1, sigma0 and sigma1.
#ifdef CONST_AXES
maxIntervals(
axis_xmin, axis_xmax, axis_ymin, axis_ymax,
static_cast<double>(ui->hSlidMean1->minimum()) / 10.0,
static_cast<double>(ui->hSlidMean1->maximum()) / 10.0,
static_cast<double>(ui->hSlidDev1->minimum()) / 10.0,
static_cast<double>(ui->hSlidDev1->maximum()) / 10.0
);
chart->axisX()->setRange(axis_xmin-0.1*fabs(axis_xmin), axis_xmax+0.1*fabs(axis_xmax));
chart->axisY()->setRange(axis_ymin-0.1*fabs(axis_ymin), axis_ymax+0.1*fabs(axis_ymax));
#endif
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::update(){
updateAxes();
updateAreas();
}
void MainWindow::updateAxes(){
#ifndef CONST_AXES
QVector<QPointF> vec = series0->lowerSeries()->pointsVector();
vec.append(series0->upperSeries()->pointsVector());
vec.append(series1->lowerSeries()->pointsVector());
vec.append(series1->upperSeries()->pointsVector());
double xmin, xmax, ymin, ymax;
getMax(xmax, ymax, vec);
getMin(xmin, ymin, vec);
chart->axisX()->setRange(xmin-0.1*fabs(xmin), xmax+0.1*fabs(xmax));
chart->axisY()->setRange(ymin-0.1*fabs(ymin), ymax+0.1*fabs(ymax));
#endif
}
void MainWindow::updateMean0(int value){
u0 = static_cast<double>(value) / 10.0;
ui->labelMean1Val->setText(QString("%1").arg(u0));
updateSeries(series0->upperSeries(), u0, sigma0);
update();
}
void MainWindow::updateStddev0(int value){
sigma0 = static_cast<double>(value) / 10.0;
ui->labelDev1Val->setText(QString("%1").arg(sigma0));
updateSeries(series0->upperSeries(), u0, sigma0);
update();
// area(series0->upperSeries(), -99990.0, 0.0);
// double x1, x2;
// intersection(x1, x2, u0, sigma0, u0, sigma0);
}
void MainWindow::updateMean1(int value){
u1 = static_cast<double>(value) / 10.0;
ui->labelMean2Val->setText(QString("%1").arg(u1));
updateSeries(series1->upperSeries(), u1, sigma1);
update();
}
void MainWindow::updateStddev1(int value){
sigma1 = static_cast<double>(value) / 10.0;
ui->labelDev2Val->setText(QString("%1").arg(sigma1));
updateSeries(series1->upperSeries(), u1, sigma1);
update();
}
void MainWindow::zoomIn(){
axis_xmin *= 0.8;
axis_xmax *= 0.8;
axis_ymin *= 0.8;
axis_ymax *= 0.8;
chart->axisX()->setRange(axis_xmin, axis_xmax);
chart->axisY()->setRange(axis_ymin, axis_ymax);
}
void MainWindow::zoomOut(){
axis_xmin *= 1.2;
axis_xmax *= 1.2;
axis_ymin *= 1.2;
axis_ymax *= 1.2;
chart->axisX()->setRange(axis_xmin, axis_xmax);
chart->axisY()->setRange(axis_ymin, axis_ymax);
}
<file_sep>/c
#!/bin/bash
make -j$(($(nproc) + 1))
<file_sep>/r
#!/bin/bash
make -j$(($(nproc) + 1))
if [ $? -eq 0 ]
then
cd bin
./ChartPlotting
fi
<file_sep>/src/mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include <QtCharts/QAreaSeries>
QT_CHARTS_USE_NAMESPACE
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QChart *chart;
double u0 = 0.0, u1 = 1.1;
double sigma0 = 1.5, sigma1 = 1.5;
QAreaSeries *series0, *series1;
double axis_xmin, axis_xmax, axis_ymin, axis_ymax;
void update();
void updateAxes();
void updateAreas();
private slots:
void updateMean0(int);
void updateStddev0(int);
void updateMean1(int);
void updateStddev1(int);
void zoomIn();
void zoomOut();
};
#endif // MAINWINDOW_H
<file_sep>/README.md
## Difference between two bell curves.
Manipulate the mean and std. dev. of two bell curves. The area under one curve is coloured red, the other blue, and the overlapping area between the two is coloured purple.
Labels on the right display the area on the left, middle and right. Those mean different things depending on the situation. Here's what they actually mean, if you care:
1. If both Gaussians have the same std. dev, let the gaussian to the left be G1 and the one to the right of G1 be G2. What I call the "left area" is the area under G1 that is not under G2, and the "right area" is the area under G2 that is not under G1.
2. If the std. devs are different, then let the gaussian with the larger std. dev, i.e. the wider one, be G1, and the other one be G2. Then the "left area" is the area under G1 that is not under G2 on the far LEFT portion of the graph. The "right area" is the area under G1 that is not under G2 on the far RIGHT portion of the graph.
In this case, the area under G2 that is above G1 (you might call it the "top" area) is not calculated or displayed.
In both 1 and 2, the "middle area" is the purple area, which is the overlapping area under both curves.
Note in case 2, if the left or right area shows up as 0, that is not a bug. It's just that it is so small and far off toward the tail end of the distribution that you can't see it. Always remember that if G1 has the lower std. dev, it is wider. That means that near the mean, the height of the distribution G1 is lower than G2, but at the tails, it's the opposite, the height of G1 is higher than G2, even if it is so far off to the side that you can't see it. | bae50d75026309ba3adc12e3059570d9b536f88d | [
"Markdown",
"C++",
"Shell"
] | 5 | C++ | LucasGithub123/Difference-between-two-bell-curves | 7f960243b3d1f2a5d8d858328b1c3e60c217c617 | 5d0d9220c6356a8d3d9fe12cfcbf8942cd881212 |
refs/heads/master | <repo_name>mck-git/Bachelor-Project<file_sep>/src/Maps/Variables/CharMap.java
package Maps.Variables;
import DataTypes.Variables.CharVariable;
import java.util.HashMap;
public class CharMap {
private static HashMap charMap = new HashMap<String, CharVariable>();
public static void add(String name, CharVariable cv)
{
charMap.put(name,cv);
}
public static void edit(String name, CharVariable cv)
{
charMap.replace(name,cv);
}
public static CharVariable find(String name)
{
return (CharVariable) charMap.get(name);
}
public static int size()
{
return charMap.size();
}
/**
* FOR TESTING PURPOSES ONLY! DO NOT USE
*/
public static void clear()
{
charMap.clear();
}
}
<file_sep>/src/SharedResources/ExecutionType.java
package SharedResources;
public enum ExecutionType {
NORMAL,
IF_FALSE,
IF_TRUE,
WHILE,
FUNCTION,
}
<file_sep>/src/Maps/Functions/BooleanFunctionMap.java
package Maps.Functions;
import DataTypes.Functions.BooleanFunction;
import DataTypes.Token;
import java.util.ArrayList;
import java.util.HashMap;
public class BooleanFunctionMap {
private static HashMap booleanFunctionMap = new HashMap<String,ArrayList<ArrayList<Token>>>();
public static void add(String name, BooleanFunction booleanFunction)
{
booleanFunctionMap.put(name,booleanFunction);
}
public static BooleanFunction find(String name)
{
return (BooleanFunction) booleanFunctionMap.get(name);
}
public static int size()
{
return booleanFunctionMap.size();
}
/**
* FOR TESTING PURPOSES ONLY! DO NOT USE
*/
public static void clear()
{
booleanFunctionMap.clear();
}
}
<file_sep>/src/DataTypes/Variables/BooleanVariable.java
package DataTypes.Variables;
public class BooleanVariable extends Variable{
boolean value;
public BooleanVariable(String name, boolean value)
{
super(name);
this.value = value;
}
public BooleanVariable(String name)
{
super(name);
}
public boolean getValue()
{
return this.value;
}
}
<file_sep>/src/Maps/Lists/BooleanListMap.java
package Maps.Lists;
import DataTypes.Lists.BooleanList;
import java.util.HashMap;
public class BooleanListMap {
private static HashMap booleanListMap = new HashMap<String,BooleanList>();
public static void add(String name, BooleanList integerList)
{
booleanListMap.put(name,integerList);
}
public static BooleanList find(String name)
{
return (BooleanList) booleanListMap.get(name);
}
public static int size()
{
return booleanListMap.size();
}
/**
* FOR TESTING PURPOSES ONLY! DO NOT USE
*/
public static void clear()
{
booleanListMap.clear();
}
}
<file_sep>/src/Maps/Variables/StringMap.java
package Maps.Variables;
import DataTypes.Variables.StringVariable;
import java.util.HashMap;
public class StringMap {
private static HashMap stringMap = new HashMap<String, StringVariable>();
public static void add(String name, StringVariable stringVariable)
{
stringMap.put(name,stringVariable);
}
public static void edit(String name, StringVariable stringVariable)
{
stringMap.replace(name, stringVariable);
}
public static StringVariable find(String name)
{
return (StringVariable) stringMap.get(name);
}
public static int size()
{
return stringMap.size();
}
/**
* FOR TESTING PURPOSES ONLY! DO NOT USE
*/
public static void clear()
{
stringMap.clear();
}
}
<file_sep>/src/Compile/Loops.java
package Compile;
import DataTypes.Token;
import Errors.InvalidSyntaxException;
import SharedResources.ExecutionType;
import java.util.ArrayList;
public class Loops {
private static ArrayList<Token> conditionalTokens = new ArrayList<>();
private static ArrayList< ArrayList<Token> > linesOfCodeInLoop = new ArrayList<>();
public static void initiateWhile(ArrayList<Token> tokens) throws InvalidSyntaxException
{
if ( ! Conditionals.evaluateConditionalLine(tokens) )
{
Translator.setExecutionType(ExecutionType.IF_FALSE);
return;
}
conditionalTokens = (ArrayList<Token>) tokens.clone();
Translator.setExecutionType(ExecutionType.WHILE);
linesOfCodeInLoop.clear();
}
public static void saveLine(ArrayList<Token> tokens)
{
linesOfCodeInLoop.add((ArrayList<Token>) tokens.clone());
}
public static void executeLoop() throws InvalidSyntaxException
{
Translator.setExecutionType(ExecutionType.NORMAL);
while (Conditionals.evaluateConditionalLine(conditionalTokens) ) // && count < 2
{
for (ArrayList<Token> t : linesOfCodeInLoop) {
Translator.handleLine(t);
}
}
}
}
<file_sep>/src/Compile/ListHandler.java
package Compile;
import DataTypes.Functions.FunctionContainer;
import DataTypes.Lists.*;
import DataTypes.Token;
import DataTypes.Variables.*;
import Errors.InvalidSyntaxException;
import Maps.Lists.BooleanListMap;
import Maps.Lists.CharListMap;
import Maps.Lists.IntegerListMap;
import Maps.Lists.StringListMap;
import Parser.Lexer;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class ListHandler {
public static Variable findGenericListValue (ArrayList<Token> tokens) throws InvalidSyntaxException
{
boolean foundList = false;
int indexStart = 0;
ListContainer lc = null;
for (int i = 0; i < tokens.size(); i++)
{
String tokenContent = tokens.get(i).getContent();
if (!foundList)
{
lc = Mapper.findList(tokenContent);
if (lc == null) {
continue;
}
foundList = true;
indexStart = i;
}
else if (tokenContent.equals("]"))
{
ArrayList<Token> subList = new ArrayList<>(tokens.subList(indexStart, i));
if (lc.getType().equals("int"))
return new IntegerVariable("",
findIntegerListIndex(subList));
if (lc.getType().equals("string"))
return new StringVariable("",
findStringListIndex(subList));
if (lc.getType().equals("char"))
return new CharVariable("",
findCharListIndex(subList));
if (lc.getType().equals("boolean"))
return new BooleanVariable("",
findBooleanListIndex(subList));
}
}
return null;
// throw new InvalidSyntaxException(Lexer.getLineNumber());
}
public static int findIntegerListIndex(ArrayList<Token> tokens) throws InvalidSyntaxException, NullPointerException
{
IntegerList foundList = null;
for (Token t : tokens)
{
String tokenContent = t.getContent();
if (foundList == null)
foundList = IntegerListMap.find(tokenContent);
else if (Calculations.isNumeric(tokenContent))
return foundList.get(Integer.parseInt(tokenContent));
try
{
IntegerVariable integerVariable = (IntegerVariable) Mapper.findVariable(tokenContent).getVariable();
if (integerVariable != null)
return foundList.get(integerVariable.getValue());
} catch (NullPointerException ignored) {}
}
throw new InvalidSyntaxException(Lexer.getLineNumber());
}
public static boolean findBooleanListIndex(ArrayList<Token> tokens) throws InvalidSyntaxException
{
BooleanList foundList = null;
for (Token t : tokens)
{
String tokenContent = t.getContent();
if (foundList == null)
foundList = BooleanListMap.find(tokenContent);
else if (Calculations.isNumeric(tokenContent))
return foundList.get(Integer.parseInt(tokenContent));
try
{
IntegerVariable integerVariable = (IntegerVariable) Mapper.findVariable(tokenContent).getVariable();
if (integerVariable != null)
return foundList.get(integerVariable.getValue());
} catch (NullPointerException ignored) {}
}
throw new InvalidSyntaxException(Lexer.getLineNumber());
}
public static String findStringListIndex(ArrayList<Token> tokens) throws InvalidSyntaxException
{
StringList foundList = null;
for (Token t : tokens)
{
String tokenContent = t.getContent();
if (foundList == null)
foundList = StringListMap.find(tokenContent);
else if (Calculations.isNumeric(tokenContent))
return foundList.get(Integer.parseInt(tokenContent));
try
{
IntegerVariable integerVariable = (IntegerVariable) Mapper.findVariable(tokenContent).getVariable();
if (integerVariable != null)
return foundList.get(integerVariable.getValue());
} catch (NullPointerException ignored) {}
}
throw new InvalidSyntaxException(Lexer.getLineNumber());
}
public static char findCharListIndex(ArrayList<Token> tokens) throws InvalidSyntaxException
{
CharList foundList = null;
for (Token t : tokens)
{
String tokenContent = t.getContent();
if (foundList == null)
foundList = CharListMap.find(tokenContent);
else if (Calculations.isNumeric(tokenContent))
return foundList.get(Integer.parseInt(tokenContent));
try
{
IntegerVariable integerVariable = (IntegerVariable) Mapper.findVariable(tokenContent).getVariable();
if (integerVariable != null)
return foundList.get(integerVariable.getValue());
} catch (NullPointerException ignored) {}
}
throw new InvalidSyntaxException(Lexer.getLineNumber());
}
}
<file_sep>/src/DataTypes/Token.java
package DataTypes;
import SharedResources.InputType;
public class Token {
String content;
InputType inputType;
public Token (String content, InputType inputType)
{
this.content = content;
this.inputType = inputType;
}
public InputType getInputType() {
return inputType;
}
public String getContent() {
return content;
}
}
<file_sep>/src/Parser/Lexer.java
package Parser;
import java.io.*;
import java.util.ArrayList;
import Compile.Translator;
import DataTypes.Token;
import Errors.InvalidSyntaxException;
import SharedResources.InputType;
public class Lexer {
private static String buffer = "";
private static ArrayList<Token> tokens = new ArrayList<>();
private static InputType m = InputType.NORMAL;
private static int lineNumber = 0;
public static void read(String filename) throws IOException, InvalidSyntaxException
{
File file = new File(filename);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = bufferedReader.readLine();
while (line != null)
{
lineNumber++;
tokenizeString(line);
clearBlankTokens();
Translator.handleLine(tokens);
line = bufferedReader.readLine();
tokens.clear();
m = InputType.NORMAL;
}
fileReader.close();
}
private static void tokenizeString(String line)
{
for (char c : line.toCharArray())
{
// NORMAL MODE
if (m == InputType.NORMAL)
readInputNormal(c);
// ARGUMENT MODE
else if (m == InputType.ARGUMENTS)
readInputArgument(c);
// STRING MODE
else if (m == InputType.STRING)
readInputString(c);
}
endTokenAndSwitchType(InputType.NORMAL);
}
private static void readInputNormal(char c) {
if ( c == ' ' || c == '\n' || c == ';' || c == '\t')
endTokenAndSwitchType(InputType.NORMAL);
// SYMBOLS
else if ( c == '+' || c == '-' || c == '/' || c == '*'
|| c == '&' || c == '|'
|| c == '(' || c == ')'
|| c == '{' || c == '}'
|| c == '!' || c == ','
|| c == '[' || c == ']')
{
endTokenAndSwitchType(InputType.NORMAL);
buffer += c;
endTokenAndSwitchType(InputType.NORMAL);
}
else if (c == '=' && buffer.equals("="))
{
buffer += c;
endTokenAndSwitchType(InputType.NORMAL);
}
else if (c == '"')
endTokenAndSwitchType(InputType.STRING);
else
buffer += c;
}
private static void readInputArgument(char c) {
if ( c == ',' && m == InputType.ARGUMENTS )
endTokenAndSwitchType(InputType.ARGUMENTS);
}
private static void readInputString(char c) {
if (c == '"')
endTokenAndSwitchType(InputType.NORMAL);
else
buffer += c;
}
private static void clearBlankTokens()
{
int i = 0;
while ( i < tokens.size() )
{
if (tokens.get(i).getContent().equals(""))
tokens.remove(i);
else
i++;
}
}
private static void endTokenAndSwitchType(InputType it)
{
tokens.add( new Token(buffer, m) );
buffer = "";
m = it;
}
public static int getLineNumber()
{
return lineNumber;
}
}
<file_sep>/Tests/Compile/FunctionExecutorTest.java
package Compile;
import DataTypes.Functions.Function;
import DataTypes.Functions.FunctionContainer;
import DataTypes.Functions.IntegerFunction;
import DataTypes.Token;
import DataTypes.Variables.IntegerVariable;
import DataTypes.Variables.Variable;
import DataTypes.Variables.VariableContainer;
import Errors.InvalidSyntaxException;
import Maps.Functions.IntegerFunctionMap;
import Maps.Functions.VoidFunctionMap;
import Maps.Variables.IntegerMap;
import Maps.Variables.TemporaryVariablesMap;
import SharedResources.InputType;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
class FunctionExecutorTest {
@Test
void findAndRunVoidFunction() throws Exception
{
Mapper.clearMaps();
ArrayList<Token> line1 = new ArrayList<>();
ArrayList<Token> line2 = new ArrayList<>();
ArrayList<Token> line3 = new ArrayList<>();
line1.add(new Token("func", InputType.NORMAL));
line1.add(new Token("void", InputType.NORMAL));
line1.add(new Token("test", InputType.NORMAL));
line1.add(new Token("(", InputType.NORMAL));
line1.add(new Token(")", InputType.NORMAL));
line1.add(new Token("{", InputType.NORMAL));
line2.add(new Token("int", InputType.NORMAL));
line2.add(new Token("a", InputType.NORMAL));
line2.add(new Token("=", InputType.NORMAL));
line2.add(new Token("5", InputType.NORMAL));
line3.add(new Token("}", InputType.NORMAL));
Translator.handleLine(line1);
Translator.handleLine(line2);
Translator.handleLine(line3);
assertEquals(1, VoidFunctionMap.size());
assertEquals(0, IntegerMap.size());
ArrayList<Token> line4 = new ArrayList<>();
line4.add(new Token("test", InputType.NORMAL));
line4.add(new Token("(", InputType.NORMAL));
line4.add(new Token(")", InputType.NORMAL));
Translator.handleLine(line4);
assertEquals(1, IntegerMap.size());
IntegerVariable a = IntegerMap.find("a");
assertEquals(5,a.getValue());
}
@Test
void findAndRunIntegerFunction() throws Exception
{
Mapper.clearMaps();
ArrayList<Token> line1 = new ArrayList<>();
ArrayList<Token> line2 = new ArrayList<>();
ArrayList<Token> line3 = new ArrayList<>();
ArrayList<Token> line4 = new ArrayList<>();
line1.add(new Token("func", InputType.NORMAL));
line1.add(new Token("int", InputType.NORMAL));
line1.add(new Token("test", InputType.NORMAL));
line1.add(new Token("(", InputType.NORMAL));
line1.add(new Token(")", InputType.NORMAL));
line1.add(new Token("{", InputType.NORMAL));
line2.add(new Token("int", InputType.NORMAL));
line2.add(new Token("a", InputType.NORMAL));
line2.add(new Token("=", InputType.NORMAL));
line2.add(new Token("5", InputType.NORMAL));
line3.add(new Token("return", InputType.NORMAL));
line3.add(new Token("2", InputType.NORMAL));
line4.add(new Token("}", InputType.NORMAL));
Translator.handleLine(line1);
Translator.handleLine(line2);
Translator.handleLine(line3);
Translator.handleLine(line4);
assertEquals(1, IntegerFunctionMap.size());
assertEquals(0, IntegerMap.size());
ArrayList<Token> line5 = new ArrayList<>();
line5.add(new Token("test", InputType.NORMAL));
line5.add(new Token("(", InputType.NORMAL));
line5.add(new Token(")", InputType.NORMAL));
Translator.handleLine(line5);
assertEquals(1, IntegerMap.size());
IntegerVariable a = IntegerMap.find("a");
assertEquals(5,a.getValue());
}
@Test
void findAndRunNonexistingFunction() throws Exception
{
Mapper.clearMaps();
try {
ArrayList<Token> line4 = new ArrayList<>();
line4.add(new Token("test", InputType.NORMAL));
line4.add(new Token("(", InputType.NORMAL));
line4.add(new Token(")", InputType.NORMAL));
Translator.handleLine(line4);
fail("Handle line is supposed to not parse as function is not declared");
} catch (InvalidSyntaxException ignored) {
}
}
@Test
void findAndRunVoidFunctionWithArguments() throws Exception
{
Mapper.clearMaps();
ArrayList<Token> line0 = new ArrayList<>();
ArrayList<Token> line1 = new ArrayList<>();
ArrayList<Token> line2 = new ArrayList<>();
ArrayList<Token> line3 = new ArrayList<>();
ArrayList<Token> line4 = new ArrayList<>();
line0.add(new Token("int",InputType.NORMAL));
line0.add(new Token("a",InputType.NORMAL));
line0.add(new Token("=",InputType.NORMAL));
line0.add(new Token("0",InputType.NORMAL));
line1.add(new Token("func", InputType.NORMAL));
line1.add(new Token("void", InputType.NORMAL));
line1.add(new Token("test", InputType.NORMAL));
line1.add(new Token("(", InputType.NORMAL));
line1.add(new Token("int", InputType.NORMAL));
line1.add(new Token("b", InputType.NORMAL));
line1.add(new Token(")", InputType.NORMAL));
line1.add(new Token("{", InputType.NORMAL));
line2.add(new Token("a", InputType.NORMAL));
line2.add(new Token("=", InputType.NORMAL));
line2.add(new Token("b", InputType.NORMAL));
line3.add(new Token("}", InputType.NORMAL));
Compile.Translator.handleLine(line0);
Compile.Translator.handleLine(line1);
Compile.Translator.handleLine(line2);
Compile.Translator.handleLine(line3);
assertEquals(1, Maps.Functions.VoidFunctionMap.size());
FunctionContainer fcTest = Mapper.findFunction("test");
Function test = fcTest.getFunction();
ArrayList<Variable> args = test.getArgumentVariables();
assertEquals(1, args.size());
line4.add(new Token("test", InputType.NORMAL));
line4.add(new Token("(", InputType.NORMAL));
line4.add(new Token("2", InputType.NORMAL));
line4.add(new Token(")", InputType.NORMAL));
Translator.handleLine(line4);
assertEquals(0, TemporaryVariablesMap.size());
assertEquals(1, IntegerMap.size());
VariableContainer vc = Mapper.findVariable("a");
IntegerVariable var = (IntegerVariable) vc.getVariable();
assertEquals(2, var.getValue());
}
@Test
void findAndRunIntFunctionWithArguments() throws Exception
{
Mapper.clearMaps();
ArrayList<Token> line0 = new ArrayList<>();
ArrayList<Token> line1 = new ArrayList<>();
ArrayList<Token> line2 = new ArrayList<>();
ArrayList<Token> line3 = new ArrayList<>();
ArrayList<Token> line4 = new ArrayList<>();
line0.add(new Token("int",InputType.NORMAL));
line0.add(new Token("a",InputType.NORMAL));
line0.add(new Token("=",InputType.NORMAL));
line0.add(new Token("0",InputType.NORMAL));
line1.add(new Token("func", InputType.NORMAL));
line1.add(new Token("int", InputType.NORMAL));
line1.add(new Token("test", InputType.NORMAL));
line1.add(new Token("(", InputType.NORMAL));
line1.add(new Token("int", InputType.NORMAL));
line1.add(new Token("b", InputType.NORMAL));
line1.add(new Token(")", InputType.NORMAL));
line1.add(new Token("{", InputType.NORMAL));
line2.add(new Token("return", InputType.NORMAL));
line2.add(new Token("b", InputType.NORMAL));
line2.add(new Token("+", InputType.NORMAL));
line2.add(new Token("1", InputType.NORMAL));
line3.add(new Token("}", InputType.NORMAL));
Compile.Translator.handleLine(line0);
Compile.Translator.handleLine(line1);
Compile.Translator.handleLine(line2);
Compile.Translator.handleLine(line3);
assertEquals(1, Maps.Functions.IntegerFunctionMap.size());
FunctionContainer fcTest = Mapper.findFunction("test");
Function test = fcTest.getFunction();
ArrayList<Variable> args = test.getArgumentVariables();
assertEquals(1, args.size());
line4.add(new Token("a", InputType.NORMAL));
line4.add(new Token("=", InputType.NORMAL));
line4.add(new Token("test", InputType.NORMAL));
line4.add(new Token("(", InputType.NORMAL));
line4.add(new Token("2", InputType.NORMAL));
line4.add(new Token(")", InputType.NORMAL));
Translator.handleLine(line4);
assertEquals(1, TemporaryVariablesMap.size());
assertEquals(1, IntegerMap.size());
VariableContainer vc = Mapper.findVariable("a");
IntegerVariable var = (IntegerVariable) vc.getVariable();
assertEquals(3, var.getValue());
}
}<file_sep>/src/Compile/Mapper.java
package Compile;
import DataTypes.Functions.*;
import DataTypes.Lists.*;
import DataTypes.Variables.*;
import Maps.Functions.*;
import Maps.Lists.BooleanListMap;
import Maps.Lists.CharListMap;
import Maps.Lists.IntegerListMap;
import Maps.Lists.StringListMap;
import Maps.Variables.*;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import static Compile.FunctionExecutor.functionsExecuting;
public class Mapper {
// INTEGERS
public static void addToIntMap(IntegerVariable iv)
{
IntegerMap.add(iv.getName(),iv);
}
public static void redefineInt(IntegerVariable iv)
{
IntegerMap.edit(iv.getName(),iv);
}
// STRINGS
public static void addToStringMap(StringVariable sv)
{
StringMap.add(sv.getName(), sv);
}
public static void redefineString(StringVariable sv)
{
StringMap.edit(sv.getName(),sv);
}
// CHARS
public static void addToCharMap(CharVariable cv)
{
CharMap.add(cv.getName(), cv);
}
public static void redefineChar(CharVariable cv)
{
CharMap.edit(cv.getName(),cv);
}
// BOOLEANS
public static void addToBooleanMap(BooleanVariable bv)
{
BooleanMap.add(bv.getName(),bv);
}
public static void redefineBoolean(BooleanVariable bv)
{
BooleanMap.edit(bv.getName(),bv);
}
// VOID FUNCTIONS
public static void storeVoidFunction(VoidFunction voidFunction)
{
VoidFunctionMap.add(voidFunction.getName(),voidFunction);
}
// INT FUNCTIONS
public static void storeIntFunction(IntegerFunction integerFunction)
{
IntegerFunctionMap.add(integerFunction.getName(), integerFunction);
}
// CHAR FUNCTIONS
public static void storeCharFunction(CharFunction charFunction)
{
CharFunctionMap.add(charFunction.getName(), charFunction);
}
// STRING FUNCTIONS
public static void storeStringFunction(StringFunction stringFunction)
{
StringFunctionMap.add(stringFunction.getName(), stringFunction);
}
// BOOLEAN FUNCTIONS
public static void storeBooleanFunction(BooleanFunction booleanFunction)
{
BooleanFunctionMap.add(booleanFunction.getName(), booleanFunction);
}
// LISTS
public static void storeIntegerList(IntegerList integerList)
{
IntegerListMap.add(integerList.getName(), integerList);
}
public static void storeCharList(CharList charList)
{
CharListMap.add(charList.getName(), charList);
}
public static void storeStringList(StringList stringList)
{
StringListMap.add(stringList.getName(), stringList);
}
public static void storeBooleanList(BooleanList booleanList)
{
BooleanListMap.add(booleanList.getName(), booleanList);
}
// FINDER FUNCTIONS
public static VariableContainer findVariable(String varname)
{
Variable result;
result = IntegerMap.find(varname);
if (result != null)
return new VariableContainer("int",result);
result = CharMap.find(varname);
if (result != null)
return new VariableContainer("char",result);
result = StringMap.find(varname);
if (result != null)
return new VariableContainer("string",result);
result = BooleanMap.find(varname);
if (result != null)
return new VariableContainer("boolean",result);
try
{
Function fc = functionsExecuting.getFirst();
ArrayList<Variable> arguments = fc.getArgumentVariables();
for (Variable v : arguments)
{
if (v.getName().equals(varname)) {
result = TemporaryVariablesMap.find(varname);
}
}
if (result != null)
{
if (result instanceof IntegerVariable)
return new VariableContainer("int",result);
if (result instanceof CharVariable)
return new VariableContainer("char",result);
if (result instanceof BooleanVariable)
return new VariableContainer("boolean",result);
if (result instanceof StringVariable)
return new VariableContainer("string",result);
}
} catch (NoSuchElementException ignored) {}
return null;
}
public static VariableContainer findReturnValue()
{
Variable result = TemporaryVariablesMap.find("returnValue");
if (result instanceof IntegerVariable)
return new VariableContainer("int", result);
return null;
}
public static FunctionContainer findFunction(String name)
{
Function result;
result = VoidFunctionMap.find(name);
if (result != null)
return new FunctionContainer("void",result);
result = IntegerFunctionMap.find(name);
if (result != null)
return new FunctionContainer("int",result);
result = BooleanFunctionMap.find(name);
if (result != null)
return new FunctionContainer("boolean",result);
result = StringFunctionMap.find(name);
if (result != null)
return new FunctionContainer("string",result);
result = CharFunctionMap.find(name);
if (result != null)
return new FunctionContainer("char",result);
return null;
}
public static ListContainer findList(String listName)
{
List result;
result = IntegerListMap.find(listName);
if (result != null)
return new ListContainer("int",result);
result = StringListMap.find(listName);
if (result != null)
return new ListContainer("string",result);
result = CharListMap.find(listName);
if (result != null)
return new ListContainer("char",result);
result = BooleanListMap.find(listName);
if (result != null)
return new ListContainer("boolean",result);
return null;
}
/**
* FOR TESTING PURPOSES ONLY! DO NOT USE
*/
public static void clearMaps() {
IntegerMap.clear();
BooleanMap.clear();
StringMap.clear();
CharMap.clear();
TemporaryVariablesMap.clear();
VoidFunctionMap.clear();
IntegerFunctionMap.clear();
CharFunctionMap.clear();
BooleanFunctionMap.clear();
StringFunctionMap.clear();
IntegerListMap.clear();
CharListMap.clear();
StringListMap.clear();
BooleanListMap.clear();
}
}
<file_sep>/src/DataTypes/Functions/StringFunction.java
package DataTypes.Functions;
import Compile.Mapper;
import DataTypes.Token;
import java.util.ArrayList;
public class StringFunction extends Function{
public StringFunction(String name, ArrayList<ArrayList<Token>> linesOfCodeInMethod)
{
super(name,linesOfCodeInMethod);
}
public void store()
{
Mapper.storeStringFunction(this);
}
}
<file_sep>/src/DataTypes/Lists/IntegerList.java
package DataTypes.Lists;
import java.util.ArrayList;
public class IntegerList extends List {
ArrayList<Integer> listValues;
public IntegerList(String name)
{
super(name);
listValues = new ArrayList<>();
}
public void add(int num)
{
listValues.add(num);
}
public int get(int index)
{
return listValues.get(index);
}
public int length()
{
return listValues.size();
}
}
<file_sep>/src/DataTypes/Lists/StringList.java
package DataTypes.Lists;
import java.util.ArrayList;
public class StringList extends List {
ArrayList<String> listValues;
public StringList(String name)
{
super(name);
listValues = new ArrayList<>();
}
public void add(String string)
{
listValues.add(string);
}
public String get(int index)
{
return listValues.get(index);
}
public int length()
{
return listValues.size();
}
}
<file_sep>/src/DataTypes/Variables/IntegerVariable.java
package DataTypes.Variables;
public class IntegerVariable extends Variable{
private int value;
private String name;
public IntegerVariable(String name, int value)
{
super(name);
this.value = value;
}
public IntegerVariable(String name)
{
super(name);
}
public int getValue() {
return this.value;
}
}
<file_sep>/src/Maps/Functions/CharFunctionMap.java
package Maps.Functions;
import DataTypes.Functions.CharFunction;
import DataTypes.Token;
import java.util.ArrayList;
import java.util.HashMap;
public class CharFunctionMap {
private static HashMap charFunctionMap = new HashMap<String,ArrayList<ArrayList<Token>>>();
public static void add(String name, CharFunction charFunction)
{
charFunctionMap.put(name,charFunction);
}
public static CharFunction find(String name)
{
return (CharFunction) charFunctionMap.get(name);
}
public static int size()
{
return charFunctionMap.size();
}
/**
* FOR TESTING PURPOSES ONLY! DO NOT USE
*/
public static void clear()
{
charFunctionMap.clear();
}
}
<file_sep>/src/Compile/FunctionExecutor.java
package Compile;
import DataTypes.Functions.Function;
import DataTypes.Functions.FunctionContainer;
import DataTypes.Token;
import DataTypes.Variables.*;
import Errors.InvalidSyntaxException;
import Maps.Variables.TemporaryVariablesMap;
import Parser.Lexer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class FunctionExecutor {
public static LinkedList<Function> functionsExecuting = new LinkedList<>();
/**
* Takes tokens and executes any function found within
* @param tokens Tokens to read through
* @throws InvalidSyntaxException Thrown if the function contains invalid syntax
*/
public static void findAndRunFunction(ArrayList<Token> tokens) throws InvalidSyntaxException
{
boolean functionFound = false;
FunctionContainer foundFunctionContainer;
Function function = null;
ArrayList<Variable> argumentNames = null;
int argumentIndex = 0;
for (Token token : tokens)
{
String tokenContent = token.getContent();
if (!functionFound)
{
foundFunctionContainer = Mapper.findFunction(tokenContent);
if (foundFunctionContainer == null) {
continue;
}
function = foundFunctionContainer.getFunction();
argumentNames = function.getArgumentVariables();
functionFound = true;
}
else
{
if (tokenContent.equals("(") ||
tokenContent.equals(","))
continue;
else if (tokenContent.equals(")"))
break;
Variable arg = argumentNames.get(argumentIndex);
if ( (arg instanceof IntegerVariable) && Calculations.isNumeric(tokenContent) )
TemporaryVariablesMap.add(arg.getName(), new IntegerVariable(arg.getName(), Integer.parseInt(tokenContent)) );
else if ( (arg instanceof BooleanVariable) && Calculations.isBoolean(tokenContent) )
TemporaryVariablesMap.add(arg.getName(), new BooleanVariable(arg.getName(), Boolean.valueOf(tokenContent)) );
else if ( (arg instanceof StringVariable) && tokenContent.length() > 1 && Character.isLetter(tokenContent.charAt(0)) )
TemporaryVariablesMap.add(arg.getName(), new StringVariable(arg.getName(), tokenContent));
else if ( (arg instanceof CharVariable) && tokenContent.length() == 1 && Character.isLetter(tokenContent.charAt(0)))
TemporaryVariablesMap.add(arg.getName(), new CharVariable(arg.getName(), tokenContent.charAt(0)));
}
}
if (functionFound)
{
execute(function);
return;
}
throw new InvalidSyntaxException(Lexer.getLineNumber());
}
/**
* Executes the given function by calling the Translator
* @param function Function to execute
* @throws InvalidSyntaxException Thrown if the function contains invalid syntax
*/
public static void execute(Function function) throws InvalidSyntaxException
{
functionsExecuting.push(function);
ArrayList<ArrayList<Token>> lines = function.getLinesOfCodeInMethod();
for (ArrayList<Token> line : lines)
Translator.handleLine(line);
functionsExecuting.pop();
TemporaryVariablesMap.removeVariables(function.getArgumentVariables());
}
}
<file_sep>/src/Maps/Functions/VoidFunctionMap.java
package Maps.Functions;
import DataTypes.Token;
import DataTypes.Functions.VoidFunction;
import java.util.ArrayList;
import java.util.HashMap;
public class VoidFunctionMap {
private static HashMap voidFunctionMap = new HashMap<String,ArrayList<ArrayList<Token>>>();
public static void add(String name, VoidFunction vf)
{
voidFunctionMap.put(name,vf);
}
public static VoidFunction find(String name)
{
return (VoidFunction) voidFunctionMap.get(name);
}
public static int size()
{
return voidFunctionMap.size();
}
/**
* FOR TESTING PURPOSES ONLY! DO NOT USE
*/
public static void clear()
{
voidFunctionMap.clear();
}
}
<file_sep>/src/Maps/Lists/CharListMap.java
package Maps.Lists;
import DataTypes.Lists.CharList;
import java.util.HashMap;
public class CharListMap {
private static HashMap charListMap = new HashMap<String,CharList>();
public static void add(String name, CharList charList)
{
charListMap.put(name,charList);
}
public static CharList find(String name)
{
return (CharList) charListMap.get(name);
}
public static int size()
{
return charListMap.size();
}
/**
* FOR TESTING PURPOSES ONLY! DO NOT USE
*/
public static void clear()
{
charListMap.clear();
}
}
<file_sep>/src/DataTypes/Functions/Function.java
package DataTypes.Functions;
import DataTypes.Token;
import DataTypes.Variables.Variable;
import java.lang.reflect.Array;
import java.util.ArrayList;
public abstract class Function {
private String name;
private ArrayList< ArrayList<Token> > linesOfCodeInMethod;
private ArrayList<Variable> argumentVariables;
public Function(String name, ArrayList< ArrayList<Token> > linesOfCodeInMethod)
{
this.name = name;
this.linesOfCodeInMethod = linesOfCodeInMethod;
this.argumentVariables = new ArrayList<>();
}
public abstract void store();
public void addLineOfCode(ArrayList<Token> tokens)
{
linesOfCodeInMethod.add( (ArrayList<Token>) tokens.clone() );
}
public void addArguments(ArrayList<Variable> arguments)
{
argumentVariables.addAll( (ArrayList<Variable>) arguments.clone() );
}
public void addArgument(Variable argument)
{
argumentVariables.add(argument);
}
public ArrayList<ArrayList<Token>> getLinesOfCodeInMethod()
{
return linesOfCodeInMethod;
}
public String getName()
{
return name;
}
public ArrayList<Variable> getArgumentVariables() {
return argumentVariables;
}
}
<file_sep>/src/Compile/Operations/BooleanNumOperation.java
package Compile.Operations;
public enum BooleanNumOperation {
GREATER,
LESSER,
EQUALS
}
<file_sep>/Tests/Compile/PrinterTest.java
package Compile;
import DataTypes.Token;
import SharedResources.InputType;
import org.junit.After;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import javax.print.DocFlavor;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
class PrinterTest {
//
// private final ByteArrayOutputStream sysout = new ByteArrayOutputStream();
// private final ByteArrayOutputStream syserr = new ByteArrayOutputStream();
//
// @Before
// public void preparePrintTest() {
// System.setOut(new PrintStream(sysout));
// System.setErr(new PrintStream(syserr));
// }
//
// @After
// public void restoreOutputs() {
// System.setOut(System.out);
// System.setErr(System.err);
// }
//
// @Test
// void testPrintString() throws Exception
// {
// ByteArrayOutputStream sysout = new ByteArrayOutputStream();
// ByteArrayOutputStream syserr = new ByteArrayOutputStream();
//
// System.setOut(new PrintStream(sysout));
// System.setErr(new PrintStream(syserr));
//
// ArrayList<Token> line1 = new ArrayList<>();
//
// line1.add(new Token("print", InputType.NORMAL));
// line1.add(new Token("Hello World", InputType.STRING));
//
// Translator.handleLine(line1);
//
// assertEquals("[out]: Hello World", sysout.toString());
//
//
// }
}<file_sep>/src/DataTypes/Variables/CharVariable.java
package DataTypes.Variables;
public class CharVariable extends Variable{
char value;
public CharVariable(String name, char value)
{
super(name);
this.value = value;
}
public CharVariable(String name)
{
super(name);
}
public char getValue() {
return this.value;
}
}
| 1c76e8327cfdf88785b494568e03f0bfa02ddf9d | [
"Java"
] | 24 | Java | mck-git/Bachelor-Project | 113b15409e1d5448e470bf3d5d131e33ad949144 | 29630cdaa044991e291a770489bb12cd58f49cd6 |
refs/heads/master | <file_sep># Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{jwysiwyg_rails}
s.version = "0.1.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["<NAME>"]
s.date = %q{2011-12-10}
s.description = %q{Rails 3.1 engine for jwysiwyg}
s.email = %q{<EMAIL>}
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"app/assets/images/ajax-loader.gif",
"app/assets/images/jquery.wysiwyg.bg.png",
"app/assets/images/jquery.wysiwyg.gif",
"app/assets/images/jquery.wysiwyg.jpg",
"app/assets/images/jquery.wysiwyg.no-alpha.gif",
"app/assets/images/plugins/fileManager/icon.png",
"app/assets/images/plugins/fileManager/images/application.png",
"app/assets/images/plugins/fileManager/images/code.png",
"app/assets/images/plugins/fileManager/images/css.png",
"app/assets/images/plugins/fileManager/images/db.png",
"app/assets/images/plugins/fileManager/images/directory.png",
"app/assets/images/plugins/fileManager/images/doc.png",
"app/assets/images/plugins/fileManager/images/file.png",
"app/assets/images/plugins/fileManager/images/film.png",
"app/assets/images/plugins/fileManager/images/flash.png",
"app/assets/images/plugins/fileManager/images/folder_open.png",
"app/assets/images/plugins/fileManager/images/html.png",
"app/assets/images/plugins/fileManager/images/java.png",
"app/assets/images/plugins/fileManager/images/linux.png",
"app/assets/images/plugins/fileManager/images/mkdir.png",
"app/assets/images/plugins/fileManager/images/music.png",
"app/assets/images/plugins/fileManager/images/pdf.png",
"app/assets/images/plugins/fileManager/images/php.png",
"app/assets/images/plugins/fileManager/images/picture.png",
"app/assets/images/plugins/fileManager/images/ppt.png",
"app/assets/images/plugins/fileManager/images/prev-directory.png",
"app/assets/images/plugins/fileManager/images/psd.png",
"app/assets/images/plugins/fileManager/images/remove.png",
"app/assets/images/plugins/fileManager/images/rename.png",
"app/assets/images/plugins/fileManager/images/ruby.png",
"app/assets/images/plugins/fileManager/images/script.png",
"app/assets/images/plugins/fileManager/images/txt.png",
"app/assets/images/plugins/fileManager/images/upload.png",
"app/assets/images/plugins/fileManager/images/xls.png",
"app/assets/images/plugins/fileManager/images/zip.png",
"app/assets/javascripts/controls/wysiwyg.colorpicker.js",
"app/assets/javascripts/controls/wysiwyg.cssWrap.js",
"app/assets/javascripts/controls/wysiwyg.image.js",
"app/assets/javascripts/controls/wysiwyg.link.js",
"app/assets/javascripts/controls/wysiwyg.table.js",
"app/assets/javascripts/i18n/lang.cs.js",
"app/assets/javascripts/i18n/lang.de.js",
"app/assets/javascripts/i18n/lang.en.js",
"app/assets/javascripts/i18n/lang.es.js",
"app/assets/javascripts/i18n/lang.fr.js",
"app/assets/javascripts/i18n/lang.he.js",
"app/assets/javascripts/i18n/lang.hr.js",
"app/assets/javascripts/i18n/lang.it.js",
"app/assets/javascripts/i18n/lang.ja.js",
"app/assets/javascripts/i18n/lang.nl.js",
"app/assets/javascripts/i18n/lang.pl.js",
"app/assets/javascripts/i18n/lang.pt_br.js",
"app/assets/javascripts/i18n/lang.ru.js",
"app/assets/javascripts/i18n/lang.se.js",
"app/assets/javascripts/i18n/lang.sl.js",
"app/assets/javascripts/i18n/lang.zh-cn.js",
"app/assets/javascripts/jquery.wysiwyg.js",
"app/assets/javascripts/plugins/wysiwyg.autoload.js",
"app/assets/javascripts/plugins/wysiwyg.fileManager.js",
"app/assets/javascripts/plugins/wysiwyg.fullscreen.js",
"app/assets/javascripts/plugins/wysiwyg.i18n.js",
"app/assets/javascripts/plugins/wysiwyg.rmFormat.js",
"app/assets/stylesheets/jquery.wysiwyg.css",
"app/assets/stylesheets/jquery.wysiwyg.modal.css",
"app/assets/stylesheets/jquery.wysiwyg.old-school.css",
"app/assets/stylesheets/jwysiwyg.css",
"app/assets/stylesheets/plugins/fileManager/wysiwyg.fileManager.css",
"jwysiwyg_rails.gemspec",
"lib/engine.rb",
"lib/jwysiwyg_rails.rb",
"test/helper.rb",
"test/test_jwysiwyg_rails.rb"
]
s.homepage = %q{http://github.com/jwigal/jwysiwyg_rails}
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.5.2}
s.summary = %q{Rails 3.1 engine for jwysiwyg}
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<rails>, ["~> 3.1"])
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"])
s.add_development_dependency(%q<rcov>, [">= 0"])
else
s.add_dependency(%q<rails>, ["~> 3.1"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
s.add_dependency(%q<rcov>, [">= 0"])
end
else
s.add_dependency(%q<rails>, ["~> 3.1"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
s.add_dependency(%q<rcov>, [">= 0"])
end
end
| 6dab653ea326e4a2e82326267f378b842ae022a4 | [
"Ruby"
] | 1 | Ruby | Logic-Seeker/jwysiwyg_rails | 9f2e27e984fb165527fef1a8c4c2fdb5b0c29eea | 4e7613fb47ba7ccb37c17e1d0088feb66def8b98 |
refs/heads/master | <file_sep>$(document).ready( function() {
var xml = "<test><contenu id='2'><title>toto</title><url>url</url></contenu><contenu id='1'><title>toto</title><url>url</url></contenu></test>";
var json = asxParser(xml);
var json2 = xmlToJSON.parseString(readAsText2());
console.log(json);
console.log(json2);
});
function readAsText2(){
var file;
// Resolves helloWorld.doc file that is located in the
// documents root location
tizen.filesystem.resolve('wgt-package', function(dir) {
file = dir.resolve("SeqA.asx");
console.log(dir);
console.log(typeof file);
file.readAsText(
function(str) {
console.log("The file content " + str);
return str;
},
function(e) {console.log("Error " + e.message);},
"UTF-8");
}, function(e) {console.log("Error" + e.message);}, "r");
}
function asxParser(xml){
//variables
var result = [];
var data = [];
//console.log("debut");
try{
$(xml).find('contenu').each(
function()
{
//attributs et noeudsFils formant l'objet contenu
var tmpId = $(this).attr('id');
var title = $(this).find('title').text();
var url = $(this).find('url').text();
data.push({id:tmpId,title:title,url:url});
}).promise().done(function(){
for(var i=0;i<data.length;i++){
result.push(JSON.stringify(data[i]));
// console.log(result);
// console.log(data[i].id);
}
});
//console.log("après");
}catch(e){
console.log("erreur" +e.message);
}
//console.log("fin");
return result;
} | 77e5b0af178c7ac76271d1195ef7a5e13ad51764 | [
"JavaScript"
] | 1 | JavaScript | Amaryill/Parser | fb63fe778dabf4331c3cb7a2e635e80b548e9eba | 28d1c8ecffe8d22263381f9216f94001a75a6e83 |
refs/heads/master | <file_sep>import Vue from 'vue'
import Vuex from 'vuex'
import Search from '../components/Search.vue'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
current_user:'',
favorites: [],
forecast: [],
cityName: ''
},
mutations:{
setCurrentUser(state,current_user){
state.current_user = current_user
},
setFavorites(state,array){
state.favorites = array
},
setForecast(state,array){
state.forecast = array
},
setCityName(state,name){
state.cityName = name
}
},
getters:{
getCityName: state=> {
return state.cityName
}
}
})
<file_sep>import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import Vuex from 'vuex'
import App from './App.vue'
import Favorite from './components/Favorite.vue'
import Signup from './components/Signup.vue'
import auth from './auth/auth'
import store from './store/store.js'
Vue.use(VueRouter)
Vue.use(VueResource)
Vue.use(Vuex)
Vue.http.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token')
const routes = [
{
path: '/favorites',
component: Favorite,
beforeRouteEnter: auth.checkAuth()
},
{
path:'/signup',
component: Signup
},
{
path: '/home',
component: App
}
]
const router = new VueRouter({
routes,
mode: 'history',
redirect:{
'*':'/home'
},
base: 'http://localhost:9292'
})
const app = new Vue({
el: "#app",
router:router,
store,
render: h => h(App)
})
<file_sep>const API_URL = 'http://localhost:9292'
const LOGIN_URL = API_URL + '/api/login'
const SIGN_UP_URL = API_URL + '/api/signup'
export default {
authenticated: false,
data: '',
token: '',
curr_user: '',
logIn(contex,credentials){
contex.$http.post(LOGIN_URL,credentials).then(function(data){
this.data = JSON.parse(data.body)
if(this.data['error']){
contex.error = this.data['error']
}else{
this.curr_user = this.data['current_user']
this.token = this.data['token']
localStorage.setItem('token',this.token)
this.authenticated = true
this.$store.commit('setCurrentUser',this.curr_user)
}
},(response) => {
contex.error = response
})
},
signUp(contex,credentials){
contex.$http.post(SIGN_UP_URL,credentials).then(function(data){
contex.error = 'Account created successfully'
}, (response)=> {
contex.error = 'Error when creating!'
})
},
logOut(contex){
localStorage.removeItem('token')
contex.current_user = ''
this.authenticated = false
},
checkAuth(){
var jwt = localStorage.getItem('token')
if(jwt){
this.authenticated = true
console.log("checkAuth")
}
else{
this.authenticated = false
}
},
getAuthHeader(){
return{
'Authorization': 'Bearer ' + localStorage.getItem('token')
}
}
} | c72ddd15b013dd431ac83cab9599250e8ae76069 | [
"JavaScript"
] | 3 | JavaScript | nickmandev/weather_web_front_end | 57d26e3160907acb24b7ab49a84ecd2aa646bd65 | 2560ff9cedcbba3957bff50c57ee4c73354eb5da |
refs/heads/master | <repo_name>comptatest/repositorytest<file_sep>/src/com/demos/cine/model2/CPanier.java
package com.demos.cine.model2;
import java.util.ArrayList;
public class CPanier {
private ArrayList<CLignePanier> contenu = new ArrayList<>();
public void ajouter(CArticle a,int qte){
CLignePanier lp = new CLignePanier(a,qte);
contenu.add(lp);
}
public String toString(){
String description="";
for(CLignePanier lp:contenu){
description+=
lp.getArt().getReference() +" "+lp.getQte()+"\n";
}
return description;
}
public double getPrixTotalHT(){
double prix=0;
for(CLignePanier lp:contenu){
prix+=lp.getArt().getPrixHT()*lp.getQte();
}
return prix;
}
} | f3c477c37c483bc8b48d29fd1ee79bbefcb1f7cb | [
"Java"
] | 1 | Java | comptatest/repositorytest | fe38fddce93e7efa271193d9e3977e9a42346d1b | 6d72fa086c221df063a5e2b77c82f2bd330dd2a4 |
refs/heads/master | <repo_name>Arunimarajkiran/Vscodes<file_sep>/src/app/greetingsmodel.ts
export class GreetingModels{
}<file_sep>/src/app/login/login.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-login',
template:`
<form>
Username:<input [(ngModel)]=username name='username'/>
Password:<input [(ngModel)]=password name='password'/>
<button (click)=check()>Login</button>
<span *ngIf='isTrue'>Hello {{display}}</span>
</form>
`,
styles: []
})
export class LoginComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
index:number;
isTrue:boolean=false;
username:string;
password:string;
display:string='Not Logged In..';
uname:any[]=['Arunima','Harshita','Vibhanshu','Virat','Mishti','Rey','Tim','Sid','Emir','Rehan'];
pass:any[]=['<PASSWORD>','<PASSWORD>','<PASSWORD>','<PASSWORD>','<PASSWORD>','<PASSWORD>','Tim<PASSWORD>','Sid<PASSWORD>','Emi@123','Re<PASSWORD>'];
check()
{
if(this.uname.indexOf(this.username) != -1)
{
this.index = this.uname.indexOf(this.username);
if(this.pass.indexOf(this.password) == this.index)
{
this.isTrue = !this.isTrue;
this.display = this.username;
}
else{
this.display="Invalid username or password";
}
}
else
{
this.display="User Not Found";
}
}
}
<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<!--<app-print-name></app-print-name>-->
<!--<app-directivescomp></app-directivescomp>-->
<!--<app-emptable></app-emptable>-->
<!--<app-greetings></app-greetings>-->
<app-login></app-login>
`,
styles: ['p{font-weight:bold}']
})
export class AppComponent {
title = 'MyFirstAngularApp';
}
<file_sep>/src/app/emptable/emptable.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-emptable',
templateUrl: './emptable.component.html',
styleUrls: ['./emptable.component.css']
})
export class EmptableComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
employees:any[]=
[{ id:1, name:'Ray', age:22, designation:'Manager'},
{ id:2, name:'Niya', age:32, designation:'IT'},
{ id:3, name:'Mishti', age:27, designation:'Operator'},
{ id:4, name:'Mark', age:33, designation:'Manager'},
{ id:5, name:'Magneta', age:21, designation:'Trainee' }
];
}
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from "./app.component";
import { FirstComponent } from "./firstcomp";
import { LuckynumberComponent } from './luckynumber/luckynumber.component';
import { HelloName } from "./helloname";
import { FormsModule } from '@angular/forms';
import { PrintNameComponent } from './print-name/print-name.component';
import { DirectivescompComponent } from './directivescomp/directivescomp.component';
import { EmptableComponent } from './emptable/emptable.component';
import { GreetingsComponent } from './greetings/greetings.component';
import { LoginComponent } from './login/login.component';
@NgModule({
declarations: [
AppComponent,
FirstComponent,
LuckynumberComponent,
HelloName,
PrintNameComponent,
DirectivescompComponent,
EmptableComponent,
GreetingsComponent,
LoginComponent,
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
//bootstrap:[FirstComponent]
//bootstrap:[CounterComponent]
//bootstrap:[AppComponent]
//bootstrap:[PrintNameComponent]
})
export class AppModule { }
<file_sep>/src/app/directivescomp/directivescomp.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-directivescomp',
templateUrl: './directivescomp.component.html',
styleUrls: ['./directivescomp.component.css']
})
export class DirectivescompComponent implements OnInit {
isValid:boolean=false;
constructor() { }
ngOnInit(): void {
}
cities:any[]=["Mumbai","Gujrat","Pune","Delhi"];
}
| 94fb8151fdc0017b784ba6ae2175f6a01183f317 | [
"TypeScript"
] | 6 | TypeScript | Arunimarajkiran/Vscodes | b61082bdb14a4ff7ade3c7aed04d7a97eb137bc3 | b39cb70dbfb55c8765259353e963d3c0793a8574 |
refs/heads/master | <file_sep>#!/usr/bin/env python
# PD the Ripper
# If you thought Jack was mean.....
import os
import color_console as cons
import sys
import glob
from subprocess import check_output
import re
def menume():
ripper_path = raw_input("Path to regripper: ")
input_dir = raw_input("Input Directory: ")
output_dir = raw_input("Output Directory: ")
host_name = raw_input("Hostname: ")
# ripper_path = "C:\RegRipper"
# input_dir = "C:\Users\Hanson\Desktop\path"
# output_dir = "C:\output"
# host_name="ccc"
checkthingsexist(ripper_path, input_dir, output_dir, host_name)
def checkthingsexist(ripper_path, input_dir, output_dir, hostname):
print(os.path.isdir(ripper_path))
print(os.path.exists(ripper_path + "\\rip.exe"))
if (os.path.isdir(ripper_path)):
sucessure("Regripper directory located")
else:
failture("Regripper directory not found")
if os.path.exists(ripper_path + "\\rip.exe"):
sucessure("Rip.exe located")
else:
failture("rip.exe not found in directory" + ripper_path)
try:
if os.path.isdir(input_dir):
sucessure("Input Directory is Valid")
else:
failture("Input Directory is Invalid")
except:
failture("Something isnt quite right with" + input_dir)
try:
if os.path.isdir(output_dir):
sucessure("Output Directory is Valid")
else:
warningsure("Output Directory not found")
warningsure("We can create that now (y) or return to menu (n)")
createdir = raw_input("Create Directory: ")
createdir = createdir.lower()
except:
failture("Something not right with " + output_dir)
if createdir == 'y':
try:
if not os.path.exists(output_dir):
os.makedirs(output_dir)
except:
print "Directory Creation Failed"
menume()
else:
failture("You chose not to create directory returning to menu....")
# os.system('cls')
menume()
gsd(input_dir, ripper_path, output_dir, hostname)
def gsd(input_dir, ripper_path, output_dir, hostname):
os.chdir(input_dir)
for file in glob.glob("SYSTEM"):
print file
outputcommand=("cd " + ripper_path + " && rip.exe -r " + input_dir + "\\" + file + " -f all > " + output_dir + "\\" + hostname + "_SYSTEM_RR.txt")
print outputcommand
check_output("" + outputcommand + "", shell=True)
mastertimeline(file, output_dir, ripper_path, input_dir,hostname)
i = 0
for file in glob.glob("*NTUSER.DAT"):
i += 1
print file
j = str(i)
filetocheck = output_dir + "\\" + hostname + "_" + j + "_ntuser_RR.txt"
outputcommand = ("cd " + ripper_path + " && rip.exe -r " + input_dir + "\\" + file + " -f ntuser > " + filetocheck)
print outputcommand
check_output("" + outputcommand + "", shell=True)
mastertimeline(file, output_dir, ripper_path, input_dir, hostname)
for file in glob.glob("SECURITY"):
outputcommand = ("cd " + ripper_path + " && rip.exe -r " + input_dir + "\\" + file + " -f security > " + output_dir + "\\" + hostname + "_SECURITY_RR.txt")
print outputcommand
check_output("" + outputcommand + "", shell=True)
mastertimeline(file, output_dir, ripper_path, input_dir, hostname)
for file in glob.glob("SOFTWARE"):
outputcommand = ("cd " + ripper_path + " && rip.exe -r " + input_dir + "\\" + file + " -f software > " + output_dir + "\\" + hostname + "_SOFTWARE_RR.txt")
print outputcommand
check_output("" + outputcommand + "", shell=True)
mastertimeline(file, output_dir, ripper_path, input_dir, hostname)
for file in glob.glob("SAM"):
outputcommand = ("cd " + ripper_path + " && rip.exe -r " + input_dir + "\\" + file + " -f security > " + output_dir + "\\" + hostname + "_SAM_RR.txt")
print outputcommand
check_output("" + outputcommand + "", shell=True)
mastertimeline(file, output_dir, ripper_path, input_dir, hostname)
for file in glob.glob("amcache.hve"):
outputcommand = ("cd " + ripper_path + " && rip.exe -r " + input_dir + "\\" + file + " -f security > " + output_dir + "\\" + hostname + "_amcache.txt")
print outputcommand
check_output("" + outputcommand + "", shell=True)
mastertimeline(file, output_dir, ripper_path, input_dir, hostname)
i = 0
for file in glob.glob("*usrclass.DAT"):
i += 1
print file
j = str(i)
filetocheck = output_dir + "\\" + hostname + "_" + j + "_usrclass_RR.txt"
outputcommand = ("cd " + ripper_path + " && rip.exe -r " + input_dir + "\\" + file + " -f all > " + filetocheck)
print outputcommand
check_output("" + outputcommand + "", shell=True)
mastertimeline(file, output_dir, ripper_path, input_dir, hostname)
def mastertimeline(file, output_dir, ripper_path, input_dir, hostname):
outputcommand = ("cd " + ripper_path + " && rip.exe -r " + input_dir + "\\" + file + " -p regtime -c > " + output_dir + "\\" + hostname + "_timeline_RR.csv")
check_output("" + outputcommand + "", shell=True)
def failture(ustats):
cons.FOREGROUND_RED
print "[x] Failed: " + ustats
cons.FOREGROUND_WHITE
print " Returning to menu......"
# os.system('cls')
menume()
def sucessure(ustats):
cons.FOREGROUND_GREEN
print "[-] Passed: " + ustats
cons.FOREGROUND_WHITE
def warningsure(ustats):
cons.FOREGROUND_YELLOW
print "[?] Warning: " + ustats
cons.FOREGROUND_WHITE
return
if __name__ == "__main__":
cons.FOREGROUND_WHITE
print "Version1.0 - Bug in directory creation on windows...output directory needs to exists"
print "No super timeline yet - will be coming soon"
menume()
<file_sep># pdtheripper
Work in Progress
| 8d933942e6d35c46afec4e1360d977a146ce4c2f | [
"Markdown",
"Python"
] | 2 | Python | Pr0t3an/pdtheripper | 803c4ce6545f6ffc655e2f4527dfcecbcfbd2004 | 312080b096e1cdb0010687a6dea32ddbe96d29b0 |
refs/heads/master | <repo_name>388664/TetrisCplusplus<file_sep>/Source Code/Tetris/Tetris/LaunchOptions.h
class LaunchOptions
{
public:
LaunchOptions();
~LaunchOptions();
private:
};
LaunchOptions::LaunchOptions()
{
}
LaunchOptions::~LaunchOptions()
{
}<file_sep>/Source Code/Tetris/Tetris/Main.cpp
#include <iostream>
#include <string>
#include <SDL.h>
#include <SDL_ttf.h>
#include <SDL_image.h>
#include "SDL_mixer.h"
#include "D34_Button.h"
#include "LaunchHome.h"
#include "Data.h"
#include "D34_SDL2.h"
#include <windows.h>
#undef main
using namespace d34;
using namespace std;
SDL_Window* g_window;
SDL_Renderer* g_renderer;
D34_SDL2 g_D34_SDL2;
bool Init();
void Quit();
int main() {
HWND window;
AllocConsole();
window = FindWindowA("ConsoleWindowClass", NULL);
ShowWindow(window, 0);
if (Init()) {
LaunchHome lau_home(g_renderer, g_D34_SDL2);
lau_home.Run();
Quit();
}
return 0;
}
bool Init() {
g_window = NULL;
g_renderer = NULL;
//initializes the subsystems
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
printf("Unable to initialize SDL %s\n", SDL_GetError());
return false;
}
//Initialize the truetype font API.
if (TTF_Init() < 0)
{
SDL_Log("%s", TTF_GetError());
return false;
}
//Initialize the SDL_mixer
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) == -1)
{
printf("%s", Mix_GetError());
}
//Create window
g_window = SDL_CreateWindow("Tetris Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, data::SCREEN_WIDTH, data::SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (g_window == NULL)
{
printf("Could not create window %s", SDL_GetError());
return false;
}
SDL_Surface* icon = IMG_Load("tetris_icon.bmp");
SDL_SetWindowIcon(g_window, icon);
//create a renderer
g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED);
if (g_renderer == NULL)
{
printf("Could not create render %s", SDL_GetError());
return false;
}
//Init SDL_Image
int imgFlags;
imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
return false;
} imgFlags = IMG_INIT_JPG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
return false;
} imgFlags = IMG_INIT_TIF;
if (!(IMG_Init(imgFlags) & imgFlags))
{
printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
return false;
}
}
void Quit() {
SDL_DestroyRenderer(g_renderer);
SDL_DestroyWindow(g_window);
Mix_CloseAudio();
TTF_Quit();
IMG_Quit();
SDL_Quit();
}<file_sep>/Source Code/Tetris/Tetris/Data.h
#ifndef _DATA_H_
#define _DATA_H_
#include <iostream>
#include <SDL.h>
using namespace std;
namespace data {
enum Window
{
SCREEN_WIDTH = 705,
SCREEN_HEIGHT = 610,
};
enum Launch_play
{
BORDER = 5,
BORDER_CELL = 5,
CELL_SIZE = 30,
NUM_WIDTH = 15,
NUM_HEIGHT = 20,
BOARD_BLOCK_WIDTH = 450,
BOARD_BLOCK_HEIGHT = 600,
};
enum Launch_Hight_Score {
NUM_HIGHT_SCORE = 10,
};
struct Info_Player
{
string name;
int mark;
int level;
int num_block;
double time_play;
};
namespace level1 {
const int mark = 100;
const double speed = 1;
}
namespace level2 {
const int mark = 200;
const double speed = 0.8;
}
namespace level3 {
const int mark = 300;
const double speed = 0.6;
}
namespace level4 {
const int mark = 400;
const double speed = 0.4;
}
namespace level5 {
const int mark = 500;
const double speed = 0.2;
}
namespace level6 {
const int mark = 600;
const double speed = 0.1;
}
}
#endif // !_DATA_H_
<file_sep>/Source Code/Tetris/Tetris/D34_SDL2.cpp
#include "D34_SDL2.h"
using namespace d34;
void D34_SDL2::Free_Texture(SDL_Texture* texture) {
if (texture != NULL) {
SDL_DestroyTexture(texture);
texture = NULL;
}
}
void D34_SDL2::Free_TTF_Font(TTF_Font* ttf_font) {
if (ttf_font != NULL) {
TTF_CloseFont(ttf_font);
ttf_font = NULL;
}
}
void D34_SDL2::Free_Surface(SDL_Surface* surface) {
if (surface != NULL) {
SDL_FreeSurface(surface);
surface = NULL;
}
}
SDL_Surface* D34_SDL2::Load_Image_SDL_Image(std::string file_path, const SDL_PixelFormat* format)
{
//The final optimized image
SDL_Surface* optimizedSurface = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = IMG_Load(file_path.c_str());
if (loadedSurface == NULL)
{
printf("Unable to load image %s! SDL_image Error: %s\n", file_path.c_str(), IMG_GetError());
}
else
{
//Convert surface to screen format
optimizedSurface = SDL_ConvertSurface(loadedSurface, format, 0);
if (optimizedSurface == NULL)
{
printf("Unable to optimize image %s! SDL Error: %s\n", file_path.c_str(), SDL_GetError());
}
//Get rid of old loaded surface
SDL_FreeSurface(loadedSurface);
}
return optimizedSurface;
}
SDL_Texture* D34_SDL2::Load_Image_BMP_To_Texture(const std::string& file, SDL_Renderer* ren)
{
SDL_Texture* texture = nullptr;
//Nạp ảnh từ tên file (với đường dẫn)
SDL_Surface* loadedImage = SDL_LoadBMP(file.c_str());
//Nếu không có lỗi, chuyển đổi về dạng texture and và trả về
if (loadedImage != nullptr) {
texture = SDL_CreateTextureFromSurface(ren, loadedImage);
Free_Surface(loadedImage);
//Đảm bảo việc chuyển đổi không có lỗi
if (texture == nullptr) {
printf("\nError load bmp");
}
}
else {
printf("\nError load bmp");
}
return texture;
}
/**
* Vẽ một SDL_Texture lên một SDL_Renderer tại toạ độ (x, y), trong khi
* giữ nguyên chiều rộng và cao của ảnh
* @param tex: texture nguồn chúng ta muốn vẽ ra
* @param ren: thiết bị renderer chúng ta muốn vẽ vào
* @param x: hoành độ
* @param y: tung độ
*/
void D34_SDL2::Load_Image_BMP(SDL_Renderer* ren, const std::string& file, int x, int y)
{
//nạp ảnh vào texture
SDL_Texture* tex = Load_Image_BMP_To_Texture(file, ren);
//Thiết lập hình chữ nhật đích mà chúng ta muốn vẽ ảnh vào trong
SDL_Rect dst;
dst.x = x;
dst.y = y;
//Truy vẫn texture để lấy chiều rộng và cao (vào chiều rộng và cao tương ứng của hình chữ nhật đích)
SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h);
//Đưa toàn bộ ảnh trong texture vào hình chữ nhật đích
SDL_RenderCopy(ren, tex, NULL, &dst);
Free_Texture(tex);
}
/**
* Vẽ một SDL_Texture lên một SDL_Renderer tại toạ độ (x, y), với
* chiều rộng và cao mới
* @param tex: texture nguồn chúng ta muốn vẽ ra
* @param ren: thiết bị renderer chúng ta muốn vẽ vào
* @param x: hoành độ
* @param y: tung độ
* @param w: chiều rộng (mới)
* @param h: độ cao (mới)
*/
void D34_SDL2::Load_Image_BMP(SDL_Renderer* ren, const std::string& file, int x, int y, int w, int h)
{
//nạp ảnh vào texture
SDL_Texture* tex = Load_Image_BMP_To_Texture(file, ren);
//Thiết lập hình chữ nhật đích mà chúng ta muốn vẽ ảnh vào trong
SDL_Rect dst;
dst.x = x;
dst.y = y;
dst.w = w;
dst.h = h;
//Đưa toàn bộ ảnh trong texture vào hình chữ nhật đích
//(ảnh sẽ co dãn cho khớp với kích cỡ mới)
SDL_RenderCopy(ren, tex, NULL, &dst);
Free_Texture(tex);
}
TTF_Font* D34_SDL2::Convert_Font_To_TTF_Font(Font font, int font_size) {
if (font < 0 || font_size < 0) std::cout << "\nConvert Font in Button Error: ";
TTF_Font* ttf_font = nullptr;
std::string path_font = "";
switch (font) {
case FONT_TIMES_NEW_ROMAN:
path_font = "FONT_TIMES_NEW_ROMAN.ttf";
break;
case FONT_ROBUS:
path_font = "FONT_ROBUS.ttf";
break;
case FONT_GLUE_GUN:
path_font = "FONT_GLUE_GUN.ttf";
break;
case FONT_STARCRAFT:
path_font = "FONT_STARCRAFT.ttf";
break;
}
if (path_font == "") {
std::cout << "\nLoad font error";
}
else ttf_font = TTF_OpenFont(path_font.c_str(), font_size);
return ttf_font;
}
SDL_Color D34_SDL2::Convert_Color_To_SDL_Color_RGB(Color color) {
std::string color_str;
switch (color) {
case WHITE:
color_str = "255255255";
break;
case FIRE_BRICK:
color_str = "255048048";
break;
case RED:
color_str = "255000000";
break;
case YELLOW:
color_str = "255255000";
break;
case GOLD:
color_str = "238201000";
break;
case ORANGE:
color_str = "255165000";
break;
case BLUE:
color_str = "000000255";
break;
case DARK_BLUE:
color_str = "0000000139";
break;
case DARK_ORCHID:
color_str = "154050205";
break;
case PURPLE:
color_str = "128000128";
break;
case STEEL_BLUE:
color_str = "099184255";
break;
case CORN_FLOWER_BLUE:
color_str = "100149237";
break;
case LAWN_GREEN:
color_str = "10225551";
break;
case GREEN:
color_str = "000255000";
break;
}
SDL_Color sdl_color;
sdl_color.r = ((int)color_str[0] - 48) * 100 + ((int)color_str[1] - 48) * 10 + ((int)color_str[2] - 48);
sdl_color.g = ((int)color_str[3] - 48) * 100 + ((int)color_str[4] - 48) * 10 + ((int)color_str[5] - 48);
sdl_color.b = ((int)color_str[6] - 48) * 100 + ((int)color_str[7] - 48) * 10 + ((int)color_str[8] - 48);
return sdl_color;
}
void D34_SDL2::D34_SetRenderDrawColor_RGB(SDL_Renderer* renderer, Color color) {
SDL_Color sdl_color = Convert_Color_To_SDL_Color_RGB(color);
SDL_SetRenderDrawColor(renderer, sdl_color.r, sdl_color.g, sdl_color.b, 255);
}
SDL_Rect D34_SDL2::Load_Text(SDL_Renderer* renderer, const std::string& text, int rec_x, int rec_y, Font font, int font_size, Color color)
{
SDL_Rect rect{ 0,0,0,0 };
if (text == "") return rect;
SDL_Color sdl_color = Convert_Color_To_SDL_Color_RGB(color);
TTF_Font* ttf_font = Convert_Font_To_TTF_Font(font, font_size);
SDL_Surface* surface = TTF_RenderText_Blended(ttf_font, text.c_str(), sdl_color);
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
rect = SDL_Rect{ rec_x,rec_y,surface->w,surface->h };
SDL_RenderCopy(renderer, texture, NULL, &rect);
SDL_FreeSurface(surface);
Free_TTF_Font(ttf_font);
Free_Texture(texture);
return rect;
}
char D34_SDL2::Convert_Key_To_Char(SDL_Keycode key) {
switch (key)
{
case SDLK_0:
return '0';
case SDLK_1:
return '1';
case SDLK_2:
return '2';
case SDLK_3:
return '3';
case SDLK_4:
return '4';
case SDLK_5:
return '5';
case SDLK_6:
return '6';
case SDLK_7:
return '7';
case SDLK_8:
return '8';
case SDLK_9:
return '9';
case SDLK_q:
return 'q';
case SDLK_w:
return 'w';
case SDLK_e:
return 'e';
case SDLK_r:
return 'r';
case SDLK_t:
return 't';
case SDLK_y:
return 'y';
case SDLK_u:
return 'u';
case SDLK_i:
return 'i';
case SDLK_o:
return 'o';
case SDLK_p:
return 'p';
case SDLK_a:
return 'a';
case SDLK_s:
return 's';
case SDLK_d:
return 'd';
case SDLK_f:
return 'f';
case SDLK_g:
return 'g';
case SDLK_h:
return 'h';
case SDLK_j:
return 'j';
case SDLK_k:
return 'k';
case SDLK_l:
return 'l';
case SDLK_z:
return 'z';
case SDLK_x:
return 'x';
case SDLK_c:
return 'c';
case SDLK_v:
return 'v';
case SDLK_b:
return 'b';
case SDLK_n:
return 'n';
case SDLK_m:
return 'm';
default:
return NULL;
}
}
//<file_sep>/Source Code/Tetris/Tetris/LaunchHome.cpp
#include <string>
#include "LaunchHome.h"
#include "D34_Button.h"
#include "LaunchPlay.h"
#include "LaunchHightScore.h"
#include "D34_SDL2.h"
#include <SDL_mixer.h>
using namespace d34;
using namespace d34_btn;
LaunchHome::LaunchHome(SDL_Renderer* _renderer, D34_SDL2& _D34_SDL2)
{
g_renderer = _renderer;
g_D34_SDL2 = _D34_SDL2;
// BUTTON NEW GAME
btn_newgame.Load_Context("New Game");
btn_newgame.Load_Context(d34_btn::FONT_STARCRAFT, 25);
btn_newgame.Load_Context(d34_btn::COLOR_WHITE);
btn_newgame.Set_Color_Button(d34_btn::COLOR_BLUE);
btn_newgame.Width(220);
btn_newgame.Height(50);
btn_newgame.X((SCREEN_WIDTH - btn_newgame.Width()) / 2);
btn_newgame.Y(200);
// BUTTON HIGHT SCORE
btn_hightscore.Load_Context("Hight score");
btn_hightscore.Load_Context(d34_btn::FONT_STARCRAFT, 25);
btn_hightscore.Load_Context(d34_btn::COLOR_WHITE);
btn_hightscore.Set_Color_Button(d34_btn::COLOR_BLUE);
btn_hightscore.Width(220);
btn_hightscore.Height(50);
btn_hightscore.X((SCREEN_WIDTH - btn_hightscore.Width()) / 2);
btn_hightscore.Y(270);
// BUTTON EXIT
btn_exit.Load_Context("Exit");
btn_exit.Load_Context(d34_btn::FONT_STARCRAFT, 25);
btn_exit.Load_Context(d34_btn::COLOR_WHITE);
btn_exit.Set_Color_Button(d34_btn::COLOR_BLUE);
btn_exit.Width(220);
btn_exit.Height(50);
btn_exit.X((SCREEN_WIDTH - btn_exit.Width()) / 2);
btn_exit.Y(340);
//Dừng LaunchHome 1s để chương trình load xong
SDL_Delay(1000);
}
LaunchHome::~LaunchHome() {
}
bool LaunchHome::Run() {
bool isRun = true;
SDL_Event e;
//loop main
while (isRun) {
Sound_Background();
//Event
if (SDL_WaitEvent(&e)) {
switch (e.type)
{
case SDL_QUIT:
isRun=false;
break;
case SDL_MOUSEMOTION:
// Animatio /////////////////////////////////////////////////////////////////////
btn_newgame.Animation(g_renderer, e.button.x, e.button.y, d34_btn::COLOR_WHITE, d34_btn::COLOR_RED);
btn_hightscore.Animation(g_renderer, e.button.x, e.button.y, d34_btn::COLOR_WHITE, d34_btn::COLOR_RED);
btn_exit.Animation(g_renderer,e.button.x, e.button.y, d34_btn::COLOR_WHITE, d34_btn::COLOR_RED);
break;
case SDL_MOUSEBUTTONDOWN:
// Click ////////////////////////////////////////////////////////////////////
if (btn_newgame.IS_Mouse_In_Button(e.button.x, e.button.y))
{
btn_newgame.Sound_Click();
LaunchPlay lan_play(g_renderer, g_D34_SDL2);
lan_play.Run();
btn_newgame.Load_Context(d34_btn::COLOR_WHITE);
}
else if (btn_hightscore.IS_Mouse_In_Button(e.button.x, e.button.y)) {
btn_hightscore.Sound_Click();
LaunchHightScore lan_hight_score(g_renderer, g_D34_SDL2);
lan_hight_score.Run();
btn_hightscore.Load_Context(d34_btn::COLOR_WHITE);
}
else if (btn_exit.IS_Mouse_In_Button(e.button.x, e.button.y)) {
btn_exit.Sound_Click();
isRun = false;
}
break;
}
}
//LOAD SCREEN ///////////////////////////////////////////////////
SDL_RenderClear(g_renderer);
g_D34_SDL2.Load_Image_BMP(g_renderer, "Tetris_background.bmp", 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
btn_newgame.Load_Button(g_renderer);
btn_hightscore.Load_Button(g_renderer);
btn_exit.Load_Button(g_renderer);
//DRAW
SDL_RenderPresent(g_renderer);
}
return false;
}
void LaunchHome::Sound_Background() {
Mix_Music* music = Mix_LoadMUS("music_menu.mp3");
if (music == NULL)
{
printf("%s", Mix_GetError());
}
if(!Mix_PlayingMusic()) Mix_PlayMusic(music, -1);
}<file_sep>/Source Code/Tetris/Tetris/LaunchHightScore.cpp
#include "LaunchHightScore.h"
#include <SDL.h>
#include "Data.h"
#include <fstream>
#include <SDL_mixer.h>
using namespace data;
using namespace d34;
LaunchHightScore::LaunchHightScore(SDL_Renderer* _g_renderer,D34_SDL2& _g_D34_SDL2)
{
g_renderer = _g_renderer;
g_D34_SDL2 = _g_D34_SDL2;
//gán NUM_HIGHT_SCORE người chơi vào mảng
ifstream rf("hight_score.txt", ios::in);
for (int i = 0; i < NUM_HIGHT_SCORE && !rf.eof(); i++) //mảng thông tin trong file luôn có NUM_HIGHT_SCORE phần tử
{
rf >> ary_player[i].name;
rf >> ary_player[i].mark;
rf >> ary_player[i].level;
rf >> ary_player[i].num_block;
rf >> ary_player[i].time_play;//đã xử lý nên phần thập phân chỉ có hàng đơn vị
}
rf.close();
if (!rf.good()) cout << "\nError occurred at reading time!";
// BUTTON EXIT
btn_exit.Load_Context("Exit");
btn_exit.Load_Context(d34_btn::FONT_STARCRAFT, 25);
btn_exit.Load_Context(d34_btn::COLOR_WHITE);
btn_exit.Set_Color_Button(d34_btn::COLOR_BLUE);
btn_exit.Width(220);
btn_exit.Height(50);
btn_exit.X((SCREEN_WIDTH - btn_exit.Width()) / 2);
btn_exit.Y(500);
}
LaunchHightScore::~LaunchHightScore() {}
void LaunchHightScore::Run()
{
bool isRun = true;
SDL_Event e;
int font_size_board = 15;
//Initialization Rect
SDL_Rect rec_header{ 40,70,624,30 };//{x,y,w,h}
SDL_Rect rec_stt = g_D34_SDL2.Load_Text(g_renderer, "STT", 0, -100, FONT_STARCRAFT, font_size_board, WHITE);
SDL_Rect rec_name = g_D34_SDL2.Load_Text(g_renderer, "Name", 0, -100, FONT_STARCRAFT, font_size_board, WHITE);
SDL_Rect rec_mark = g_D34_SDL2.Load_Text(g_renderer, "Mark", 0, -100, FONT_STARCRAFT, font_size_board, WHITE);
SDL_Rect rec_level = g_D34_SDL2.Load_Text(g_renderer, "Level", 0, -100, FONT_STARCRAFT, font_size_board, WHITE);
SDL_Rect rec_block = g_D34_SDL2.Load_Text(g_renderer, "Block", 0, -100, FONT_STARCRAFT, font_size_board, WHITE);
SDL_Rect rec_time = g_D34_SDL2.Load_Text(g_renderer, "Time", 0, -100, FONT_STARCRAFT, font_size_board, WHITE);
//loop main
while (isRun) {
Sound_Hight_Score();
#pragma region EVENT
if (SDL_WaitEvent(&e)) {
switch (e.type)
{
case SDL_QUIT:
isRun = false;
break;
case SDL_MOUSEMOTION:
// Animatio /////////////////////////////////////////////////////////////////////
btn_exit.Animation(g_renderer, e.button.x, e.button.y, d34_btn::COLOR_WHITE, d34_btn::COLOR_RED);
break;
case SDL_MOUSEBUTTONDOWN:
// Click ////////////////////////////////////////////////////////////////////
if (btn_exit.IS_Mouse_In_Button(e.button.x, e.button.y))
{
btn_exit.Sound_Click();
isRun = false;
}
break;
}
}
#pragma endregion
#pragma region LOAD SCREEN
SDL_RenderClear(g_renderer);
g_D34_SDL2.Load_Image_BMP(g_renderer, "Background_hight_score.bmp", 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
btn_exit.Load_Button(g_renderer);
#pragma region Load Board
#pragma region load header
g_D34_SDL2.D34_SetRenderDrawColor_RGB(g_renderer, CORN_FLOWER_BLUE);
SDL_RenderFillRect(g_renderer, &rec_header);
//STT
rec_stt.x = 65 - rec_stt.w / 2;
rec_stt.y = 85 - rec_stt.h / 2;
rec_stt = g_D34_SDL2.Load_Text(g_renderer, "STT", rec_stt.x, rec_stt.y, FONT_STARCRAFT, font_size_board, WHITE);
//Name
rec_name.x = 190 - rec_name.w / 2;
rec_name.y = 85 - rec_name.h / 2;
rec_name = g_D34_SDL2.Load_Text(g_renderer, "Name", rec_name.x, rec_name.y, FONT_STARCRAFT, font_size_board, WHITE);
//Mark
rec_mark.x = 340 - rec_mark.w / 2;
rec_mark.y = 85 - rec_mark.h / 2;
rec_mark = g_D34_SDL2.Load_Text(g_renderer, "Mark", rec_mark.x, rec_mark.y, FONT_STARCRAFT, font_size_board, WHITE);
//Level
rec_level.x = 427 - rec_level.w / 2;
rec_level.y = 85 - rec_level.h / 2;
rec_level = g_D34_SDL2.Load_Text(g_renderer, "Level", rec_level.x, rec_level.y, FONT_STARCRAFT, font_size_board, WHITE);
//Block
rec_block.x = 514 - rec_block.w / 2;
rec_block.y = 85 - rec_block.h / 2;
rec_block = g_D34_SDL2.Load_Text(g_renderer, "Block", rec_block.x, rec_block.y, FONT_STARCRAFT, font_size_board, WHITE);
//Time
rec_time.x = 614 - rec_time.w / 2;
rec_time.y = 85 - rec_time.h / 2;
rec_time = g_D34_SDL2.Load_Text(g_renderer, "Time", rec_time.x, rec_time.y, FONT_STARCRAFT, font_size_board, WHITE);
#pragma endregion
#pragma region load content
for (int i = 0; i < NUM_HIGHT_SCORE; i++)
{
if (ary_player[i].num_block > 0 && ary_player[i].mark>=0 && ary_player[i].level>0) {
//xử lý lưu kiểu double 1 số sau dấu phẩy cho time_play
string strtime = to_string(ary_player[i].time_play);
strtime = strtime.substr(0, strtime.find('.', 0) + 2);
SDL_Rect rec_content_stt = g_D34_SDL2.Load_Text(g_renderer, to_string(i+1), 0, -100, FONT_STARCRAFT, font_size_board, WHITE);
SDL_Rect rec_content_name = g_D34_SDL2.Load_Text(g_renderer, ary_player[i].name, 0, -100, FONT_STARCRAFT, font_size_board, WHITE);
SDL_Rect rec_content_mark = g_D34_SDL2.Load_Text(g_renderer, to_string(ary_player[i].mark), 0, -100, FONT_STARCRAFT, font_size_board, WHITE);
SDL_Rect rec_content_level = g_D34_SDL2.Load_Text(g_renderer, to_string(ary_player[i].level), 0, -100, FONT_STARCRAFT, font_size_board, WHITE);
SDL_Rect rec_content_block = g_D34_SDL2.Load_Text(g_renderer, to_string(ary_player[i].num_block),0, -100, FONT_STARCRAFT, font_size_board, WHITE);
SDL_Rect rec_content_time = g_D34_SDL2.Load_Text(g_renderer, strtime, 0, -100, FONT_STARCRAFT, font_size_board, WHITE);
//stt
rec_content_stt.x = 65 - rec_content_stt.w / 2;
rec_content_stt.y = 85 + (i+1) * 30 - rec_content_stt.h / 2;
rec_content_stt = g_D34_SDL2.Load_Text(g_renderer, to_string(i+1), rec_content_stt.x, rec_content_stt.y, FONT_STARCRAFT, font_size_board, WHITE);
//name
rec_content_name.x = 190 - rec_content_name.w / 2;
rec_content_name.y = 85 + (i + 1) * 30 - rec_content_name.h / 2;
rec_content_name = g_D34_SDL2.Load_Text(g_renderer, ary_player[i].name, rec_content_name.x, rec_content_name.y, FONT_STARCRAFT, font_size_board, WHITE);
//mark
rec_content_mark.x = 340 - rec_content_mark.w / 2;
rec_content_mark.y = 85 + (i + 1) * 30 - rec_content_mark.h / 2;
rec_content_mark = g_D34_SDL2.Load_Text(g_renderer, to_string(ary_player[i].mark), rec_content_mark.x, rec_content_mark.y, FONT_STARCRAFT, font_size_board, WHITE);
//level
rec_content_level.x = 427 - rec_content_level.w / 2;
rec_content_level.y = 85 + (i + 1) * 30 - rec_content_level.h / 2;
rec_content_level = g_D34_SDL2.Load_Text(g_renderer, to_string(ary_player[i].level), rec_content_level.x, rec_content_level.y, FONT_STARCRAFT, font_size_board, WHITE);
//block
rec_content_block.x = 514 - rec_content_block.w / 2;
rec_content_block.y = 85 + (i + 1) * 30 - rec_content_block.h / 2;
rec_content_block = g_D34_SDL2.Load_Text(g_renderer, to_string(ary_player[i].num_block), rec_content_block.x, rec_content_block.y, FONT_STARCRAFT, font_size_board, WHITE);
//time
rec_content_time.x = 614 - rec_content_time.w / 2;
rec_content_time.y = 85 + (i + 1) * 30 - rec_content_time.h / 2;
rec_content_time = g_D34_SDL2.Load_Text(g_renderer, strtime, rec_content_time.x, rec_content_time.y, FONT_STARCRAFT, font_size_board, WHITE);
}
}
#pragma endregion
#pragma endregion
#pragma endregion
//cout << "rec_stt(x,y)= (" << rec_stt.x << "," << rec_stt.y << ")" << endl;
//cout << "rec_header(x,y)= (" << rec_header.x << "," << rec_header.y << ")" << endl;
////Draw Line
//g_D34_SDL2.D34_SetRenderDrawColor_RGB(g_renderer, WHITE);
//SDL_RenderDrawLine(g_renderer, 90, 100, 90, 130);
//SDL_RenderDrawLine(g_renderer, 290, 100, 290, 130);
//SDL_RenderDrawLine(g_renderer, 390, 100, 390, 130);
//SDL_RenderDrawLine(g_renderer, 464, 100, 464, 130);
//SDL_RenderDrawLine(g_renderer, 564, 100, 564, 130);
//DRAW
SDL_RenderPresent(g_renderer);
}
}
void LaunchHightScore::Sound_Hight_Score() {
Mix_Music* music = Mix_LoadMUS("music_hight_score.mp3");
if (music == NULL)
{
printf("%s", Mix_GetError());
}
if (!Mix_PlayingMusic()) Mix_PlayMusic(music, -1);
}<file_sep>/Source Code/Tetris/Tetris/LaunchHome.h
#ifndef _LAUNCH_HOME_H_
#define _LAUNCH_HOME_H_
#include <SDL.h>
#include "D34_Button.h"
#include "D34_SDL2.h"
using namespace d34;
class LaunchHome
{
public:
LaunchHome(SDL_Renderer*, D34_SDL2&);
~LaunchHome();
bool Run();
void Sound_Background();
private:
const int SCREEN_WIDTH = 705;
const int SCREEN_HEIGHT = 610;
SDL_Renderer* g_renderer;
D34_SDL2 g_D34_SDL2;
d34_btn::D34_Button btn_newgame;
d34_btn::D34_Button btn_hightscore;
d34_btn::D34_Button btn_exit;
};
#endif // !_LAUNCH_HOME_H_
<file_sep>/Source Code/Tetris/Tetris/D34_Button.h
#ifndef _D34_BUTTON_H_
#define _D34_BUTTON_H_
#include <iostream>
#include <sdl.h>
#include <sdl_ttf.h>
#include <string>
using namespace std;
namespace d34_btn {
enum Font
{
FONT_TIMES_NEW_ROMAN = 0,
FONT_ROBUS,
FONT_GLUE_GUN,
FONT_STARCRAFT,
};
enum Color
{
COLOR_RED =0,
COLOR_YELLOW,
COLOR_BLUE,
COLOR_GREEN,
COLOR_GRAY,
COLOR_BLACK,
COLOR_WHITE,
};
enum Horizontal
{
HORIZONTAL_NULL = 0,
HORIZONTAL_LEFT,
HORIZONTAL_CENTER,
HORIZONTAL_RIGHT,
};
enum Vertical
{
VERTICAL_NULL = 0,
VERTICAL_TOP,
VERTICAL_CENTER,
VERTICAL_BOTTOM,
};
struct Context
{
string text;
size_t size;
Font font;
Color color;
Horizontal horizontal;
Vertical vertical;
};
//khi set font cho context thì phải set font cho p_context_ttf_font
//khi load horizontal và vertical cho context thì phải load x va y cho rec_context
class D34_Button {
public:
/*
padding
margin
*/
D34_Button();
~D34_Button();
//coordinate button
void X(int x);
int X();
void Y(int y);
int Y();
//dimension button
void Width(size_t width);
size_t Width();
void Height(size_t height);
size_t Height();
bool IS_Mouse_In_Button(int mouse_x, int mouse_y );
void Animation(SDL_Renderer* renderer, int mouse_x, int mouse_y, Color color_before, Color color_after);
void Sound_Click();
void Set_Color_Button(Color color);
void Load_Context(
string text = "Button",
Font font = FONT_TIMES_NEW_ROMAN,
int font_size = 20,
Color color = COLOR_BLACK,
Horizontal hor = HORIZONTAL_CENTER,
Vertical ver = VERTICAL_CENTER
);
void Load_Context(
string text = "Button",
Font font = FONT_TIMES_NEW_ROMAN,
int font_size = 20,
Color color = COLOR_BLACK,
int padding_left = 0,
int padding_top = 0
);
void Load_Context(const char* text);
void Load_Context(Font font, int font_size);
void Load_Context(Horizontal hor, Vertical ver);
void Load_Context(int padding_left, int padding_top);
void Load_Context(Color color);
void Load_Button(SDL_Renderer* renderer);
private:
SDL_Rect rec_btn;
Color btn_color;
Context context;
SDL_Rect rec_context;
TTF_Font* context_ttf_font;
TTF_Font* Convert_Font_To_TTF_Font(Font font, int font_size);
SDL_Color Convert_Color_To_SDL_Color(Color color);
void Convert_Context_Alignment();
void Free_Texture(SDL_Texture*);
void Free_TTF_Font(TTF_Font*);
void Free_Surface(SDL_Surface*);
};
}
#endif // !_D34_BUTTON_H_<file_sep>/Source Code/Tetris/Tetris/ManageTetromino.h
#ifndef _MANAGE_TETROMINO_H_
#define _MANAGE_TETROMINO_H_
#include <SDL.h>
#include <iostream>
#include "Data.h"
#include "Tetromino.h"
#include "D34_SDL2.h"
using namespace d34;
class ManageTetromino
{
public:
ManageTetromino();
~ManageTetromino();
void Draw(SDL_Renderer* _renderer, D34_SDL2& _D34_SDL2);
bool Is_Collision(Tetromino&);
void Unite(Tetromino&);
int Reward();
void Sound_Reward();
private:
const int board_w = 450;
const int board_h = 600;
const int board_x = data::BORDER;
const int board_y = data::BORDER;
char data[data::NUM_WIDTH][data::NUM_HEIGHT];// chứa các kí tự: 0, I, J, L, O, S, T, Z
};
#endif // !_MANAGE_TETROMINO_H_
<file_sep>/Source Code/Tetris/Tetris/LaunchPlay.cpp
#include "LaunchPlay.h"
#include "ManageTetromino.h"
#include "Tetromino.h"
#include <fstream>
#include <ctime>
#include <SDL_mixer.h>
using namespace data;
using namespace std;
LaunchPlay::LaunchPlay(SDL_Renderer* _g_renderer, D34_SDL2& _g_D34_SDL2):
tetromino_ {static_cast<Tetromino::Type>(rand() % 7)}
{
//tetromino_ = Tetromino{ static_cast<Tetromino::Type>(rand() % 7) };
srand(time(NULL));
g_renderer = _g_renderer;
g_D34_SDL2 = _g_D34_SDL2;
player.name = "Player";
player.mark = 0;
player.level = 1;
player.num_block = 1;
player.time_play = 0.0;
speed=data::level1::speed;
ifstream rf("Hight_score.txt", ios::in);
if (!rf) cout << "\nCannot open file!";
string str_temp = "";
rf >> str_temp;
rf >> hight_mark;
rf.close();
if (!rf.good()) cout << "\nError occurred at reading time!";
btn_exit.Load_Context("Exit");
btn_exit.Load_Context(d34_btn::FONT_STARCRAFT, 25);
btn_exit.Load_Context(d34_btn::COLOR_WHITE);
btn_exit.Set_Color_Button(d34_btn::COLOR_BLUE);
btn_exit.Width(200);
btn_exit.Height(50);
btn_exit.X(480);
btn_exit.Y(SCREEN_HEIGHT - BORDER - btn_exit.Height() - 10);
}
LaunchPlay::~LaunchPlay() {}
bool LaunchPlay::Enter_Name() {
bool success = true;
bool isRun = true;
player.name = "_";
SDL_Event e;
//Text Hint
SDL_Rect rec_hint = g_D34_SDL2.Load_Text(g_renderer, "Enter your name", 0, -100, d34::FONT_STARCRAFT, 25, d34::WHITE);
rec_hint.x = (data::SCREEN_WIDTH - rec_hint.w) / 2;
rec_hint.y = 200;
//Text name
SDL_Rect rec_name = g_D34_SDL2.Load_Text(g_renderer, player.name, 0, 0, d34::FONT_STARCRAFT, 25, d34::WHITE);
rec_name.y = rec_hint.y + rec_hint.h + 20;
//Button OK
d34_btn::D34_Button btn_ok;
btn_ok.Load_Context("OK");
btn_ok.Load_Context(d34_btn::FONT_STARCRAFT, 25);
btn_ok.Load_Context(d34_btn::COLOR_WHITE);
btn_ok.Set_Color_Button(d34_btn::COLOR_BLUE);
btn_ok.Width(200);
btn_ok.Height(50);
btn_ok.X((SCREEN_WIDTH - btn_ok.Width()) / 2);
btn_ok.Y(rec_name.y + rec_name.h + 20);
//Main loop
while (isRun)
{
SDL_SetRenderDrawColor(g_renderer, 0, 0, 0, 0);
SDL_RenderClear(g_renderer);
//Text Hint
rec_hint = g_D34_SDL2.Load_Text(g_renderer, "Enter your name", rec_hint.x, rec_hint.y, d34::FONT_STARCRAFT, 25, d34::WHITE);
//Text Name
rec_name.x = (data::SCREEN_WIDTH - rec_name.w) / 2;
rec_name = g_D34_SDL2.Load_Text(g_renderer, player.name, rec_name.x, rec_name.y, d34::FONT_STARCRAFT, 25, d34::WHITE);
//Button OK
btn_ok.Load_Button(g_renderer);
SDL_RenderPresent(g_renderer);
SDL_WaitEvent(&e);
switch (e.type) {
case SDL_KEYDOWN:
Sound_KeyBoard();
player.name.pop_back();
switch (e.key.keysym.sym)
{
case SDLK_BACKSPACE:
if (player.name.size() > 0)
player.name.pop_back();
break;
case SDLK_RETURN: //phim enter
isRun = false;
break;
default:
if (player.name.size()<=14 && g_D34_SDL2.Convert_Key_To_Char(e.key.keysym.sym) != NULL) {
player.name += g_D34_SDL2.Convert_Key_To_Char(e.key.keysym.sym);
}
break;
}
player.name += "_";
cout << "\n" << player.name;
cout << "\n" << player.name.size();
break;
case SDL_MOUSEBUTTONDOWN:
if (btn_ok.IS_Mouse_In_Button(e.button.x, e.button.y)) {
btn_ok.Sound_Click();
success = true;
isRun = false;
}
break;
case SDL_QUIT:
success = false;
isRun = false;
break;
}
}
if (player.name == "_" || player.name == "") player.name = "Player";
else player.name.pop_back();
return success;
}
bool LaunchPlay::Run() {
//chỉ xét va chạm khi block tự rơi xuống còn dùng sự kiện thì vẫn không xét va chạm
SDL_Event e;
bool isRun = true;
bool isLost = false;
isRun = Enter_Name();
time_start = clock();
player.time_play = 0;
Sound_Play();
//Main loop
while (isRun) {
//EVENT ///////////////////////////////////////////////////////////////////////
//Event chỉ thay đổi tọa độ Tetromino không có chức năng khác
if (SDL_PollEvent(&e))
{
switch (e.type)
{
case SDL_MOUSEMOTION:
if (btn_exit.IS_Mouse_In_Button(e.button.x, e.button.y))
btn_exit.Load_Context(d34_btn::COLOR_RED);
else
btn_exit.Load_Context(d34_btn::COLOR_WHITE);
break;
case SDL_MOUSEBUTTONDOWN:
if (btn_exit.IS_Mouse_In_Button(e.button.x, e.button.y))
{
btn_exit.Sound_Click();
isRun = false;
}
break;
case SDL_KEYDOWN:
{
switch (e.key.keysym.sym)
{
case SDLK_DOWN:
{
Tetromino t = tetromino_;
t.Move(0, 1);
if (!manage_.Is_Collision(t))
tetromino_ = t;
}
break;
case SDLK_RIGHT:
{
Tetromino t = tetromino_;
t.Move(1, 0);
if (!manage_.Is_Collision(t))
tetromino_ = t;
}
break;
case SDLK_LEFT:
{
Tetromino t = tetromino_;
t.Move(-1, 0);
if (!manage_.Is_Collision(t))
tetromino_ = t;
}
break;
case SDLK_UP:
{
Tetromino t = tetromino_;
t.Rotate();
if (!manage_.Is_Collision(t))
tetromino_ = t;
}
break;
}
}
break;
case SDL_QUIT:
isRun = false;
break;
}
}
//LOAD SCREEN ////////////////////////////////////////////////////////////
g_D34_SDL2.D34_SetRenderDrawColor_RGB(g_renderer, BLUE);
SDL_RenderClear(g_renderer);
//load board
manage_.Draw(g_renderer, g_D34_SDL2);
tetromino_.Draw(g_renderer, g_D34_SDL2);
//load information
{
//background
SDL_Rect rec_info{ BORDER * 2 + BOARD_BLOCK_WIDTH,BORDER,SCREEN_WIDTH - BORDER * 3 - BOARD_BLOCK_WIDTH,SCREEN_HEIGHT - BORDER * 2 };
SDL_SetRenderDrawColor(g_renderer, 0, 0, 0, 0);
SDL_RenderFillRect(g_renderer, &rec_info);
//Hight Mark
if (hight_mark > 9999) hight_mark = 9999;
if (hight_mark < player.mark) hight_mark = player.mark;
g_D34_SDL2.Load_Text(g_renderer, "Highest: " + to_string(hight_mark),
BORDER * 3 + BOARD_BLOCK_WIDTH,
BORDER * 2, FONT_GLUE_GUN, 40, WHITE);
//Mark
if (player.mark > 99999) player.mark = 99999;
g_D34_SDL2.Load_Text(g_renderer, "Mark: " + to_string(player.mark),
BORDER * 3 + BOARD_BLOCK_WIDTH,
BORDER * 2 + 60, FONT_GLUE_GUN, 40, WHITE);
//Level
if (player.mark < level1::mark) {
speed = level1::speed;
g_D34_SDL2.Load_Text(g_renderer, "Level: 1",
BORDER * 3 + BOARD_BLOCK_WIDTH,
BORDER * 2 + 120, FONT_GLUE_GUN, 40, WHITE);
}
else if (player.mark < level2::mark) {
speed = level2::speed;
g_D34_SDL2.Load_Text(g_renderer, "Level: 2",
BORDER * 3 + BOARD_BLOCK_WIDTH,
BORDER * 2 + 120, FONT_GLUE_GUN, 40, WHITE);
}
else if (player.mark < level3::mark) {
speed = level3::speed;
g_D34_SDL2.Load_Text(g_renderer, "Level: 3",
BORDER * 3 + BOARD_BLOCK_WIDTH,
BORDER * 2 + 120, FONT_GLUE_GUN, 40, WHITE);
}
else if (player.mark < level4::mark) {
speed = level4::speed;
g_D34_SDL2.Load_Text(g_renderer, "Level: 4",
BORDER * 3 + BOARD_BLOCK_WIDTH,
BORDER * 2 + 120, FONT_GLUE_GUN, 40, WHITE);
}
else if (player.mark < level5::mark) {
speed = level5::speed;
g_D34_SDL2.Load_Text(g_renderer, "Level: 5",
BORDER * 3 + BOARD_BLOCK_WIDTH,
BORDER * 2 + 120, FONT_GLUE_GUN, 40, WHITE);
}
else {
speed = level6::speed;
g_D34_SDL2.Load_Text(g_renderer, "Level: Max",
BORDER * 3 + BOARD_BLOCK_WIDTH,
BORDER * 2 + 120, FONT_GLUE_GUN, 40, WHITE);
}
//Block
g_D34_SDL2.Load_Text(g_renderer, "Block: " + to_string(player.num_block),
BORDER * 3 + BOARD_BLOCK_WIDTH,
BORDER * 2 + 180, FONT_GLUE_GUN, 40, WHITE);
//Time
if (player.time_play > 99999)
g_D34_SDL2.Load_Text(g_renderer, "Time: " + to_string(99999) + "s",
BORDER * 3 + BOARD_BLOCK_WIDTH,
BORDER * 2 + 180, FONT_GLUE_GUN, 40, WHITE);
else {
string strtime = to_string(player.time_play);
strtime = strtime.substr(0, strtime.find('.', 0) + 2);
g_D34_SDL2.Load_Text(g_renderer, "Time: " + strtime + "s",
BORDER * 3 + BOARD_BLOCK_WIDTH,
BORDER * 2 + 240, FONT_GLUE_GUN, 40, WHITE);
}
//Exit Button
btn_exit.Load_Button(g_renderer);
}
//TETROMINO RƠI TỰ DO //////////////////////////////////////////////////////
if (((double)(clock()-time_start))/1000 > player.time_play)
{
player.time_play+=speed;
//tạo tetromino mới để xét collision
Tetromino t = tetromino_;
t.Move(0, 1);
//khi tetromino vừa tạo ra collíion với tetromino khác thì unite tetromino_ nếu không thì tetromino vừa tạo ra gán cho tetromino_
if (manage_.Is_Collision(t))
{
player.num_block++;
manage_.Unite(tetromino_);
player.mark += manage_.Reward();
tetromino_ = Tetromino{ static_cast<Tetromino::Type>(rand() % 7) };
if (manage_.Is_Collision(tetromino_))
{
isRun = false;
isLost = true;
}
}
else
{
tetromino_ = t;
}
}
//DRAW /////////////////////////////////////////////////////////////////////
SDL_RenderPresent(g_renderer);
}
Save_Info_Player();
//Lost
Mix_HaltChannel(-1);
if (isLost) Lost();
return true;
}
void LaunchPlay::Save_Info_Player() {
//cập nhật thông tin người chơi
//level
if (speed == 1) player.level = 1;
else if (speed == 0.8) player.level = 2;
else if (speed == 0.6) player.level = 3;
else if (speed == 0.4) player.level = 4;
else if (speed == 0.2) player.level = 5;
else if (speed == 0.1) player.level = 6;
Info_Player ary_player[NUM_HIGHT_SCORE + 1];
//gán NUM_HIGHT_SCORE + 1 người chơi vào mảng
ary_player[NUM_HIGHT_SCORE] = player; //gán info player hiện tại vào cuối mảng
ifstream rf("hight_score.txt", ios::in);
for (int i = 0; i < NUM_HIGHT_SCORE && !rf.eof(); i++) //mảng thông tin trong file luôn có NUM_HIGHT_SCORE phần tử
{
rf >> ary_player[i].name;
rf >> ary_player[i].mark;
rf >> ary_player[i].level;
rf >> ary_player[i].num_block;
rf >> ary_player[i].time_play;//đã xử lý nên phần thập phân chỉ có hàng đơn vị
}
rf.close();
//sắp xếp
for (int i = 0; i < NUM_HIGHT_SCORE + 1 - 1; i++)
{
for (int j = 0; j < NUM_HIGHT_SCORE + 1 - 1 - i; j++)
{
Info_Player swap_temp;
if (ary_player[j].mark < ary_player[j + 1].mark) {//so sánh mark trước
swap_temp = ary_player[j];
ary_player[j] = ary_player[j + 1];
ary_player[j + 1] = swap_temp;
}
else if (ary_player[j].mark == ary_player[j + 1].mark) {//nếu mark bằng nhau
if (ary_player[j].num_block < ary_player[j + 1].num_block) {//so sánh num_block
swap_temp = ary_player[j];
ary_player[j] = ary_player[j + 1];
ary_player[j + 1] = swap_temp;
}
else if (ary_player[j].num_block == ary_player[j + 1].num_block) {//nếu num_block bằng nhau
if (ary_player[j].time_play < ary_player[j + 1].time_play) {//so sánh time_play
swap_temp = ary_player[j];
ary_player[j] = ary_player[j + 1];
ary_player[j + 1] = swap_temp;
}
}
}
}
}
//lưu mảng có NUM_HIGHT_SCORE phần tử vào file
ofstream wf("hight_score.txt", ios::out);
for (int i = 0; i < NUM_HIGHT_SCORE; i++)
{
if (ary_player[i].num_block > 0 && ary_player[i].mark >= 0 && ary_player[i].level > 0) {
if (ary_player[i].name == "") ary_player[i].name = "Player";
wf << ary_player[i].name << " ";
wf << ary_player[i].mark << " ";
wf << ary_player[i].level << " ";
wf << ary_player[i].num_block << " ";
//xử lý lưu kiểu double 1 số sau dấu phẩy cho time_play
string strtime = to_string(ary_player[i].time_play);
strtime = strtime.substr(0, strtime.find('.', 0) + 2);
wf << strtime << " ";
}
}
wf.close();
}
void LaunchPlay::Lost() {
Sound_Lost();
SDL_RenderClear(g_renderer);
g_D34_SDL2.Load_Image_BMP(g_renderer, "Lost_background.bmp", 0, 0, data::SCREEN_WIDTH, data::SCREEN_HEIGHT);
SDL_RenderPresent(g_renderer);
bool exit = false;
SDL_Event e;
while (!exit)
{
if (SDL_WaitEvent(&e)) {
if (e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_QUIT)
exit = true;
}
}
Mix_HaltMusic();
}
void LaunchPlay::Sound_Play() {
Mix_Chunk* sound_play = Mix_LoadWAV("music_play.wav");
if (sound_play == NULL)
{
printf("%s", Mix_GetError());
}
Mix_PlayChannel(-1, sound_play, -1);
}
void LaunchPlay::Sound_KeyBoard() {
Mix_Music* music = Mix_LoadMUS("music_keyboard2.mp3");
if (music == NULL)
{
printf("%s", Mix_GetError());
}
Mix_PlayMusic(music, 1);
}
void LaunchPlay::Sound_Lost() {
Mix_Music* music = Mix_LoadMUS("music_lost.mp3");
if (music == NULL)
{
printf("%s", Mix_GetError());
}
Mix_PlayMusic(music, 1);
}<file_sep>/Source Code/Tetris/Tetris/ReadMe.txt
Decription Game:
>màn hình menu
-nhấn New game để chơi game mới
-nhấn Hight score để xem xếp hạng
-nhấn Exit để thoát game
>màn hình Hight Score
-sắp xếp theo điểm số, nếu điểm số bằng nhau thì xếp theo số block, nếu số block bằng nhau thì xếp theo time play
-nhần exit để về menu
>màn hình play
-hiển thì số điểm cao nhất (Hightest) và thông tin người chơi (Mark, Level, Block, Time)
-nhấn Exit để về menu
Decription Code:
>D34_Button.h: tạo GUI button
>D34_SDL2.h: tối ưu các hàm của các thư viện sdl cho dễ dùng
>Data.h: lưu trữ các số liệu như width, height, board, cell,...
>LaunchHightScore.h: màn hình hight score
>LaunchHome.h: màn hình menu
>LaunchPlay.h: màn hình chơi
>ManageTetromino.h: xử lý các thao tác của tetromino
>Tetromino.h: chứa các dữ liệu tetromino<file_sep>/Source Code/Tetris/Tetris/ManageTetromino.cpp
#include "ManageTetromino.h"
#include "Tetromino.h"
#include "D34_SDL2.h"
#include <SDL_mixer.h>
using namespace d34;
ManageTetromino::ManageTetromino()
{
for (int x = 0; x < data::NUM_WIDTH; x++)
{
for (int y = 0; y < data::NUM_HEIGHT; y++)
{
data[x][y] = '0';
}
}
}
ManageTetromino::~ManageTetromino() {}
void ManageTetromino::Draw(SDL_Renderer* g_renderer, D34_SDL2& g_D34_SDL2) {
//draw bacground board
g_D34_SDL2.Load_Image_BMP(g_renderer, "Background_board_brick.bmp", board_x, board_y, board_w, board_h);
//draw block
for (int x = 0; x < data::NUM_WIDTH; x++)
{
for (int y = 0; y < data::NUM_HEIGHT; y++)
{
if (data[x][y] != '0') {
switch (data[x][y]) {
case 'I':
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_light_blue.bmp", data::BORDER + x * data::CELL_SIZE,data::BORDER + y * data::CELL_SIZE, data::CELL_SIZE, data::CELL_SIZE);
break;
case 'J':
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_orange.bmp", data::BORDER + x * data::CELL_SIZE, data::BORDER + y * data::CELL_SIZE, data::CELL_SIZE, data::CELL_SIZE);
break;
case 'L':
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_blue.bmp", data::BORDER + x * data::CELL_SIZE, data::BORDER + y * data::CELL_SIZE, data::CELL_SIZE, data::CELL_SIZE);
break;
case 'O':
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_yellow.bmp", data::BORDER + x * data::CELL_SIZE, data::BORDER + y * data::CELL_SIZE, data::CELL_SIZE, data::CELL_SIZE);
break;
case 'S':
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_green.bmp", data::BORDER + x * data::CELL_SIZE, data::BORDER + y * data::CELL_SIZE, data::CELL_SIZE, data::CELL_SIZE);
break;
case 'T':
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_purple.bmp", data::BORDER + x * data::CELL_SIZE, data::BORDER + y * data::CELL_SIZE, data::CELL_SIZE, data::CELL_SIZE);
break;
case 'Z':
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_red.bmp", data::BORDER + x * data::CELL_SIZE, data::BORDER + y * data::CELL_SIZE, data::CELL_SIZE, data::CELL_SIZE);
break;
}
//draw block
//SDL_SetRenderDrawColor(g_renderer, color.r, color.g, color.b, 255);
//SDL_Rect rec_outsize{
// x * data::CELL_SIZE + data::BORDER,
// y * data::CELL_SIZE + data::BORDER,
// data::CELL_SIZE,
// data::CELL_SIZE };
//SDL_RenderFillRect(g_renderer, &rec_outsize);
//SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 255);
//SDL_Rect rec_insize{
// x * data::CELL_SIZE + data::BORDER + data::BORDER_CELL,
// y * data::CELL_SIZE + data::BORDER + data::BORDER_CELL,
// data::CELL_SIZE - data::BORDER_CELL * 2,
// data::CELL_SIZE - data::BORDER_CELL * 2 };
//SDL_RenderFillRect(renderer, &rec_insize);
}
}
}
}
bool ManageTetromino::Is_Collision(Tetromino& t) {
for (int x = 0; x < 4; ++x)
for (int y = 0; y < 4; ++y)
if (t.Is_Block(x, y))
{
auto wx = t.X()+ x;
auto wy = t.Y() + y;
if (wx < 0 || wx >= data::NUM_WIDTH || wy < 0 || wy >= data::NUM_HEIGHT)
return true;
if (data[wx][wy]!='0')
return true;
}
return false;
}
void ManageTetromino::Unite(Tetromino& t)
{
for (int x = 0; x < 4; ++x)
for (int y = 0; y < 4; ++y)
if (t.Is_Block(x, y)) {
data[t.X() + x][t.Y() + y] = t.Get_Char_Type();
}
}
int ManageTetromino::Reward(){
int reward = 0;
for (int y = data::NUM_HEIGHT - 1; y >= 0; --y)
{
bool isReward = true;
//check hàng có đủ block để ăn hay không
for (int x = 0; x < data::NUM_WIDTH; ++x)
if (data[x][y]=='0')
{
isReward = false;
break;
}
if (isReward)
{
Sound_Reward();
//tăng điểm
reward += data::NUM_WIDTH;
//đẩy các block xuống sau khi ăn hàng block
for (int yy = y - 1; yy >= 0; --yy)
for (int x = 0; x < data::NUM_WIDTH; ++x)
data[x][yy + 1] = data[x][yy];
//sau khi đẩy thì cho các block trên cùng bằng '0'
for (int x = 0; x < data::NUM_WIDTH; ++x)
data[x][0] = '0';
//sau khi ăn thì reset lại y để set tiếp
y++;
}
}
return reward;
}
void ManageTetromino::Sound_Reward() {
Mix_Music* music = Mix_LoadMUS("music_reward.mp3");
if (music == NULL)
{
printf("%s", Mix_GetError());
}
Mix_PlayMusic(music, 1);
}<file_sep>/Source Code/Tetris/Tetris/D34_SDL2.h
#ifndef _D34_SDL2_H_
#define _D34_SDL2_H_
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
namespace d34 {
enum Font
{
FONT_TIMES_NEW_ROMAN = 0,
FONT_ROBUS,
FONT_GLUE_GUN,
FONT_STARCRAFT,
};
enum Color {
WHITE=0,
FIRE_BRICK,
RED,
YELLOW,
GOLD,
ORANGE,
BLUE,
DARK_BLUE,
DARK_ORCHID,
PURPLE,
STEEL_BLUE,
CORN_FLOWER_BLUE,
LAWN_GREEN,
GREEN,
};
class D34_SDL2
{
public:
//load mọi định dạng ảnh, giữ nguyên kích cỡ ảnh
SDL_Surface* Load_Image_SDL_Image(std::string file_path, const SDL_PixelFormat* fomat);
//load ảnh bmp giũ nguyên kích cỡ của ảnh
void Load_Image_BMP(SDL_Renderer* renderer, const std::string& file, int x, int y);
//load ảnh bmp co dãn theo w hà h
void Load_Image_BMP(SDL_Renderer* renderer, const std::string& file, int x, int y, int w, int h);
TTF_Font* Convert_Font_To_TTF_Font(Font font, int font_size);
//khi add color thì phải sửa hàm Convert_Color_To_SDL_Color_RGB(data::Color color)
SDL_Color Convert_Color_To_SDL_Color_RGB(Color color);
void D34_SetRenderDrawColor_RGB(SDL_Renderer*, Color);
//Trả về rect chứa text
SDL_Rect Load_Text(SDL_Renderer* renderer, const std::string& text, int rec_x, int rec_y, Font font, int font_size, Color color);
//chuyển đổi key sang kí tự
char Convert_Key_To_Char(SDL_Keycode key);
private:
// Hàm nạp texture từ file ảnh, để vẽ lên renderer tương ứng
SDL_Texture* Load_Image_BMP_To_Texture(const std::string& file, SDL_Renderer* ren);
void Free_Texture(SDL_Texture*);
void Free_TTF_Font(TTF_Font*);
void Free_Surface(SDL_Surface*);
};
}
#endif // !_D34_SDL2_H_<file_sep>/Source Code/Tetris/Tetris/LaunchHightScore.h
#ifndef _LAUNCH_HIGHT_SCORE_H_
#define _LAUNCH_HIGHT_SCORE_H_
#include <SDL.h>
#include "D34_SDL2.h"
#include "D34_Button.h"
#include "Data.h"
#include <vector>
using namespace d34;
using namespace data;
class LaunchHightScore
{
public:
LaunchHightScore(SDL_Renderer* _g_renderer, D34_SDL2& _g_D34_SDL2);
~LaunchHightScore();
void Run();
void Sound_Hight_Score();
private:
SDL_Renderer* g_renderer;
D34_SDL2 g_D34_SDL2;
Info_Player ary_player[NUM_HIGHT_SCORE];
d34_btn::D34_Button btn_exit;
};
#endif // !_LAUNCH_HIGHT_SCORE_H_
/*
rec_header
rec_rank
rec_name
rec_mark
rec_level
rec_block
rec_time
*/
<file_sep>/Source Code/Tetris/Tetris/D34_Button.cpp
#include "D34_Button.h"
#include <iostream>
#include <SDL.h>
#include <SDL_ttf.h>
#include <SDL_mixer.h>
using namespace d34_btn;
D34_Button::D34_Button() {
X(0);
Y(0);
Width(100);
Height(30);
Set_Color_Button(COLOR_GRAY);
Load_Context("Button", FONT_TIMES_NEW_ROMAN, 20, COLOR_BLACK, HORIZONTAL_CENTER, VERTICAL_CENTER);
context_ttf_font = NULL;
}
D34_Button::~D34_Button() {
}
TTF_Font* D34_Button::Convert_Font_To_TTF_Font(Font font, int font_size) {
if (font < 0 || font_size < 0) std::cout << "\nConvert Font in Button Error: ";
TTF_Font* ttf_font = nullptr;
string path_font = "";
switch (font) {
case FONT_TIMES_NEW_ROMAN:
path_font = "FONT_TIMES_NEW_ROMAN.ttf";
break;
case FONT_ROBUS:
path_font = "FONT_ROBUS.ttf";
break;
case FONT_GLUE_GUN:
path_font = "FONT_GLUE_GUN.ttf";
break;
case FONT_STARCRAFT:
path_font = "FONT_STARCRAFT.ttf";
break;
}
if (path_font == "") {
std::cout << "\nLoad font error";
}
else ttf_font = TTF_OpenFont(path_font.c_str(), font_size);
return ttf_font;
}
SDL_Color D34_Button::Convert_Color_To_SDL_Color(Color color) {
if (color < 0) std::cout << "\nConvert Color int Button Error: ";
SDL_Color sdl_color;
switch (color) {
case COLOR_RED:
sdl_color.r = 255;
sdl_color.g = 0;
sdl_color.b = 0;
sdl_color.a = 255;
break;
case COLOR_YELLOW:
sdl_color.r = 255;
sdl_color.g = 255;
sdl_color.b = 0;
sdl_color.a = 0;
break;
case COLOR_BLUE:
sdl_color.r = 51;
sdl_color.g = 102;
sdl_color.b = 255;
sdl_color.a = 0;
break;
case COLOR_GREEN:
sdl_color.r = 102;
sdl_color.g = 255;
sdl_color.b = 51;
sdl_color.a = 0;
break;
case COLOR_GRAY:
sdl_color.r = 194;
sdl_color.g = 194;
sdl_color.b = 163;
sdl_color.a = 255;
break;
case COLOR_BLACK:
sdl_color.r = 0;
sdl_color.g = 0;
sdl_color.b = 0;
sdl_color.a = 0;
break;
case COLOR_WHITE:
sdl_color.r = 255;
sdl_color.g = 255;
sdl_color.b = 255;
sdl_color.a = 0;
break;
}
return sdl_color;
}
void D34_Button::Convert_Context_Alignment() {
switch (context.horizontal) {
case HORIZONTAL_NULL:
break;
case HORIZONTAL_LEFT:
rec_context.x = rec_btn.x;
break;
case HORIZONTAL_CENTER:
rec_context.x = rec_btn.x + (rec_btn.w - rec_context.w) / 2;
break;
case HORIZONTAL_RIGHT:
rec_context.x = rec_btn.x + rec_btn.w - rec_context.w;
break;
}
switch (context.vertical) {
case VERTICAL_NULL:
break;
case VERTICAL_TOP:
rec_context.y = rec_btn.y;
break;
case VERTICAL_CENTER:
rec_context.y = rec_btn.y + (rec_btn.h - rec_context.h) / 2;
break;
case VERTICAL_BOTTOM:
rec_context.y = rec_btn.y + rec_btn.h - rec_context.h;
break;
}
}
//coordinate button
void D34_Button::X(int x) {
this->rec_btn.x = x;
}
int D34_Button::X() {
return rec_btn.x;
}
void D34_Button::Y(int y) {
this->rec_btn.y = y;
}
int D34_Button::Y() {
return rec_btn.y;
}
//dimension button
void D34_Button::Width(size_t w) {
this->rec_btn.w = w;
}
size_t D34_Button::Width() {
return rec_btn.w;
}
void D34_Button::Height(size_t h) {
this->rec_btn.h = h;
}
size_t D34_Button::Height() {
return rec_btn.h;
}
bool D34_Button::IS_Mouse_In_Button(int mouse_x, int mouse_y ) {
if (mouse_x >= rec_btn.x && mouse_x <= rec_btn.x + rec_btn.w
&& mouse_y >= rec_btn.y && mouse_y <= rec_btn.y + rec_btn.h) return true;
else return false;
}
void D34_Button::Animation(SDL_Renderer* renderer, int mouse_x, int mouse_y, Color text_color_before, Color text_color_after) {
if (this->IS_Mouse_In_Button(mouse_x,mouse_y))
this->Load_Context(d34_btn::COLOR_RED);
else
this->Load_Context(d34_btn::COLOR_WHITE);
}
void D34_Button::Sound_Click() {
Mix_Music* music = Mix_LoadMUS("music_button_click.mp3");
if (music == NULL)
{
printf("%s", Mix_GetError());
}
Mix_PlayMusic(music, 1);
}
void D34_Button::Set_Color_Button(Color color) {
btn_color = color;
}
/// <summary>
/// LOAD_CONTEXT
/// </summary>
/// <param name="text"></param>
/// <param name="font"></param>
/// <param name="font_size"></param>
/// <param name="color"></param>
/// <param name="hor"></param>
/// <param name="ver"></param>
void D34_Button::Load_Context(
string text,
Font font,
int font_size,
Color color,
Horizontal hor,
Vertical ver) {
context.text = text;
context.font = font;
Convert_Font_To_TTF_Font(font, font_size);
context.size = font_size;
context.color = color;
context.horizontal = hor;
context.vertical = ver;
}
void D34_Button::Load_Context(
string text,
Font font,
int font_size,
Color color,
int padding_left,
int padding_top
) {
context.text = text;
context.font = font;
Convert_Font_To_TTF_Font(font, font_size);
context.size = font_size;
context.color = color;
rec_context.x = padding_left + rec_btn.x;
rec_context.y = padding_top + rec_btn.y;
}
void D34_Button::Load_Context(const char* text) {
context.text = text;
}
void D34_Button::Load_Context(Font font, int font_size) {
context.font = font;
context.size = font_size;
Convert_Font_To_TTF_Font(font, font_size);
}
void D34_Button::Load_Context(Horizontal hor, Vertical ver){
context.horizontal = hor;
context.vertical = ver;
}
void D34_Button::Load_Context(int padding_left, int padding_top) {
rec_context.x = rec_btn.x + padding_left;
rec_context.y = rec_btn.y + padding_top;
}
void D34_Button::Load_Context(Color color) {
context.color = color;
}
void D34_Button::Load_Button(SDL_Renderer* renderer) {
//draw button
SDL_Color sdl_btn_color = Convert_Color_To_SDL_Color(btn_color);
SDL_SetRenderDrawColor(renderer, sdl_btn_color.r, sdl_btn_color.g, sdl_btn_color.b, sdl_btn_color.a);
SDL_RenderFillRect(renderer, &rec_btn);
//draw context
//convert font, text, color
Free_TTF_Font(context_ttf_font);
context_ttf_font = Convert_Font_To_TTF_Font(context.font, context.size);
SDL_Color sdl_context_color = Convert_Color_To_SDL_Color(context.color);
SDL_SetRenderDrawColor(renderer, sdl_context_color.r, sdl_context_color.g, sdl_context_color.b, sdl_context_color.a);
if (context.text == "") context.text = "Button";
SDL_Surface* surface = TTF_RenderText_Blended(context_ttf_font, context.text.c_str(), sdl_context_color);
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
rec_context.w = surface->w;
rec_context.h = surface->h;
Free_Surface(surface);
//convert horizontal, vertical
Convert_Context_Alignment();
SDL_RenderCopy(renderer, texture, NULL, &rec_context);
//std::cout << "\nLoaded a button, text: " << context.text;
Free_Texture(texture);
}
void D34_Button::Free_Texture(SDL_Texture* texture) {
if (texture != NULL) {
SDL_DestroyTexture(texture);
texture = NULL;
}
}
void D34_Button::Free_TTF_Font(TTF_Font* ttf_font) {
if (ttf_font != NULL) {
TTF_CloseFont(ttf_font);
ttf_font = NULL;
}
}
void D34_Button::Free_Surface(SDL_Surface* surface) {
if (surface != NULL) {
SDL_FreeSurface(surface);
surface = NULL;
}
}<file_sep>/Source Code/Tetris/Tetris/LaunchPlay.h
#ifndef _LAUNCH_PLAY_H_
#define _LAUNCH_PLAY_H_
#include <SDL.h>
#include "ManageTetromino.h"
#include "Tetromino.h"
#include "Data.h"
#include "D34_SDL2.h"
#include "D34_Button.h"
#include <cstdlib>
#include <ctime>
#include <SDL_mixer.h>
using namespace d34;
using namespace data;
class LaunchPlay
{
public:
LaunchPlay(SDL_Renderer* _g_renderer, D34_SDL2& _D34_SDL2);
~LaunchPlay();
bool Enter_Name();
bool Run();
void Save_Info_Player();
void Lost();
void Sound_Play();
void Sound_KeyBoard();
void Sound_Lost();
private:
SDL_Renderer* g_renderer;
D34_SDL2 g_D34_SDL2;
ManageTetromino manage_;
Tetromino tetromino_;
clock_t time_start;
int hight_mark;
double speed;
Info_Player player;
//Button
d34_btn::D34_Button btn_exit;
};
#endif // !_LAUNCH_PLAY_H_<file_sep>/Source Code/Tetris/Tetris/Tetromino.cpp
#include "Tetromino.h"
#include "ManageTetromino.h"
Tetromino::Tetromino(Type type) {
type_ = type;
x_ = 6;
y_ = 0;
angle_ = 0;
}
Tetromino::~Tetromino() {}
void Tetromino::Draw(SDL_Renderer* g_renderer,D34_SDL2& g_D34_SDL2)
{
for (auto x = 0; x < 4; ++x)
for (auto y = 0; y < 4; ++y)
if (Is_Block(x, y))
{
switch (type_) {
case I:
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_light_blue.bmp", (x + x_) * data::CELL_SIZE + data::BORDER,(y + y_) * data::CELL_SIZE + data::BORDER, data::CELL_SIZE, data::CELL_SIZE);
break;
case J:
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_orange.bmp", (x + x_) * data::CELL_SIZE + data::BORDER, (y + y_) * data::CELL_SIZE + data::BORDER, data::CELL_SIZE, data::CELL_SIZE);
break;
case L:
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_blue.bmp", (x + x_) * data::CELL_SIZE + data::BORDER, (y + y_) * data::CELL_SIZE + data::BORDER, data::CELL_SIZE, data::CELL_SIZE);
break;
case O:
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_yellow.bmp", (x + x_) * data::CELL_SIZE + data::BORDER, (y + y_) * data::CELL_SIZE + data::BORDER, data::CELL_SIZE, data::CELL_SIZE);
break;
case S:
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_green.bmp", (x + x_) * data::CELL_SIZE + data::BORDER, (y + y_) * data::CELL_SIZE + data::BORDER, data::CELL_SIZE, data::CELL_SIZE);
break;
case T:
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_purple.bmp", (x + x_) * data::CELL_SIZE + data::BORDER, (y + y_) * data::CELL_SIZE + data::BORDER, data::CELL_SIZE, data::CELL_SIZE);
break;
case Z:
g_D34_SDL2.Load_Image_BMP(g_renderer, "Block_red.bmp", (x + x_) * data::CELL_SIZE + data::BORDER, (y + y_) * data::CELL_SIZE + data::BORDER, data::CELL_SIZE, data::CELL_SIZE);
break;
}
/*SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 0);
SDL_Rect rec_outsize{
(x + x_) * data::CELL_SIZE + data::BORDER,
(y + y_) * data::CELL_SIZE + data::BORDER,
data::CELL_SIZE,
data::CELL_SIZE };
SDL_RenderFillRect(renderer, &rec_outsize);*/
//SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 255);
//SDL_Rect rec_insize{
// (x+x_) * data::CELL_SIZE + data::BORDER + data::BORDER_CELL,
// (y+y_) * data::CELL_SIZE + data::BORDER + data::BORDER_CELL,
// data::CELL_SIZE - data::BORDER_CELL * 2,
// data::CELL_SIZE - data::BORDER_CELL * 2 };
//SDL_RenderFillRect(renderer, &rec_insize);
}
}
void Tetromino::Move(int add_x_, int add_y_) {
x_ += add_x_;
y_ += add_y_;
}
void Tetromino::Rotate()
{
angle_ += 3;
angle_ %= 4;
}
bool Tetromino::Is_Block(int x, int y)
{
return Shapes[type_][angle_][x + y * 4] == '.';
}
int Tetromino::X()
{
return x_;
}
int Tetromino::Y()
{
return y_;
}
char Tetromino::Get_Char_Type() {
if (type_ == I) return 'I';
if (type_ == J) return 'J';
if (type_ == L) return 'L';
if (type_ == O) return 'O';
if (type_ == S) return 'S';
if (type_ == T) return 'T';
if (type_ == Z) return 'Z';
}
| 4855e65d32932f85fe10fcd93d32d094181be3c3 | [
"Text",
"C++"
] | 17 | C++ | 388664/TetrisCplusplus | bdfa76dd5eb233fedae98151cbea2a1932379909 | 001223e0cb0c0930c96d05a63a3104f928a92bc4 |
refs/heads/master | <repo_name>rahasyac/WebServer<file_sep>/WebServer.java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
/**
* CSE 4344
* Lab # 1 Web Server Programming
* Spring 2019
* Name: <NAME>
*
* Description:
* The program implements the multi-thread Web Server
* This server listens the TCP connections and serves
* the connection parallel
* Each connection will be handled in one thread.
*
* The web server support the image resource too
*
* The web server implements:
* Protocol: HTTP 1.0
* Response GET method
* Response 200, 301, 404 code
*
*/
public final class WebServer extends Thread
{
private static final int PORT = 8081; //default port
private int serverPort; //server port
// constructor @param port server port
public WebServer(int port){
this.serverPort = port;
}
private ServerSocket socket; // server socket
/**
* main method to start web server
* @param argv argv[0] is server port
* otherwise, default port will be used
*/
public static void main(String argv[]) throws Exception
{
//server port
int serverPort = PORT;
//check argument
if (argv.length == 1){
try{
serverPort = Integer.parseInt(argv[0]);
}catch(Exception e){
System.out.println("The provided port is not valid. Use default port: " + PORT);
}
}else if (argv.length > 1){
System.out.println("Too many the arguments. Use default port: " + PORT);
}
//start the main thread
(new WebServer(serverPort)).start();
System.out.println("The web server is running on port " + serverPort);
}
/**
* this method is called by start method
* run the server in main thread
* This method will create many threads
* each thread serves for one connection
* after thread created, this method continues listen the new one
*/
public void run() {
try {
socket = new ServerSocket(serverPort);
} catch (Exception e) {
System.err.println("Error binding to port " + serverPort + ": " + e);
}
//Process HTTP service requests in an infinite loop.
while (true) {
try {
// wait and listen for new client connection
Socket clientSocket = socket.accept();
// construct an object to process the HTTP request message.
HttpRequest request = new HttpRequest(clientSocket);
// start the thread.
(new Thread(request)).start();
} catch (Exception e) {
//ignore
break;
}
}
}
}
/**
* The HttpRequest class is created by the WebServer that
* serves for one client connection
*
*/
final class HttpRequest implements Runnable
{
/**
* new line character that is used in HTTP protocol
*/
final static String CRLF = "\r\n";
/**
* TCP client socket
*/
private Socket socket;
/**
* Constructor
* @param socket client socket
*/
public HttpRequest(Socket socket)
{
this.socket = socket;
}
/**
* Implement the run() method of the Runnable interface.
* This method is called by start method
*
*/
public void run()
{
//process the user request
try {
processRequest();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
/**
* process the user request
* It extracts the file name from the HTTP request
* then validate and process it (by reading file)
* This method handles the response with 200, 301, 404 code
* @throws Exception if error
*/
private void processRequest() throws Exception
{
// Get a reference to the socket's input and output streams.
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
// Set up input stream filters.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Get the request line of the HTTP request message.
String requestLine = br.readLine();
// Display the request line.
System.out.println();
System.out.println(requestLine);
// Get and display the header lines.
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
// Extract the filename from the request line.
StringTokenizer tokens = new StringTokenizer(requestLine);
String method = tokens.nextToken(); // "GET" or "POST" or others
// requested file input stream
FileInputStream fis = null;
boolean fileExists = true; //request file existing?
// Construct the response message.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (method.equals("GET")){ //get method
String fileName = tokens.nextToken();
// Prepend a "." so that file request is within the current directory.
fileName = "." + fileName;
// Open the requested file
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
//file exists, code is 200
if (fileExists) {
statusLine = "HTTP/1.1 200 OK" + CRLF;
contentTypeLine = "Content-type: " +
contentType( fileName ) + CRLF;
} else { //resource not found, code is 404
statusLine = "HTTP/1.1 404 Not Found" + CRLF;
contentTypeLine = "Content-type: text/html" + CRLF;
entityBody = "<HTML>" +
"<HEAD><TITLE>Not Found</TITLE></HEAD>" +
"<BODY>Not Found</BODY></HTML>";
}
}else{//post or other method ?
statusLine = "HTTP/1.1 303 See Other" + CRLF;
contentTypeLine = "Content-type: text/html" + CRLF;
entityBody = "<HTML>" +
"<HEAD><TITLE>See Other</TITLE></HEAD>" +
"<BODY>See Other</BODY></HTML>";
fileExists = false; //request file not existing
}
// Send the status line.
os.writeBytes(statusLine);
// Send the content type line.
os.writeBytes(contentTypeLine);
// Send a blank line to indicate the end of the header lines.
os.writeBytes(CRLF);
// Send the entity body.
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes(entityBody);
}
// Close streams and socket.
os.close();
br.close();
socket.close();
}
/**
* read from input stream and
* send bytes to output stream
* until end of file
*
* @param fis input stream
* @param os output stream
* @throws Exception if read or write error
*/
private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception
{
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while((bytes = fis.read(buffer)) != -1 ) {
os.write(buffer, 0, bytes);
}
}
/**
* write the content based on the file name extension
* @param fileName file name
* @return content type
*/
private static String contentType(String fileName)
{
//htm or html
if(fileName.endsWith(".htm") || fileName.endsWith(".html")){
return "text/html";
}
//gif image
if(fileName.endsWith(".gif")) {
return "image/gif";
}
//jpeg image
if(fileName.endsWith(".jpeg")) {
return "image/jpeg";
}
return "application/octet-stream";
}
}
/**
* Refrences
*https://medium.com/@ssaurel/create-a-simple-http-web-server-in-java-3fc12b29d5fd
*https://realpython.com/python-sockets/
* instruction to use wireshark: http://www.cs.wayne.edu/fengwei/17sp-csc4992/labs/lab1-Instruction.pdf
*/
| 7fab283aba0867e9a5fbd9701e6f7303cbda173a | [
"Java"
] | 1 | Java | rahasyac/WebServer | 8cb6846bf9dc57783a4aabca7f4257dc40831d88 | 1de7e8099be3709ead3639aabca0064af6c792f9 |
refs/heads/main | <file_sep>import sys
OFFSET = 0x1E8
def main():
if len(sys.argv) != 4:
print(f'Usage: {sys.argv[0]} <base> <add> <out>')
return -1
base_filename = sys.argv[1]
add_filename = sys.argv[2]
out_filename = sys.argv[3]
with open(base_filename, 'rb') as f:
base_data = f.read()
with open(add_filename, 'rb') as f:
add_data = f.read()
tmp = list(base_data)
for i in range(len(add_data)):
tmp[i + OFFSET] = add_data[i]
with open(out_filename, 'wb') as f:
f.write(bytes(tmp))
return 0
if __name__ == '__main__':
main()
<file_sep>CC := clang
OBJCOPY := llvm-objcopy
SRC_DIR := ./src
INC_DIR := ./inc
FLAGS := -O2 -nostdlib -mthumb --target=armv6-none-eabi -I $(INC_DIR)
OUTPUT_DIR := ./output
OUTPUT_FILE := music
BIN_OUT_FILE := music.bin
WELD_OUT_FILE := music.weld
UF2_OUT_FILE := music.uf2
convert: weld
python3 scripts/uf2conv.py $(OUTPUT_DIR)/$(WELD_OUT_FILE) -o $(OUTPUT_DIR)/$(UF2_OUT_FILE)
weld: build
python3 scripts/weld.py resources/flash.bin $(OUTPUT_DIR)/$(BIN_OUT_FILE) $(OUTPUT_DIR)/$(WELD_OUT_FILE)
build: setup
$(CC) $(FLAGS) $(SRC_DIR)/* -o $(OUTPUT_DIR)/$(OUTPUT_FILE)
$(OBJCOPY) --dump-section .text=$(OUTPUT_DIR)/$(BIN_OUT_FILE) $(OUTPUT_DIR)/$(OUTPUT_FILE)
setup:
mkdir -p $(OUTPUT_DIR)
clean:
rm -rf $(OUTPUT_DIR)<file_sep>#include "music.h"
// everything needs to be position independent here
// so that means
// 1. no functions aside from main
// 2. no data accesses
// we also don't want to overwrite anything important, so:
// 3. no static variables
__attribute__((always_inline)) static void buzz(int delay /* don't actually know what this is but i think it's some timer delay thing */) {
unsigned *buzzer = (unsigned*)DATA_BUZZER;
FUNC_SETUP_TIMER(*buzzer);
FUNC_TRIGGER_TIMER(buzzer, 0, delay);
}
__attribute__((always_inline)) static void update_led(int led, uint8_t *col) {
FUNC_UPDATE_LED(led, col);
}
__attribute__((always_inline)) static void play_song(int * song, int song_len)
{
uint8_t colors[4][3] = {{0}};
int spin[4] = {0};
colors[0][0] = 255;
colors[0][1] = 255;
colors[0][2] = 0;
colors[1][0] = 0;
colors[1][1] = 255;
colors[1][2] = 255;
colors[2][0] = 255;
colors[2][1] = 0;
colors[2][2] = 255;
colors[3][0] = 255;
colors[3][1] = 255;
colors[3][2] = 255;
spin[0] = 1;
spin[1] = 2;
spin[2] = 3;
spin[3] = 0;
for (int seq = 0; seq < song_len; ++seq)
{
uint8_t oldcolors[4][3];
for (int i = 0; i < 4; ++i)
{
oldcolors[i][0] = colors[i][0];
oldcolors[i][1] = colors[i][1];
oldcolors[i][2] = colors[i][2];
update_led(i + 1, colors[i]);
}
for (int i = 0; i < 4; ++i)
{
colors[i][0] = oldcolors[spin[i]][0];
colors[i][1] = oldcolors[spin[i]][1];
colors[i][2] = oldcolors[spin[i]][2];
}
buzz(song[seq]);
for (volatile int i = 0; i < 230000; ++i);
}
}
int _start(void)
{
int sandstorm[200];
int soviet[200];
int starwars[250];
// this only really works for a very limited set of frequencies
int magic = 400000;
int c5 = magic / 523;
int d5 = magic / 587;
int e5 = magic / 659;
int f5 = magic / 698;
int g5 = magic / 784;
int a5 = magic / 880;
int asharp5 = magic / 932;
int b5 = magic / 988;
int c6 = magic / 1047;
int d6 = magic / 1174;
int e6 = magic / 1318;
int f6 = magic / 1396;
int g6 = magic / 1568;
int len_starwars = 0;
starwars[len_starwars++] = c5;
starwars[len_starwars++] = c5;
starwars[len_starwars++] = c5;
starwars[len_starwars++] = c5;
starwars[len_starwars++] = c5;
starwars[len_starwars++] = c5;
starwars[len_starwars++] = c5;
starwars[len_starwars++] = c5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = f5;
starwars[len_starwars++] = f5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = e5;
starwars[len_starwars++] = e5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = d5;
starwars[len_starwars++] = d5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = f5;
starwars[len_starwars++] = f5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = e5;
starwars[len_starwars++] = e5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = d5;
starwars[len_starwars++] = d5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = c6;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = g5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = f5;
starwars[len_starwars++] = f5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = e5;
starwars[len_starwars++] = e5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = f5;
starwars[len_starwars++] = f5;
starwars[len_starwars++] = 0;
starwars[len_starwars++] = d5;
starwars[len_starwars++] = d5;
starwars[len_starwars++] = d5;
starwars[len_starwars++] = d5;
starwars[len_starwars++] = 0;
// lord have mercy on my soul
int len_soviet = 0;
soviet[len_soviet++] = c6;
soviet[len_soviet++] = c6;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = f6;
soviet[len_soviet++] = f6;
soviet[len_soviet++] = f6;
soviet[len_soviet++] = f6;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = c6;
soviet[len_soviet++] = c6;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = d6;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = e6;
soviet[len_soviet++] = e6;
soviet[len_soviet++] = e6;
soviet[len_soviet++] = e6;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = a5;
soviet[len_soviet++] = a5;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = a5;
soviet[len_soviet++] = a5;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = d6;
soviet[len_soviet++] = d6;
soviet[len_soviet++] = d6;
soviet[len_soviet++] = d6;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = c6;
soviet[len_soviet++] = c6;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = asharp5;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = c6;
soviet[len_soviet++] = c6;
soviet[len_soviet++] = c6;
soviet[len_soviet++] = c6;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = f5;
soviet[len_soviet++] = f5;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = f5;
soviet[len_soviet++] = f5;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = g5;
soviet[len_soviet++] = g5;
soviet[len_soviet++] = g5;
soviet[len_soviet++] = g5;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = g5;
soviet[len_soviet++] = g5;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = a5;
soviet[len_soviet++] = a5;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = b5;
soviet[len_soviet++] = b5;
soviet[len_soviet++] = b5;
soviet[len_soviet++] = b5;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = b5;
soviet[len_soviet++] = b5;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = c6;
soviet[len_soviet++] = c6;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = d6;
soviet[len_soviet++] = d6;
soviet[len_soviet++] = d6;
soviet[len_soviet++] = d6;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = e6;
soviet[len_soviet++] = e6;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = f6;
soviet[len_soviet++] = f6;
soviet[len_soviet++] = 0;
soviet[len_soviet++] = g6;
soviet[len_soviet++] = g6;
soviet[len_soviet++] = g6;
soviet[len_soviet++] = g6;
soviet[len_soviet++] = 0;
int len_sandstorm = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = d6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = d6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = d6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = d6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = d6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = d6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = d6;
sandstorm[len_sandstorm++] = d6;
sandstorm[len_sandstorm++] = d6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = a5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = a5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = b5;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = 0;
sandstorm[len_sandstorm++] = e6;
sandstorm[len_sandstorm++] = 0;
while (1)
{
volatile unsigned down = *(volatile unsigned*)GPIO_PINS;
if ((down & KEY1) == 0)
{
play_song(sandstorm, len_sandstorm);
}
else if ((down & KEY3) == 0)
{
play_song(soviet, len_soviet);
}
}
}
<file_sep># DC29 Badge Stuff
## What's in the repo
+ Funny music code
+ Firmware used (in case of updates)
## Dumping/flashing the firmware
+ To access firmware: hold down bottom right button when plugging into USB - a drive with a UF2 file should appear
+ Use [uf2conv](https://github.com/microsoft/uf2/blob/master/utils/uf2conv.py) (also needs [this](https://github.com/microsoft/uf2/blob/master/utils/uf2families.json) json file in the same folder)
+ `python3 uf2conv.py DC29Human3.UF2` -> dump firmware
+ `python3 uf2conv.py flash.bin -o NEW.UF2` -> create new firmware
+ To reflash firmware: drag your new UF2 file back into the drive and it should automatically reboot
## Compiling
+ Run `make` to compile. Output file is in output/music.uf2
+ If you are on MacOS: use homebrew to install a full clang build (`brew install llvm`) as lld isn't a thing on the default clang for some fucking reason
+ If you are on linux - make sure lld is installed (`sudo apt install lld`)
## Usage
+ Run `make`
+ Reflash `output/music.uf2` over to the device
+ Press buttons and have fun!
<file_sep>#pragma once
#include <stdint.h>
#define BASE_ADDRESS 0x2000
#define REBASE(x) ((x) + (BASE_ADDRESS))
// thanks arm
#define THUMB(x) ((x) + 1)
// don't know what exactly these do but they seem to set up some sort of timer connected to the buzzer
#define FUNC_SETUP_TIMER ((void(*)(unsigned))THUMB(REBASE(0x99E6)))
#define FUNC_TRIGGER_TIMER ((void(*)(unsigned*, int, int))THUMB(REBASE(0x44C0)))
// this one just updates an LED with a one-based index and a byte array with [R, G, B]
#define FUNC_UPDATE_LED ((void(*)(int, uint8_t*))THUMB(REBASE(0x5114)))
// structure relevant to buzzer
#define DATA_BUZZER 0x20000E54
// gpio pins - same for most SAMD21 microcontrollers
#define GPIO_PINS 0x41004420
// keys on the badge
#define KEY1 0x10
#define KEY2 0x20
#define KEY3 0x40
#define KEY4 0x80
| 77dd86a4d171caec840b782fc5c0f577abece6d1 | [
"Markdown",
"C",
"Python",
"Makefile"
] | 5 | Python | Monstriu/music-on-dc29-badge | 35fc7c6c569fdde4cb1a143d3be33b6c689805d0 | 5d41eabce3043fcb93e78512555fbe063f60355d |
refs/heads/master | <repo_name>reikabow/cucumber-client<file_sep>/src/auth/Auth.js
import auth0 from 'auth0-js';
import history from '../history'
import authVariables from './authVariables'
class Auth {
auth0 = new auth0.WebAuth(authVariables);
userProfile;
login = () => {
this.auth0.authorize();
};
logout = () => {
// Clear access token and ID token from local storage
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
localStorage.removeItem('expires_at');
// navigate to the home route
history.replace('/');
};
getAccessToken = () => {
const accessToken = localStorage.getItem('access_token');
if (!accessToken) {
throw new Error('No access token found');
}
return accessToken;
};
getIdToken = () => {
const idToken = localStorage.getItem('id_token');
if (!idToken) {
throw new Error('No id token found');
}
return idToken;
}
getProfile = () => {
const accessToken = this.getAccessToken();
return new Promise((resolve, reject) => {
this.auth0.client.userInfo(accessToken, (err, profile) => {
if (profile)
resolve(profile);
else
reject();
});
});
};
isAuthenticated = () => {
// Check whether the current time is past the
// access token's expiry time
let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
return new Date().getTime() < expiresAt;
};
handleAuthentication = () => {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
history.replace('/');
} else if (err) {
history.replace('/');
console.log(err);
}
});
};
setSession = (authResult) => {
// Set the time that the access token will expire at
let expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
localStorage.setItem('access_token', authResult.accessToken);
localStorage.setItem('id_token', authResult.idToken);
localStorage.setItem('expires_at', expiresAt);
// navigate to the home route
history.replace('/');
};
}
const auth = new Auth();
export default auth;
<file_sep>/src/components/ItemView.js
// @flow
import React from 'react';
import Button from 'material-ui/Button';
import Paper from 'material-ui/Paper';
import type { Transaction } from '../lib/api';
type Props = {
transaction: Transaction,
deleteItem: (id: number) => void,
editItem: (id: number) => void
};
const Item = (props: Props) => {
const { transaction, deleteItem, editItem } = props;
const { id, category_id, price, quantity, units, notes } = transaction;
return (
<Paper>
Category: { category_id }, Price: ${ price }, Quantity: { quantity } { units }, Notes: { notes }
<Button onClick={ () => { deleteItem(id) } }>Delete</Button>
<Button onClick={ () => { editItem(id) } }>Edit</Button>
</Paper>
);
}
export default Item;
<file_sep>/src/components/EditItem.js
// @flow
import React, { Component } from 'react';
import Button from 'material-ui/Button'
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
import type { Transaction } from '../lib/api';
type Props = {
transaction: Transaction,
saveItem: (id: number, transaction: Transaction) => Promise<>, // To satisfy linter
deleteItem: (id: number) => void
};
type State = {
transaction: Transaction,
errors: Array<string>
};
class EditItem extends Component<Props, State> {
state = {
transaction: this.props.transaction,
errors: []
}
isValid = (): boolean => {
const { price, quantity } = this.state.transaction;
const errors: Array<string> = [];
if (!price || isNaN(price))
errors.push('Price should be a number');
if (!quantity || isNaN(quantity))
errors.push('Quantity should be a number');
if (errors.length) {
this.setState({ errors });
return false;
} else {
return true;
}
}
attemptSave = (id: number) => {
if (this.isValid())
this.props.saveItem(id, this.state.transaction);
}
onCategoryStringChange = (e: SyntheticInputEvent<>) => {
const { transaction } = this.state;
const { target: { value } } = e;
this.setState({ transaction: Object.assign(transaction, { categoryString: value }) });
}
onPriceChange = (e: SyntheticInputEvent<>) => {
const { transaction } = this.state;
const { target: { value } } = e;
this.setState({ transaction: Object.assign(transaction, { price: value }) });
}
onNotesChange = (e: SyntheticInputEvent<>) => {
const { transaction } = this.state;
const { target: { value } } = e;
this.setState({ transaction: Object.assign(transaction, { notes: value }) });
}
onQuantityChange = (e: SyntheticInputEvent<>) => {
const { transaction } = this.state;
const { target: { value } } = e;
this.setState({ transaction: Object.assign(transaction, { quantity: value }) });
}
onUnitsChange = (e: SyntheticInputEvent<>) => {
const { transaction } = this.state;
const { target: { value } } = e;
this.setState({ transaction: Object.assign(transaction, { units: value }) });
}
render() {
const { categoryString, price, notes, quantity, units } = this.state.transaction;
return (
<Paper>
<div id="errors">
{ this.state.errors.join(', ') }
</div>
<div id="fields">
<TextField
className="tf"
onChange={ this.onCategoryStringChange }
label="Category"
value={ categoryString }
/>
<TextField
onChange={ this.onPriceChange }
className="tf"
label="Price"
value={ price }
/>
<TextField
onChange={ this.onNotesChange }
className="tf"
label="Notes"
value={ notes }
/>
<TextField
onChange={ this.onQuantityChange }
className="tf"
label="Quantity"
value={ quantity }
/>
<TextField
onChange={ this.onUnitsChange }
className="tf"
label="Units"
value={ units }
/>
<br/>
<Button
className="button"
onClick={ () => this.attemptSave(this.props.transaction.id) }
>
Save
</Button>
<Button
className="button"
onClick={ () => this.props.deleteItem(this.props.transaction.id) }
>
Delete
</Button>
</div>
</Paper>
);
}
}
export default EditItem;
<file_sep>/src/lib/tree.js
// Rows is a list of node objects with an id, name, and parent id
export function buildTree(categories) {
let rows = categories.map(({ id, name }) => ({ id, name }))
let root = rows.find(e => e.name === 'ROOT');
if (!root) {
throw new Error("bad tree: no root");
}
// Appends all children of node id to a list in node id called children
const helper = (node) => {
let children = categories.filter(e => e.parent_id === node.id).map(({ id, name }) => ({ id, name }));
if (!children.length) {
return;
}
node.children = children;
for (let ch of node.children) {
helper(ch);
}
}
helper(root);
return root;
}
<file_sep>/src/routes.js
import React from 'react';
import { Route, BrowserRouter } from 'react-router-dom';
import App from './pages/App';
import Callback from './pages/Callback';
import Cart from './pages/Cart';
import Profile from './pages/Profile';
import AppBar from './components/AppBar';
import auth from './auth/Auth';
import history from './history';
const handleAuthentication = (nextState, replace) => {
if (/access_token|id_token|error/.test(nextState.location.hash)) {
auth.handleAuthentication();
}
};
export const makeMainRoutes = () => {
return (
<BrowserRouter history={ history }>
<div>
<AppBar auth={ auth }/>
<Route exact path="/" render={ (props) =>
<App auth={ auth } {...props}/>
}/>
<Route path="/callback" render={ (props) => {
handleAuthentication(props);
return <Callback {...props} />;
} }/>
<Route path="/cart" render={ (props) =>
<Cart auth={ auth } {...props}/>
}/>
<Route path="/profile" render={ (props) =>
<Profile auth={ auth } {...props}/>
}/>
</div>
</BrowserRouter>
);
}
<file_sep>/src/pages/Cart.js
// @flow
import React, { Component } from 'react';
import Button from 'material-ui/Button';
import Item from '../components/Item';
import findIndex from 'lodash/findIndex';
import { newTransaction, getRoot, addTransactions } from '../lib/api';
import { buildTree } from '../lib/tree';
import type { Transaction } from '../lib/api';
import type { Category } from '../lib/api';
type Props = {};
type State = {
items: Array<Transaction>,
nextId: number,
editActive: boolean,
editId: ?number,
categories: Array<Category>,
categoryTree: null
}
class Cart extends Component<Props, State> {
state = {
items: [],
nextId: 0,
editActive: false,
editId: null,
categories: [],
newCategories: [],
categoryTree: null
}
//
// UTILITIES
//
// Get the index of a cart item
getIndex = (id: number): number => {
const index = findIndex(this.state.items, item => item.id === id);
return index;
}
//
// CART HANDLERS
//
// Add an item to the cart
addItem = (): void => {
const { items, nextId } = this.state;
const newItems: Array<Transaction> = [...items, newTransaction(nextId)];
this.setState({
items: newItems,
editActive: true,
editId: nextId,
nextId: nextId + 1
});
}
// Delete a cart item
deleteItem = (id : number): void => {
const { items, editId, editActive } = this.state;
const index = this.getIndex(id);
const newItems: Array<Transaction> = [...items.slice(0, index), ...items.slice(index + 1)];
if (editActive && editId === id) { // The editing window is being deleted
this.setState({
items: newItems,
editActive: false,
editId: null
});
} else {
this.setState({
items: newItems
});
}
}
// Activate the edit window on a cart item
editItem = (id: number): void => {
this.setState({
editId: id,
editActive: true
});
}
// Close the edit window on a cart item, saving the changes
saveItem = async (id: number, item: Transaction) => {
// TODO: Add category to transaction derived from categoryString
const category = await getRoot();
const category_id = category.id;
const { items } = this.state;
const index = this.getIndex(id);
const newItems = [...items.slice(0, index), Object.assign(item, { category_id, id }), ...items.slice(index + 1)];
this.setState({
items: newItems,
editId: null,
editActive: false
});
}
// Clear the cart
clear = (): void => {
this.setState({
items: [],
nextId: 0,
editActive: false,
editId: null
});
}
// Submit the contents of the cart to the server
handleSubmit = async () => {
try {
addTransactions(this.state.items);
this.clear();
} catch (err) {
// TODO: Handle errors better
alert(`Submission error: ${err.message}`);
}
}
//
// REACT
//
// https://github.com/facebook/flow/issues/1803
async _componentDidMount() {
const { getIdToken } = this.props.auth;
const response: Response = await fetch('/api/categories', { headers: {'Authorization': `Bearer ${getIdToken()}`} });
const categories: Array<Category> = await response.json();
this.setState({ categories });
this.setState({ categoryTree: buildTree(categories) })
}
componentDidMount() {
this._componentDidMount();
}
render() {
const { items, editActive } = this.state;
return (
<div id="Cart">
{ items.length > 0 &&
items.map(item =>
<Item
key={ item.id }
editActive={ this.state.editId === item.id }
deleteItem={ this.deleteItem }
editItem={ this.editItem }
saveItem={ this.saveItem }
transaction={ item }
/>
) }
{ !editActive &&
<Button onClick={ this.addItem }>Add item</Button> }
{ items.length > 0 && !editActive &&
<Button onClick={ this.handleSubmit }>Submit</Button> }
</div>
);
}
}
export default Cart;
<file_sep>/src/lib/tree.spec.js
import { buildTree } from './tree';
it('should work', () => {
const rows = [{id: 0, name: 'ROOT'}, {id: 1, parent_id: 0, name: 'a'}, {id: 2, parent_id: 0, name: 'b'}];
expect(buildTree(rows)).toEqual({id: 0, name: 'ROOT', children: [{id: 1, name: 'a'}, {id: 2, name: 'b'}]})
})
it('should work even more', () => {
const a = {id: 0, name: 'ROOT'};
const b = {id: 1, name: 'meat', parent_id: 0};
const c = {id: 2, name: 'chicken', parent_id: 1};
const d = {id: 3, name: 'chicken wings', parent_id: 2};
const e = {id: 4, name: 'buffalo wings', parent_id: 2};
const f = {id: 5, name: 'wing stop', parent_id: 4};
const g = {id: 6, name: 'wing zone', parent_id: 4};
const rows = [a, b, c, d, e, f, g];
expect(buildTree(rows)).toEqual({
id: 0, name: 'ROOT', children: [{
id: 1, name: 'meat', children: [{
id: 2, name: 'chicken', children: [{
id: 3, name: 'chicken wings'
}, {
id: 4, name: 'buffalo wings', children: [{
id: 5, name: 'wing stop'
}, {
id: 6, name: 'wing zone'
}]
}]
}]
}]
})
});
<file_sep>/src/lib/api.js
// @flow
import auth from '../auth/Auth';
export type Category = {
id: number,
name: string
};
export type Transaction = {
id: number, // used to order transactions in a cart
category_id: ?number, // id of the current matched category
categoryString: string, // the representation of the category path as a string
price: string,
quantity: string,
units: string,
notes: string
};
const basicHeader = () => ({
headers: {
'Authorization': `Bearer ${auth.getIdToken()}`
}
});
export const newTransaction = (id: number): Transaction => ({
id,
category_id: null,
categoryString: '',
price: '',
quantity: '1',
units: 'units',
notes: ''
});
export const getChildren = async (c: Category): Promise<Array<Category>> => {
const response = await fetch(`/api/children/${c.id}`, basicHeader());
if (response.status < 600 && response.status >= 500) {
throw new Error(`getChildren(${c.name}) failed`)
}
const data = await response.json();
return data;
};
export const getRoot = async (): Promise<Category> => {
const response = await fetch('/api/root', basicHeader());
if (response.status < 600 && response.status >= 500) {
throw new Error(`getRoot failed`);
}
const data = await response.json();
return data[0];
};
export const addCategory = async (parent: Category, categoryName: string) => {
const response = await fetch(`/api/categories/${parent.id}/${categoryName}`, basicHeader());
if (response.status < 600 && response.status >= 500) {
throw new Error(`addCategory(${parent.name}, ${categoryName}) failed`);
}
};
export const addTransactions = async (transactions: Array<Transaction>) => {
const response = await fetch('/api/transactions', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${auth.getIdToken()}`
},
method: 'POST',
body: JSON.stringify(transactions)
});
if (response.status < 600 && response.status >= 500) {
throw new Error('addTransactions failed');
}
};
| c280bb2bd8c9764f32480da43d0222abf02e9464 | [
"JavaScript"
] | 8 | JavaScript | reikabow/cucumber-client | e6fef8cc6c4857a7c3cfe674ad4009fb8fa9501d | 6463453746c9668602ffc89839b2ec0243fa0f36 |
refs/heads/master | <repo_name>cnafoyo/DelaniStudio<file_sep>/README.md
# Delani Studio
#### Recreating a landing page for a fictional studio, 2020
#### By cnafoyo
## Description
This is a landing page for a fictional studio.
has a welcome page, some details about us, the serivices we offer, what we do portfolio and how to reach us.
## Setup/Installation Requirements
You can access the details on the website:https://cnafoyo.github.io/DelaniStudio/
You should be able to hover through the content of our design,development and product management.
## Technologies Used
HTML, CSS, javaScript and jQuery.
## Support and contact details
contact; 0721729021;<EMAIL>
### License
MIT Licenct
Copyright (c) 2020 <NAME>
<file_sep>/js/scripts.js
$(document).ready(function () {
$("#design-text").hide();
$("#design").click(function () {
$("#design-text").slideToggle("slow");
$("#design-img").slideToggle("slow");
});
$("#development-text").hide();
$("#development").click(function () {
$("#development-text").slideToggle("slow");
$("#development-img").slideToggle("slow");
});
$("#product-text").hide();
$("#product").click(function () {
$("#product-text").slideToggle("slow");
$("#product-img").slideToggle("slow");
});
$(".portfolio").each(function () {
$(this).find("p").hide()
$(this).animate({ opacity: 1 });
$(this).hover(function () {
$(this).stop().animate({ opacity: .4 }, 200);
$(this).find("p").fadeIn();
}, function () {
$(this).stop().animate({ opacity: 1 }, 400)
$(this).find("p").fadeOut();
});
});
}); | 818b3e76294a8c9edab66675ac93cee00d82bda2 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | cnafoyo/DelaniStudio | 73ff470d91239a8251315086f88270f4969e0cc5 | 82c7b4c0ef4c9c8a4a5187693a55329f588a0ad5 |
refs/heads/master | <file_sep>inp = raw_input('Europe floor?'"
usf = int(inp) + 1
print = "US floor",usf
<file_sep>nam = 'katie ' + 'scott '
print nam
nam2 = 'is ' + 'the best'
print nam2
print nam + nam2
lots = nam * 10
print lots<file_sep>nam = raw_input('Katie')
print = 'Welcome',nam
<file_sep>hours = raw_input('Enter Hours')
rate = raw_input('Enter Rate')
hours1 = int(hours)
type(hours)
rate1 = float(rate)
type(rate1)
wpay = rate1 * hours1
print wpay
#solving to find yearly salary
ypay = wpay * 35
print ypay - (wpay * 2) <file_sep>width = 17
height = 12.0
#question 1 - answer; int/ 8
A = width/2
type(A)
print A
#question 2 - answer; float/8
B = width/2.0
type(B)
print B
#question 3 - answer; float/4
C = height/3
type(C)
print C
#question 4 - answer; int/11
D = 1 + 2 * 5
print D
<file_sep>print "I'm gonna be the best coder everrrrrrr" <file_sep>tempC = 'What is the temperature in Saudi Arabia in Celcius?'
Celc = raw_input(tempC)
Celc = int(Celc)
FarH = Celc * 1.8 + 32
print FarH
| fdc584083193fe09df2ea7d128e45c7e84dc0163 | [
"Python"
] | 7 | Python | kayscott/Ch_1-2_Exercises | 9472f3b3ac52bd72668b448410df013859e12725 | 2afb04d7c4e7929d426e6e2814390bea25982be1 |
refs/heads/master | <file_sep># Deep Learning // Classical AI Projects
Completed projects from Udacity's Deep Learning & Artificial Intelligence NanoDegree Programs
Course Detail:
Deep Learning NanoDegree - https://www.udacity.com/course/deep-learning-nanodegree-foundation--nd101
Artificial Intelligence NanoDegree - https://www.udacity.com/course/artificial-intelligence-nanodegree--nd889
<file_sep>assignments = []
rows = 'ABCDEFGHI'
cols = '123456789'
reversed_cols = cols[::-1]
def cross(A, B):
"Cross product of elements in A and elements in B."
return [s + t for s in A for t in B]
boxes = cross(rows, cols)
row_units = [cross(r, cols) for r in rows]
col_units = [cross(rows, c) for c in cols]
square_units = [cross(rs, cs) for rs in ('ABC', 'DEF', 'GHI') for cs in ('123', '456', '789')]
diagonal_units = [[r + c for r, c in zip(rows, cols)], [r + c for r, c in zip(rows, reversed_cols)]]
unit_list = row_units + col_units + square_units + diagonal_units
units = dict((s, [u for u in unit_list if s in u]) for s in boxes)
peers = dict((s, set(sum(units[s], [])) - set([s])) for s in boxes)
#print(units)
#print(peers)
def assign_value(values, box, value):
"""
Please use this function to update your values dictionary!
Assigns a value to a given box. If it updates the board record it.
"""
# Don't waste memory appending actions that don't actually change any values
if values[box] == value:
return values
values[box] = value
if len(value) == 1:
assignments.append(values.copy())
return values
def make_dictionary(grid):
"""
Convert grid into a dict of {square: char} with '123456789' for empties.
Args:
grid(string) - A grid in string form.
Returns:
A grid in dictionary form
Keys: The boxes, e.g., 'A1'
Values: The value in each box, e.g., '8'. If the box has no value, then the value will be '123456789'.
"""
values = []
all_digits = '123456789'
grid = list(grid)
for char in grid:
if char == '.':
values.append(all_digits)
elif char in all_digits:
values.append(char)
#print(len(values))
assert len(values) == 81
g_dict = (dict(zip(boxes, values)))
return g_dict
def display(values):
"""
Display the values as a 2-D grid.
Args:
values(dict): The sudoku in dictionary form
"""
print(values)
width = 1 + max(len(values[square]) for square in boxes)
line = '+'.join(['-' * (width * 3)] * 3)
for r in rows:
print(''.join(values[r + c].center(width) + ('|' if c in '36' else '')
for c in cols))
if r in 'CF' : print(line)
print()
print
def eliminate(values):
"""
Iterate through all boxes and whenever there is a box with a single value,
eliminate that value from its peers.
Args:
Sudoku in dictionary form.
Returns:
Reduced sudoku in dictionary form.
"""
solved_values = [box for box in values.keys() if len(values[box]) == 1]
for box in solved_values:
digit = values[box]
for peer in peers[box]:
values[peer] = values[peer].replace(digit, '')
return values
def only_choice(values):
"""
Iterate through all units, and if there is a unit with only one possible value left,
assign the value to this box.
Args:
Sudoku in dictionary form.
Returns:
Reduced sudoku in dictionary form.
"""
for unit in unit_list:
for digit in '123456789':
dplaces = [box for box in unit if digit in values[box]]
if len(dplaces) == 1:
values = assign_value(values, dplaces[0], digit)
return values
def naked_twins(values):
"""Eliminate values using the naked twins strategy.
Args:
values(dict): a dictionary of the form {'box_name': '123456789', ...}
Returns:
the values dictionary with the naked twins eliminated from peers
"""
no_more_twins = False
while not no_more_twins:
board_before = values
for unit in unit_list:
maybe_naked = {}
naked_count = 1
for box in unit:
if len(values[box]) == 2:
for label, possibilities in maybe_naked.items():
if possibilities == values[box]:
naked_count += 1
naked_values = list(possibilities)
naked_twins = [label, box]
maybe_naked[box] = values[box]
if naked_count == 2:
#print()
#print(naked_values)
#print()
for box in unit:
if (box != naked_twins[0]) and (box != naked_twins[1]):
#print(values[box])
values[box] = values[box].replace(naked_values[0], '')
values[box] = values[box].replace(naked_values[1], '')
#print(values[box])
naked_count = 1
board_after = values
if board_before == board_after:
no_more_twins = True
return values
def reduce_puzzle(values):
"""
Reduces sudoku grid using constraint propagation of
eliminate, only_choice, and naked_twins
Args:
values: a sudoku grid in dictionary form
Returns:
The dictionary representation of the reduced sudoku grid. False if no solution exists.
"""
solved_values = [box for box in values.keys()]
stalled = False
while not stalled:
solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])
values = eliminate(values)
values = only_choice(values)
values = naked_twins(values)
solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])
stalled = solved_values_before == solved_values_after
# sanity check - no box should ever have zero possibilities unless unsolvable
if len([box for box in values.keys() if len(values[box]) == 0]):
return False
return values
def search(values):
"""
Reduces sudoku grid using constraint propagation (reduce puzzle)
then tests values for squares with fewest possible values remaining
Args:
values: a sudoku grid in dictionary form
Returns:
The dictionary representation of the solved sudoku grid. False if no solution exists.
"""
values = reduce_puzzle(values)
if values == False:
return False # previous failed test
if all(len(values[s]) == 1 for s in boxes):
print("Solved!")
return values # puzzle solved :)
# choose square to search with fewest possibilities
n,s = min((len(values[s]), s) for s in boxes if len(values[s]) > 1)
# use recurrence to solve each of the resulting sudokus - if it returns a value (i.e. not False), return that answer
for value in values[s]:
new_sudoku = values.copy()
new_sudoku[s] = value
attempt = search(new_sudoku)
if attempt:
return attempt
def solve(grid):
"""
Find the solution to a Sudoku grid.
Args:
grid(string): a string representing a sudoku grid.
Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'
Returns:
The dictionary representation of the final sudoku grid. False if no solution exists.
"""
sudoku_grid = make_dictionary(grid)
solved_sudoku = search(sudoku_grid)
return solved_sudoku
if __name__ == '__main__':
diag_sudoku_grid = '9.1....8.8.5.7..4.2.4....6...7......5..............83.3..6......9................'
diag_sudoku_solved = solve(diag_sudoku_grid)
#print(type(diag_sudoku_grid))
display(diag_sudoku_solved)
try:
from visualize import visualize_assignments
visualize_assignments(assignments)
except SystemExit:
pass
except:
print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')
<file_sep>"""Finish all TODO items in this file to complete the isolation project, then
test your agent's strength against a set of known agents using tournament.py
and include the results in your report.
"""
import random
class SearchTimeout(Exception):
"""Subclass base exception for code clarity. """
pass
def opp_diff(game, player):
"""
Heuristic evaluation function that calculates the difference between the number of legal moves available
to our player and the number legal moves available to our opponent
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
-------
float
The heuristic value of the current game state to the specified player.
"""
# Check for win/loss
if game.is_winner(player):
return float('inf')
elif game.is_loser(player):
return float('-inf')
# Heuristic evaluation
return float(len(game.get_legal_moves(player)) - len(game.get_legal_moves(game.get_opponent(player))))
def opp_diff_defensive(game, player):
"""
Similar mathematical structure to opp_diff, except the number of legal moves available to our player is weighted by a
factor of theta (> 1), giving our agent a defensive orientation
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
-------
float
The heuristic value of the current game state to the specified player.
"""
# Check for win/loss
if game.is_winner(player):
return float('inf')
elif game.is_loser(player):
return float('-inf')
# Initialize variable for heuristic evaluation
player_moves = game.get_legal_moves(player)
opponent_moves = game.get_legal_moves(game.get_opponent(player))
theta = 2
# Heuristic evaluation
return float(theta * len(player_moves) - len(opponent_moves))
def opp_diff_aggressive(game, player):
"""
Similar mathematical structure to opp_diff, except the number of legal moves available to our opponent is weighted by
a factor of 'theta' (> 1), giving our agent an aggressive orientation
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
-------
float
The heuristic value of the current game state to the specified player.
"""
# Check for win/loss
if game.is_winner(player):
return float('inf')
elif game.is_loser(player):
return ('-inf')
# Initialize variable for heuristic evaluation
player_moves = game.get_legal_moves(player)
opponent_moves = game.get_legal_moves(game.get_opponent(player))
theta = 2
# Heuristic evaluation
return float(len(player_moves) - theta * len(opponent_moves))
def opp_diff_decay(game, player):
"""
Similar mathematical structure to opp_diff aggressive / defensive variations, except we incorporate a "game_ratio"
variable that reflects how much of the game has been completed. In the beginning of the game, our player puts
more value on its own mobility; however, as the game progresses, the player becomes more aggressive in limiting
its opponents moves.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
-------
float
The heuristic value of the current game state to the specified player.
"""
# Check for win/loss
if game.is_winner(player):
return float('inf')
elif game.is_loser(player):
return float('-inf')
# Initialize variables for heuristic evaluation
player_moves = len(game.get_legal_moves(player))
opponent_moves = len(game.get_legal_moves(game.get_opponent(player)))
game_ratio = float(((game.height * game.width) - len(game.get_blank_spaces())) / (game.height * game.width))
theta = 3
# Heuristic evaluation
return float(((1 - game_ratio) * theta * player_moves) - (game_ratio * opponent_moves))
def custom_score(game, player):
"""
This is the best performing heuristic:
Oppositional Difference Between Open Moves - Forward-Thinking Orientation
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
-------
float
The heuristic value of the current game state to the specified player.
"""
return opp_diff_defensive(game, player)
def custom_score_2 (game, player):
return opp_diff(game, player)
def custom_score_3 (game, player):
return opp_diff_decay(game, player)
class IsolationPlayer:
"""Base class for minimax and alphabeta agents -- this class is never
constructed or tested directly.
******************** DO NOT MODIFY THIS CLASS ********************
Parameters
----------
search_depth : int (optional)
A strictly positive integer (i.e., 1, 2, 3,...) for the number of
layers in the game tree to explore for fixed-depth search. (i.e., a
depth of one (1) would only explore the immediate sucessors of the
current state.)
score_fn : callable (optional)
A function to use for heuristic evaluation of game states.
timeout : float (optional)
Time remaining (in milliseconds) when search is aborted. Should be a
positive value large enough to allow the function to return before the
timer expires.
"""
def __init__(self, search_depth=3, score_fn=custom_score, timeout=10.):
self.search_depth = search_depth
self.score = score_fn
self.time_left = None
self.TIMER_THRESHOLD = timeout
class MinimaxPlayer(IsolationPlayer):
"""Game-playing agent that chooses a move using depth-limited minimax
search. You must finish and test this player to make sure it properly uses
minimax to return a good move before the search time limit expires.
"""
def get_move(self, game, time_left):
"""Search for the best move from the available legal moves and return a
result before the time limit expires.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
time_left : callable
A function that returns the number of milliseconds left in the
current turn. Returning with any less than 0 ms remaining forfeits
the game.
Returns
-------
(int, int)
Board coordinates corresponding to a legal move; may return
(-1, -1) if there are no available legal moves.
"""
self.time_left = time_left
# Initialize the best move so that this function returns something
# in case the search fails due to timeout
best_move = (-1, -1)
try:
# The try/except block will automatically catch the exception
# raised when the timer is about to expire.
return self.minimax(game, self.search_depth)
except SearchTimeout:
pass # Handle any actions required after timeout as needed
# Return the best move from the last completed search iteration
return best_move
def minimax(self, game, depth):
"""
Implement depth-limited minimax search algorithm as described in
the lectures.
Parameters
----------
game : isolation.Board
An instance of the Isolation game `Board` class representing the
current game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
Returns
-------
(int, int)
The board coordinates of the best move found in the current search;
(-1, -1) if there are no legal moves
"""
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
# Record all legal moves available to our player
legal_moves = game.get_legal_moves()
# If no legal moves are available, return (-1, -1)
if not legal_moves:
return (-1, -1)
# Initialize best_score and best_move
best_score = float('-inf')
best_move = legal_moves[0]
for move in legal_moves:
future_state = game.forecast_move(move)
score = self.min_play(future_state, depth - 1)
if score > best_score:
best_score = score
best_move = move
return best_move
def min_play(self, future_state, depth):
"""
Minimizing player in minimax game
Parameters
----------
future_state : isolation.Board
An instance of the Isolation game `Board` class representing a
future game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
Returns
-------
lowest_score : int
An integer reflecting the lowest score of a forecasted move
given the evaluation function custom_score
"""
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
legal_moves = future_state.get_legal_moves()
lowest_score = float('inf')
# Base case for recursion in depth-limited search- return score of current position
if depth == 0 or not legal_moves:
return self.score(future_state, self)
for move in legal_moves:
future_state_min = future_state.forecast_move(move)
lowest_score = min(lowest_score, float(self.max_play(future_state_min, depth - 1)))
return lowest_score
def max_play(self, future_state, depth):
"""
Maximizing player in minimax game
Parameters
----------
future_state : isolation.Board
An instance of the Isolation game `Board` class representing a
future game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
Returns
-------
highest_score : int
An integer reflecting the highest score of a forecasted move
given the evaluation function custom_score
"""
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
legal_moves = future_state.get_legal_moves()
highest_score = float('-inf')
# Base case for recursion in depth-limited search- return score of current position
if depth == 0 or not legal_moves:
return self.score(future_state, self)
for move in legal_moves:
future_state_max = future_state.forecast_move(move)
highest_score = max(highest_score, float(self.min_play(future_state_max, depth - 1)))
return float(highest_score)
class AlphaBetaPlayer(IsolationPlayer):
"""Game-playing agent that chooses a move using iterative deepening minimax
search with alpha-beta pruning. You must finish and test this player to
make sure it returns a good move before the search time limit expires.
"""
def get_move(self, game, time_left):
"""Search for the best move from the available legal moves and return a
result before the time limit expires.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
time_left : callable
A function that returns the number of milliseconds left in the
current turn. Returning with any less than 0 ms remaining forfeits
the game.
Returns
-------
(int, int)
Board coordinates corresponding to a legal move; may return
(-1, -1) if there are no available legal moves.
"""
self.time_left = time_left
legal_moves = game.get_legal_moves(self)
if not legal_moves:
return (-1, -1)
best_move = legal_moves[0]
# The try/except block will automatically catch the exception
# raised when the timer is about to expire.
depth = 1
try:
while True:
best_move = self.alphabeta(game, depth)
depth += 1
except SearchTimeout:
pass # Handle any actions required after timeout as needed
# Return the best move if maximum depth reached
return best_move
def alphabeta(self, game, depth, alpha=float("-inf"), beta=float("inf")):
"""Implement depth-limited minimax search with alpha-beta pruning as
described in the lectures.
Parameters
----------
game : isolation.Board
An instance of the Isolation game `Board` class representing the
current game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
alpha : float
Alpha limits the lower bound of search on minimizing layers
beta : float
Beta limits the upper bound of search on maximizing layers
Returns
-------
(int, int)
The board coordinates of the best move found in the current search;
(-1, -1) if there are no legal moves
"""
# Make sure we return move before time runs out
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
# Record all legal moves available to our player
legal_moves = game.get_legal_moves()
# If no legal moves are available, return (-1, -1)
if not legal_moves:
return (-1, -1)
# Initialize best_score and best_move
best_score = float('-inf')
best_move = legal_moves[0]
for move in legal_moves:
future_state = game.forecast_move(move)
score = self.ab_min_play(future_state, depth - 1, alpha, beta)
if score > beta:
return move
alpha = max(alpha, score)
if score > best_score:
best_score = score
best_move = move
return best_move
def ab_min_play(self, future_state, depth, alpha, beta):
"""
Minimizing player in minimax game with alphabeta pruning
Parameters
----------
future_state : isolation.Board
An instance of the Isolation game `Board` class representing a
future game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
alpha : float
Alpha limits the lower bound of search on minimizing layers
beta : float
Beta limits the upper bound of search on maximizing layers
Returns
-------
lowest_score : int
An integer reflecting the lowest score of a forecasted move
given the evaluation function custom_score
"""
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
legal_moves = future_state.get_legal_moves()
lowest_score = float('inf')
# Base case for recursion in depth-limited search - return score of current position
if depth == 0 or not legal_moves:
return self.score(future_state, self)
for move in legal_moves:
future_state_min = future_state.forecast_move(move)
lowest_score = min(lowest_score, float(self.ab_max_play(future_state_min, depth - 1, alpha, beta)))
beta = min(beta, lowest_score)
if beta <= alpha:
break
return beta
def ab_max_play(self, future_state, depth, alpha, beta):
"""
Maximizing player in minimax game
Parameters
----------
future_state : isolation.Board
An instance of the Isolation game `Board` class representing a
future game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
alpha : float
Alpha limits the lower bound of search on minimizing layers
beta : float
Beta limits the upper bound of search on maximizing layers
Returns
-------
highest_score : int
An integer reflecting the highest score of a forecasted move
given the evaluation function custom_score
"""
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
legal_moves = future_state.get_legal_moves()
highest_score = float('-inf')
# Base case for recursion in depth-limited search - return score of current position
if depth == 0 or not legal_moves:
return self.score(future_state, self)
for move in legal_moves:
future_state_max = future_state.forecast_move(move)
highest_score = max(highest_score, float(self.ab_min_play(future_state_max, depth - 1, alpha, beta)))
alpha = max(alpha, highest_score)
if alpha >= beta:
break
return alpha
<file_sep># Artificial Intelligence Nanodegree
## Introductory Project: Diagonal Sudoku Solver
# Question 1 (Naked Twins)
Q: How do we use constraint propagation to solve the naked twins problem?
A: Constraint Propagation is about 'using local constraints to dramatically reduce the search space' for an algorithm. In the case
of a Sudoku, the local constraints are the possible values for each square given what we already know about the square's peers.
As we enforce these constraints, we introduce new constraints to other areas of the board., which further reduce our search space.
In the case of the naked twins problem, the existence of naked twins is yet another constraint that we can enforce. If two squares
are naked twins, the two remaining possible values for those squares MUST appear in those two squares. As a result, we can eliminate
those values from those squares' peers to reduce our board's search space.
# Question 2 (Diagonal Sudoku)
Q: How do we use constraint propagation to solve the diagonal sudoku problem?
A: Diagonal units are yet another constraint that we can enforce to reduce the search space of our board. Similar to the constraints of
our board's rows, columns, and squares, we know that if a number appears in a diagonal unit of our board, it cannot appear in any other
square (or peer) in that diagonal unit. Therefore, if there is only one remaining possible value for a square of a diagonal unit,
we can remove that value from all peers in that square's diagonal unit.
### Install
This project requires **Python 3**.
We recommend students install [Anaconda](https://www.continuum.io/downloads), a pre-packaged Python distribution that contains all of the necessary libraries and software for this project.
Please try using the environment we provided in the Anaconda lesson of the Nanodegree.
##### Optional: Pygame
Optionally, you can also install pygame if you want to see your visualization. If you've followed our instructions for setting up our conda environment, you should be all set.
If not, please see how to download pygame [here](http://www.pygame.org/download.shtml).
### Code
* `solution.py` - You'll fill this in as part of your solution.
* `solution_test.py` - Do not modify this. You can test your solution by running `python solution_test.py`.
* `PySudoku.py` - Do not modify this. This is code for visualizing your solution.
* `visualize.py` - Do not modify this. This is code for visualizing your solution.
### Visualizing
To visualize your solution, please only assign values to the values_dict using the ```assign_values``` function provided in solution.py
### Submission
Before submitting your solution to a reviewer, you are required to submit your project to Udacity's Project Assistant, which will provide some initial feedback.
The setup is simple. If you have not installed the client tool already, then you may do so with the command `pip install udacity-pa`.
To submit your code to the project assistant, run `udacity submit` from within the top-level directory of this project. You will be prompted for a username and password. If you login using google or facebook, visit [this link](https://project-assistant.udacity.com/auth_tokens/jwt_login for alternate login instructions.
This process will create a zipfile in your top-level directory named sudoku-<id>.zip. This is the file that you should submit to the Udacity reviews system.
| 69701df9e4e1a72232776b6e3189061da067fc0b | [
"Markdown",
"Python"
] | 4 | Markdown | dkatz24/DLND-Projects | 5c99e48725566e263d9582ce35afe7cdf76d87ec | cad52a1fa3b076c59f536c30df8a76283165f2e0 |
refs/heads/master | <file_sep>// CardGame.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
#include "Match.h"
#include <ctime>
int main()
{
srand(time(NULL));
Match* match = new Match(2);
system("Pause");
return 0;
}
<file_sep>#include "stdafx.h"
#include "EffectSimple.h"
void EffectSimple::doEffect()
{
}
void EffectSimple::notify()
{
}
EffectSimple::EffectSimple()
{
}
EffectSimple::~EffectSimple()
{
}
<file_sep>#pragma once
#include "Board.h"
#include <list>
#include "Pool.h"
#include "GameElement.h"
#include "TriggerSimple.h"
#include "TypeEvent.h"
class Match;
using namespace std;
class Player : public GameElement
{
private:
int nbCardDeck;
public:
Board* myBoard;
Pool* graveGuard;
Pool* hand;
Pool* deck;
Match* currentMatch;
TriggerSimple* playCard;
void round();
Player(int pNbCardDeck, Match* pCurrentMatch);
~Player();
};
<file_sep>#include "stdafx.h"
#include "Stack.h"
Stack::Stack()
{
listOfEffects = new list<IEffect*>();
}
Stack::~Stack()
{
}
<file_sep>#include "stdafx.h"
#include "Heal.h"
void Heal::doEffect()
{
targetGameElement->lifePoint += amountLife;
}
void Heal::notify()
{
}
Heal::Heal(int amount)
{
amountLife = amount;
}
void Heal::setAction(GameElement* target)
{
targetGameElement = target;
}
Heal::~Heal()
{
}
<file_sep>#include "stdafx.h"
#include "Board.h"
int Board::checkMana(int myMana)
{
return 0;
}
Board::Board()
{
}
Board::~Board()
{
}
<file_sep>#include "stdafx.h"
#include "TriggerSimple.h"
void TriggerSimple::addListener()
{
}
void TriggerSimple::removeListener()
{
}
void TriggerSimple::notifyListener(GameElement* pElement)
{
list<IEffect*>::iterator it;
for (it == listOfEffect.begin(); it != listOfEffect.end(); it++)
{
IEffect* tmp = *it;
tmp->notify();
}
}
TriggerSimple::TriggerSimple(TypeEvent type)
{
typeEvent = type;
}
TriggerSimple::~TriggerSimple()
{
}
<file_sep>#pragma once
#include "IEffect.h"
class Celerite : public IEffect
{
public:
void doEffect() override;
void notify() override;
Celerite();
~Celerite();
};
<file_sep>#pragma once
enum Type {
Creature,
Ephemere,
Terrain,
Enchantement,
Artefact,
Rituel,
};<file_sep>#pragma once
class Mana
{
public:
int ManaBlanc;
int ManaRouge;
int ManaVert;
int ManaBleu;
int ManaNoir;
int ManaInColor;
Mana();
~Mana();
};
<file_sep>#pragma once
#include "IEffect.h"
class Monster :
public IEffect
{
public:
void doEffect() override;
void notify() override;
Monster();
~Monster();
};
<file_sep>#pragma once
#include "Type.h"
#include "IEffect.h"
#include <list>
#include "GameElement.h"
using namespace std;
class Card : public GameElement
{
public:
Type typeCard;
// Base effect
IEffect* handEffect;
IEffect* playingEffect;
IEffect* putEffect;
IEffect* dieEffect;
Card();
~Card();
};
<file_sep>#pragma once
#include "GameElement.h"
class Creature : public GameElement
{
public:
Creature();
~Creature();
};
<file_sep>#pragma once
#include "../IEffect.h"
class EffectSimple : public IEffect
{
public:
void doEffect();
void notify();
EffectSimple();
~EffectSimple();
};
<file_sep>#include "stdafx.h"
#include "Celerite.h"
void Celerite::doEffect()
{
}
void Celerite::notify()
{
}
Celerite::Celerite()
{
}
Celerite::~Celerite()
{
}
<file_sep>#include "stdafx.h"
#include "Monster.h"
void Monster::doEffect()
{
}
void Monster::notify()
{
}
Monster::Monster()
{
}
Monster::~Monster()
{
}
<file_sep>#pragma once
enum TypeEvent {
handEvent,
playingEvent,
putEvent,
dieEvent,
lifePlayerEvent,
};<file_sep>#pragma once
#include <list>
#include "Card.h"
using namespace std;
class Pool
{
private:
int nbCard;
public:
list<Card*> listOfCard;
void addCard();
void removeCard();
Card getCard();
Pool();
Pool(int pNbCard);
~Pool();
};
<file_sep>#include "stdafx.h"
#include "Match.h"
Match::Match(int pNbPlayer)
{
nbPlayer = pNbPlayer;
listOfPlayer = new list<Player*>();
for (int i = 0; i < nbPlayer; i++)
{
listOfPlayer->push_back(new Player(50, this));
}
}
Match::~Match()
{
}
<file_sep>#include "stdafx.h"
#include "Mana.h"
Mana::Mana()
{
}
Mana::~Mana()
{
}
<file_sep>#include "stdafx.h"
#include "IEffect.h"
IEffect::IEffect()
{
}
IEffect::~IEffect()
{
}
<file_sep>#pragma once
#include "IEffect.h"
#include "TypeEvent.h"
#include <list>
using namespace std;
class TriggerSimple
{
public:
list<IEffect*> listOfEffect;
TypeEvent typeEvent;
void addListener();
void removeListener();
void notifyListener(GameElement* pElement);
TriggerSimple(TypeEvent type);
~TriggerSimple();
};
<file_sep>#pragma once
#include "IEffect.h"
class Heal :
public IEffect
{
public:
GameElement* targetGameElement;
int amountLife;
void setAction(GameElement* target);
void doEffect() override;
void notify() override;
Heal(int amount);
~Heal();
};
<file_sep>#include "stdafx.h"
#include "Blast.h"
void Blast::doEffect()
{
}
void Blast::notify()
{
}
void Blast::setAction(GameElement* target)
{
targetGameElement = target;
}
Blast::Blast(int amount)
{
power = amount;
}
Blast::~Blast()
{
}
<file_sep>#include "stdafx.h"
#include "Player.h"
void Player::round()
{
// prendre une carte de ça main
// On appelle le trigger
// La jouer à son board
//Selectionne carte 1
//handEvent.removeElement(carte1);
//playingEvent.Addelenet(CArte1);
//notify triggerAdverse j'ailedroitdejouer?(carte1)
//notify est-ce que j'ai le droit de joeur ça ?
//si oui playCard
//si non playingEvent.remove(carte1)
//handEvent.addElement(carte1)
playCard->notifyListener(hand->getCard());
}
void Player::playCard()
{
}
void Player::draw()
{
// Ajoute les listenner
}
Player::Player(int pNbCardDeck, Match* pCurrentMatch)
{
deck = new Pool(pNbCardDeck);
graveGuard = new Pool();
hand = new Pool();
playCard = new TriggerSimple(TypeEvent::playingEvent);
currentMatch = pCurrentMatch;
//Creation main
//handCard->addlistener(carteMain[1]*->)
}
Player::~Player()
{
}
<file_sep>#pragma once
#include "IEffect.h"
class EffectMultiple
{
public:
void notify();
void addEffect(IEffect* pEffect);
void removeEffect(IEffect* pEffect);
IEffect* getChild();
EffectMultiple();
~EffectMultiple();
};
<file_sep>#include "Effects\EffectSimple.h"<file_sep>#include "stdafx.h"
#include "EffectMultiple.h"
EffectMultiple::EffectMultiple()
{
}
EffectMultiple::~EffectMultiple()
{
}
<file_sep>#pragma once
#include "Player.h"
#include <list>
#include "TriggerSimple.h"
class Stack;
using namespace std;
class Match
{
private:
int nbPlayer;
public:
list<Player*>* listOfPlayer;
list<TriggerSimple>* trigger;
Match(int pNbPlayer);
~Match();
};
<file_sep>#include "stdafx.h"
#include "Pool.h"
#include <iostream>
void Pool::addCard()
{
}
void Pool::removeCard()
{
}
Pool::Pool()
{
}
Pool::Pool(int pNbCard)
{
nbCard = pNbCard;
for (int i = 0; i < pNbCard; i++)
{
//ajout carte
}
}
Pool::~Pool()
{
}
<file_sep>#pragma once
class GameElement
{
public:
int lifePoint;
GameElement();
~GameElement();
};
<file_sep>#pragma once
#include "Player.h"
#include <list>
#include "Card.h"
using namespace std;
class Board
{
public:
list<Card*> listOfCard;
void addCard();
void removeCard();
int checkMana(int myMana);
Board();
~Board();
};
<file_sep>#pragma once
enum TypeMana {
Blanc,
Rouge,
Vert,
Bleu,
Noir,
Incolor
};<file_sep>#pragma once
#include "IEffect.h"
class Blast :
public IEffect
{
public:
GameElement* targetGameElement;
int power;
void doEffect() override;
void notify() override;
void setAction(GameElement* target);
Blast(int amount);
~Blast();
};
<file_sep>#pragma once
#include "Match.h"
#include "IEffect.h"
#include <list>
using namespace std;
class Stack
{
public:
list<IEffect*>* listOfEffects;
Stack();
~Stack();
};
<file_sep>#pragma once
#include "GameElement.h"
#include "Stack.h"
class IEffect
{
public:
virtual void doEffect() = 0;
virtual void notify() = 0;
IEffect();
~IEffect();
};
| c1afc750ecbb26d5b0727ca71f4e461239b3577a | [
"C",
"C++"
] | 36 | C++ | Elencrak/CardGame | 745659ed8222997511b0b30a47bd80fc73db08da | 6b90f61b6800b053528ef59cc07074f24560e023 |
refs/heads/master | <repo_name>ocadni/ocadni.github.io<file_sep>/assets/presentations/2019-02-19 havana/CityChrone Presentation_files/animate_slow_curve.js
( function( document ) {
let w = parseInt(d3.select("#line").style("width"));
let h = 250;
//console.log(w, h)
//console.log(d3)
var svg = d3.select("#line")
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("id", "visualization")
.attr("xmlns", "http://www.w3.org/2000/svg");
var data = d3.range(11).map(function(n){
n /= 10.;
let num = 1. - n*n + n * (Math.random() - 0.5);
//console.log(num, n)
return num > 0 ? num : 0;} )
var x = d3.scaleLinear().domain([0, 10]).range([1, 250]);
var y = d3.scaleLinear().domain([0, 1.1]).range([1, w-10]);
var line = d3.line()
.curve(d3.curveCardinal)
.x(function(d,i) {return x(i);})
.y(function(d) {return y(d);})
let path = null;
let trans_foward = function(){
path = svg.append("path")
.attr("d", line(data))
.attr("stroke", "steelblue")
.attr("stroke-width", "4")
.attr("fill", "none");
var totalLength = path.node().getTotalLength();
path
.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(20000)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0);
}
let trans_backward = function(){
path.remove()};
document.addEventListener( "impress:stepenter", trans_foward);
document.addEventListener( "impress:stepleave", trans_backward)
})( document );
<file_sep>/_posts/2018-12-05-In_risposta.markdown
---
layout: post
title: "In risposta a Wu Ming 1"
date: 2018-12-5
author: <NAME>
categories: Posts
cover: "/assets/img/posts/corridoi.png"
---
### e al suo articolo: <a href="http://www.notav.info/post/8-dicembre-2018-no-tav-contro-lentita-e-lo-stato-di-cose-presente-di-wu-ming-1/" target="_blank">“8 dicembre 2018, No Tav, contro l’Entità e lo stato di cose presente”</a>
Le risposte seguono i punti dell'articolo originale.
1. Wu Ming 1 scade, come spesso accade ad ambo le parti, in una scocciante e tediosa delegittimazione delle posizioni diverse dalle proprie. Incapace di descrivere le sfumature e la complessità delle argomentazioni, si comporta come un Travaglio qualsiasi, deridendo l’altro, e facendo trasparire il suo maschilismo appellando le organizzatrici della manifestazione come “indubbiamente più presentabili ed eleganti, le «Madamin del sìTav»”, deleggittimandole. L’unica risposta al primo punto possibile per me è: io non lo faccio. Io non dipingo il movimento NoTav come un covo di bifolchi ingnoranti. O pagati dalla sitaf, l’autostrada della valle. Io ascolto le vostre idee con attenzione.
2. Non si capisce quale classe sociale voglia contrapporre alla “borghesia”. Vaneggia di una classe borghese a capo del progetto, come se i noTav fossero proletari. Qui si sta parlando di opere pubbliche e di un treno. Cerchiamo di rimanere sul pezzo.
3. **le bugie dei SiTav** (Qui Wu Ming 1 passa in rassegna quelle che considera le bugie dette dai SiTav. Di seguito le risposte alle risposte alle "bugie SiTav"):
- **Amici dei TIR**. In tutti i discorsi noTav non si mostra mai il grafico qui sotto. Tra la Francia e l’Italia il 92% delle merci passa su TIR. Molto di più degli altri valichi alpini. Perchè? E’ una cosa buona? Lasciamo le cose così? La linea storica è sottoutilizzata perche assolutamente non adeguata (e non si può [aggiornare][storica]) e non competitiva rispetto al trasporto su gomma. Lasciando le cose così ci si rassegna ai milioni di TIR sulle nostre strade e nelle valli alpine. Molte informazioni si possono trovare nel [quaderno 11][quaderni] dell’osservatorio, per capire le ragioni di questi dati.
<div class="fake-img l-body">
<p>
{% include figure.html path="/assets/img/posts/trasporto.jpg" class="img-fluid rounded z-depth-1" zoomable=true %}
</p>
</div>
- **Ormai si sta facendo!** Sì, basta andare sul sito ufficiale per vedere lo stato di avanzamento lavori: [link][avanzamento]. Siamo al 15%.
- **Resteremo isolati!** (per Wu Ming 1 è un progetto fantasma, il corridoio mediterraneo non esiste). Diciamo che a ovest di Lione è praticamente finito visto che in Francia e Spagna già esistono le linee. A est, dopo l’Italia, le cose sono più lunghe, ma diciamo che per fare l’alta capacità, essendo pianura, è molto più semplice, bastano piccoli interventi sulle linee storiche di pianura. Inoltre è fondamentale per connettersi alla [via della seta][seta] finanziata a man bassa dalla Cina. Di nuovo, La linea storica non è satura perché non è assolutamente conveniente rispetto al traffico su gomma, come dimostra il grafico sopra (perché non lo citano mai?!).
- **Torino si è espressa!** ha ragione Wu Ming. Torino non si è espressa. Alla manifestazione SiTav saranno stati molto meno, come in tutte le manifestazioni. Che facciamo, vediamo chi ha la manifestazione più grande, o si fa, per esempio, un referendum (nazionale)?
- **«Retrogradi! Cosa c’è di male nell’alta velocità ferroviaria?» (qui Wu Ming 1 sostiene che in Italia si è importato il modello francese della TAV, fatto di gallerie e ferrovie dritte, invece di rispettare il territorio italiano, tenerci le curve e puntare sui pendolini e mantenere le linee esistenti, cosa che ci è costato moltissimo)**. In verità abbiamo importato il modello alta velocità che c’è in tutto il mondo, non "solo" quello francese. È così in Germania, in Spagna, in Giappone, in Cina. Ovunque. Inoltre dice che abbiamo speso moltissimo per collegare le nostre città. Noi abbiamo speso per la TAV, tutta, in Italia, una cifra vicino ai 35 miliardi di euro. La Spagna oltre i 45 Miliardi. (LA SPAGNA!, non la prima economia mondiale). E’ vero che il nostro territorio è più muntuoso, ma le nostre città sono molto più vicine, abbiamo una densità abitativa superiore rispetto alla Francia e alla Spagna. Quindi alla fine abbiamo speso di meno di loro per collegare la maggior parte delle nostre città (manca il Sud! Ma almeno per Bari si sta facendo). Tralascio le difficoltà tecniche del pendolino e le vomitate che ti potresti fare sopra attraversando gli appennini “pendolando”. Sostiene poi che la TAV è per ricchi e classista. Si vede che non è mai riuscito a prendere un’offerta super-economy di trenitalia, che ti costa meno di un bus. Inoltre la TAV non è in contrapposizione al trasporto locale su ferro. ANZI! Bisogna togliere finanziamenti al trasporto su gomma, alle strade e autostrade italiane, non alle ferrovie. Giusto per capire i numeri in gioco: il costo della costruzione della rete **autostradale** italiana può essere [stimato][stime], in maniera molto conservativa, essere intorno ai 200 Miliardi di euro. **Il costo sostenuto per la costruzione delle autostrade è di circa 8 volte il costo della TAV**. Le battaglie andrebbero fatte lì, non sulle ferrovie. Io mi chiedo, per esempio, le due statali che passano in Val di Susa, sono sostenibili? Chi le paga? Noi con le nostre tasse. I miliardi che mettiamo ogni anno sulla rete stradale e autostradale vanno spostati sul traporto su ferro. Invece si pone, in maniera miope, in contrapposizione la TAV con il trasporto locale su ferro!
- **Grillini!**. Concordo con Wu Ming 1. I notav non sono grillini. Chiude il suo punto sulla lotta al sessismo dei notav. Cosa che stride con il suo punto uno, dove sembra che non abbia ben chiaro cosa sia il sessismo.
- **Il movimento reale che abolisce lo stato di cose presente**. Qui traspare tutto l’ideologia che si porta dietro il movimento NOTAV nel criticare la costruzione di una galleria di una ferrovia. Wu Ming 1 sostiene che la lotta NOTAV sia una lotta di classe. Mi sento in parte di dargli ragione, almeno se la vogliamo mettere in questi termini. Mi sembra una lotta della classe feudale e rurale contro la classe borghese. Molte delle critiche mosse al progetto sottendono questa visione, quando per esempio si difende la natura privata delle terre contro l’esproprio statale. O quando si tessono le lodi di una non bene specificata visione di società agricola e naturale, dove il piccolo è bello, dove l’industria è cattiva e dove le piccole opere possano salvare il mondo. Tipo i mulini ad acqua e i piccoli rattoppi. Io credo che l’aver scelto come battaglia simbolica la lotta contro una ferrovia, sia stato uno dei più grandi errori fatti dalla sinistra “antagonista” in questi ultimi anni. Dobbiamo scegliere bene gli obiettivi delle nostre lotte, non bisogna disperdere energie e dividerci. C'è da accogliere e salvare i migranti. C'è da salvarci tutti dal riscaldamento globale.
Aggiungo qualche articolo:
- Non si può aggiornare più la linea storica: [link][storica].
- Perché nessuno protesta (qui sì, sarebbe stato utile fare le barricate) per il raddoppio del tunnel autostradale del frejus: [link][raddoppio].
- Quaderni osservatorio, con analisi costi e benifici: [link][quaderni].
A latere i motivi per fare il tunnel:
- Non costa uno sproposito. Il tunnel di base costa all'Italia intorno ai 3 Miliardi di euro spalmati in 10-15 anni. Una cifra del tutto sostenibile per L'Italia. L'unione Europea finanzia il 40% dell'opera. Quindi è un ottimo investimento, con un grande ritorno sia economico che infrastrutturale che di efficentamento del sistema per l'Italia.
- Essere più vicini alla Francia e alla Spagna via treno è un'ottima cosa in chiave integrazione europea. Sono ricadute sociali, ma anche economiche.
- La ferrovia è sia per merci che per passeggeri. (Spesso si legge il contrario)
- Rende competitivo lo spostamento delle merci su ferro invece che su gomma, togliendo dalle strade milioni di tragitti fatti con i TIR. (Ogni anno passano 40 Milioni di tonnellate di merci tra L'italia e la Francia su TIR. Ogni Tir porta intorno alle 30/40 tonnellate, Sono milioni di viaggi di TIR che attraversano le valli montane e la Liguria).
- Rende competitivo, abbassando i tempi di spostamento, il tragitto tra Torino/Milano e Parigi. Ma anche verso Marsiglia, Barcellona, Bruxelles. Toglie passeggeri all'aereo, uno dei modi più inquinanti per muoversi.
[fluxes]: /assets/img/posts/trasporto.jpg
[avanzamento]: http://www.telt-sas.com/it/home-it/
[seta]: https://www.lavoce.info/archives/50049/italia-cina-un-treno-non-perdere/
[storica]: http://veritav.net/la-favola-dellutilizzo-della-linea-storica-mauro-olivero-pistoletto/
[raddoppio]: https://it.wikipedia.org/wiki/Traforo_stradale_del_Frejus
[quaderni]: http://presidenza.governo.it/osservatorio_torino_lione/quaderni.html
[stime]: http://www.buonasfalto.it/ambiente/il-valore-delle-nostre-strade
<file_sep>/_pages/about.md
---
layout: about
title: about
permalink: /
subtitle: <a href='https://www.epfl.ch/about/'>EPFL</a>
profile:
align: right
image: profile-ocadni.jpg
address: >
<p>Lausanne, Switzerland</p>
presentations: true # includes a list of news items
selected_papers: true # includes a list of papers marked as "selected={true}"
social: true # includes social icons at the bottom of the page
---
I work as postdoctoral researcher at the <a href='https://www.epfl.ch/about/'>EPFL</a> in Lausanne, Switzerland.
I have a Ph.D. in statistical physics of the Politecnico di Torino. I graduated in physics at the "La Sapienza" university of Rome.
My current areas of research are generative neural network, statistical physics, epidemic inference problems and urban science.
I'm the creator and webmaster of the <a href = "http://www.citychrone.org" target="_blank">CityChrone</a> project.
<br>
<file_sep>/_presentations/2019-07-01-cattle_infer.markdown
---
layout: post
title: Bayesian framework for inference in epidemic processes on livestock movement networks at CCS/Italy 2019
date: 2019-07-01
author: <NAME>
categories: Posts
---
Presentation of the "Bayesian framework for inference in epidemic processes on livestock movement networks" at [CCS/Italy 2019](https://italy.cssociety.org/index.php/ccs-italy-2019/).<file_sep>/_pages/presentations.md
---
layout: page
title: presentations
permalink: /presentations/
description: Presentations
nav: true
nav_order: 1
---
<div class="post">
<ul class="post-list">
{% assign sorted_presentations = site.presentations | sort: 'date' | reverse %}
{% for post in sorted_presentations %}
{% if post.external_source == blank %}
{% assign read_time = post.content | number_of_words | divided_by: 180 | plus: 1 %}
{% else %}
{% assign read_time = post.feed_content | strip_html | number_of_words | divided_by: 180 | plus: 1 %}
{% endif %}
{% assign year = post.date | date: "%Y" %}
{% assign tags = post.tags | join: "" %}
{% assign categories = post.categories | join: "" %}
<li>
<h3>
{% if post.redirect == blank %}
<a class="post-title" href="{{ post.url | prepend: site.baseurl }}">{{ post.title }}</a>
{% else %}
{% if post.redirect contains '://' %}
<a class="post-title" href="{{ post.redirect }}" target="_blank">{{ post.title }}</a>
<svg width="2rem" height="2rem" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
<path d="M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9" class="icon_svg-stroke" stroke="#999" stroke-width="1.5"
fill="none" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="round"></path>
</svg>
{% else %}
<a class="post-title" href="{{ post.redirect | relative_url }}">{{ post.title }}</a>
{% endif %}
{% endif %}
</h3>
<p>{{ post.description }}</p>
<p class="post-meta">
{{ read_time }} min read ·
{{ post.date | date: '%B %-d, %Y' }}
{%- if post.external_source %}
· {{ post.external_source }}
{%- endif %}
</p>
<p class="post-tags">
<a href="{{ year | prepend: '/presentations/' | prepend: site.baseurl}}">
<i class="fas fa-calendar fa-sm"></i> {{ year }} </a>
{% if tags != "" %}
·
{% for tag in post.tags %}
<a href="{{ tag | prepend: '/presentations/tag/' | prepend: site.baseurl}}">
<i class="fas fa-hashtag fa-sm"></i> {{ tag }}</a>
{% endfor %}
{% endif %}
{% if categories != "" %}
·
{% for category in post.categories %}
<a href="{{ category | prepend: '/presentations/category/' | prepend: site.baseurl}}">
<i class="fas fa-tag fa-sm"></i> {{ category }}</a>
{% endfor %}
{% endif %}
</p>
</li>
{% endfor %}
</ul>
{% include pagination.html %}
</div><file_sep>/_presentations/2017-07-01-lipariComplex.markdown
---
layout: post
title: "Presentation of the CityChrone project at the complex Lipari School 2017"
date: 2017-07-25
author: <NAME>
categories: Posts
cover: "/assets/presentations/kreyon2017/scientific/img/Cohesion.png"
---
# lipari2017
Presentation of [CityChrone](www.citychrone.org) at [Lipari School on Computational Complex and Social Systems](https://complex.liparischool.it/) by [indaco biazzo](ocadni.github.io)
## Instruction to see the presentation:
Download or clone the repository. Open with your favorite browser the index.html page.
## Instruction for first notebook with folium
* <a href="https://www.python.org/downloads/" target="_blank">python</a>(version 3)
* <a href="https://jupyter.org/install.html" target="_blank">notebook jupyter</a>
* Run from the terminal jupyter-notebook
* Open from your browser the page myFirstFoliumMap.ipynb
<file_sep>/assets/presentations/PechaKucha2018/myjs/progress_time/progress_time.js
/* global document */
( function( document ) {
"use strict";
var root;
var stepids = [];
let time_limit = 20;
// Get stepids from the steps under impress root
var getSteps = function() {
stepids = [];
var steps = root.querySelectorAll( ".step" );
for ( var i = 0; i < steps.length; i++ )
{
stepids[ i + 1 ] = steps[ i ].id;
}
};
// Wait for impress.js to be initialized
document.addEventListener( "impress:init", function( event ) {
root = event.target;
getSteps();
var gc = event.detail.api.lib.gc;
gc.pushCallback( function() {
stepids = [];
if ( progressbar ) {
progressbar.style.width = "";
}
if ( progress ) {
progress.innerHTML = "";
}
} );
} );
var progressbar = document.querySelector( "div.impress-progressbar-time div" );
var progress = document.querySelector( "div.impress-progress-time" );
if ( null !== progressbar || null !== progress ) {
let intervalId = null;
document.addEventListener( "impress:stepleave", function( event ) {
updateProgressbar( 0 );
clearInterval(intervalId);
} );
document.addEventListener( "impress:steprefresh", function( event ) {
getSteps();
updateProgressbar( 0 );
} );
document.addEventListener( "impress:stepenter", function(event) {
var currentStep = event.target;
//console.log( "Entered the Step Element '" + currentStep.id + "'" );
let seconds_counter = 1;
let step_time = 1;
intervalId = setInterval(function(){
//console.log(seconds_counter)
updateProgressbar( seconds_counter, time_limit );
seconds_counter += step_time;
if(seconds_counter > time_limit) clearInterval(intervalId);
//updateProgressBar();
} ,step_time * 1000);
});
}
function updateProgressbar( seconds, time_limit ) {
if ( null !== progressbar ) {
var width = 100 * (seconds / time_limit);
progressbar.style.width = width.toFixed( 2 ) + "%";
}
if ( null !== progress ) {
progress.innerHTML = seconds.toFixed(0);
}
}
} )( document );
<file_sep>/_presentations/2018-10-29-PechaKucha.markdown
---
layout: post
title: "PechaKucha presentation of Citychrone Project at ComplexCity workshop"
date: 2018-10-29
author: <NAME>
categories: Posts
cover: "/assets/presentations/PechaKucha2018/img/Gram.png"
---
# ComplexCity [ComplexCity@PoliTO].
[Slides][PechaKucha2018] of the presentation of CityChrone project by <NAME>..
<div class="fake-img l-body">
<a href="/assets/presentations/PechaKucha2018/presentation.html" target="_blank">
{% include figure.html path="/assets/img/CityChrone_Presentation.png" class="img-fluid rounded z-depth-1" %}
</a>
</div>
[image]: http://ocadni.github.io/assets/presentations/kreyon2017/scientific/img/Cohesion.png
[imagePresentation]: /assets/img/CityChrone_Presentation.png
[PechaKucha2018]: http://ocadni.github.io/assets/presentations/PechaKucha2018/presentation.html
[ComplexCity@PoliTO]: https://complexcity.polito.it/
<file_sep>/assets/presentations/2019-02-19 havana/myjs/utils.js
( function( document ) {
//**** GIF ****
let intervalId = null;
let gif_iso = () =>{
if($("#isochrones").hasClass("active")){
count = 0
let path = "./img/isochrones/";
let images = [
"a_paris1_crop.jpg",
"a_paris2_crop.jpg",
"a_paris3_crop.jpg",
"a_paris4_crop.jpg",
"a_paris5_crop.jpg",
]
intervalId = setInterval(function(){
//let num_img = count % 5 + 1
//console.log(num_img)
$("#img_iso").fadeTo(100, 0.6,()=>{
$("#img_iso").attr("src",path + images[count % 5]);
$("#img_iso").fadeTo(100, 1);
});
count += 1
}, 2 * 1000);
}
}
document.addEventListener( "impress:stepenter", gif_iso);
//document.addEventListener( "impress:steprefresh", gif_iso);
document.addEventListener( "impress:stepleave", function( event ) {
clearInterval(intervalId);});
//*** VIDEO AUTOPLAY ****
let autoplay_video = () => {
if($("#citychrone_explore").hasClass("active")){
let video1 = document.getElementById('select_city');
video1.muted = true;
video1.play();
/*video1.oncanplaythrough = function() {
video1.muted = true;
video1.play();
}*/
let video2 = document.getElementById('video_explore');
video2.muted = true;
video2.play();
/*video2.oncanplaythrough = function() {
video2.muted = true;
video2.play();
console.log("inside!!", video2)
}*/
console.log("autoplay!!!", video2);
//video.play();
}
if($("#new_scenario_citychrone").hasClass("active")){
let video1 = document.getElementById('new_scenario_video');
video1.muted = true;
video1.play();
/*video1.oncanplaythrough = function() {
video1.muted = true;
video1.play();
}*/
let video2 = document.getElementById('check_res_video');
video2.muted = true;
video2.play();
/*video2.oncanplaythrough = function() {
video2.muted = true;
video2.play();
console.log("inside!!", video2)
}*/
console.log("autoplay!!!", video2);
//video.play();
}
};
document.addEventListener( "impress:stepenter", autoplay_video);
})(document);
<file_sep>/assets/img/presentation/PechaKucha2018/myjs/myd3/metrolines.js
( function( document ) {
let w = parseInt(d3.select("#metrolines").style("width"));
let h = parseInt(d3.select("#metrolines").style("height"));
//console.log(w, h)
//console.log(d3)
var svg = d3.select("#metrolines")
.append("svg")
.attr("width", w)
.attr("height", h)
.attr("id", "visualization");
let stops = 10;
var x = d3.scaleLinear().domain([0, stops]).range([0, w]);
var x_inv = d3.scaleLinear().domain([0, stops]).range([w, 0]);
var y = d3.scaleLinear().domain([0, stops]).range([10, h - 10]);
var y_inv = d3.scaleLinear().domain([0, stops]).range([h - 10, 10]);
var line = d3.line()
.x(function(d,i) {return x(i);})
.y(function(d) {return y(d);})
.curve(d3.curveStep)
var line_inv = d3.line()
.x(function(d,i) {return x_inv(i);})
.y(function(d) {return y(d);})
.curve(d3.curveStep)
var line_inv_inv = d3.line()
.x(function(d,i) {return x_inv(i);})
.y(function(d) {return y(d);})
.curve(d3.curveStep)
let paths = [];
let animate = (path) => {
var totalLength = path.node().getTotalLength();
path
.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(20000)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0)
};
// data is created inside the function so it is always unique
let repeat = () => {
if ($("#questions").hasClass("active")){
var M1 = [0];
for(let i = 1; i < stops; i++){
M1[i] = 2 + M1[i-1] + 2 * Math.floor(0.3-Math.random());
}
var M2 = [9];
for(let i = 1; i < stops; i++){
M2[i] = -1 + M2[i-1] + 2 * Math.floor(0.3-Math.random());
}
var M3 = [0];
for(let i = 1; i < stops; i++){
M3[i] = 2 + M3[i-1] + 2 * Math.floor(0.3-Math.random());
}
var M4 = [9];
for(let i = 1; i < stops; i++){
M4[i] = -1 + M4[i-1] + 2 * Math.floor(0.3-Math.random());
}
/*d3.range(20).map(function(n){
return Math.ceil( 0.5 - Math.random()) + n
})*/
//console.log(M1, M2)
// Uncomment following line to clear the previously drawn line
//svg.selectAll("path").remove();
// Set a light grey class on old paths
//svg.selectAll("path").attr("class", "old");
var path_M1 = svg.append("path")
.attr("d", line(M1))
.attr("class", "M1 metro_lines")
animate(path_M1);
paths.push(path_M1)
var path_M2 = svg.append("path")
.attr("d", line(M2))
.attr("class", "M2 metro_lines")
animate(path_M2);
paths.push(path_M2)
var path_M3 = svg.append("path")
.attr("d", line_inv(M3))
.attr("class", "M3 metro_lines")
animate(path_M3);
paths.push(path_M3)
var path_M4 = svg.append("path")
.attr("d", line_inv_inv(M4))
.attr("class", "M4 metro_lines")
animate(path_M4);
paths.push(path_M4)
}
};
let trans_foward = function(){
path = svg.append("path")
.attr("d", line(data))
.attr("stroke", "steelblue")
.attr("stroke-width", "4")
.attr("fill", "none");
var totalLength = path.node().getTotalLength();
path
.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(20000)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0);
}
let trans_backward = function(){
for (p in paths){
paths[p].remove()
}
paths = [];
};
document.addEventListener( "impress:stepenter", repeat);
document.addEventListener( "impress:stepleave", trans_backward)
})( document );
<file_sep>/_presentations/2019-02-19-havana.markdown
---
layout: post
title: Presentation of the citychrone project - Universita de L'havana
date: 2019-02-19
author: <NAME>
categories: Posts
cover: "/assets/presentations/fourth_smartData/img/circularRer.png"
---
[Slides][PechaKucha2018] of the presentation at the University of Havana, Cuba.
<div class="fake-img l-body">
<a href="/assets/presentations/2019-02-19 havana/presentation.html" target="_blank">
{% include figure.html path="/assets/img/CityChrone_Presentation.png" class="img-fluid rounded z-depth-1" %}
</a>
</div>
[imagePresentation]: /assets/img/CityChrone_Presentation.png
[PechaKucha2018]: http://ocadni.github.io/assets/presentations/fourth_smartData/presentation.html
<file_sep>/_presentations/2021-10-16-redbull.markdown
---
layout: post
title: sustainability and urban mobility at the red bull basement workshop [2021 (Turin)
date: 2021-10-16
author: <NAME>
categories: Posts
---
Presentation of "sustainability and urban mobility" at [red bull basement workshop](https://www.facebook.com/events/157439499917965/?_rdr)(2021 -- turin italy)
[slide](/assets/presentations/2021-10-16%20Red%20Bull%20talk/slidesmartcities.pptx)<file_sep>/_presentations/2021-12-02 complexMadrid.markdown
---
layout: post
title: CityChrone - an interactive platform for transport network analysis and planning in urban systems -- at the complex networks conference [2021 Madrid]
date: 2021-12-02
author: <NAME>
categories: Posts
---
Presentation of "CityChrone - an interactive platform for transport network analysis and planning in urban systems" at [Complex Network conference](https://2021.complexnetworks.org/)(2021 -- Madrid Spain)
[slide](/assets/presentations/2021-12-02-Madrid/243_Biazzo.pptx)<file_sep>/assets/presentations/fourth_smartData/presentation.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=1024" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>CityChrone Presentation</title>
<meta name="description" content=" presentation of CityChrone Table " />
<meta name="author" content="<NAME>" />
<link href="http://fonts.googleapis.com/css?family=Open+Sans:regular,semibold,italic,italicsemibold|PT+Sans:400,700,400italic,700italic|PT+Serif:400,700,400italic,700italic" rel="stylesheet" />
<!--
Impress.js doesn't depend on any external stylesheets. It adds all of the styles it needs for the
presentation to work.
This style below contains styles only for demo presentation. Browse it to see how impress.js
classes are used to style presentation steps, or how to apply fallback styles, but I don't want
you to use them directly in your presentation.
Be creative, build your own. We don't really want all impress.js presentations to look the same,
do we?
When creating your own presentation get rid of this file. Start from scratch, it's fun!
-->
<link href="css/my.css" rel="stylesheet" />
<link href="css/impress-demo.css" rel="stylesheet" />
<link rel="shortcut icon" href="favicon.png" />
<!-- Latest compiled and minified CSS -->
<!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">!-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="./css/css/font-awesome.css">
<!-- Optional theme -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_CHTML'></script>
</head>
<body class="impress-not-supported">
<div class="fallback-message">
<p>Your browser <b>doesn't support the features required</b> by impress.js, so you are presented with a simplified version of this presentation.</p>
<p>For the best experience please use the latest <b>Chrome</b>, <b>Safari</b> or <b>Firefox</b> browser.</p>
</div>
<div id="impress">
<!-- Slide 1!-->
<div id="" class="step slide" data-x="-1000" data-y="-1500">
<div class="colorTextTitle titleText text-center">
<div> <strong>
Universal scores for accessibility and inequalities in urban areas
</strong></div>
<br>
</div>
<div class="firstImg">
</div>
<div style="top:80%; position: absolute; font-size: 30px">
Indaco Biazzo
<br>
<span class="small h6" style="width: 30px ;">
<span style="width: 50%;">Politecnico di Torino</span>
</span>
<br>
<span style="width: 100%;" class=" h5"><a href="" target="_blank">SmartData@PoliTO</a> - DISAT</span>
</div>
<div style="top:80%;left: 40%;position: absolute; font-size: 30px">
<div class="text-center" style="font-size: 25px">
personal page -- <a href="http://indacobiazzo.me/" target="_blank"> http://indacobiazzo.me/</a>
</div>
<div class="text-center" style=" font-size: 25px" >
<strong><span style="color: #f16913">C</span>ity<span style="color: #31a354">C</span>hro<span style="color: #2171b5">n</span>e</strong> -- <a href="www.citychrone.org" target="_blank"> www.citychrone.org</a>
</div>
</div>
</div>
<!-- Slide 2!-->
<div data-background-color="" class="step slide" data-x="0" data-y="-1500">
<div class="title h0"><strong>Today:</strong></div>
<br>
<div class = 'my-container'>
<ul class = "list-group list-group-flush">
<a href="#" class="list-group-item list-group-item-action" >
<div class="h2">
<strong>Introduction:</strong>
<div class="small text-muted">Motivation and context.
</div>
</div>
</a>
<a href="#" class="list-group-item list-group-item-action" > <div class="h2 strong"><strong>
Scientific results:</strong>
<div class="small text-muted">Universal scores for accessibility and inequalities in urban areas.
</div>
</div>
</a>
<a href="#" class="list-group-item list-group-item-action">
<div class="h2">
<strong>CityChrone Platform:</strong>
<div class="small text-muted">
an interactive platform for urban accessibility studies and planning.
</div>
</div>
</a>
</ul>
</div>
</div>
<!-- Slide 4!-->
<div class="step slide" data-x="1000" data-y="-1500">
<div class="h4 text-right">
Motivations
</div>
<div class="container">
<div class="row">
<div class="col-4">
<div class="">
<img class="img-fluid" src="./img/no_entry.png" alt="Generic placeholder image" width="70%">
</div>
</div>
<div class="col align-self-center">
<h3 class="">High entrance barriers</h3>
<h4 class="">
You need a Ph.D. in the specific domain to do research. But sometimes even to understand the results.
</h4>
</div>
</div>
<br>
<div class="row">
<div class="col-4">
<img class="img-fluid" src="./img/branches.png" alt="Generic placeholder image" width="80%">
</div>
<div class="col align-self-center">
<h3 class="">Overspecialization in Science</h3>
<h4 class="">
Very difficult to cross the <span style = "color:#47BE1F;">branches</span> of science.
</h4>
</div>
</div>
<div class="row">
<div class="col-4">
<div id="line"> </div>
</div>
<div class="col align-self-center">
<h2 class="">
Slow learning
<span style = "color:steelblue;">curve</span>
</h2>
<h4>
Very difficult to perform self-education path
</h4>
</div>
</div>
</div>
<small class="h6">
images:[
<a href="https://www.kisspng.com/png-branch-tree-drawing-clip-art-branches-clipart-1580707/" target="_blank" class="h7">
Branch Tree Drawing Clip art - branches clipart @kisspng
</a>,]
</small>
</div>
<!-- Slide 5!-->
<div class="step slide" data-x="2000" data-y="-1500">
<div class="h4 text-right">
Components
</div>
<div class="container">
<div class="row">
<div class="col-4">
<div class="">
<img class="img-fluid" src="./img/KISS.gif" alt="Generic placeholder image" width="70%">
</div>
</div>
<div class="col align-self-center">
<h3 class=""><i>"Simplicity is the ultimate sophistication"</i></h3>
</div>
</div>
<br>
<br>
<div class="row">
<div class="col-4">
<div class="embed-responsive embed-responsive-16by9">
<video class="embed-responsive-item float-right" id="check_res_video" muted autoplay loop oncanplay="this.muted=true">
<source src="./video/coll_detect.mov" type="video/mp4">
</video>
</div> </div>
<div class="col align-self-center">
<h3 class="">Data visualization</h3>
<h4 class="">
Interactive visualizations of results.
</h4>
</div>
</div>
<br>
<br>
<div class="row">
<div class="col-4">
<div class="">
<img class="img-fluid" src="./img/game.png" alt="Generic placeholder image" width="70%">
</div>
</div>
<div class="col align-self-center">
<h2 class="">
Gamification
</h2>
<h4>
Involve general audience to partecipate.
</h4>
</div>
</div>
</div>
<br>
<small class="h6 text left-align">
images:[
<a href="https://www.flickr.com/photos/92501682@N00/5067471752" target="_blank" class="h7">
Jegi - flickr
</a>]
</small>
</div>
<!-- Slide 6!-->
<div class="step slide" data-x="3000" data-y="-1500">
<div class="h4 text-right">
Motivations 2
</div>
<div class="row justify-content-between">
<div class="list-group-item list-group-item-action col align-items-start">
<p class="mb-1">I was born in Rome</p>
<small class="text-primary">I had a very difficult childhood
</small>
</div>
</div>
<br>
<img src="./img/busTraffico.jpeg" class="rounded" alt="" style="width:30%;height:30%;position: absolute; top: 61%;">
<img src="./img/Blocco-del-traffico-2.jpg" class="rounded" alt="" style="width:30%;height:30%; position: absolute;">
<img src="./img/trafficoroma.jpg" class="rounded" style="width:69%;height:69%;position: relative;left: 35%;">
</div>
<div class="step" data-x="3000" data-y="-900">
<h1 class = "text-center" style="font-size: 50px;">
<b style="">
Rome public transport are "not so good".
</b>
<div class="text-muted" style="font-size: 30px;">
Ok. But how much compared to the other cities?
</div>
</h1>
</div>
<div class="step" data-x="3000" data-y="-700">
<h1 class = "text-center" style="font-size: 50px;">
<b style="">
Where is the better served [by public transport] place in the city?
</b>
<div class="text-muted" style="font-size: 30px;">
And in the world?
</div>
</h1>
</div>
<!-- Slide 7!-->
<div id="" class="step" data-x="-2000" data-y="0">
<b class=" text-center">Urban Accessibility measures</b>
</div>
<!-- Slide 8!-->
<div class="step slide" data-x="-1000" data-y="0">
<div class = 'my-container'>
<b class=" text-center ">Urban Accessibility measures</b>
<br>
<br>
<div class="list-group list-group-flush">
<div href="#" class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-200">
<h2 class="mb-2"> Huge scientific literature</h2>
</div>
<p class="mb-1 h3 text-muted">The first definition of accessiblity in urban context is done more than 50 years ago</p>
</div>
<div href="#" class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-100">
<h2 class="mb-1">Many different definitions of accessibility</h2>
</div>
<p class="mb-1 h3 text-muted">But no attemp to compute it at large scale.</p>
</div>
<div href="#" class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-100">
<h2 class="mb-1">A science of city needs quantitative measurement.</h2>
</div>
<p class="mb-1 h3 text-muted">We want easy to understand, easy to compute and meaningful quantities to measure public transport efficiency.</p>
</div>
</div>
<br>
<div class="text text-center text-primary"> And we define and measure them.
</div>
</div>
</div>
<div class="step " data-x="-1000" data-y="1000" id="">
<div class="display-4 title">
Boundaries and Tessellation.
</div>
<iframe class='iframeComplete' src="./pages/parisBoundaries.html" frameborder="0"></iframe>
</div>
<!-- Slide 15!-->
<div class="step " data-x="500" data-y="1000" id="isochrones">
<div class="h2">
It is possible to compute <b>isochrones</b>
</div>
<img src="./img/isochrones/a_paris1_crop.jpg" class="img-fluid img-thumbnail" id="img_iso">
</div>
<!-- Slide 16!-->
<div class="step " data-x="1500" data-y="1000" id="">
<div class="h1 title">
First step towards an accessibility measure:
</div>
<div class="h3 title">
The larger isochrones are, the faster you move.
</div>
<img src="./img/from_paper/isochrones.svg" class="img-fluid img-thumbnail" id="">
</div>
<!-- Slide 17!-->
<div class="step slide " data-x="1500" data-y="2000" id="">
<div class="h1 text-primary text-center">Velocity Score</div>
<div class="h4">
Consider the Area of the Isochrone a time \(t\) computed in \(P\):
<span class="h5"> \begin{equation}
r(t,P) = \sqrt{\frac{A(t, P)}{\pi}}
\end{equation}
</span>
<div> dividing by time, we obtain a quantity with the dimension of a velocity: </div>
<span class="h5">
\begin{equation}
v(t,P) = \frac{r(t,P)}{t}
\end{equation}
</span>
Integrating over time:
<span class="h5">
\begin{equation}
v_{score}(P) = \frac{\int_0^{\infty} v(t, P) f(t) dt}{\int_0^{\infty} f(t) dt},
\end{equation}
</span>
\(f(t)^1\) is the daily time budget distribution for public transport.
<br>
<br>
<div class="text-info text-center h3">The Velocity Score can be consider as the average velocity of a daily typical trip taking a random direction from \(P\).
</div>
<br>
<div class="small h7 text-muted" style="font-size: .65em;"> \(^1\) <NAME>, <NAME>. Energy laws in human travel behaviour. New Journal of Physics 5, 48 IOP Publishing, 2003.
</div>
</div>
</div>
<!-- Slide 18!-->
<div class="step " data-x="3000" data-y="2000" id="vel_score">
<div class="title">
Velocity Score
<div class="h4 text-muted">
Average velocity taking a random direction
</div>
</div>
<div class="text-muted h3">
Paris
<span class="float-right"> Rome </span>
</div>
<img src="./img/scores/legend_paris.png" class="rounded float-center img-vel" alt="...">
<img src="./img/scores/vel_paris.jpg" class="rounded float-left img-vel" alt="...">
<img src="./img/scores/vel_roma.jpg" class="rounded float-right img-vel" alt="...">
<div class="">
</div>
<hr>
<div class="text-center h3">
interactive maps and more cities:
</div>
<div class="text-center h3">
<div>
<strong> <a href="http://citychrone.org"> citychrone.org </a> </strong>
</div>
</div>
</div>
<!-- Slide 19!-->
<div class="step slide " data-x="1500" data-y="3000" id="">
<div class="h1 text-primary text-center">Sociality Score</div>
<div class="h4">
Consider the populations inside the Isochrone a time \(t\) computed in \(P\):
\begin{equation}
s(t,P) = \sum_{i \mid t_i(P) < t} p(h_i),
\end{equation}
<div class="h4"> we sum over all the hexagons with time \(t_i\) less than \(t\) and \(p(h_i)\) is the population within \(h_i\).
</div>
\begin{equation}
s(P) = \frac{\int_0^{\infty} s(t,P)f(t)dt}{\int_0^{\infty} f(t) dt},
\end{equation}
<div class="h4"> \(f(t)^1\) is the daily time budget distribution for public transport.</div>
<br>
<div class="text-info text-center h3">The Sociality Score quantifies how many citizens it is possible to reach with a daily typical trip starting from \(P\).
</div>
<br>
<br>
<br>
<div class="small h7 text-muted" style="font-size: .65em;"> \(^1\) <NAME>, <NAME>. Energy laws in human travel behaviour. New Journal of Physics 5, 48 IOP Publishing, 2003.
</div>
</div>
</div>
<!-- Slide 20!-->
<div class="step" data-x="3000" data-y="3000" id="soc_score">
<div class="title">
Sociality Score
<div class="h4 text-muted">
Number of people is possible to reach in a typical day trip starting from a point.
</div>
</div>
<div class="text-muted h3">
Paris
<span class="float-right"> Rome </span>
</div>
<img src="./img/scores/legend_soc.png" class="rounded float-center img-soc" alt="...">
<img src="./img/scores/soc_paris.jpg" class="rounded float-left img-soc" alt="...">
<img src="./img/scores/soc_roma.jpg" class="rounded float-right img-soc" alt="...">
<div class="">
</div>
<hr>
<div class="text-center h3">
interactive maps and more cities:
</div>
<div class="text-center h3">
<div>
<strong> <a href="http://citychrone.org"> citychrone.org </a> </strong>
</div>
</div>
</div>
<!-- Slide 21!-->
<div class="step " data-x="4500" data-y="2000" id="">
City Rankings
</div>
<!-- Slide 22!-->
<div class="step " data-x="6000" data-y="2000" id="">
<div class="text-center">City Velocity </div>
<div class="text-muted h3 text-center">Velocity Score per person</div>
<img src="./img/CityVelocityPop.png" height="400px" style="margin-left:0px">
</div>
<!-- Slide 23!-->
<div class="step " data-x="7500" data-y="2000" id="">
<div class="text-center">City Sociality </div>
<div class="text-muted h3 text-center">Sociality Score per person</div>
<img src="./img/CitySocialityPop.png" height="400px" style="margin-left:0px">
</div>
<!-- Slide 24!-->
<div class="step " data-x="9000" data-y="2000" id="">
<div class="text-center">Cohesion </div>
<div class="text-muted h3 text-center">City Sociality divided by total population</div>
<!--<div class="text-muted h3 text-center">How easy is for two random person in city to meet each other?</div>!-->
<img src="./img/CohesionPop.png" height="400px" style="margin-left:0px">
</div>
<!-- Slide 21!-->
<div class="step " data-x="4500" data-y="3000" id="">
Distributions
</div>
<!-- Slide 25!-->
<div class="step " data-x="6000" data-y="3000" id="">
<div class="text-center">Values distribution </div>
<div class="text-muted h3 text-center">Area distributions - Population distributions</div>
<!--<div class="text-muted h3 text-center">How easy is for two random person in city to meet each other?</div>!-->
<img src="./img/violin_plot.png" height="550px" style="margin-left:-100px">
</div>
<!-- Slide 26!-->
<div class="step " data-x="7500" data-y="3000" id="">
<div class="title h1">
<div class="text-center">
Inequality distribution of
<b class = "text-primary">accessibilities</b> </div>
</div>
<img src="./img/from_paper/one_ninenine.svg" height="420px" style="margin-left:-10px">
</div>
<div class="step " data-x="9000" data-y="3000" id="">
<div class="text-center h2 ">Exponential decay from the center of the city.</div>
<img src="./img/point_time_Decay.png" height="320px" style="margin-left:-10px">
<div class="h5">
<span class="h5 text-muted">fitting function:</span> \(f(t) = e^{-t/\tau} + \sigma_0 \)</div>
<img src="./img/exponentialDecay_no_log.svg" height="320px" style="margin-left:-10px">
</div>
<!-- Slide 27!-->
<div class="step " data-x="10500" data-y="3000">
<div class="text-center h2 ">Exponential decay from the center of the city.</div>
<div class="text-center">
<div class="h5">
<span class="h5 text-muted">fitting function:</span> \(f(t) = e^{-t/\tau} + \sigma_0 \)
</div>
<img src="./img/exponentialDecayVel_presentation.svg" height="600px" style="margin-left:-100px"></div>
</div>
<!-- Slide 29!-->
<div class="step " data-x="12500" data-y="3000">
<div id="metrolines" ></div>
<h1 class = "text-center display-4">
<b style="">
Why these patterns are observed in all cities?
</b>
<div class="text-muted h2">
Are these inequalities unavoidable?
</div>
</h1>
<br>
<h1 class = "text-center display-4">
<b style="">
Can be modified or optimized?
</b>
<div class="text-muted h2" >
In which way?
</div>
</h1>
</div>
<!-- Slide 29!-->
<div class="step" data-x="-6000" data-y="4000">
<q> <strong><span style="color: #f16913">C</span>ity<span style="color: #31a354">C</span>hro<span style="color: #2171b5">n</span>e</strong> <br>
<small>Interactive platform</small>
</q>
</div>
<!-- Slide 29.5!-->
<div class="step slide" data-x="-5000" data-y="4000">
<div class="title text-primary">
Citizen Science <small>[DataViz & Gamification]</small>
</div>
<div class="container">
<div class="row">
<div class="col-8 align-self-center">
<strong>SETI@home</strong> [1999]: <span class="text-muted h5">analyze radio signals, searching for signs of extraterrestrial intelligence. People can partecipate using their PC, donating their computational resources.</span>
</div>
<div class="col-4 align-self-center">
<img src="img/seti@home.jpg"/>
</div>
</div>
<br>
<div class="row">
<div class="col-8 align-self-center">
<strong>foldit</strong> [2008]: <span class="text-muted h5">fold the structures of selected proteins as perfectly as possible, using tools provided in the game. Nature paper with credits more than 57000 authors.</span>
</div>
<div class="col-4 align-self-center">
<img src="img/foldit_mov.gif" height="100%" width="80%"/>
</div>
</div>
<br>
<div class="row">
<div class="col-8 align-self-center">
<strong>Quantum Moves</strong> [2012]: <span class="text-muted h5">simulations of logical operations in a quantum computer.</span><span class="text-muted h5"> Played over 8 million times by more than 200,000 players worldwide.
<b>The 200 000 players were all beaten by the stochastic optimization method. :(</b>
</span>
</div>
<div class="col-4 align-self-center">
<img src="img/quantum_moves.gif" height="100%" width="80%"/>
</div>
</div>
</div>
</div>
<!-- Slide 30!-->
<div class="step slide" data-x="-3500" data-y="4000" id="">
<div class="text-center strong h1">Algorithms: routing in urban context </div>
<br>
<br>
<p class="text-center">
Walking routing algortimh:
<br>
<a href="http://project-osrm.org/" target="_blank">OSRM</a>
</p>
<hr>
<br>
<p class="text-center">
New class of public transport routing algorithms:
<br>
<a href="https://link.springer.com/chapter/10.1007/978-3-642-38527-8_6" target="_blank">CSA [2013]</a>,
<a href="https://www.microsoft.com/en-us/research/publication/round-based-public-transit-routing/" target="_blank">RAPTOR [2011]</a>
</p>
<p class="text-muted small text-center">This new class of algoritms are easy to implements and fast, but they have some crucial limitations in urban context.</p>
<p class="text-muted small text-center">They needs to be closure by transitiveness in the walking path.</p>
<br>
<p class="h2 text-danger text-center"> We modified the CSA and the RAPTOR algorithm in order to use it in urban context. </p>
</div>
<!-- Slide 30!-->
<div class="step" data-x="-2000" data-y="4000">
<q> <strong><span style="color: #f16913">C</span>ity<span style="color: #31a354">C</span>hro<span style="color: #2171b5">n</span>e</strong> <br>
<small>Interactive platform</small>
</q>
<div class="container">
<div class="row">
<div class="col">
<div class="embed-responsive embed-responsive-16by9">
<video class="embed-responsive-item float-left" id="select_city" muted autoplay loop controls oncanplay="this.muted=true">
<source src="./video/select_a_city.mp4" type="video/mp4">
</video>
</div>
</div>
<div class="col">
<div class="embed-responsive embed-responsive-16by9">
<video class="embed-responsive-item float-right" id="video_explore" muted autoplay loop controls oncanplay="this.muted=true">
<source src="./video/explore_citychrone.mp4" type="video/mp4">
</video>
</div>
</div>
</div>
</div>
</div>
<!-- Slide 31!-->
<div id="" class="step " data-x="0" data-y="4000">
<h1 class = "text-center display-4 title">
<b class="">
Now I know how much Rome public transports suck
</b>
</h1>
<div class="text-muted h2 text-center">
What we have to do to reach Paris?
</div>
<br>
<h1 class = "text-center display-4 title">
<b style="">
What are the best interventions given a budget?
</b>
</h1>
<div class="display-3 text-success text-center" >
Let's Play!
</div>
</div>
<!-- Slide 32!-->
<div id="new_scenario_citychrone" class="step" data-x="1500" data-y="4000">
<q> <strong><span style="color: #f16913">C</span>ity<span style="color: #31a354">C</span>hro<span style="color: #2171b5">n</span>e</strong> <br>
<small>Interactive platform for exploring new scenario</small>
</q>
<div class="container">
<div class="row">
<div class="col">
<div class="embed-responsive embed-responsive-16by9">
<video class="embed-responsive-item float-left" id="new_scenario_video" muted autoplay loop controls oncanplay="this.muted=true">
<source src="./video/new_scenario.mp4" type="video/mp4">
</video>
</div>
</div>
<div class="col">
<div class="embed-responsive embed-responsive-16by9">
<video class="embed-responsive-item float-right" id="check_res_video" muted autoplay loop controls oncanplay="this.muted=true">
<source src="./video/check_the_results.mp4" type="video/mp4">
</video>
</div>
</div>
</div>
</div>
</div>
<!-- Slide 33!-->
<div id="" class="step" data-x="3000" data-y="4000">
<div class="text-center"> Budget: 5 Bilion € </div>
<div class="h5 text-center"><span class="text-muted">Name Scenario:</span> Gram <span class="text-muted">Author:</span> Pietro </div>
<div class="text-center">
<img src="./img/Gram.png" class="rounded img-rensponse" style="height:500px" >
</div>
</div>
<div id="" class="step" data-x="4000" data-y="4000">
<div class="text-center"> After 1 year </div>
<div class="h5 text-center"><span class="text-muted">Name Scenario:</span> rer + circle <span class="text-muted">Author:</span> mat </div>
<div class="text-center">
<img src="./img/circularRer.png" class="rounded img-rensponse" style="height:500px" >
</div>
</div>
<!-- Slide 19!-->
<div id="" class="step slide" data-x="-4000" data-y="5000">
<div class="text-center display-4"> Useful Links </div>
<br>
<p class ="h1">
Interactive platform:
<div>
<a href="http://project.citychrone.org" target="_blank">citychrone.org</a>
</div>
</p>
<p class ="h1">
Open Source and Open Data:
<div><a href="http://project.citychrone.org" target="_blank">project.citychrone.org</a></div>
</p>
<p class ="h1">
Article:
<div>
<a href="https://arxiv.org/abs/1810.03017" target="_blank">
theoretical results [arxiv]
</a>
</div>
</p>
<p class ="h1">Today presentation:
<div>
<a href="http://indacobiazzo.me" target="_blank">indacobiazzo.me</a>
</div>
</p>
<p class ="h1">Sponsor:
<div>
<a href="https://smartdata.polito.it/" target="_blank">SmartData@PoliTO</a>
</div>
</p>
<br>
<br>
</div>
<div class="step " data-x="0" data-y="8000" id="">
<div class = 'my-container'>
<div class="div-site-or-expl">
<p>
Collaborators:
</p>
</div>
<div class="div-site-or" style = "width: 100%; height: 900px; margin-top: -100px">
<iframe class='frame-site' src="http://project.citychrone.org" frameborder="0"></iframe>
</div>
</div>
</div>
<div id="overview" class="step" data-x="3000" data-y="2000" data-scale="10">
</div>
<script>
if ("ontouchstart" in document.documentElement) {
document.querySelector(".hint").innerHTML = "<p>Tap on the left or right to navigate</p>";
}
</script>
<script src="js/impress.js"></script>
<script src="js/jquery.js"></script>
<script src="myjs/d3.js"></script>
<script src="myjs/progress_time/progress_time.js"></script>
<script src="myjs/myd3/animate_slow_curve.js"></script>
<script>impress().init();</script>
<script src="myjs/jquery.js"></script>
<script src="js/popper.js"></script>
<script src="js/bootstrap.js"></script>
<script src="myjs/utils.js"></script>
<script src="js/slide.js"></script>
<script>
(function(){
// Your base, I'm in it!
var originalAddClassMethod = jQuery.fn.addClass;
jQuery.fn.addClass = function(){
// Execute the original method.
var result = originalAddClassMethod.apply( this, arguments );
// trigger a custom event
jQuery(this).trigger('cssClassChanged');
// return the original result
return result;
}
})();
impress().init();
$(document).ready(function () {
enableTouchMouseOver();
});
</script>
</body>
</html>
<file_sep>/_presentations/2019-05-02-interact_story copy.markdown
---
layout: post
title: "Presentation of CityChrone Project at the Interactive Storytelling course of Torino University"
date: 2019-05-02
author: <NAME>
categories: Posts
cover: "/assets/presentations/interactive_storytelling/img/dataMinutes.png"
---
[Slides][interact_story] of the presentation of the CityChrone project by <NAME> at the Interactive Storytelling course, Università di Torino:
[here][interact_story].
<div class="fake-img l-body">
<a href="/assets/presentations/interactive_storytelling/presentation.html" target="_blank">
{% include figure.html path="/assets/img/CityChrone_Presentation.png" class="img-fluid rounded z-depth-1" %}
</a>
</div>
[image]: /assets/presentations/interactive_storytelling/scientific/img/Cohesion.png
[imagePresentation]: /assets/img/CityChrone_Presentation.png
[interact_story]: /assets/presentations/interactive_storytelling/presentation.html
<file_sep>/_presentations/2017-12-18-smartData2017.markdown
---
layout: post
title: "Presentation of Citychrone Project at SmartData Politecnico di Torino"
date: 2017-12-18
author: <NAME>
categories: Posts
---
[Slides][smartData2017] of the presentation of the CityChrone project by <NAME> at SmartData, Politecnico di Torino:
[here][smartData2017].
<div class="fake-img l-body">
<a href="/assets/presentations/smartData2017/index.html" target="_blank">
{% include figure.html path="/assets/img/CityChrone_Presentation.png" class="img-fluid rounded z-depth-1" %}
</a>
</div>
[image]: http://ocadni.github.io/assets/presentations/kreyon2017/scientific/img/Cohesion.png
[imagePresentation]: /assets/img/CityChrone_Presentation.png
[smartData2017]: http://ocadni.github.io/assets/presentations/smartData2017/index.html
[SmartData]: https://smartdata.polito.it/
<file_sep>/_presentations/2017-09-08-kreyon 2017.markdown
---
layout: post
title: Presentations of the CityChrone project at the "Scientific event at Kreyon2017"
date: 2017-09-08
author: <NAME>
categories: Posts
cover: "/assets/presentations/kreyon2017/scientific/img/Cohesion.png"
---
### Scientific Presentation at [Kreyon 2017][kreyon2017]
[Slides][ScientKreyon2017] of the presentation of the CityChrone project by <NAME> at the Kreyon Conference 2017:
[here][ScientKreyon2017].
<div class="fake-img l-body">
<a href="/assets/presentations/kreyon2017/scientific/index.html" target="_blank">
{% include figure.html path="/assets/img/CityChrone_Presentation.png" class="img-fluid rounded z-depth-1" %}
</a>
</div>
[image]: http://ocadni.github.io/assets/presentations/kreyon2017/scientific/img/Cohesion.png
[imagePresentation]: /assets/img/CityChrone_Presentation.png
[ScientKreyon2017]: http://ocadni.github.io/assets/presentations/kreyon2017/scientific/index.html
[kreyon2017]: http://kreyon.net/kreyonConference/<file_sep>/_presentations/2015-12-10-DataBeer.markdown
---
layout: post
title: "Presentation of The CityChrone Project at the DataBeers Torino"
date: 2015-12-10
author: <NAME>
categories: Posts
cover: "/assets/presentations/kreyon2017/scientific/img/Cohesion.png"
---
Presentation of [CityChrone](www.citychrone.org) at the [DataBeers - Torino](https://databeerstorino.tumblr.com/)
[Slides](/assets/presentations/dataBeer2015/index.html) | 80c9067e799c3d7c62a146575379e763e4dcc7f5 | [
"JavaScript",
"HTML",
"Markdown"
] | 18 | JavaScript | ocadni/ocadni.github.io | 3638fe1a94e994e808601d7c4ff5b8110036c746 | b831b0e9f52118fb148d1cc7b876e124f2434a89 |
refs/heads/master | <file_sep><?php
class News {
public $id;
public $title;
public $news;
public $date;
public function allNews() {
$conn = mysqli_connect(System::_DBHOST,System::_DBUSER,System::_DBPASS,System::_DBNAME);
$result = mysqli_query($conn,"SELECT id, title, news FROM all_news order by id desc");
if ($result) {
while ($row = mysqli_fetch_array($result)) {
$url = 'comments.php?id='.$row['id'];
echo '<p>'.$row['title'].'<br>
'.$row['news'].'<br>
<a href="javascript:showComments(\''.$url.'\')">Add new comments or show!</a></p>';
}
} else {
echo 'No news for display!';
}
}
public function addNews(){
$conn = mysqli_connect(System::_DBHOST,System::_DBUSER,System::_DBPASS,System::_DBNAME);
mysqli_query($conn,"INSERT INTO all_news VALUES(null,'{$this->title}','{$this->news}', NOW())");
}
}
<file_sep><?php
include ('modules/header.php');
require_once('config.php');
if(isset($_POST['btn_submit']) && $_POST['btn_submit']!=""){
$email = $_POST['email'];
$password = $_POST['password'];
$conn = new mysqli("localhost","root","","news");
$res = $conn->query("select * from users where email = '$email'");
$user = $res->fetch_object('User');
if(!$user){
die ('Non-existent user!<br><a href="login.php">Try again</a>');
} else {
if($user->checkPass($password)){
$user->setCookies();
$user->isAdmin();
} else {
die ('Incorrect password!<br><a href="login.php">Try again</a>');
}
}
}
$form = new FormHelper("post","");
$form->open_tag();
echo "Email: <br>";
$form->input("text","email");
echo "<br>";
echo "Password: <br>";
$form->input("password","<PASSWORD>");
echo "<br><br>";
$form->input('submit','btn_submit',"Log In");
$form->close_tag();
?>
<a href="register.php">Register</a>
</body>
</html>
<file_sep><?php
include ('modules/header.php');
session_start();
require_once ('config.php');
if(!isset($_SESSION['userid']) || $_SESSION['broswer']!=$_SERVER['HTTP_USER_AGENT']){
die('You must have an account created to access the site!<br><a href="login.php">Log In</a>');
}
$id = $_SESSION['userid'];
$conn = new mysqli("localhost","root","","vesti");
$res = $conn->query("select * from users where id = '$id'");
$user = $res->fetch_object();
$comments = new Comments;
$comments->select();
$comments->showComments();
if(isset($_POST['btn_submit']) && $_POST['btn_submit']!=""){
if(isset($_POST['title']) && isset($_POST['author']) && isset($_POST['comment'])){
if (!empty($_POST['title']) && !empty($_POST['author']) && !empty($_POST['comment'])) {
if (preg_match("/^[0-9a-zA-Z ]*$/",$_POST['title']) && preg_match("/^[0-9a-zA-Z ]*$/",$_POST['author'])){
$comments = new Comments;
$comments->title = $_POST['title'];
$comments->author = $_POST['author'];
$comments->comment = $_POST['comment'];
if($comments->addComments() === FALSE){
echo "Error! Try again!!";
} else echo "The comment was send!";
} else {
echo "Only alpha-numeric characters are allowed!";
}
} else {
echo "All fields must be filled!";
}
} else {
echo "All fields must be sent!";
}
}
$form = new FormHelper("post","");
$form->open_tag();
echo "Title: <br>";
$form->input("text","title");
echo "<br>";
echo "Author: <br>";
$form->input("text","author");
echo "<br>";
echo "Comment: <br>";
$form->input("text","comment");
echo "<br><br>";
$form->input("submit","btn_submit","Send comment!");
$form->close_tag();
?>
</body>
</html>
<file_sep><?php
include ('modules/header.php');
session_start();
require_once('config.php');
$person = new Person;
if(isset($_POST['btn_submit']) && $_POST['btn_submit']!=""){
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])){
if(!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['password'])){
if (preg_match("/^[a-zA-Z ]*$/",$_POST['name'])){
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
if(strlen($_POST['password']) > 7){
$person = new Person;
$person->name = $_POST['name'];
$person->email = $_POST['email'];
$person->password = $_POST['<PASSWORD>'];
if($person->Insert() === FALSE){
echo "Error! Try again!";
} else echo "Successful registration!";
} else {
echo "Password must contain min 8 characters!";
}
} else {
echo "Incorrect email format!";
}
} else {
echo "Only alpha-numeric characters!";
}
} else {
echo "You must send all fields";
}
} else {
echo "You must send all fields";
}
}
$form = new FormHelper("post","");
$form->open_tag();
echo "Name: <br>";
$form->input("text","name");
echo "<br>";
echo "Email: <br>";
$form->input("text","email");
echo "<br>";
echo "Password: <br>";
$form->input("password","<PASSWORD>");
echo "<br><br>";
$form->input("submit","btn_submit","Register!");
$form->close_tag();
?>
</body>
</html>
<a href="login.php">Log In</a>
</body>
</html>
<file_sep><?php
class FormHelper
{
public $method = "POST";
public $action = "";
public function __construct($method,$action){
$this->method = $method;
$this->action = $action;
}
function open_tag(){
echo "<form method='{$this->method}' action='{$this->action}'>";
}
function close_tag(){
}
function input($type,$name,$value=''){
echo "<input type='{$type}' name='{$name}' value='{$value}'>";
}
}<file_sep><?php
include ('modules/header.php');
session_start();
require_once ('config.php');
if(!isset($_SESSION['userid']) || $_SESSION['broswer']!=$_SERVER['HTTP_USER_AGENT']){
die('You must have an account created to access the site!<br><a href="login.php">Log In</a>');
}
$id = $_SESSION['userid'];
$conn = new mysqli("localhost","root","","news");
$res = $conn->query("select * from users where id = '$id'");
$user = $res->fetch_object();
echo "Welcome " . $user->name . "<br>";
echo "<a href='logout.php'>Logout</a><br><br>";
$news = new News;
$news->allNews();
?>
<script type="text/javascript">
function showComments(url)
{
comments = window.open(url, "Comment", "menubar=0,resizable=0,width=380,height=480")
//comments.focus()
}
</script>
</body>
</html>
<file_sep><?php
class Comments {
public $id;
public $nid;
public $title;
public $author;
public $comment;
public function select(){
if (isset($_GET['id'])) {
$this->id = $_GET['id'];
} else {
echo 'Select news to view comments!';
exit();
}
}
public function showComments(){
$this->id = $_GET['id'];
$conn = mysqli_connect(System::_DBHOST,System::_DBUSER,System::_DBPASS,System::_DBNAME);
$result = mysqli_query($conn, "SELECT * FROM comments WHERE nid = $this->id");
if($result){
while ($row = mysqli_fetch_array($result)){
echo '<b>'.$row['title'].'<br></b>
<b>'.$row['author'].'<br></b>
<b>Comment : </b>'.$row['comment'].'<br>
<hr width="80%">';
}
} else echo "There are no comments!<br>";
}
public function addComments(){
$this->id = $_GET['id'];
$conn = mysqli_connect(System::_DBHOST,System::_DBUSER,System::_DBPASS,System::_DBNAME);
mysqli_query($conn,"INSERT INTO comments (nid, title, author, comment, date) VALUES ('{$this->id}','{$this->title}','{$this->author}','{$this->comment}',NOW())");
}
}
<file_sep><?php
class User {
public $id;
public $name;
public $email;
public $password;
public function checkPass($password){
return $this->password == $password;
}
public function setCookies(){
session_start();
$_SESSION["broswer"] = $_SERVER['HTTP_USER_AGENT'];
$_SESSION["userid"] = $this->id;
}
public function Logout(){
session_destroy();
setcookie("PHPSESSID","",time(),"/");
header("Location: login.php");
}
public function isAdmin(){
session_start();
if($this->email == "<EMAIL>" && $this->password == "<PASSWORD>"){
header("Location: admin.php");
} else {
header("Location: news.php");
}
}
}
<file_sep><?php
include ('modules/header.php');
session_start();
require_once ('config.php');
if(!isset($_SESSION['userid']) || $_SESSION['broswer']!=$_SERVER['HTTP_USER_AGENT']){
die('You must have an account created to access the site!<br><a href="login.php">Log In</a>');
}
$id = $_SESSION['userid'];
$conn = new mysqli("localhost","root","","vesti");
$res = $conn->query("select * from users where id = '$id'");
$user = $res->fetch_object();
echo "Welcome " . $user->name . "<br>";
echo "<a href='logout.php'>Logout</a><br>";
echo "<a href='news.php'>View News</a><br><br>";
echo "Add news!<br><br>";
$news = new News;
if (isset($_POST['btn_submit']) && $_POST['btn_submit']!="") {
if (isset($_POST['naslov']) && isset($_POST['vest'])){
if (!empty($_POST['naslov']) && !empty($_POST['vest'])) {
$news = new News;
$news->title = $_POST['title'];
$news->news = $_POST['news'];
if($news->addNews() === FALSE){
echo "Error! Try again!";
} else echo "News send!";
} else {
echo "All fields must be filled!";
}
} else {
echo "All fields must be send!";
}
}
$form = new FormHelper("post","");
$form->open_tag();
echo "Title: <br>";
$form->input("text","title");
echo "<br>";
echo "News: <br>";
$form->input("text","news");
echo "<br><br>";
$form->input("submit","btn_submit","Send news!");
$form->close_tag();
?>
</body>
</html>
<file_sep><?php
require_once('config.php');
session_start();
$user = new User;
$user->Logout();<file_sep><?php
class Person
{
public $id;
public $name;
public $email;
public $password;
public $type;
public function Update(){
$conn = mysqli_connect(System::_DBHOST,System::_DBUSER,System::_DBPASS,System::_DBNAME);
mysqli_query($conn,"update users set name='{$this->name}',email='{$this->email}', password='{$<PASSWORD>}' where id = {$this->id}");
}
public function Insert(){
$conn = mysqli_connect(System::_DBHOST,System::_DBUSER,System::_DBPASS,System::_DBNAME);
mysqli_query($conn,"insert into users values(null,'{$this->name}','{$this->email}','{$this->password}')");
}
}<file_sep>-- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 17, 2017 at 02:11 PM
-- Server version: 5.7.14
-- PHP Version: 5.6.25
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `vesti`
--
-- --------------------------------------------------------
--
-- Table structure for table `comments`
--
CREATE TABLE `comments` (
`id` int(11) NOT NULL,
`nid` int(11) NOT NULL,
`title` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`author` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`comment` varchar(512) COLLATE utf8_unicode_ci NOT NULL,
`date` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `comments`
--
INSERT INTO `comments` (`id`, `nid`, `title`, `author`, `comment`, `date`) VALUES
(1, 3, 'Com 1', 'John', 'First com', '2017-04-17 16:07:44'),
(2, 3, 'Com 2', 'Peter', 'Second com', '2017-04-17 16:09:58'),
(3, 4, 'Com 3 ', 'Mike', 'Third com', '2017-04-17 16:10:35');
-- --------------------------------------------------------
--
-- Table structure for table `all_news`
--
CREATE TABLE `all_news` (
`id` int(11) NOT NULL,
`title` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`news` varchar(512) COLLATE utf8_unicode_ci NOT NULL,
`date` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `all_news`
--
INSERT INTO `all_news` (`id`, `title`, `news`, `date`) VALUES
(3, 'News 1', 'First news', '2017-04-17 13:06:28'),
(4, 'News 2', 'This is a second news...', '2017-04-17 13:29:04');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(60) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `password`) VALUES
(1, 'Peter', '<EMAIL>', '<PASSWORD>'),
(2, 'Nicole', '<EMAIL>', '<PASSWORD>'),
(3, 'Jenny', '<EMAIL>', 'jenny123'),
(4, 'Bobby', '<EMAIL>', '<PASSWORD>'),
(5, 'Mike', '<EMAIL>', 'mike123'),
(6, 'Admin', '<EMAIL>', 'admin1234');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `comments`
--
ALTER TABLE `comment`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `all_news`
--
ALTER TABLE `all_news`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `comments`
--
ALTER TABLE `comments`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `all_news`
--
ALTER TABLE `all_news`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=81;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| edefb41ae319872151231ecb36411a06f0878636 | [
"SQL",
"PHP"
] | 12 | PHP | Mlagor88/News-Portal-with-User-Register | 4afd1a4f369ccf093cd804e485199f69ffdd86f0 | 2196f3143dfc037d0f447d5401d45a7780a44b8d |
refs/heads/master | <repo_name>migliorinie/delphoto<file_sep>/delphoto.py
#! /usr/bin/python3
import time
from time import gmtime, strftime
import os
import cv2
import pyautogui
import pygame as pg
#Globals
password = "<PASSWORD>"
def take_pic(name):
camera = cv2.VideoCapture(0)
return_value, image = camera.read()
del(camera)
cv2.imwrite(name, image)
savedir= os.path.dirname(os.path.realpath(__file__))
def get_name():
os.system("mkdir -p "+savedir+"/images")
return savedir+'/images/delfino'+strftime("%m_%d_%H_%M_%S", gmtime())+'.png'
def main():
pg.init()
clock = pg.time.Clock()
font = pg.font.Font(None, 32)
pyautogui.screenshot(savedir+"/sfondo.png")
picture = pg.image.load(savedir+"/sfondo.png")
pg.display.set_mode((1366,768), pg.FULLSCREEN)
main_surface = pg.display.get_surface()
main_surface.blit(picture, (0,0))
pg.display.update()
exit = False
active = False
pwd_box = pg.Rect(600, 300, 32, 96)
input_box = pg.Rect(600, 364, 32, 32)
main_surface.blit(picture, (0,0))
pg.display.flip()
writing = "Inserire password"
photoname = ""
while not exit:
for event in pg.event.get():
timer = 300
if (event.type == pg.KEYDOWN or event.type == pg.MOUSEBUTTONDOWN) and not active:
active = True
photoname = get_name()
take_pic(photoname)
pwd = ''
if event.type == pg.KEYDOWN and active:
if event.key == pg.K_RETURN:
if pwd == password:
os.system("rm "+photoname)
exit = True
else:
pwd = ''
writing = "Password errata!"
elif event.key == pg.K_BACKSPACE:
pwd = pwd[:-1]
elif event.key == pg.K_ESCAPE:
active = False
else:
pwd += event.unicode
main_surface.blit(picture, (0,0))
if active:
cheese_surface = font.render("Say cheese!", True, pg.Color('black'))
inp_surface = font.render(writing, True, pg.Color('black'))
txt_surface = font.render('*'*len(pwd), True, pg.Color('black'))
width = max(200, txt_surface.get_width()+10)
input_box.w = width
pwd_box.w = width
pg.draw.rect(main_surface, pg.Color('white'), pwd_box, 0)
pg.draw.rect(main_surface, pg.Color('grey'), input_box, 2)
main_surface.blit(cheese_surface, (pwd_box.x+5, pwd_box.y+5))
main_surface.blit(inp_surface, (pwd_box.x+5, pwd_box.y+37))
main_surface.blit(txt_surface, (input_box.x+5, input_box.y+5))
pg.display.flip()
clock.tick(30)
timer -= 1
if timer == 0:
active = False
main_surface.blit(picture, (0,0))
pg.display.flip()
if __name__ == "__main__":
main()<file_sep>/README.md
## Delphoto
#### Requirements
* scrot
* pygame
* openCV
* pyautogui
| 9ce0d7bffb66cc58e82dcfe70d46093a1d2523c3 | [
"Markdown",
"Python"
] | 2 | Python | migliorinie/delphoto | 6d526f4824e9025e92cf1b8be48810646cf0b6e3 | 8145f37bf5e4136555f858ac9b369139141e069b |
refs/heads/main | <file_sep>package org.openweather.testrunner;
import org.junit.runner.RunWith;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
@RunWith(Cucumber.class)
@CucumberOptions(features = "src\\test\\resources\\Features", glue = {
"org.openweather.stepdefinations" }, monochrome = true, plugin = { "pretty",
"html:target\\HtmlReports" , "json:target/cucumber-reports/cucumber.json"})
public class TestRunner {
}
<file_sep># api-assignment
API Tech assignment for WooliesX
1. This framework contains RestAssured framework which drives the api automation
2. Uses a Maven project structure and written in Java.
3. Tests are written in Gherkin and are stored in feature files.
4. Cucumber report is used for reporting
# Pre-requisites
- Java
- Maven
# Setting up API Automation
- Install Java and set path.
- Install Maven and set path.
- Clone respective repository or download zip.
- git clone https://github.com/ShwetaGou/api-assignment.git
# Running features
- Goto project directory.
- Use "mvn clean install" command to run features and generate the result.
- Reports | b18e9ddea0d5374b4d0621620f9e6103d30ae601 | [
"Markdown",
"Java"
] | 2 | Java | ShwetaGou/api-assignment | 1ee1ed33ba077c7e333a33c03a21bdf2d9b11546 | 620eeaa390cf310a522fb713e66ec08ef41cbd07 |
refs/heads/master | <repo_name>KaylanHusband/SeleniumTesting<file_sep>/seleniumtests/ChromeSeleniumTestSuite.java
package com.sevatec.gsalegacyquery.seleniumtests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class ChromeSeleniumTestSuite {
private static WebDriver driver;
private Select dropDown;
@Test
public void launchBrowser() {
System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Selenium\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://localhost:4200");
assertEquals("http://localhost:4200/",driver.getCurrentUrl());
}
@Test
public void createNewApplication() {
driver.findElement(By.id("New Application")).click();
driver.findElement(By.id("userInput")).sendKeys("Test");
driver.findElement(By.id("submit2")).click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
dropDown = new Select(driver.findElement(By.id("application")));
System.out.println(dropDown.getAllSelectedOptions());
dropDown.selectByVisibleText("Test");
}
@Test
public void createStakeHolder() {
dropDown = new Select(driver.findElement(By.id("application")));
dropDown.selectByVisibleText("New Application 3");
driver.findElement(By.id("submit")).click();
assertEquals("http://localhost:4200/main/stakeholders",driver.getCurrentUrl());
driver.findElement(By.id("name")).sendKeys("Test Name");
driver.findElement(By.id("role")).sendKeys("Test Role");
driver.findElement(By.id("phone")).sendKeys("New Phone");
driver.findElement(By.id("email")).sendKeys("New Email");
driver.findElement(By.id("moreInfo")).sendKeys("New More Info");
}
@Test
public void updateStaffing() {
driver.findElement(By.id("staffing")).click();
assertEquals("http://localhost:4200/main/staffing",driver.getCurrentUrl());
driver.findElement(By.id("input")).sendKeys("Test Data");
}
@Test
public void updateSecurity() {
driver.findElement(By.id("security")).click();
assertEquals("http://localhost:4200/main/security",driver.getCurrentUrl());
driver.findElement(By.id("input")).sendKeys("Test Data");
}
@Test
public void updateEnvironment() {
driver.findElement(By.id("environment")).click();
assertEquals("http://localhost:4200/main/environment",driver.getCurrentUrl());
driver.findElement(By.id("input")).sendKeys("Test Data");
}
@Test
public void updateDevelopment() {
driver.findElement(By.id("development")).click();
assertEquals("http://localhost:4200/main/development",driver.getCurrentUrl());
driver.findElement(By.id("input")).sendKeys("Test Data");
}
@Test
public void updateRuntime() {
driver.findElement(By.id("runtime")).click();
assertEquals("http://localhost:4200/main/runtime",driver.getCurrentUrl());
driver.findElement(By.id("input")).sendKeys("Test Data");
}
@Test
public void updateMonitoring() {
driver.findElement(By.id("monitoring")).click();
assertEquals("http://localhost:4200/main/monitoring",driver.getCurrentUrl());
driver.findElement(By.id("input")).sendKeys("Test Data");
}
@Test
public void updateNetwork() {
driver.findElement(By.id("network")).click();
assertEquals("http://localhost:4200/main/network",driver.getCurrentUrl());
driver.findElement(By.id("input")).sendKeys("Test Data");
}
@Test
public void updateAccess() {
driver.findElement(By.id("access")).click();
assertEquals("http://localhost:4200/main/access",driver.getCurrentUrl());
driver.findElement(By.id("input")).sendKeys("Test Data");
}
@Test
public void updateAgreement() {
driver.findElement(By.id("agreement")).click();
assertEquals("http://localhost:4200/main/agreement",driver.getCurrentUrl());
driver.findElement(By.id("input")).sendKeys("Test Data");
}
@Test
public void updateOperation() {
driver.findElement(By.id("operation")).click();
assertEquals("http://localhost:4200/main/operation",driver.getCurrentUrl());
driver.findElement(By.id("input")).sendKeys("Test Data");
}
@Test
public void updateDocumentation() {
driver.findElement(By.id("documentation")).click();
assertEquals("http://localhost:4200/main/documentation",driver.getCurrentUrl());
driver.findElement(By.id("input")).sendKeys("Test Data");
}
@Test
public void updateProjects() {
driver.findElement(By.id("projects")).click();
assertEquals("http://localhost:4200/main/projects",driver.getCurrentUrl());
driver.findElement(By.id("input")).sendKeys("Test Data");
}
@Test
public void reviewTest() throws InterruptedException {
driver.findElement(By.id("review")).click();
assertEquals("http://localhost:4200/main/review",driver.getCurrentUrl());
driver.findElement(By.id("expand")).click();
Thread.sleep(3000);
driver.findElement(By.id("collapse")).click();
Thread.sleep(3000);
driver.findElement(By.id("exit")).click();
}
} | 52b4f57e0aefdd1ce584b972f3dd8cb716467f33 | [
"Java"
] | 1 | Java | KaylanHusband/SeleniumTesting | 5726fbe22b38c126cb367dafb5f5e56ddce56f3a | 6b77bbdee39a4dc6510fc4a0ad087dae6569fd0c |
refs/heads/master | <repo_name>phamvanha2228/pacf_algorithm<file_sep>/README.md
# pacf_algorithm
Primal affine scalling optimization.
Implement the primal affine scaling algorithm.
The constraints matrix A will have to be expanded with a new variable needed by the Big-M method.
<file_sep>/PAFS.py
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 11:14:32 2020
@author: VanHa
"""
import numpy as np
import pandas as pd
import scipy.io
from scipy.sparse import csr_matrix
## FUNTION CALCULATE DUAL GAP
def dual_gap_cal(c, b, x, y):
cx = np.dot(np.transpose(c), x)
by = np.dot(np.transpose(b),y)
dg = (abs(cx-by))/(1.0 + abs(cx))
return dg
## FUNTION CALCULATE Y
def calculate_y(aa, dd, cc):
term1 = np.dot(np.dot(aa, dd), np.transpose(aa))
term2 = np.dot(np.dot(aa, dd), cc)
# ADAt = np.dot(np.dot(a,d), np.transpose(a))
# ADC = np.dot(np.dot(a,d), c)
y = np.linalg.solve(term1, term2)
return y
def optimization(A, B, C):
#### get number of column and row from the object functions and contraints
m = A.shape[0] ##m rows.
n = A.shape[1] ##n columns ~ n variables
opt_gap=1.0e-8
rho=0.9995
iteration= []
f_obj = []
x_val = []
alpha_val =[]
### checking A, B , C matrices
if C.shape[1] != 1 or B.shape[1]!= 1:
raise Exception("Error: c and b must be column vectors")
if C.shape[0] != n or B.shape[0] != m:
raise Exception("Error: inconsistent dimensions for c, b and A")
if np.linalg.matrix_rank(A) != m:
raise Exception("Error: matrix A is not full row rank")
## INITIALATION
#### infeasibilites:
e = np.ones((n,1), dtype = int)
r= B - np.dot(A,e)
##### Big-M method:
M = n*max(abs(C))
Aext = np.hstack((A,r))
Cext = np.vstack((C,M))
X = np.ones((n+1, 1))
D = np.eye(n+1)
#### Calculate "y"
Y= calculate_y(Aext, D, Cext)
dual_gap = dual_gap_cal(Cext,B, X, Y)
## ITERATIVE PROCEDURE
k = 0
while dual_gap > opt_gap:
z= Cext - np.dot(np.transpose(Aext), Y)
delta = np.dot(-D,z)
if np.all(delta >= 0):
print("Unbounded problem.")
break
alpha = rho*np.min(-X[delta < 0] / delta[delta < 0])
X = X + alpha*delta
D = np.diag(np.ravel(X))**2
Y= calculate_y(Aext, D, Cext)
dual_gap = dual_gap_cal(Cext, B, X, Y)
obj_func = np.dot(np.transpose(Cext), X)
### calculate the result table:
iteration.append(k)
f_obj.append(obj_func.ravel()[0])
alpha_val.append(alpha)
x_val.append(X)
d = {'Iteration': iteration, 'Object function': f_obj, 'alpha': alpha_val}
df = pd.DataFrame(d)
k +=1
if X[n] > 1e-8:
print("Infeasible problem.")
else:
pass
for i in range(1,n+1):
print ('X%s: %01f' %(i, X[i-1]))
print(df)
print(X[0:n])
def mat_parse(file):
mat_content = scipy.io.loadmat(file)
mat_struct = mat_content['Problem']
val = mat_struct[0, 0]
maxtrixA = csr_matrix(val['A']).todense()
vectorB = val['b']
vectorC = val['aux'][0][0][0]
return maxtrixA, vectorB, vectorC
q,v,t = mat_parse("lp_adlittle.mat")
prob = optimization(q, v, t)
| 0ea92b30ed2e50bba84919b15b22e303d6c903e7 | [
"Markdown",
"Python"
] | 2 | Markdown | phamvanha2228/pacf_algorithm | 2a7f193ffd42a2b392ad4499c57370806681b072 | b987026d3d15c0dabdc5dea6bdf6ee11012e669b |
refs/heads/master | <repo_name>wadahideyuki/danon<file_sep>/bio/gensen/sozai/modal-plainyogurt.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/bio/gensen/sozai/css/modal.css">
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-P4BBDH"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-P4BBDH');</script>
<!-- End Google Tag Manager -->
</head>
<body>
<article id="plain-yogurt" class="modal-article">
<h1>プレーンヨーグルトに込めた<br>ダノンビオの思い
<small>ダノンビオ 西田開発員のメッセージ</small></h1>
<section>
<h2>死んでしまうビフィズス菌を、<br class="sp"> 生きて腸まで届けたい。<br>
その想いで探し当てたのが、<br class="sp">BE80でした。</h2>
<p>「生きたまま腸まで届くビフィズス菌をヨーグルトに入れてお客様に届ける」ことがダノンビオ開発時のミッションでした。発酵乳から分離して発見されたBE80は、胃酸や小腸の殺菌力に耐え、しかも工場での生産に向いているという、私たちが探し求めていた、ヨーグルトに向いている菌。「生きたまま腸まで届く」ことを高生存といいますが、BE80は、胃と小腸で殺菌力がかかるいわゆる消化間で生き残ることができる高生存ビフィズス菌です。高生存がおなかの不快感をやわらげることと密接に関わっていることも、臨床試験結果に示されています。</p>
</section>
<section>
<picture>
<source media="(max-width:767px)" srcset="/bio/gensen/sozai/img/sp/modal-plainyogurt-fig.png">
<img srcset="/bio/gensen/sozai/img/modal-plainyogurt-fig.jpg" alt="">
</picture>
<h2>ダノンビオ<sup>*</sup>で得られる「実感」を、<br class="sp">ぜひあなたに。<br>
健康なのに、<br class="sp">おなかの不快感がある方へ</h2>
<p>ダノンビオは1980年代に開発したときから「健康にいい食品をお客様にお届けしたい」という意義で存在する商品です。このことをお客様に言葉で直接的にお伝えする表示ができる、ということで「おなかの不快感をやわらげる」機能をダノンビオ(プレーン・加糖)に表示しました。おなかの不快感とは、ガス、張り、ゴロゴロ感、痛みまでいかない違和感など、基本的に健康な人が下腹部に覚える不快感のことです。スッキリすることで一日を調子よく気分も軽く過ごしたい、ダノンビオ*はそんな方に食べていただきたいヨーグルト。BE80は高生存で空腹時の胃酸にも強いため、食べるタイミングは空腹時でも食後でも、いつでも構いません。</p>
</section>
<section>
<h2>フレッシュで安全でおいしい、<br class="sp">しかも機能的。<br>
そんなダノンビオ<sup>*</sup>を、毎日お届けしたいから。</h2>
<p>ダノンビオ<sup>*</sup>には、このヨーグルトならではの強みがあります。お話ししてきたように、お腹の不快感をやわらげる機能をお客様自身が実感できる商品であること。そして、機能性を支える科学的根拠があり、作用基準を高いレベルで持ち得ていることです。また、ダノンビオは世界ブランドのヨーグルトで、世界中で同じ成分・同じ菌の組合せで作っていますが、日本は日本の工場で生産しています。その理由は、よりフレッシュな状態で、安全安心・おいしいダノンビオをお客様にお届けしたいからです。私たち開発チームの想いはただ一つ、おいしくてお客様に愛されるヨーグルトをお届けしたいということ。栄養と機能に優れた商品を、お客様のくらしに継続して取り入れていただけたら、と願っています。</p>
</section>
<p class="note">BE80 届出表示:本品にはビフィズス菌BE80が含まれ、おなかの不快感※をやわらげることが報告されています。※おなかの不快感とは、健康な人の日常生活でみられる下部消化管における過剰なガスの発生とおなかの張り、ゴロゴロ感や違和感のことです。食生活は、主食、主菜、副菜を基本に、食事のバランスを。本品は、事業者の責任において特定の保健の目的が期待できる旨を表示するものとして、消費者庁長官に届け出されたものです。ただし、特定保健用食品と異なり、消費者庁長官による個別審査を受けたものではありません。 摂取上の注意:●本品は多量摂取により疾病が治癒したり、より健康が増進するものではありません。●本品は、疾病の診断、治療、予防を目的としたものではありません。●本品は、疾病に罹患している者、未成年者、妊産婦(妊娠を計画している者を含む。)及び授乳婦を対象に開発された食品ではありません。●疾病に罹患している場合は医師に、医薬品を服用している場合は医師、薬剤師に相談してください。●体調に異変を感じた際は、速やかに摂取を中止し、医師に相談してください。●一日あたりの摂取目安量:2カップ(150g) 機能性関与成分名:●ビフィズス菌BE80(Bifidodacterium Lactis CNCM I-2494)含有量:89億個</p>
<p class="note">*ダノンビオ プレーン・加糖です。</p>
</article>
<div class="modal-closer">閉じる</div>
<script src="/bio/gensen/sozai/js/modal.js"></script>
</body>
</html><file_sep>/bio/gensen/js/script.js
function autoplayMutedSupported() {
var v = document.createElement('video');
v.muted = true;
v.play();
return !v.paused;
}
;(function($) {
$(function(){
if(_uac.isiOS){
if(_uac.iosVer >= 10){
$("html").addClass("ios10above");
}
}
if(autoplayMutedSupported()){
$("html").addClass("videoautoplay");
}else{
$("html").addClass("no-videoautoplay");
}
});
})(jQuery);<file_sep>/README.md
# danon
danon
<file_sep>/bio/14dayschallenge/app/js/script.js
var isDebug = true;
//本番用にはこれをコメントアウトしてconsole.logを無効化
if(! isDebug){
window.console = {};
window.console.log = function(i){return;};
window.console.time = function(i){return;};
window.console.timeEnd = function(i){return;};
}
;(function($) {
var json, d, o, q, cs, lv, mmtNow, mmtNowBegin, mmtFirst, mmtAdviceLastOpened, mmtMenuOpen, diff, diffB, i, ii, val, tnCookieName, tnCookies;
var turnId = 0, dayId = 0, oTurn, oDay, numTurn, savedTurnId, savedDayId;
var arrFood, arrYogurt, arrExercise, arrJikkan, arrBowel;
var dailyPeriod = [3,0,0]; //各日の区切り時間(時,分,秒)
var advicePeriod = 4; //ワンポイントアドバイスの表示インターバル(時間)
var dayPerTurn = 14; //各ターンの最大DAY数
var currentMode = "main"; //現在のモード(main / reuslt)
var oTimer;
//var timerInterval = 10 * 1000; //タイマー実施間隔(ミリ秒)
var timerInterval = 10 * 1000; //タイマー実施間隔(ミリ秒)
var isHome = false; //ホーム画面表示中か否かを示すフラグ
$(function(){
//ボタン類初期設定
init();
//クエリ読み込み
q = query2object();
if(!q){
//クエリがついていなかったらキャンペーントップにリダイレクト
location.href = "https://www.danone.co.jp/bio/14dayschallenge/";
}
//コース、LV取得
cs = q.course[0].charAt(0);
lv = parseInt(q.course[0].charAt(1));
//コース内容等反映
$("html").addClass("cs-"+cs+lv);
$("#your-course em").text(cs.toUpperCase());
//現在日付取得
updateMmtNow();
//Cookie読み込み
json = Cookies.getJSON("json");
tnCookies = {};
if(json != undefined){
for(i=0;i<json.tn.length;i++){
tnCookieName = json.tn[i];
tnCookies[tnCookieName] = Cookies.getJSON(tnCookieName);
}
if(isDebug){
console.log("区切り時間上書き",parseInt(json.ph)+"時"+parseInt(json.pm)+"分");
//区切り時間上書き
dailyPeriod = [parseInt(json.ph), parseInt(json.pm), 0];
}
//現在日付取得
updateMmtNow();
}
//Cookieの状態で処理分岐
if(json != undefined){
console.log("Cookie:あり");
//Cookieの記録と現在のCS/LVは一致しているか?
if(q.course[0] == (json.cs + json.lv)){
console.log("Cookieの記録と現在のCS/LV:一致");
setTurnId(json.tn.length - 1);
//再訪トラッキングコード
if(json.ga == 0){
console.log("再訪トラッキングコード未送出");
//トラッキングコード送出
ga('send', 'event', 'repeat', 'repeat-access', 'repeat-complete');
//console.log('send', 'event', 'repeat', 'repeat-access', 'repeat-complete');
//$("a#repeat-tracker").trigger("click");
/*dataLayer.push({
'event': 'click',
'eventCategory': 'repeat',
'eventAction': 'rpeat-access',
'eventLabel': 'repeat-complete'
});*/
//json更新
json.ga = 1;
}
//実行中のターンはあるか?(最新のターンは現在実行中か?)
if(oTurn.s == 0){
console.log("最新のターンは現在:実行中");
//実行中ターン初日の開始時刻を取得
setMmtFirst(oTurn.y, oTurn.m, oTurn.d);
//実行中ターンの最新日をセット
setDayId(oTurn.l.length - 1);
//Cookie上の実行中ターンの最新日と現在日付の差を取得
diff = mmtNowBegin.diff(moment(mmtFirst).add(dayId, "days"), "days");
//Cookie上の実行中ターンの初日と現在日付の差を取得
diffB = mmtNowBegin.diff(mmtFirst, "days");
//Cookie上の実行中ターンの最新日と現在日付は一致するか?
if((diff == 0) && (diffB < dayPerTurn)){
console.log("Cookie上の実行中ターンの最新日と現在日付は:一致");
//データ更新
updateData();
//変数更新
updateVars();
//ホーム画面表示更新
updateHomeScreen();
}else{
console.log("Cookie上の実行中ターンの最新日と現在日付は:不一致");
//Cookie上の最新日と現在日付の差が13日以内か?
if((diff < dayPerTurn) && (diffB < dayPerTurn)){
console.log("Cookie上の最新日と現在日付の差:13日以内");
//Cookie上の最新日と現在日付の間の空白日付分のダミーデータを作成
for(i=0;i<diff;i++){
//DAYデータ新規作成
addDayData(turnId);
}
//データ更新
updateData();
//変数更新
updateVars();
//ホーム画面表示更新
updateHomeScreen();
}else{
console.log("Cookie上の最新日と現在日付の差:14日以上");
//Cookie上の実行中のターンの記録を「終了」に変更
oTurn.s = 1;
//新ターンデータ作成
addTurnData();
//DAYデータ新規作成
addDayData(json.tn.length - 1);
//データ更新
updateData();
//変数更新
updateVars();
//ホーム画面表示更新
updateHomeScreen();
}
}
}else{
console.log("最新のターンは現在:終了済み");
//実行中のデータを終了済みへ
oTurn.s = 1;
//新ターンデータ作成
addTurnData();
//DAYデータ新規作成
addDayData(json.tn.length - 1);
//データ更新
updateData();
//変数更新
updateVars();
//ホーム画面表示更新
updateHomeScreen();
}
}else{
console.log("Cookieの記録と現在のCS/LV:不一致");
//Cookieのクリア
clearAllCookies();
//基準値と異なればSTART画面を表示
showStartScreen();
}
}else{
console.log("Cookie:なし");
//Cookieが無ければSTART画面を表示
showStartScreen();
}
//リサイズ処理
$(window).on("scroll orientationchange resize", function(e){
onResize();
}).trigger("resize");
});
//turnIdセット関数
function setTurnId(val){
console.log("setTurnId", val);
turnId = val;
tnCookieName = json.tn[val];
oTurn = tnCookies[json.tn[val]];
}
//dayIdセット関数
function setDayId(val){
console.log("setDayId", val);
dayId = val;
oDay = oTurn.l[val];
}
//ボタン類初期設定
function init(){
console.log("init");
//モーダル:開くボタン
$(".modal-launcher").on("click", function(e){
var href = $(this).attr("href");
if(href.charAt(0) == "#"){
e.preventDefault();
openModal(href.substr(1));
}
});
//モーダル:閉じるボタン
$(".modal-closer").on("click", function(e){
e.preventDefault();
closeModal();
//ホーム画面表示更新
updateHomeScreen();
});
/*
//モーダル:背景クリックで閉じる(スタート画面を除く)
$("#modal").on("click", function(e){
if(($(e.target).is("#modal"))&&(! $(e.target).is(".modal-start"))){
closeModal();
}
});
*/
//これまでの結果を見るボタン
$("#btn-log-all").on("click", function(e){
e.preventDefault();
switchMode("result");
});
$("#result a.btn-top").on("click", function(e){
e.preventDefault();
switchMode("main");
});
//#day-indicator
$("#day-indicator>ul>li").each(function(i){
$(this).on("click", function(e){
if($(this).is(".done") || $(this).is(".today")){
//表示中ではないDAYがクリックされたら処理
if(i != dayId){
console.log("day-indicator:click", i, dayId);
//dayId変更
setDayId(i);
//変数更新
updateVars();
//ホーム画面表示更新
updateHomeScreen();
}
}
});
});
//#menuボタン
$("#menu>ul>li>a").on("click", function(e){
e.preventDefault();
switch($(this).attr("href")){
case "#modal-food":
openMenu("food");
break;
case "#modal-yogurt":
openMenu("yogurt");
break;
case "#modal-exercise":
openMenu("exercise");
break;
case "#modal-jikkan":
openMenu("jikkan");
break;
case "#modal-bowel":
openMenu("bowel");
break;
}
});
$(".modal-checksheet a.btn-close").on("click", function(e){
e.preventDefault();
closeMenu();
});
//#modal-adviceの閉じるボタン
$(".modal-advice>a.btn-close").on("click", function(e){
e.preventDefault();
//ADVICEコンテンツ消去
hideModalContent($(this).data("nextContent"));
});
//チェックシート
$(".modal-checksheet input[type='checkbox'], .modal-checksheet input[type='radio']").on("change", onFormChange);
//結果画面
$(document).on("click", ".result-unit>table>tbody>tr>td.cell-day>a", function(e){
e.preventDefault();
//#resultから今日のチェックを開く
savedTurnId = turnId;
savedDayId = dayId;
setTurnId($(this).parents("tr").data("turn"));
setDayId($(this).parents("tr").data("day"));
openModal("modal-todayscheck");
});
$(document).on("click", ".result-unit>table>tbody>tr>td.cell-edit>a", function(e){
//ターンとDAYを設定
setTurnId($(this).parents("tr").data("turn"));
setDayId($(this).parents("tr").data("day"));
//モードを変更
switchMode("main");
//ホーム画面表示更新
updateHomeScreen();
});
//#modal-howtoの「このサイトについて」ボタン
$("#modal-howto .btn-about").on("click", function(e){
e.preventDefault();
//「ページの使い方」コンテンツ消去
hideModalContent("modal-aboutsite");
});
//#modal-aboutsiteの閉じるボタン
$("#modal-aboutsite .btn-close").on("click", function(e){
e.preventDefault();
closeModal();
});
//トラッキングリンク設定
$("#tracking-links a").on("click", function(e){
e.preventDefault();
});
}
//START画面表示
function showStartScreen(){
console.log("showStartScreen");
openModal("modal-start");
//ボタン類設定
$("#modal-start button").on("click", function(){
//START画面消去
hideStartScreen();
});
}
//START画面消去
function hideStartScreen(){
console.log("hideStartScreen");
//モーダル消去
closeModal();
//初期データ作成
createInitialData();
//ターンデータ新規作成
addTurnData();
//DAYデータ新規作成
addDayData(0);
//データ更新
updateData();
//変数更新
updateVars();
//ホーム画面表示更新
updateHomeScreen();
}
//初期データ作成
function createInitialData(){
console.log("createInitialData");
json = {};
//コースとレベルを取得
json.cs = cs;
json.lv = lv;
//値の初期化
json.tf = json.te = 0;
json.tn = [];
json.ga = 0;
json.ph = 3;
json.pm = 0;
json.updated = 0;
}
//ターンデータ新規作成
function addTurnData(){
//現在時刻取得
updateMmtNow();
//ターンCookie名生成・記録
tnCookieName = "tn" + json.tn.length;
console.log("addTurnData", tnCookieName);
json.tn.push(tnCookieName);
//ターンCookieの初期化&保存
tnCookies[tnCookieName] = {
y: mmtNowBegin.year(),
m: mmtNowBegin.month(),
d: mmtNowBegin.date(),
s:0,
r:0,
c:0,
l:[]
};
//実行中ターンの最新日をセット
setMmtFirst(mmtNowBegin.year(), mmtNowBegin.month(), mmtNowBegin.date());
//変数更新
setTurnId(json.tn.length - 1);
}
//DAYデータ新規作成
function addDayData(tId){
console.log("addDayData", tId);
oTurn = tnCookies[json.tn[tId]];
oTurn.l.push({
f:0,
e:0,
y:0,
j:0,
b:0,
s:0
});
//変数更新
setDayId(oTurn.l.length - 1);
}
//データ更新
function updateData(){
console.log("updateData");
var hasCompleted;
//評価更新
for(i=0;i<json.tn.length;i++){
o = tnCookies[json.tn[i]];
hasCompleted = true;
//各DAYの評価
for(ii=0;ii<o.l.length;ii++){
val = 0;
d = o.l[ii];
if(parseInt(d.f) > 0){
val++;
}
if(parseInt(d.e) > 0){
val++;
}
if(parseInt(d.y) > 0){
val++;
}
if(parseInt(d.j) > 0){
val++;
}
d.s = val;
//もしひとつもチェックされていない日があったらコンプリートフラグを下ろす
if(val == 0){
hasCompleted = false;
}
}
//各ターンの評価
o.r = 0; //現状は意味ナシ
console.log("CHECK", o.l.length, dayPerTurn, hasCompleted);
//コンプリートフラグが立っていて、かつCookieに未記録であったら記録する
if((o.l.length == dayPerTurn) && hasCompleted && (o.c == 0)){
o.c = 1;
//トラッキングコード送出
console.log("コンプリートトラッキングコード送出");
ga('send', 'event', '14days', '14days-access', '14days-complete');
//console.log('send', 'event', '14days', '14days-access', '14days-complete');
//$("a#complete-tracker").trigger("click");
}
}
//処理中のjsonオブジェクトの更新日と実際のCookieの更新日が一致しない場合はリロードを喚起
checkCookieUpdate();
//更新日記録
json.updated = new Date().getTime();
//Cookie更新
console.log("Cookies.set", "json", json);
Cookies.set("json", json, {expires: 365 * 5, path: "/14dayschallenge/app/"});
for(i=0;i<json.tn.length;i++){
console.log("Cookies.set", json.tn[i]);
Cookies.set(json.tn[i], tnCookies[json.tn[i]], {expires: 365 * 5, path: "/14dayschallenge/app/"});
}
}
//変数更新
function updateVars(){
console.log("updateVars");
//総ターン数を取得
numTurn = json.tn.length;
}
//ホーム画面表示更新
function updateHomeScreen(){
console.log("updateHomeScreen", turnId, dayId);
//ホーム画面表示ステータス更新
isHome = true;
//現在時刻更新
updateMmtNow();
//----------
// 日またぎ処理
//----------
//日またぎ処理監視タイマースタート
if(! oTimer){
console.log("日またぎ処理監視タイマースタート");
oTimer = setInterval(function(){
checkDate();
}, timerInterval);
}
//日またぎ処理実行
checkDate();
//----------
// #day-indicator処理
//----------
//DAYの状態に応じてクラス付与
var len = oTurn.l.length;
$("#day-indicator>ul>li").each(function(i){
//一旦クラスをリセット
$(this).removeClass();
//指定DAYチェック
if(i == dayId){
//指定DAYだったら.onクラスを付与
$(this).addClass("on");
}
//today or doneチェック
if((turnId == (numTurn - 1))&&(i == (len - 1))){
//最新ターンの最新DAYだったら.todayクラスを付与
$(this).addClass("today");
}else if(i < len){
//過去DAYだったら.doneクラスを付与
$(this).addClass("done");
}
});
//適切な位置へ移動
var pos = 0, scrollMax = $("#day-indicator>ul").width() - $(window).width(), scrollUnit = $(window).width() / 5;
switch(dayId){
case 0:
case 1:
case 2:
pos = 0;
break;
case 11:
case 12:
case 13:
pos = scrollMax;
break;
default:
pos = scrollUnit * (dayId - 2) + 1;
break;
}
$("#day-indicator").stop().animate({
scrollLeft: pos
}, "fast");
//----------
// #menuチェック処理
//----------
//チェック状態をクリア
$("#menu>ul>li.done").removeClass("done");
//チェック状態を反映
if(oDay.f > 0){
$("#menu-food").addClass("done");
}
if(oDay.e > 0){
$("#menu-exercise").addClass("done");
}
if(oDay.y > 0){
$("#menu-yogurt").addClass("done");
}
if(oDay.j > 0){
$("#menu-jikkan").addClass("done");
}
if(oDay.b > 0){
$("#menu-bowel").addClass("done");
}
}
//MENU実行
function openMenu(mId){
console.log("openMenu", mId);
//
var $advDiv, pos;
updateMmtNow();
//MENU開扉時の時刻を保存
mmtMenuOpen = mmtNowBegin.clone();
switch(mId){
//「FOOD」「YOGURT」「JIKKAN」処理
case "food":
case "yogurt":
case "jikkan":
mmtAdviceLastOpened = moment.unix(json.tf);
//ボタンの最後の押下から所定の時間が経過しているか?
if(mmtNow.diff(mmtAdviceLastOpened, "hours") >= advicePeriod){
//アドバイス画面表示
openModal("modal-advice-food");
//アドバイスランダム表示
$advDiv = $("#modal-advice-food-" + cs);
pos = Math.floor(Math.random() * $advDiv.children("dl").length);
$advDiv.children("dl").eq(pos).appendTo($advDiv);
//閉じるボタン設定
$("#modal-advice-food a.btn-close").data("nextContent", "modal-" + mId);
//データ更新
json.tf = mmtNow.unix();
updateData();
}else{
//MENUコンテンツ表示
openModal("modal-" + mId);
}
break;
//「EXERCISE」処理
case "exercise":
mmtAdviceLastOpened = moment.unix(json.te);
//ボタンの最後の押下から所定の時間が経過しているか?
if(mmtNow.diff(mmtAdviceLastOpened, "hours") >= advicePeriod){
//アドバイス画面表示
openModal("modal-advice-exercise");
//アドバイスランダム表示
$advDiv = $("#modal-advice-exercise>div");
pos = Math.floor(Math.random() * $advDiv.children("dl").length);
$advDiv.children("dl").eq(pos).appendTo($advDiv);
//閉じるボタン設定
$("#modal-advice-exercise a.btn-close").data("nextContent", "modal-" + mId);
//データ更新
json.te = mmtNow.unix();
updateData();
}else{
//MENUコンテンツ表示
openModal("modal-" + mId);
}
break;
//「お通じ」処理
case "bowel":
//MENUコンテンツ表示
openModal("modal-" + mId);
break;
}
}
//MENU終了
function closeMenu(){
console.log("closeMenu");
/*
switch($(".modal-checksheet.visible").attr("id")){
case "modal-food":
break;
case "modal-yogurt":
break;
case "modal-exercise":
break;
case "modal-jikkan":
break;
case "modal-bowel":
break;
}
*/
//データ更新
//updateData();
//モーダル消去
closeModal();
//現在時刻取得
//updateMmtNow();
//mmtNow = moment().add(15,"days");
//データ上の最新ターンの最新データの日付と現在の日付との差異を取得
//diff = mmtNowBegin.diff(moment(mmtFirst).add(oTurn.l.length - 1, "days"), "days");
//ホーム画面表示更新
updateHomeScreen();
}
//モーダルオーバーレイ表示
function openModal(contentId){
console.log("openModal", contentId);
$("body").addClass("modal-open");
//ホーム画面表示ステータス更新
isHome = false;
$("#modal")
.removeClass()
.addClass(contentId)
.stop()
.fadeIn()
.scrollTop(0);
showModalContent(contentId);
}
//モーダルオーバーレイ消去
function closeModal(){
console.log("closeModal");
//変数が保持されていた場合に更新
if(savedTurnId != undefined){
setTurnId(savedTurnId);
setDayId(savedDayId);
savedTurnId = savedDayId = undefined;
}
//消去
$("#modal").stop().fadeOut(function(){
$("body").removeClass("modal-open");
$("#modal").removeClass();
$("#modal .visible").removeClass("visible");
});
}
//モーダルコンテンツ表示
function showModalContent(mId){
console.log("showModalContent", mId);
//#modalにクラス指定
if(! $("#modal").is("." + mId)){
$("#modal").addClass(mId);
}
//指定コンテンツ表示
if($("#modal>.visible").length > 0){
$("#modal>.visible").removeClass("visible").delay(340).queue(function(){
$("#"+mId).addClass("visible");
//指定コンテンツ初期化
initModalContent();
});
}else{
$("#"+mId).addClass("visible");
//指定コンテンツ初期化
initModalContent();
}
}
//モーダルコンテンツ消去
function hideModalContent(nextId){
console.log("hideModalContent", nextId);
$("#modal>.visible").removeClass("visible");
setTimeout(function(){
//#modalのクラス削除
$("#modal").removeClass();
//指定コンテンツ表示
showModalContent(nextId);
}, 340);
}
//モーダルコンテンツ初期化
function initModalContent(){
console.log("initModalContent", $("#modal .visible").attr("id"));
//データの値を反映
switch($("#modal .visible").attr("id")){
case "modal-food":
arrFood = dec2arr(oDay.f, 15, 2, true);
$.each(arrFood, function(i){
if(this == 1){
$("[name='check-food'][value='"+i+"']").prop("checked", true);
}else{
$("[name='check-food'][value='"+i+"']").prop("checked", false);
}
});
break;
case "modal-exercise":
arrExercise = dec2arr(oDay.e, 15, 2, true);
$.each(arrExercise, function(i){
if(this == 1){
$("[name='check-exercise'][value='"+i+"']").prop("checked", true);
}else{
$("[name='check-exercise'][value='"+i+"']").prop("checked", false);
}
});
break;
case "modal-yogurt":
$("[name='check-yogurt']").each(function(i){
$(this).prop("checked", (i < oDay.y));
});
break;
case "modal-jikkan":
$("[name='check-jikkan']").each(function(i){
$(this).prop("checked", (parseInt($(this).prop("value")) == oDay.j));
});
break;
case "modal-bowel":
console.log(oDay.b);
if(oDay.b == 1){
//$("[name='check-bowel'][value='0']]").prop("checked", false);
$("[name='check-bowel'][value='1']").prop("checked", true);
}else{
$("[name='check-bowel'][value='0']").prop("checked", true);
//$("[name='check-bowel'][value='1]]").prop("checked", false);
}
break;
case "modal-todayscheck":
val = 0;
//チェックマーク
$("#modal-todayscheck .menus td").removeClass("checked");
if(oDay.f > 0){
$("#modal-todayscheck .menus td.food").addClass("checked");
val++;
}
if(oDay.e > 0){
$("#modal-todayscheck .menus td.exercise").addClass("checked");
val++;
}
if(oDay.y > 0){
$("#modal-todayscheck .menus td.yogurt").addClass("checked");
val++;
}
if(oDay.j > 0){
$("#modal-todayscheck .menus td.jikkan").addClass("checked");
val++;
}
if(oDay.b > 0){
$("#modal-todayscheck .menus td.bowel").addClass("checked");
}
//プログラムコンプリート度
$("#modal-todayscheck .complete td dl").removeClass("show");
$("#modal-todayscheck .complete td dl.status-" + val).addClass("show");
break;
case "modal-aboutsite":
$("#modal").scrollTop(0);
break;
}
//リサイズイベント発生
$(window).trigger("resize");
}
//フォーム値変更ハンドラ
function onFormChange(e){
console.log("onFormChange");
var $elem = $(e.target);
switch($elem.prop("name")){
case "check-food":
//チェック内容を配列化
arrFood = dec2arr(oDay.f, 15, 2, true);
for(i=0;i<arrFood.length;i++){
arrFood[i] = ($("[name='check-food'][value='"+i+"']").prop("checked"))?1:0;
}
//jsonに記録
oDay.f = arr2dec(arrFood,2);
break;
case "check-exercise":
//チェック内容を配列化
arrExercise = dec2arr(oDay.e, 15, 2, true);
for(i=0;i<arrExercise.length;i++){
arrExercise[i] = ($("[name='check-exercise'][value='"+i+"']").prop("checked"))?1:0;
}
//jsonに記録
oDay.e = arr2dec(arrExercise,2);
break;
case "check-yogurt":
//jsonに記録
oDay.y = $("[name='check-yogurt']:checked").length;
break;
case "check-bowel":
//jsonに記録
oDay.b = $("[name='check-bowel']:checked").val();
break;
case "check-jikkan":
//jsonに記録
oDay.j = $("[name='check-jikkan']:checked").val();
break;
}
//データ更新
updateData();
}
//リサイズハンドラ
function onResize(){
var iH = window.innerHeight;
var modalPaddingH = 13 * 2;
//モーダル:チェックシートの高さ(FOOD、EXERCISE)
$(".modal-open .modal-checksheet").each(function(i){
if($(this).css("display") == "block"){
var sheetH = iH - modalPaddingH - ($(this).outerHeight() - $(this).find(".checksheet>.fit-height").height());
$(this).find(".checksheet>.fit-height").height(sheetH);
}
});
}
//モード変更
function switchMode(mode){
console.log("switchMode", mode);
switch(mode){
case "main":
//変数更新
currentMode = "main";
isHome = true;
//領域の表示
$("#main").slideDown();
$("#result").slideUp();
$("body").animate({
"scrollTop" : 0
}, "normal", function(){
clearResult();
});
break;
case "result":
//変数更新
currentMode = "result";
isHome = false;
//領域の表示
$("#main").slideUp();
$("#result").slideDown();
$("body").animate({
"scrollTop" : 0
}, "normal");
//表示の更新
updateResult();
break;
}
}
//#result更新
function updateResult(){
console.log("updateResult");
var $unit, $tr;
//表示のクリア
clearResult();
//ターン分複製
for(i=0;i<json.tn.length;i++){
o = tnCookies[json.tn[i]];
$unit = $("#result-unit-container>.result-unit-original").clone(true).removeClass("result-unit-original").addClass("result-unit");
$unit.prependTo("#result-unit-container").addClass("result-" + i);
//見出し
if(i == (json.tn.length - 1)){
$unit.find("h3").text("今回のチャレンジ結果");
}else{
$unit.find("h3").text((i+1) + "回目のチャレンジ結果");
}
//行複製&データ反映
for(ii=0;ii<o.l.length;ii++){
d = o.l[ii];
//行複製
$tr = $unit.find("tbody>tr.original").clone(true).removeClass("original");
$tr.appendTo($unit.find("table>tbody"));
$tr.data({
turn: i,
day: ii
});
//DAY記述
$tr.find(".cell-day>a").text((ii+1));
//コンプリート度
$tr.find(".cell-check").addClass("status-" + d.s);
//お通じ
if(d.b > 0){
$tr.find(".cell-bowel").addClass("checked");
}
}
//各ターンの評価
o.r = 0; //現状は意味ナシ
}
}
//#resultクリア
function clearResult(){
console.log("clearResult")
$(".result-unit").remove();
}
//#resultから今日のチェックを開く
//#resultから編集画面を開く
//Cookieのクリア
function clearAllCookies(){
console.log("clearAllCookies");
//クリア時点での最新のCookieを取得
var currentJson = Cookies.getJSON("json");
//ターンCookieのクリア
for(i=0;i<currentJson.tn.length;i++){
Cookies.remove(currentJson.tn[i], {path: "/14dayschallenge/app/"});
}
//ベースCookieのクリア
Cookies.remove("json", {path: "/14dayschallenge/app/"});
}
//mmtNowの更新
function updateMmtNow(){
var mmtDiff;
mmtNow = moment();
mmtNowBegin = moment({
"year": mmtNow.year(),
"month": mmtNow.month(),
"date": mmtNow.date(),
"hour": dailyPeriod[0],
"minute": dailyPeriod[1],
"second": 0,
"millisecond": 0
});
if(mmtNow.isBefore(mmtNowBegin)){
//区切り時間到達前であれば当該日の開始時刻は前日の同時刻
mmtNowBegin.subtract(1,"days");
}
console.log("updateMmtNow", mmtNow.format(), mmtNowBegin.format(), dailyPeriod);
}
//mmtFirstのセット
function setMmtFirst(y,m,d){
mmtFirst = moment({
"year": y,
"month": m,
"date": d,
"hour": dailyPeriod[0],
"minute": dailyPeriod[1],
"second": 0,
"millisecond": 0
});
}
//日またぎ処理
function checkDate(){
console.log("checkDate");
//処理中のjsonオブジェクトの更新日と実際のCookieの更新日が一致しない場合はリロードを喚起
checkCookieUpdate();
//ホーム画面表示中であればひまたぎ処理実行
if(isHome){
//現在時刻更新
updateMmtNow();
//現在表示中のターンはCookie上の最新ターンか?
if(turnId == (json.tn.length - 1)){
console.log("日またぎ処理:現在表示中のターンはCookie上の最新ターン");
console.log("mmtNowBegin", mmtNowBegin.format());
console.log("mmtFirst", mmtFirst.format());
//Cookie上の実行中ターンの最新日と現在日付の差を取得
diff = mmtNowBegin.diff(moment(mmtFirst).add(oTurn.l.length - 1, "days"), "days");
//Cookie上の実行中ターンの初日と現在日付の差を取得
diffB = mmtNowBegin.diff(mmtFirst, "days");
//現在のターンの最新DAYと、現在時刻(の基準日)は一致するか?
if((diff == 0) && (diffB < dayPerTurn)){
console.log("日またぎ処理:現在のターンの最新DAYと、現在時刻(の基準日)は一致→日またぎ処理なし");
}else{
console.log("日またぎ処理:現在のターンの最新DAYと、現在時刻(の基準日)は不一致");
//Cookie上の最新日と現在日付の差が13日以内か?
if((diff < dayPerTurn) && (diffB < dayPerTurn)){
console.log("Cookie上の最新日と現在日付の差:13日以内");
//Cookie上の最新日と現在日付の間の空白日付分のダミーデータを作成
for(i=0;i<diff;i++){
//DAYデータ新規作成
addDayData(turnId);
}
//データ更新
updateData();
//変数更新
updateVars();
}else{
console.log("Cookie上の最新日と現在日付の差:14日以上");
//Cookie上の実行中のターンの記録を「終了」に変更
oTurn.s = 1;
//新ターンデータ作成
addTurnData();
//DAYデータ新規作成
addDayData(json.tn.length - 1);
//データ更新
updateData();
//変数更新
updateVars();
}
//ホーム画面表示更新
updateHomeScreen();
}
}else{
console.log("日またぎ処理:現在表示中のターンはCookie上の最新ターンではない→日またぎ処理なし");
}
}
}
//Cookieが裏で更新された場合のリロード喚起処理
function checkCookieUpdate(){
console.log("checkCookieUpdate");
var presentJSON = Cookies.getJSON("json");
if(presentJSON != undefined){
if((presentJSON.updated != undefined) && (json.updated != undefined) &&(presentJSON.updated != json.updated)){
var reload = confirm("Cookieのデータが裏で更新されました。閲覧中のページを再読込して更新されたデータを反映してください。閲覧中のページを再読込しますか?");
if(reload){
location.href = (location.protocol + "//" + location.host + location.pathname + "?course=" + presentJSON.cs + presentJSON.lv);
}
}
}
}
})(jQuery);
//URLのクエリストリングをオブジェクト化
function query2object(){
var q = location.search.split("?"), a, i, s, o;
if(q.length > 1){
o = {};
q = q[1];
a = q.split("&");
for(i=0;i<a.length;i++){
s = a[i].split("=");
if(!o[s[0]]){
o[s[0]] = [s[1]];
}else{
o[s[0]].push(s[1]);
}
}
}
return o;
}
//10進数の数値をn進数表記の配列(最低digit桁の)に変換
//※convオプションをtrueにすると数値として配列に格納
function dec2arr(val, digit, n, conv){
var a, i, d;
if(!n){
n = 2;
}
a = val.toString(n).split("");
if(a.length < digit){
d = digit - a.length;
for(i=0;i<d;i++){
a.unshift("0");
}
}
if(conv){
for(i=0;i<a.length;i++){
a[i] = parseInt(a[i]);
}
}else{
a = a.join("");
}
return a;
}
//n進数表記の配列を10進数の数値に変換
function arr2dec(arr, n){
if(!n){
n = 2;
}
return parseInt(arr.join(""),n);
}
<file_sep>/bio/gensen/kodawari/wakankitsublend/js/recipe.bundle.js
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var clickCount = 0;
// ==================================================
var ClickAttention = (function () {
function ClickAttention(el) {
this.isReplayTime = false;
this.isHover = false;
this.el = el;
$(this.el).parent().on('mouseenter', this.mouseEnter.bind(this));
$(this.el).parent().on('mouseleave', this.mouseOut.bind(this));
var line_tx = 54;
var line_ty = 15;
this.tlFrame = anime.timeline({ autoplay: false, complete: this.playComplete.bind(this) });
this.tlFrame
.add({
targets: $(this.el).find('.click_frame')[0],
translateY: [4, 0],
scale: [0, 1],
opacity: [0, 1],
delay: 100,
duration: 200,
easing: 'easeOutSine'
});
this.tlText = anime.timeline({ autoplay: false, complete: this.playComplete.bind(this) });
this.tlText
.add({
targets: $(this.el).find('.click_text')[0],
scale: [0, 1],
opacity: [0, 1],
delay: 400,
duration: 350,
easing: 'easeOutBack'
});
setTimeout(function () {
this.play();
}.bind(this), 1000);
}
ClickAttention.prototype.mouseEnter = function () {
// console.info("hover");
this.isHover = true;
};
ClickAttention.prototype.mouseOut = function () {
// console.info("out");
this.isHover = false;
if (this.isReplayTime) {
this.fadeOut();
}
};
ClickAttention.prototype.play = function () {
// console.info("play");
this.isReplayTime = false;
this.completeCount = 0;
this.tlFrame.restart();
this.tlText.restart();
};
ClickAttention.prototype.playComplete = function () {
this.completeCount++;
if (this.completeCount === 2) {
setTimeout(this.replay.bind(this), 2500);
}
};
ClickAttention.prototype.replay = function () {
if (this.isHover) {
this.isReplayTime = true;
}
else {
this.fadeOut();
}
};
ClickAttention.prototype.fadeOut = function () {
anime({
targets: this.el,
opacity: [1, 0],
duration: 100,
easing: 'easeInOutQuad',
complete: this.fadeOutComplete.bind(this)
});
};
ClickAttention.prototype.fadeOutComplete = function () {
// console.info("* fadeOutComplete");
setTimeout(function () {
$(this.el).css({ opacity: 1 });
this.play();
}.bind(this), 300);
};
return ClickAttention;
}());
// ==================================================
var Taste = (function () {
function Taste() {
this.enabled = true;
this.sy = 0;
}
Taste.prototype.init = function (positions) {
this.el = $('.' + this.name);
this.showInfo = [];
for (var i = 0; i < positions.length; i++) {
this.showInfo[i] = { y: positions[i], time: -1, show: false };
}
};
Taste.prototype.getManifest = function () {
var m = jQuery.extend(true, [], this.manifest);
m.forEach(function (v) {
v.id = this.name + '_' + v.id;
v.src = 'img/' + this.name + '-' + v.src;
}.bind(this));
return m;
};
Taste.prototype.create = function (queue) {
this.queue = queue;
this.manifest.forEach(function (v) {
switch (v.id) {
case 'bg':
this.el.find('.tasteInner').append('<div class="' + v.id + '"></div>');
this.el.find('.tasteInner .' + v.id).append(this.getResult(v.id));
break;
case 'title':
this.el.find('.tasteContent').append('<div class="' + v.id + '"></div>');
this.el.find('.tasteContent .' + v.id).append(this.getResult(v.id).firstChild);
break;
default:
this.el.find('.tasteContent').append('<div class="' + v.id + '"></div>');
this.el.find('.tasteContent .' + v.id).append(this.getResult(v.id));
}
if (this.enabled === false) {
this.el.find('.' + v.id).css({
opacity: 1
});
}
}.bind(this));
if (this.enabled) {
$(document).on('scroll.' + this.name, this.scrollCheck.bind(this));
}
};
Taste.prototype.kodawari = function () {
if (0 < this.el.find('.chefkodawari').length) {
this.el.find('.chefkodawari a').modaal();
$.each(this.el.find('.chefkodawari'), function (index, kodawaribtn) {
var click = this.queue.getResult('kodawaribtn_click').firstChild.cloneNode(true);
$(kodawaribtn).append(click);
// if (clickCount % 2 === 0) {
// $(click).addClass('l');
// } else {
// $(click).addClass('r');
// }
clickCount++;
new ClickAttention(click);
}.bind(this));
}
};
Taste.prototype.showTitle = function () {
anime({
targets: '.' + this.name + ' .title-circle1',
strokeDasharray: [300, 300],
strokeDashoffset: [300, 0],
duration: 800,
easing: 'easeInQuad'
});
anime({
targets: '.' + this.name + ' .title-circle2',
strokeDasharray: [300, 300],
strokeDashoffset: [300, 0],
delay: 100,
duration: 800,
easing: 'easeInQuad'
});
anime({
targets: '.' + this.name + ' .title-text',
scale: [1.6, 1.0],
opacity: [0, 1],
delay: 700,
duration: 300,
easing: 'easeInQuad'
});
anime({
targets: '.' + this.name + ' .point',
translateX: [5, 0],
opacity: [0, 1],
delay: 800,
duration: 350,
easing: 'easeOutQuad'
});
setTimeout(function () {
this.el.find('.title').addClass('appear');
}.bind(this), 10);
};
Taste.prototype.reset = function () {
this.manifest.forEach(function (v) {
this.el.find('.' + v.id).removeAttr('style');
}.bind(this));
this.el.find('.title').removeClass('appear');
this.showInfo.forEach(function (v) {
v.time = -1;
v.show = false;
});
};
Taste.prototype.getY = function () {
var y = $(document).scrollTop() + $(window).height() - $(this.el).offset().top;
if (viewMode === 'pc') {
if (viewSize === 2) {
y *= (1 / 0.85);
}
}
return y;
};
Taste.prototype.getResult = function (id) {
return this.queue.getResult(this.name + '_' + id);
};
Taste.prototype.scrollCheck = function (evt) {
var y = this.getY();
for (var i = 0; i < this.showInfo.length; i++) {
if (this.showInfo[i].y < y && this.showInfo[i].show === false) {
this.showInfo[i].show = true;
this.showInfo[i].time = new Date().getTime();
var showDelay = this.show(i);
this.showInfo[i].time += showDelay;
break;
}
}
};
Taste.prototype.show = function (index) {
return 0;
};
return Taste;
}());
// ==================================================
var Taste1 = (function (_super) {
__extends(Taste1, _super);
function Taste1() {
var _this = _super.call(this) || this;
_this.name = 'taste1';
// this.enabled = false;
if (viewMode === 'pc') {
_this.init([150, 550]);
_this.manifest = [
{ id: 'citrus', src: 'citrus.png' },
{ id: 'effect1', src: 'effect1.png' },
{ id: 'title', src: 'title.svg' },
{ id: 'point', src: 'point.png' },
{ id: 'effect2', src: 'effect2.png' },
{ id: 'copy1', src: 'copy1.png' },
{ id: 'copy2', src: 'copy2.png' },
{ id: 'copy3', src: 'copy3.png' }
];
}
else {
_this.init([100, 350]);
_this.manifest = [
{ id: 'citrus', src: 'citrus.png' },
{ id: 'effect1', src: 'effect1@sp.png' },
{ id: 'title', src: 'title.svg' },
{ id: 'point', src: 'point.png' },
{ id: 'effect2', src: 'effect2@sp.png' },
{ id: 'copy1', src: 'copy1.png' },
{ id: 'copy2', src: 'copy2.png' },
{ id: 'copy3', src: 'copy3.png' }
];
$(_this.el).prepend('<div class="bg"><div class="bg-white"></div></div>');
}
return _this;
}
Taste1.prototype.create = function (queue) {
_super.prototype.create.call(this, queue);
this.el.find('.tasteContent').append('<div class="chefkodawari"><a href="#modal7"><img alt="" src="../img/kodawaribtn.svg"></a></div>');
};
Taste1.prototype.show = function (index) {
var spendTime = (index === 0) ? 0 : this.showInfo[index].time - this.showInfo[index - 1].time;
var delay = 0;
if (viewMode === 'pc') {
switch (index) {
case 0:
this.showTitle();
break;
case 1:
delay = Math.max(0, 1200 - spendTime);
anime({
targets: '.' + this.name + ' .copy1',
opacity: [0, 1],
delay: delay,
duration: 400,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy2',
scale: [1.4, 1],
opacity: [0, 1],
delay: delay + 500,
duration: 1100,
easing: 'easeOutQuint'
});
anime({
targets: '.' + this.name + ' .copy3',
opacity: [0, 1],
scale: [0.8, 1],
delay: delay + 700,
duration: 700,
easing: 'easeOutQuint'
});
anime({
targets: '.' + this.name + ' .effect1',
opacity: [0, 1],
scale: [0.7, 1],
delay: delay + 500,
duration: 1500,
easing: 'easeOutQuint'
});
anime({
targets: '.' + this.name + ' .citrus',
opacity: [0, 1],
delay: delay + 1200,
duration: 800,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .effect2',
opacity: [0, 1],
delay: delay + 1600,
duration: 600,
scale: [0.75, 1],
easing: 'easeOutQuint'
});
break;
}
}
else {
switch (index) {
case 0:
this.showTitle();
break;
case 1:
delay = Math.max(0, 1200 - spendTime);
anime({
targets: '.' + this.name + ' .copy1',
opacity: [0, 1],
delay: delay,
duration: 400,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy2',
scale: [1.4, 1],
opacity: [0, 1],
delay: delay + 500,
duration: 1100,
easing: 'easeOutQuint'
});
anime({
targets: '.' + this.name + ' .copy3',
opacity: [0, 1],
scale: [0.8, 1],
delay: delay + 700,
duration: 700,
easing: 'easeOutQuint'
});
anime({
targets: '.' + this.name + ' .effect1',
opacity: [0, 1],
scale: [0.7, 1],
delay: delay + 500,
duration: 1500,
easing: 'easeOutQuint'
});
anime({
targets: '.' + this.name + ' .citrus',
opacity: [0, 1],
delay: delay + 1200,
duration: 800,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .effect2',
opacity: [0, 1],
delay: delay + 1600,
duration: 600,
scale: [0.75, 1],
easing: 'easeOutQuint'
});
break;
}
}
return delay;
};
return Taste1;
}(Taste));
// ==================================================
var Taste2 = (function (_super) {
__extends(Taste2, _super);
function Taste2() {
var _this = _super.call(this) || this;
_this.name = 'taste2';
// this.enabled = false;
if (viewMode === 'pc') {
_this.init([150, 250]);
_this.manifest = [
{ id: 'citrus1', src: 'citrus1.png' },
{ id: 'citrus2', src: 'citrus2.png' },
{ id: 'effect', src: 'effect.png' },
{ id: 'title', src: 'title.svg' },
{ id: 'point', src: 'point.png' },
{ id: 'circle', src: 'circle.png' },
{ id: 'copy6', src: 'copy6.png' },
{ id: 'copy7', src: 'copy7.png' },
{ id: 'copy8', src: 'copy8.png' }
];
}
else {
_this.init([100, 300, 500]);
_this.manifest = [
{ id: 'citrus1', src: 'citrus1.png' },
{ id: 'citrus2', src: '<EMAIL>' },
{ id: 'title', src: 'title.svg' },
{ id: 'point', src: 'point.png' },
{ id: 'effect', src: '<EMAIL>' },
{ id: 'circle', src: '<EMAIL>' },
{ id: 'copy6', src: 'copy6.png' },
{ id: 'copy7', src: 'copy7.png' },
{ id: 'copy8', src: '<EMAIL>' }
];
}
return _this;
}
Taste2.prototype.create = function (queue) {
_super.prototype.create.call(this, queue);
if (viewMode === 'pc') {
this.el.find('.circle').after('<div class="chefkodawari"><a href="#modal8"><img alt="" src="../img/kodawaribtn.svg"></a></div>');
}
else {
this.el.find('.tasteContent').append('<div class="chefkodawari"><a href="#modal8"><img alt="" src="../img/kodawaribtn.svg"></a></div>');
}
};
Taste2.prototype.reset = function () {
_super.prototype.reset.call(this);
};
Taste2.prototype.show = function (index) {
var spendTime = (index === 0) ? 0 : this.showInfo[index].time - this.showInfo[index - 1].time;
var delay = 0;
if (viewMode === 'pc') {
switch (index) {
case 0:
this.showTitle();
break;
case 1:
delay = Math.max(0, 1300 - spendTime);
anime({
targets: '.' + this.name + ' .citrus1',
opacity: [0, 1],
scale: [1.01, 1],
delay: delay,
duration: 600,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .circle',
opacity: [0, 1],
scale: [0.98, 1],
translateY: [20, 0],
delay: delay,
duration: 1500,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy6',
clip: ['rect(0 0 112px 0)', 'rect(0 496px 112px 0)'],
translateX: [25, 0],
opacity: [0, 1],
delay: delay,
duration: 1200,
easing: 'easeInOutQuart'
});
anime({
targets: '.' + this.name + ' .copy7',
opacity: [0, 1],
scale: [0.95, 1],
delay: delay + 1300,
duration: 400,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy8',
clip: ['rect(0 0 104px 0)', 'rect(0 298px 104px 0)'],
opacity: [0, 1],
scale: [1.07, 1],
delay: delay + 1900,
duration: 600,
easing: 'easeOutQuart'
});
anime({
targets: '.' + this.name + ' .citrus2',
opacity: [0, 1],
scale: [1.03, 1],
delay: delay + 1300,
duration: 600,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .effect',
opacity: [0, 1],
scale: [0.9, 1],
delay: delay + 1000,
duration: 1000,
easing: 'easeOutQuint'
});
break;
}
}
else {
switch (index) {
case 0:
this.showTitle();
break;
case 1:
delay = Math.max(0, 1200 - spendTime);
anime({
targets: '.' + this.name + ' .circle',
opacity: [0, 1],
scale: [0.98, 1],
translateY: [20, 0],
delay: delay + 800,
duration: 3000,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .citrus1',
opacity: [0, 1],
scale: [1.01, 1],
delay: delay + 800,
duration: 600,
easing: 'easeOutSine'
});
break;
case 2:
delay = Math.max(0, 1200 - spendTime);
anime({
targets: '.' + this.name + ' .effect',
opacity: [0, 1],
scale: [0.9, 1],
delay: delay + 400,
duration: 1500,
easing: 'easeOutQuint'
});
anime({
targets: '.' + this.name + ' .copy6',
clip: ['rect(0 0 112px 0)', 'rect(0 496px 112px 0)'],
translateX: [16, 0],
opacity: [0, 1],
delay: delay,
duration: 600,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy7',
opacity: [0, 1],
scale: [0.95, 1],
delay: delay + 1000,
duration: 400,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy8',
clip: ['rect(0 0 104px 0)', 'rect(0 298px 104px 0)'],
translateX: [16, 0],
opacity: [0, 1],
delay: delay + 1500,
duration: 600,
easing: 'easeOutQuart'
});
anime({
targets: '.' + this.name + ' .citrus2',
opacity: [0, 1],
scale: [1.03, 1],
delay: delay + 1100,
duration: 600,
easing: 'easeOutSine'
});
break;
}
}
return delay;
};
return Taste2;
}(Taste));
// ==================================================
var Taste3 = (function (_super) {
__extends(Taste3, _super);
function Taste3() {
var _this = _super.call(this) || this;
_this.name = 'taste3';
if (viewMode === 'pc') {
_this.init([150, 300, 800, 1100]);
_this.manifest = [
{ id: 'title', src: 'title.svg' },
{ id: 'point', src: 'point.png' },
{ id: 'citrus', src: 'citrus.png' },
{ id: 'circle', src: 'circle.png' },
{ id: 'scene', src: 'scene.png' },
{ id: 'productname', src: 'productname.png' },
{ id: 'product', src: 'product.png' },
{ id: 'fruits', src: 'fruits.png' },
{ id: 'effect', src: 'effect.png' },
{ id: 'catch', src: 'catch.png' },
{ id: 'copy1', src: 'copy1.png' },
{ id: 'copy2', src: 'copy2.png' },
{ id: 'copy3', src: 'copy3.png' },
{ id: 'copy4', src: 'copy4.png' },
{ id: 'copy5', src: 'copy5.png' },
{ id: 'copy6', src: 'copy6.png' },
{ id: 'copy7', src: 'copy7.png' }
];
}
else {
_this.init([100, 250, 500, 800]);
_this.manifest = [
{ id: 'title', src: 'title.svg' },
{ id: 'point', src: 'point.png' },
{ id: 'citrus', src: 'citrus.png' },
{ id: 'circle', src: '<EMAIL>' },
{ id: 'scene', src: '<EMAIL>' },
{ id: 'productname', src: '<EMAIL>' },
{ id: 'product', src: '<EMAIL>' },
{ id: 'fruits', src: '<EMAIL>' },
{ id: 'effect', src: '<EMAIL>' },
{ id: 'catch', src: '<EMAIL>' },
{ id: 'copy1', src: 'copy1.png' },
{ id: 'copy2', src: 'copy2.png' },
{ id: 'copy3', src: 'copy3.png' },
{ id: 'copy4', src: 'copy4.png' },
{ id: 'copy5', src: 'copy5.png' },
{ id: 'copy6', src: 'copy6.png' },
{ id: 'copy7', src: 'copy7.png' }
];
}
return _this;
}
Taste3.prototype.show = function (index) {
var spendTime = (index === 0) ? 0 : this.showInfo[index].time - this.showInfo[index - 1].time;
var delay = 0;
if (viewMode === 'pc') {
switch (index) {
case 0:
this.showTitle();
break;
case 1:
delay = 1200;
// copy
anime({
targets: '.' + this.name + ' .copy1',
opacity: [0, 1],
scale: [1.1, 1],
rotate: [10, 0],
delay: delay,
duration: 600,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy2',
opacity: [0, 1],
scale: [1.1, 1],
rotate: [-5, 0],
delay: delay + 200,
duration: 600,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy3',
opacity: [0, 1],
scale: [1.2, 1],
rotate: [-8, 0],
delay: delay + 400,
duration: 600,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy4',
opacity: [0, 1],
scale: [1.3, 1],
delay: delay + 500,
duration: 600,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .bg1',
opacity: [0, 1],
delay: delay,
duration: 1500,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .circle',
opacity: [0, 1],
translateY: [10, 0],
delay: delay + 180,
duration: 700,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .citrus',
opacity: [0, 1],
scale: [1.03, 1],
delay: delay + 600,
duration: 500,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .effect',
opacity: [0, 1],
delay: delay + 1000,
duration: 400,
easing: 'easeOutSine'
});
break;
case 2:
delay = Math.max(0, 1000 - spendTime);
anime({
targets: '.' + this.name + ' .bg2',
opacity: [0, 1],
delay: delay,
duration: 3000,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy5',
opacity: [0, 1],
translateY: [12, 0],
delay: delay + 100,
duration: 350,
easing: 'easeOutQuart'
});
anime({
targets: '.' + this.name + ' .copy6',
opacity: [0, 1],
delay: delay + 600,
duration: 700,
easing: 'easeInOutSine'
});
anime({
targets: '.' + this.name + ' .copy7',
opacity: [0, 1],
delay: delay + 700,
duration: 600,
easing: 'easeInOutSine'
});
break;
case 3:
delay = Math.max(0, 500 - spendTime);
anime({
targets: '.' + this.name + ' .scene',
opacity: [0, 1],
scale: [0.97, 1],
delay: delay + 400,
duration: 650,
easing: 'easeOutQuart'
});
anime({
targets: '.' + this.name + ' .catch',
opacity: [0, 1],
translateY: [20, 0],
delay: delay + 1000,
duration: 300,
easing: 'easeOutBack'
});
break;
}
}
else {
switch (index) {
case 0:
this.showTitle();
anime({
targets: '.' + this.name + ' .bg1',
opacity: [0, 1],
delay: delay,
duration: 1500,
easing: 'easeOutSine'
});
break;
case 1:
delay = 0;
anime({
targets: '.' + this.name + ' .circle',
opacity: [0, 1],
translateY: [10, 0],
delay: delay,
duration: 700,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .citrus',
opacity: [0, 1],
scale: [1.03, 1],
delay: delay + 300,
duration: 500,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .effect',
opacity: [0, 1],
delay: delay + 700,
duration: 400,
easing: 'easeOutSine'
});
break;
case 2:
delay = Math.max(0, 1300 - spendTime);
// copy
anime({
targets: '.' + this.name + ' .copy1',
opacity: [0, 1],
scale: [1.1, 1],
rotate: [10, 0],
delay: delay,
duration: 600,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy2',
opacity: [0, 1],
scale: [1.1, 1],
rotate: [-5, 0],
delay: delay + 200,
duration: 600,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy3',
opacity: [0, 1],
scale: [1.2, 1],
rotate: [-8, 0],
delay: delay + 400,
duration: 600,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy4',
opacity: [0, 1],
scale: [1.3, 1],
delay: delay + 500,
duration: 600,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .bg2',
opacity: [0, 1],
delay: delay,
duration: 3000,
easing: 'easeOutSine'
});
anime({
targets: '.' + this.name + ' .copy5',
opacity: [0, 1],
translateY: [12, 0],
delay: delay + 1100,
duration: 500,
easing: 'easeOutQuart'
});
anime({
targets: '.' + this.name + ' .copy6',
opacity: [0, 1],
delay: delay + 1600,
duration: 700,
easing: 'easeInOutSine'
});
anime({
targets: '.' + this.name + ' .copy7',
opacity: [0, 1],
delay: delay + 1700,
duration: 600,
easing: 'easeInOutSine'
});
break;
case 3:
delay = Math.max(0, 2000 - spendTime);
anime({
targets: '.' + this.name + ' .scene',
opacity: [0, 1],
scale: [0.97, 1],
delay: delay,
duration: 650,
easing: 'easeOutQuart'
});
anime({
targets: '.' + this.name + ' .catch',
opacity: [0, 1],
translateY: [20, 0],
delay: delay + 400,
duration: 300,
easing: 'easeOutBack'
});
break;
}
}
return delay;
};
Taste3.prototype.create = function (queue) {
_super.prototype.create.call(this, queue);
if (viewMode === 'pc') {
this.el.find('.tasteContent').append('<div class="chefkodawari"><a href="#modal9"><img alt="" src="../img/kodawaribtn.svg"></a></div>');
}
else {
this.el.find('.tasteContent .catch').after('<div class="chefkodawari"><a href="#modal9"><img alt="" src="../img/kodawaribtn.svg"></a></div>');
}
};
Taste3.prototype.reset = function () {
_super.prototype.reset.call(this);
};
return Taste3;
}(Taste));
// ==================================================
// setup
var loadQueue;
var loadBgQueue;
var tastes;
var status;
var viewMode;
var viewSize = 1; // ~900 / 901~1179 / 1180
function setup() {
status = 'loading';
var ua = navigator.userAgent;
if (ua.indexOf('iPhone') > 0 || ua.indexOf('iPod') > 0 || ua.indexOf('Android') > 0 && ua.indexOf('Mobile') > 0) {
// スマートフォン用コード
viewMode = 'sp';
}
else if (ua.indexOf('iPad') > 0 || ua.indexOf('Android') > 0) {
// タブレット用コード
viewMode = 'pc';
if (ua.indexOf('Android') > 0 && window.outerWidth < 768) {
viewMode = 'sp';
}
}
else {
// PC用コード
viewMode = 'pc';
}
// viewMode = 'sp';
$('#page-body').addClass(viewMode);
if (viewMode === 'pc') {
$('#page-body .hero .products li:nth-child(1)').prepend('<h3 class="productname1"></h3>');
$('#page-body .hero .products li:nth-child(2)').prepend('<h3 class="productname2"></h3>');
$('#page-body .hero .products li:nth-child(3)').prepend('<h3 class="productname3"></h3>');
$('#page-body .hero .products li:nth-child(3)').prepend('<p class="season-limited"></p>');
$('#page-body .heroInner').append('<p class="chefname"><img alt="" src="../img/hero-chefname.svg"></p>');
$('#page-body .heroInner').append('<p class="scroll"><img alt="" src="../img/scroll.svg"></p>');
$('#page-body .recipelink').before('<p class="replaybtn"><img alt="" src="../img/replaybtn.svg"></p>');
}
else {
$('#page-body .hero .lead').before($('#page-body .hero .products'));
$('#page-body .hero .products li:nth-child(1)').append('<h3 class="productname1"></h3>');
$('#page-body .hero .products li:nth-child(2)').append('<h3 class="productname2"></h3>');
$('#page-body .hero .products li:nth-child(3)').append('<h3 class="productname3"></h3>');
$('#page-body .hero .products li:nth-child(3)').append('<p class="season-limited"></p>');
}
$('img.chimg').each(function (index) {
// console.info(img);
$(this).attr('src', $(this).attr('data-' + viewMode));
});
var taste;
var manifest = [
{ id: 'taste-title', src: 'img/taste-title.png' },
{ id: 'kodawaribtn_click', src: '../img/kodawaribtn_click.svg' }
];
loadQueue = new createjs.LoadQueue();
loadQueue.setMaxConnections(10);
tastes = [];
taste = new Taste1();
manifest = manifest.concat(taste.getManifest());
tastes.push(taste);
taste = new Taste2();
manifest = manifest.concat(taste.getManifest());
tastes.push(taste);
taste = new Taste3();
manifest = manifest.concat(taste.getManifest());
tastes.push(taste);
loadQueue = new createjs.LoadQueue();
loadQueue.on("progress", loadProgress);
loadQueue.on("complete", loadComplete);
loadQueue.loadManifest(manifest);
loadBgQueue = new createjs.LoadQueue();
loadBgQueue.setPreferXHR(false);
if (viewMode === 'pc') {
loadQueue.loadManifest([
'../img/hero-bg.jpg'
]);
}
else {
loadQueue.loadManifest([
'../img/hero-bg@sp.jpg'
]);
}
$(window).on('resize', layout);
layout();
$('.loaderOuter').addClass('appear');
}
function loadProgress(evt) {
// console.info(evt);
$('#page-body .loading .percent').text(Math.floor(evt.loaded * 100) + '%');
}
function loadComplete() {
$('#page-body .loading .percent').addClass('complete');
anime({
targets: '.loaderOuter',
opacity: [1, 0],
delay: 80,
duration: 200,
easing: 'easeInQuad',
complete: function () {
start();
}
});
$('#page-body .container').addClass('block');
}
function start() {
status = 'main';
$('#page-body .loading').remove();
$('#page-body .container').addClass('show');
tastes.forEach(function (taste, index) {
taste.create(loadQueue);
taste.kodawari();
});
$('.tastes .taste-title').append(loadQueue.getResult('taste-title'));
$('.hero .scroll')
.addClass('show')
.on('click', function () {
$("html,body").animate({ scrollTop: Math.max(500, $(window).height()) - 170 });
});
$('.replaybtn').on('click', function (evt) {
$("html,body").animate({ scrollTop: 0 }, 1000, 'swing', function () {
replay();
});
});
$('.pagetop').on('click', function (evt) {
$("html,body").animate({ scrollTop: 0 });
});
anime({
targets: '.hero .title',
scale: [0.6, 1.0],
opacity: [0, 1],
translateY: [40, 0],
delay: 100,
duration: 400,
easing: 'easeOutBack'
});
anime({
targets: '.hero .copy',
opacity: [0, 1],
delay: 300,
duration: 300,
easing: 'easeInQuad'
});
anime({
targets: '.hero .lead',
opacity: [0, 1],
delay: 700,
duration: 300,
easing: 'easeInQuad'
});
anime({
targets: '.hero li',
opacity: [0, 1],
delay: 700,
duration: 300,
easing: 'easeInQuad'
});
}
function replay() {
tastes.forEach(function (t) {
t.reset();
});
}
function layout() {
var ww = Math.max(1040, $(window).width());
var wh = Math.max(500, $(window).height());
var hh = wh - 155;
if (status === 'loading') {
if (viewMode == 'pc') {
$('.loaderOuter').css({
top: 155 + ((hh - 130) / 2) + 'px'
});
}
else {
$('.loaderOuter').css({
top: 300 + 'px'
});
}
}
if (viewMode === 'pc') {
var _viewSize;
if (ww < 1180) {
_viewSize = 2;
}
else {
_viewSize = 1;
}
$('.hero > .heroInner').css({
height: hh + 'px'
});
var cx = Math.min(ww - 494 - 30, (ww / 2) - 30);
if (wh < 620) {
cx = Math.min(ww - 600 - 30, (ww / 2) - 30);
}
var ch = 545;
if (wh < 620) {
ch = 310;
}
else if (wh < 750) {
ch = 450;
}
$('.hero .heroContent').css({
left: cx + 'px',
top: ((hh - ch) / 2) - 20 + 'px'
});
if (_viewSize != viewSize) {
$('#page-body').removeClass('size' + viewSize).addClass('size' + _viewSize);
viewSize = _viewSize;
}
}
}
setup();
},{}]},{},[1]);
<file_sep>/bio/assets/include/recommend_to_you.html
<h3 class="ttl-line ttl-lv2">あなたへのおすすめ</h3>
<ul class="content-list about-list">
<li class="cont-wakankitsu"> <a href="/bio/content/wakankitsublend/index.html">
<div> <em>キャンペーン</em>
<p> 季節限定 国産 和柑橘ブレンド</p>
</div>
</a> </li>
<li class="cont-danone"> <a href="/bio/about/campaign04/index.html">
<div><em>キャンペーン</em>
<p> ダノン会員サイトDanOn(ダンオン)で、食べて、ためて、もらえる!</p>
</div>
</a></li>
<li class="cont-14dayschallengemenu"> <a href="/bio/about/14dayschallengemenu/index.html">
<div><em> ブランドを知る</em>
<p> 14日間チャレンジMENU配信中!</p>
</div>
</a> </li>
<li class="cont-biobrand"> <a href="/bio/about/biobrand/biobrand/index.html">
<div><em> ブランドを知る</em>
<p>世界中で選ばれてNo.1** <br>
ダノンビオが愛される理由 </p>
</div>
</a></li>
<li class="cont-quality"> <a href="/bio/content/kodawari/index.html">
<div><em> おいしさと品質</em>
<p>毎日おいしく食べていただくために、<br>
ダノンビオがこだわっていること</p>
</div>
</a> </li>
<li class="cont-interview"> <a href="/bio/about/powerofbe80/interview/index.html">
<div><em>高生存ビフィズス菌 BE80のチカラ</em>
<p>ダノンビオ ひと匙(さじ)のメッセージ</p>
</div>
</a></li>
</ul>
<file_sep>/bio/gensen/common/js/script.js
var isDebug = false;
if(! isDebug){
window.console = {};
window.console.log = function(i){return;};
window.console.time = function(i){return;};
window.console.timeEnd = function(i){return;};
}
;(function($) {
/**
* グローバル関数
*/
var Func = window.Func = function(elem){
return new Func.fn.init(elem);
};
Func.fn = {
init:function(elem){
}
};
Func.fn.init.prototype = Func.fn;
Func.util = {
isPC: function(){
if($("#page-header>.inner>#global-nav-toggler+label").css("display") == "none"){
return true;
}else{
return false;
}
},
getHeaderOffset: function(){
switch(true){
case (Func.util.isPC()):
return $("#page-header").height();
break;
case (! Func.util.isPC()):
switch(true){
case ($(".fruits-features").length > 0):
return 111;
break;
case ($(".kodawariContent").length > 0):
return 140;
break;
default:
return 70;
break;
}
break;
}
}
};
/**
* DOM Ready処理
*/
$(function(){
//スムーススクロール初期化
initSmoothScroll();
//ローカルナビ初期化
initLocalNav();
//SNSボタン初期化
initSnsBtns();
});
//スムーススクロール初期化
function initSmoothScroll(){
var href, hash;
$("a").each(function(i){
href = $(this).attr("href");
hash = "";
switch(true){
case ((href.charAt(0) == "#") && (href.length > 1)):
hash = href;
break;
case (href.indexOf(location.pathname + "#") == 0):
hash = href.split(location.pathname)[1];
break;
}
if(hash != ""){
$(this).on("click", {hash:hash}, function(e){
e.preventDefault();
smoothScrollTo(e.data.hash);
});
}
});
if(location.hash){
smoothScrollTo(location.hash);
}
}
function smoothScrollTo(elemId){
var offset = 0, speed = 500, position;
offset = Func.util.getHeaderOffset();
if($(elemId).length > 0){
position = $(elemId).offset().top - offset;
$("html, body").animate({scrollTop: position}, speed);
}
}
//ローカルナビ初期化
function initLocalNav(){
$("#global-nav>ul>li")
.on("mouseover", function(e){
if(Func.util.isPC()){
var navId = undefined;
switch(true){
case ($(this).is(":nth-child(1)")):
navId = "secret";
break;
case ($(this).is(":nth-child(2)")):
navId = "recipe";
break;
}
if(navId){
openLocalNav(navId);
}
}else{
location.href = $(this).find("a").attr("href");
}
})
.on("mouseout", function(e){
if(Func.util.isPC()){
closeLocalNav();
}
});
$("#local-nav-container")
.on("mouseenter", function(e){
if(Func.util.isPC()){
$("#local-nav-container").addClass("open");
}
})
.on("mouseleave", function(e){
if(Func.util.isPC()){
$("#local-nav-container").removeClass();
$("#local-nav-container .local-nav").removeClass("open");
}
});
$("#local-nav-container .local-nav a")
.on("mousedown", function(e){
console.log("MOUSEDOWN");
$(".local-nav-opener").prop("checked", false);
});
}
function openLocalNav(navId){
$("#local-nav-container").removeClass();
$("#local-nav-container").addClass("open");
if(navId){
$("#local-nav-container").addClass(navId);
$("#local-nav-container .local-nav").removeClass("open");
$("#local-nav-container .local-nav#local-nav-" + navId).addClass("open");
}
}
function closeLocalNav(){
$("#local-nav-container").removeClass("open");
}
//SNSボタン初期化
function initSnsBtns(){
//SNSボタン挙動
$("#sns-btns .twitter>a").on("click", function(e){
e.preventDefault();
window.open($(this).attr("href"),'tweetwindow', 'width=650, height=470, personalbar=0, toolbar=0, scrollbars=1, sizable=1');
});
$("#sns-btns .facebook>a").on("click", function(e){
e.preventDefault();
window.open($(this).attr("href"),'tweetwindow', 'width=650, height=470, personalbar=0, toolbar=0, scrollbars=1, sizable=1');
});
}
})(jQuery);<file_sep>/bio/gensen/sozai/js/script.js
;(function($) {
$(function(){
//ローカルナビ初期化
initLocalNav();
//モーダル初期化
initModals();
//ページ到達管理初期化
initReachObservation();
});
//ローカルナビ初期化
function initLocalNav(){
$(window)
.on("scroll resize orientationchange", function(e){
var valScroll = $(window).scrollTop();
var $target, posTop;
$("#local-nav-secret a").each(function(i){
$target = $("#" + $(this).attr("href").split("#")["1"]);
if($target.length > 0){
posTop = $target.position().top - Func.util.getHeaderOffset();
if((valScroll >= posTop) && (valScroll < (posTop + $target.outerHeight()))){
$(this).addClass("on");
}else{
$(this).removeClass("on");
}
}
});
})
.trigger("scroll");
$("#local-nav-secret a").on("click", function(e){
var clickedLabel = $(this).text();
console.log("クリック", clickedLabel, dataLayer);
dataLayer.push({
'event': 'localNavClicked',
'clickedNav': clickedLabel
});
//ga('send', 'event', 'localnav', 'localnav-clicked', reachedLabel);
});
}
//モーダル初期化
function initModals(){
$(".modal-launcher").each(function(i){
$(this)
.modaal({
type: "ajax",
width: 800,
hide_close: true,
overlay_opacity: 0.5,
padding: 0,
before_open: function(){
var hrefArr = $($(this)[0].$elem[0]).attr("href").split("/");
var path = hrefArr[hrefArr.length - 1];
var label;
switch(path){
case "modal-1.html":
label = "製品情報:完熟ストロベリー";
break;
case "modal-2.html":
label = "製品情報:旬摘みブルーベリー";
break;
case "modal-3.html":
label = "製品情報:ジューシーアロエ";
break;
case "modal-4.html":
label = "製品情報:フレッシュ&ドライ";
break;
case "modal-5.html":
label = "製品情報:もぎたて白桃";
break;
case "modal-6.html":
label = "製品情報:芳醇マダガスカル産バニラ";
break;
case "modal-7.html":
label = "製品情報:マンゴー&マンダリン";
break;
case "modal-8.html":
label = "製品情報:洋梨フルーツミックス";
break;
case "modal-9.html":
label = "製品情報:シチリア産レモン";
break;
case "modal-plainyogurt.html":
label = "プレーンヨーグルトについて";
break;
}
console.log("モーダル開扉:", label, dataLayer);
dataLayer.push({
'event': 'sozaiModalOpened',
'openedModalLabel': label
});
//ga('send', 'event', 'modal', 'modal-opened', label);
}
})
.on("close", function(e){
$(this).modaal("close");
});
});
}
//ページ到達管理初期化
var savedReachPos = -1;
var valScroll, valReachPos, reachedLabel, observationInit = false;
function initReachObservation(){
$(window).on("scroll resize orientationchange", observeSections).trigger("scroll");
}
function observeSections(e){
valScroll = $(window).scrollTop() + window.innerHeight;
var reached;
if(! observationInit){
$("article#page-body>section:not([data-section-read])").each(function(i){
reached = (valScroll > ($(this).position().top + $(this).height()));
$(this).attr("data-section-reached", reached);
});
observationInit = true;
}else{
$("article#page-body>section:not([data-section-read])").each(function(i){
reached = (valScroll > ($(this).position().top + $(this).height()));
if(($(this).attr("data-section-reached") == "false") && reached){
$(this).attr("data-section-read", true);
reachedLabel = $(this).find(">header h2").text();
console.log("到達:", reachedLabel, dataLayer);
dataLayer.push({
'event': 'sectionReached',
'reachedSection': reachedLabel
});
//ga('send', 'event', 'section', 'section-reached', reachedLabel);
switch($("article#page-body>section[data-section-read]").length){
case 2:
console.log("完読率:D");
dataLayer.push({
'event': 'sectionCompleted',
'completedRate': "D"
});
//ga('send', 'event', 'section-completed', 'completedRate', 'D');
break;
case 4:
console.log("完読率:C");
dataLayer.push({
'event': 'sectionCompleted',
'completedRate': "C"
});
//ga('send', 'event', 'section-completed', 'completedRate', 'C');
break;
case 6:
console.log("完読率:B");
dataLayer.push({
'event': 'sectionCompleted',
'completedRate': "B"
});
//ga('send', 'event', 'section-completed', 'completedRate', 'B');
break;
case 9:
console.log("完読率:A");
dataLayer.push({
'event': 'sectionCompleted',
'completedRate': "A"
});
//ga('send', 'event', 'section-completed', 'completedRate', 'A');
$(window).off("scroll resize orientationchange", observeSections);
break;
}
}
$(this).attr("data-section-reached", reached);
});
}
}
})(jQuery);<file_sep>/bio/gensen/sozai/js/modal.js
;(function($) {
$(function(){
$(".modal-closer").on("click", function(e){
$(".modal-launcher").modaal("close");
});
var $ulContainer = $("<div id='table-ul'></div>");
var $ul, $li;
$ul = $("<ul></ul>");
for(var i=0;i<3;i++){
$li = $("<li></li>");
var th = $(".table table>tbody>tr>th").eq(i).text();
var td = $(".table table>tbody>tr>td").eq(i).text();
$li.text(th + ":" + td);
$ul.append($li);
}
$ulContainer.append($ul);
$ul = $("<ul></ul>");
for(var i=3;i<6;i++){
$li = $("<li></li>");
var th = $(".table table>tbody>tr>th").eq(i).text();
var td = $(".table table>tbody>tr>td").eq(i).text();
$li.text(th + ":" + td);
$ul.append($li);
}
$ulContainer.append($ul);
$(".modal-prod .table").append($ulContainer);
});
})(jQuery); | 1a6da6899ef817118763c5195694ba264a41f8e1 | [
"JavaScript",
"HTML",
"Markdown"
] | 9 | HTML | wadahideyuki/danon | 34b3daf11915fa887d67c73799b302ae2d04117b | f6519ffceea6e0f7cc6d9bbff6cf67b93129b894 |
refs/heads/master | <file_sep>/*PLEASE DO NOT EDIT THIS CODE*/
/*This code was generated using the UMPLE 1.29.1.4584.3d417815a modeling language!*/
// line 94 "model.ump"
// line 155 "model.ump"
public class Weapon extends MoveableObject
{
//------------------------
// MEMBER VARIABLES
//------------------------
public enum Weapons{
Candlestick,Dagger,LeadPipe,Revolver,Rope,Spanner
}
private Weapons weapon;
//------------------------
// CONSTRUCTOR
//------------------------
public Weapon(Weapons weapon)
{
this.weapon = weapon;
}
//------------------------
// INTERFACE
//------------------------
/**
* returns the weapon
* @return the weapon
*/
public Weapons getWeapon() {
return weapon;
}
/**
* sets the weapon
* @param weapon the enum of weapon
*/
public void setWeapon(Weapons weapon) {
this.weapon = weapon;
}
/**
* toString method
* @return lower case cyan colored indicator of which weapon it is
*/
@Override
public String toString() {
return boardColoration.CYAN+Character.toString(weapon.toString().charAt(0)).toLowerCase()+ boardColoration.RESET;
}
}<file_sep>/*PLEASE DO NOT EDIT THIS CODE*/
/*This code was generated using the UMPLE 1.29.1.4584.3d417815a modeling language!*/
// line 75 "model.ump"
// line 140 "model.ump"
public class RoomCard extends Card
{
//------------------------
// ENUMERATIONS
//------------------------
public enum Room { Hallway, Kitchen, Ballroom, Conservatory, BillardRoom, Hall, Study, Library, Lounge, DiningRoom }
//------------------------
// MEMBER VARIABLES
//------------------------
//RoomCard Attributes
private Room roomName;
public RoomCard(Room roomName)
{
this.roomName = roomName;
}
//------------------------
// INTERFACE
//------------------------
/**
* returns the name of the room
* @return name of the room
*/
public Room getRoomName()
{
return roomName;
}
/**
* To string method
* @return name of the room
*/
public String toString(){
return roomName.toString();
}
} | 50c343e10302513a2bb00930b120d8faaa4e7c37 | [
"Java"
] | 2 | Java | MORGANCONN/SWEN225_ASSIGNMENT_1 | ab81620bc105e0da53dbe3281d0f0141597eba22 | 55d1e7e8aeb1ed5f8e311965ada858c03bc1f693 |
refs/heads/main | <repo_name>webdever12/Tweet-Mapper<file_sep>/README.md
# Tweet-Mapper
Tweet Mapper app allows the user to specify keywords of interest, monitors tweets and plots them on the map of the world. To do this, the app makes use of an existing geographical mapping library and the Twitter API
<file_sep>/src/filters/test/TestParser.java
package filters.test;
import filters.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test the parser.
*/
public class TestParser {
@Test
public void testAnd() throws SyntaxError {
Filter f = new Parser("trump and Ivanka").parse();
assertTrue(f instanceof AndFilter);
assertEquals(f.toString(), "(trump and Ivanka)");
Filter g = new Parser("trump and Ivanka and Melania").parse();
assertTrue(g instanceof AndFilter);
assertEquals(g.toString(), "((trump and Ivanka) and Melania)");
}
@Test
public void testOr() throws SyntaxError {
Filter f = new Parser("trump or Biden").parse();
assertTrue(f instanceof OrFilter);
assertEquals(f.toString(), "(trump or Biden)");
Filter g = new Parser("trump or Biden or Clinton").parse();
assertTrue(g instanceof OrFilter);
assertEquals(g.toString(), "((trump or Biden) or Clinton)");
}
@Test
public void testBasic() throws SyntaxError {
Filter f = new Parser("trump").parse();
assertTrue(f instanceof BasicFilter);
assertEquals(((BasicFilter) f).getWord(), "trump");
}
@Test
public void testHairy() throws SyntaxError {
Filter x = new Parser("trump and (evil or blue) and red or green and not not purple").parse();
assertEquals(x.toString(), "(((trump and (evil or blue)) and red) or (green and not not purple))");
}
}
| 51192317c90d64c4fe0b65d8c5fd6e7de132fd50 | [
"Markdown",
"Java"
] | 2 | Markdown | webdever12/Tweet-Mapper | 4849ed2ade7f17ebe609ed4d2ae67c925caf10e4 | 349a16d56dc08d2d08c1a45428807ed19b2ec027 |
refs/heads/master | <repo_name>lirianom/clore<file_sep>/src/components/cardDateContainer.js
import React from 'react';
import Cards from './cards';
import '../css/style.css'
export default class CardTable extends React.Component {
constructor(props) {
super(props);
this.state = {
cards : this.props.cards,
};
}
buildCards() {
var newCardComponentArray = []
var row = []
var oldCardComponentArray = this.props.cards.map((data, key) => {
return(
<td className = "cardTable_td">
<Cards cards = {data} />
</td>
)
});
for (var i = 0, j = 1; i < oldCardComponentArray.length; j ++, i ++) {
row.push(oldCardComponentArray[i])
if (j === 5 || oldCardComponentArray[i + 1] == null) {
newCardComponentArray.push(
<tr>
{row}
</tr>
)
j = 0
row = []
}
}
return newCardComponentArray
}
render() {
return (
<table className = "cardTable_table">
<tbody >
{
this.buildCards()
}
</tbody>
</table>
)
}
}<file_sep>/src/App.js
import React from 'react';
import HomePage from './components/home'
import './css/style.css'
export default class App extends React.Component {
render() {
return (
<div className="App">
<HomePage />
</div>
);
}
}<file_sep>/ToDo.txt
Compose another component inside of SpoilerCardTable.js that takes the entire CardDate array and builds a table based on card
card date array.<file_sep>/src/components/insertCard.js
import React from 'react';
import '../css/style.css'
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
imageShown : 0
}
this.cardInput = this.cardInput.bind(this);
this.submitCard = this.submitCard.bind(this);
}
cardInput() {
}
submitCard() {
}
render() {
if (imageShown === 0) {
return(
<div>
<form onSubmit = {this.submitCard}>
Name : <input type= 'text' name= 'name' value = {this.state.value} onChange = {this.cardInput} /> <br />
Type : <input type= 'text' name= 'type' value = {this.state.value} onChange = {this.cardInput} /> <br />
Cost : <input type= 'text' name= 'name' value = {this.state.value} onChange = {this.cardInput} /> <br />
Keywords : <input type= 'text' name= 'keywords' value = {this.state.value} onChange = {this.cardInput} /> <br />
Rarity : <input type= 'text' name= 'rarity' value = {this.state.value} onChange = {this.cardInput} /> <br />
Set : <input type= 'text' name= 'set' value = {this.state.value} onChange = {this.cardInput} /> <br />
Region : <input type= 'text' name= 'region' value = {this.state.value} onChange = {this.cardInput} /> <br />
Date Released : <input type= 'text' name= 'date_released' value = {this.state.value} onChange = {this.cardInput} /> <br /> <br />
Image : <input type= 'text' name= 'image' value = {this.state.value} onChange = {this.cardInput} />
<input type="submit" value="Submit" />
</form>
</div>
)
} else if (imageShown === 1) {
return(
<div>
<form onSubmit = {this.submitCard}>
Name : <input type= 'text' name= 'name' value = {this.state.value} onChange = {this.cardInput} /> <br />
Type : <input type= 'text' name= 'type' value = {this.state.value} onChange = {this.cardInput} /> <br />
Cost : <input type= 'text' name= 'name' value = {this.state.value} onChange = {this.cardInput} /> <br />
Keywords : <input type= 'text' name= 'keywords' value = {this.state.value} onChange = {this.cardInput} /> <br />
Rarity : <input type= 'text' name= 'rarity' value = {this.state.value} onChange = {this.cardInput} /> <br />
Set : <input type= 'text' name= 'set' value = {this.state.value} onChange = {this.cardInput} /> <br />
Region : <input type= 'text' name= 'region' value = {this.state.value} onChange = {this.cardInput} /> <br />
Date Released : <input type= 'text' name= 'date_released' value = {this.state.value} onChange = {this.cardInput} /> <br />
<img src = { this.state.cardData } alt = ''/> <br />
Image : <input type= 'text' name= 'image' value = {this.state.value} onChange = {this.cardInput} />
<input type="submit" value="Submit" />
</form>
</div>
)
}
}
}<file_sep>/src/components/home.js
import React from 'react';
import CardTable from './cardTable';
import SpoilerCardTable from './spoilerCardTable';
import '../css/style.css'
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
page : 0,
}
this.changePage = this.changePage.bind(this);
}
getPage() {
console.log(this.state.page);
if (this.state.page === 0) {
return (
<CardTable />
)
} else if (this.state.page === 1) {
return (
<SpoilerCardTable />
);
}
}
changePage(event) {
var page = parseInt(event.target.value);
this.setState({
page,
});
}
render() {
return(
<div>
<p id = 'homeTitle'>Legends of Runeterra Cards</p>
<div className = "page_filter">
<button onClick = {this.changePage} type = 'button' value = {0}>All Cards</button>
<button onClick = {this.changePage} type = 'button' value = {1}>Newest Cards</button>
</div>
{this.getPage()}
</div>
)
}
}<file_sep>/src/components/spoilerCardTable.js
import React from 'react';
import file from './cards.json';
import CardDateContainer from './cardDateContainer'
import '../css/style.css'
export default class SpoilerCardTable extends React.Component {
constructor(props) {
super(props);
this.state = {
cards : null,
allCards : null,
isLoaded : false,
months : ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
};
}
componentDidMount() {
var cards = file;
var allCards = file;
var isLoaded = true;
this.setState({
cards,
allCards,
isLoaded
});
}
sortCards() {
var cards = this.state.cards;
cards.sort((a, b) => (a.date_released > b.date_released) ? 1 : -1)
}
buildCards() {
this.sortCards();
var cards = this.state.cards;
var cardDateArray = [];
var tempArray = [];
var init_date = cards[0].date_released
for (var i = 1; i < cards.length; i ++) {
if (init_date !== cards[i].date_released || i === cards.length - 1) {
init_date = cards[i].date_released;
cardDateArray.push(tempArray);
tempArray = [];
} else {
tempArray.push(cards[i])
}
}
var tempCardArray = cardDateArray.map((data, key) => {
var date = new Date(data[0].date_released);
var month = date.getMonth();
month = this.state.months[month]
var day = date.getDate();
var year = date.getFullYear();
var dateString = month + ' ' + day + ', ' + year;
return (
<div>
<tr className = "SpoilerCardTable_tr_date_title">
<td>{dateString}</td>
</tr>
<tr>
<td className = "SpoilerCardTable_td">
<CardDateContainer cards = {data} />
</td>
</tr>
</div>
)
});
return tempCardArray;
}
render() {
if (this.state.isLoaded) {
return (
<div className = "spoilerCardTable">
<table className = "spoilerCardTable_table">
<tbody >
{
this.buildCards()
}
</tbody>
</table>
</div>
)
} else {
return (
<div>
No Cards!
</div>
)
}
}
} | 75c9efb99bba5642c44d9331188129f422711194 | [
"JavaScript",
"Text"
] | 6 | JavaScript | lirianom/clore | 20ca643d531cd348f34c6d079f562a684d7f8aec | 842679ffb583eadadc27605c18894b3d5b7c6b87 |
refs/heads/master | <file_sep>CREATE DATABASE coinsite DEFAULT CHARACTER SET utf8;
USE coinsite;
CREATE TABLE IF NOT EXISTS user (id INT AUTO_INCREMENT, login VARCHAR(50) UNIQUE NOT NULL, password VARCHAR(50),
email VARCHAR(50) UNIQUE NOT NULL, role VARCHAR(50), PRIMARY KEY (id));
CREATE TABLE IF NOT EXISTS metal (id INT AUTO_INCREMENT, name VARCHAR(50) UNIQUE NOT NULL, PRIMARY KEY (id));
CREATE TABLE IF NOT EXISTS country (id INT AUTO_INCREMENT, name VARCHAR(50) UNIQUE NOT NULL, PRIMARY KEY (id));
CREATE TABLE IF NOT EXISTS theme (id INT AUTO_INCREMENT, name VARCHAR(50) NOT NULL, country_id INT NOT NULL,
PRIMARY KEY (id), FOREIGN KEY (country_id) REFERENCES country(id));
CREATE TABLE IF NOT EXISTS series (id INT AUTO_INCREMENT, name VARCHAR(50) NOT NULL, theme_id INT NOT NULL,
PRIMARY KEY (id), FOREIGN KEY (theme_id) REFERENCES theme(id));
CREATE TABLE IF NOT EXISTS coin (id INT AUTO_INCREMENT, name VARCHAR(50) NOT NULL, series_id INT NOT NULL,
releasedate DATE, designer VARCHAR(50), mintedby VARCHAR(50), description_obverse TEXT, description_reverse TEXT,
image VARCHAR(50), PRIMARY KEY(id), FOREIGN KEY (series_id) REFERENCES series(id));
CREATE TABLE IF NOT EXISTS coindescription (id INT AUTO_INCREMENT, coin_id INT NOT NULL, metal_id INT NOT NULL, denomination INT,
weight FLOAT, diameter FLOAT, mintage INT, image_obverse VARCHAR(50) UNIQUE NOT NULL, image_reverse VARCHAR(50) UNIQUE NOT NULL,
PRIMARY KEY (id), FOREIGN KEY (coin_id) REFERENCES coin(id), FOREIGN KEY (metal_id) REFERENCES metal(id));
CREATE TABLE IF NOT EXISTS user_coindescription (id INT AUTO_INCREMENT, user_id INT NOT NULL, coindescription_id INT NOT NULL, amount INT NOT NULL,
PRIMARY KEY (id), FOREIGN KEY (user_id) REFERENCES user(id), FOREIGN KEY (coindescription_id) REFERENCES coindescription(id));
CREATE TABLE IF NOT EXISTS sale (id INT AUTO_INCREMENT, user_coin_id INT NOT NULL, cost DECIMAL, PRIMARY KEY (id),
FOREIGN KEY (user_coin_id) REFERENCES user_coindescription(id));
INSERT INTO user (login, password, email, role) VALUE ('admin', 'admin', '<EMAIL>', 'ADMINISTRATOR');
INSERT INTO metal (name) VALUE ('gold');
INSERT INTO metal (name) VALUE ('silver');
INSERT INTO metal (name) VALUE ('copper-nikel');
INSERT INTO country (name) VALUE ('Republic of Belarus');
INSERT INTO country (name) VALUE ('Republic of Kazakhstan');
INSERT INTO country (name) VALUE ('Russian Federation');
SELECT * FROM country;
INSERT INTO theme (name, country_id) VALUE ('BELARUS AND THE WORLD COMMUNITY', 1);
INSERT INTO theme (name, country_id) VALUE ('BELARUSIAN HISTORY AND CULTURE', 1);
INSERT INTO theme (name, country_id) VALUE ('SPORTS', 1);
INSERT INTO theme (name, country_id) VALUE ('PROTECTION OF THE ENVIRONMENT', 1);
INSERT INTO theme (name, country_id) VALUE ('MY COUNTRY BELARUS', 1);
SELECT * FROM theme;
INSERT INTO series (name, theme_id) VALUE ('No theme', 1);
INSERT INTO series (name, theme_id) VALUE ('The 60th Anniversary of Liberation of the Republic of Belarus from the nazi invaders', 1);
INSERT INTO series (name, theme_id) VALUE ('The 60th Anniversary of Victory in the Great Patriotic war', 1);
INSERT INTO series (name, theme_id) VALUE ('Tales of the World’s Nations', 1);
INSERT INTO series (name, theme_id) VALUE ('Slavs\' Family Traditions', 1);
INSERT INTO series (name, theme_id) VALUE ('Orthodox Saints', 1);
INSERT INTO series (name, theme_id) VALUE ('Sailing Ships', 1);
INSERT INTO series (name, theme_id) VALUE ('Signs of the Zodiac', 1);
INSERT INTO series (name, theme_id) VALUE ('The Three Musketeers', 1);
INSERT INTO series (name, theme_id) VALUE ('<NAME>\'s Fairy Tales', 1);
INSERT INTO series (name, theme_id) VALUE ('Operation Bagration', 1);
INSERT INTO series (name, theme_id) VALUE ('Orthodox Churches', 1);
INSERT INTO series (name, theme_id) VALUE ('World of Sculpture Series', 1);
INSERT INTO series (name, theme_id) VALUE ('Orthodox Wonder-working Icons Series', 1);
INSERT INTO series (name, theme_id) VALUE ('Belarus\'s International Festivals Series', 1);
INSERT INTO series (name, theme_id) VALUE ('Magic of Dance', 1);
INSERT INTO series (name, theme_id) VALUE ('The Solar System Series', 1);
INSERT INTO series (name, theme_id) VALUE ('Chinese Calendar', 1);
INSERT INTO series (name, theme_id) VALUE ('Signs of the Zodiac. 2013', 1);
INSERT INTO series (name, theme_id) VALUE ('Orthodox Saints\' Lives Series', 1);
INSERT INTO series (name, theme_id) VALUE ('Zodiac Horoscope', 1);
INSERT INTO series (name, theme_id) VALUE ('Orthodox Saints. 2013', 1);
INSERT INTO series (name, theme_id) VALUE ('Skaryna\'s Way', 1);
INSERT INTO series (name, theme_id) VALUE ('No theme', 2);
INSERT INTO series (name, theme_id) VALUE ('Belarusian Cities', 2);
INSERT INTO series (name, theme_id) VALUE ('Belarusian Architectural Monuments', 2);
INSERT INTO series (name, theme_id) VALUE ('Belarusian Festivals and Rites', 2);
INSERT INTO series (name, theme_id) VALUE ('Strengthening and Defending the State', 2);
INSERT INTO series (name, theme_id) VALUE ('Belarusian Folk Legends', 2);
INSERT INTO series (name, theme_id) VALUE ('Belarusian Folk Trades and Crafts', 2);
INSERT INTO series (name, theme_id) VALUE ('Belarus\' Faiths Series', 2);
INSERT INTO series (name, theme_id) VALUE ('Belts of Slutsk', 2);
INSERT INTO series (name, theme_id) VALUE ('No theme', 3);
INSERT INTO series (name, theme_id) VALUE ('Olympic Belarus', 3);
INSERT INTO series (name, theme_id) VALUE ('No theme', 4);
INSERT INTO series (name, theme_id) VALUE ('Belarusian National Parks and Nature Reserves', 4);
INSERT INTO series (name, theme_id) VALUE ('Belarusian Nature Reserves', 4);
INSERT INTO series (name, theme_id) VALUE ('Bird of the Year', 4);
INSERT INTO series (name, theme_id) VALUE ('Horses', 4);
INSERT INTO series (name, theme_id) VALUE ('Belarusian Flowers', 4);
INSERT INTO series (name, theme_id) VALUE ('Beauty of Flowers', 4);
INSERT INTO series (name, theme_id) VALUE ('Butterflies', 4);
INSERT INTO series (name, theme_id) VALUE ('Revived Plants', 4);
INSERT INTO series (name, theme_id) VALUE ('My country Belarus', 5);
SELECT * FROM series;
INSERT INTO coin (name, series_id, releasedate, designer, mintedby, description_obverse, description_reverse, image) VALUES ('50th Anniversary of UN',
1, '19961227', 'A.Zimenko, D.Belitsky (Belarus)', 'The Royal Mint, London,Great Britain', 'features in the center the relief of the State Coat of Arms of the Republic of Belarus with the inscription in two lines beneath: "РЭСПУБЛIКА БЕЛАРУСЬ" (REPUBLIC OF BELARUS); at the bottom – face value, year of issue, precious metals coins – weight of the coin and alloy standard. ', 'features in the center – against the background of a geographic map of the Republic of Belarus – the relief of a hovering stork, in the lower left–hand part – the UN emblem and "50", along the rim – inscriptions separated by geometric ornament: "НАЦЫI, АБ\'ЯДНАНЫЯ ЗА MIP" (NATIONS UNITED FOR PEACE), "1 РУБЕЛЬ"
(1 ROUBLE).', 'http://www.nbrb.by/CoinsBanknotes/images/?id=523');
INSERT INTO coin (name, series_id, releasedate, designer, mintedby, description_obverse, description_reverse, image) VALUES ('cointest1', 2, '19990808',
'Somebody', 'Royal mint', 'obverse', 'reverse', 'imageadres1');
INSERT INTO coin (name, series_id, releasedate, designer, mintedby, description_obverse, description_reverse, image) VALUES ('cointest2', 2, '19990808',
'Somebody', 'Royal mint', 'obverse', 'reverse', 'imageadres2');
INSERT INTO coin (name, series_id, releasedate, designer, mintedby, description_obverse, description_reverse, image) VALUES ('cointest3', 13, '19990808',
'Somebody', 'Royal mint', 'obverse', 'reverse', 'imageadres3');
INSERT INTO coin (name, series_id, releasedate, designer, mintedby, description_obverse, description_reverse, image) VALUES ('cointest4', 5, '19990808',
'Somebody', 'Royal mint', 'obverse', 'reverse', 'imageadres4');
SELECT * FROM coin;
INSERT INTO coindescription (coin_id, metal_id, denomination, weight, diameter, mintage, image_obverse, image_reverse) VALUE (1, 1, 1, 8.71, 22.05, 5000, 'http://www.nbrb.by/CoinsBanknotes/images?id=512', 'http://www.nbrb.by/CoinsBanknotes/images?id=514');
INSERT INTO coindescription (coin_id, metal_id, denomination, weight, diameter, mintage, image_obverse, image_reverse) VALUE (1, 2, 1, 30.57, 38.61, 20000, 'http://www.nbrb.by/CoinsBanknotes/images?id=520', 'http://www.nbrb.by/CoinsBanknotes/images?id=522');
INSERT INTO coindescription (coin_id, metal_id, denomination, weight, diameter, mintage, image_obverse, image_reverse) VALUE (1, 3, 1, 28.28, 38.61, 40000, 'http://www.nbrb.by/CoinsBanknotes/images?id=524', 'http://www.nbrb.by/CoinsBanknotes/images?id=526');
SELECT * FROM coindescription;
INSERT INTO user_coindescription (user_id, coindescription_id, amount) VALUE (1, 1, 1);
INSERT INTO user_coindescription (user_id, coindescription_id, amount) VALUE (1, 2, 2);
INSERT INTO user_coindescription (user_id, coindescription_id, amount) VALUE (1, 3, 4);
SELECT * FROM user_coindescription;
INSERT INTO sale (user_coin_id, cost) VALUE (1, 235);
INSERT INTO sale (user_coin_id, cost) VALUE (2, 92);
INSERT INTO sale (user_coin_id, cost) VALUE (3, 40);
SELECT * FROM sale;
DROP TABLE user;
DROP TABLE metal;
DROP TABLE country;
DROP TABLE theme;
DROP TABLE series;
DROP TABLE coin;
DROP TABLE coindescription;
DROP TABLE user_coindescription;
DROP TABLE sale;
DROP DATABASE coinsite;
<file_sep>package dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ViewCoinDescriptionDto {
private long id;
private String metal;
private long denomination;
private double weight;
private double diameter;
private long mintage;
private String imageObverse;
private String imageReverse;
}
<file_sep>package servlet;
import service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/change-user-role", name = "ChangeUserRole")
public class ChangeUserRoleServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String newUserRole = req.getParameter("userRole");
long userId = Long.valueOf(req.getParameter("userId"));
UserService.getInstance().changeUserRole(userId, newUserRole);
resp.sendRedirect(req.getHeader("Referer"));
}
}
<file_sep>package servlet;
import dto.CoinDescriptionAddingDto;
import service.CoinDescriptionService;
import service.CoinService;
import service.MetalService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static util.ServletUtil.createViewPath;
@WebServlet(urlPatterns = "/add-coin-description", name = "AddCoinDescription")
public class AddCoinDescriptionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("metals", MetalService.getInstance().getAllMetals());
req.setAttribute("coins", CoinService.getInstance().getAllCoinsId());
getServletContext()
.getRequestDispatcher(createViewPath("add-coin-description"))
.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
CoinDescriptionAddingDto coin = new CoinDescriptionAddingDto(
Long.valueOf(req.getParameter("coinId")),
Long.valueOf(req.getParameter("metalId")),
Long.valueOf(req.getParameter("denomination")),
Long.valueOf(req.getParameter("mintage")),
Double.valueOf(req.getParameter("weight")),
Double.valueOf(req.getParameter("diameter")),
req.getParameter("imageObverse"),
req.getParameter("imageReverse"));
CoinDescriptionService.getInstance().addCoinDescription(coin);
}
}
<file_sep>package servlet;
import service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static util.ServletUtil.createViewPath;
@WebServlet(urlPatterns = "/all-users", name = "AllUsers")
public class AllUsersServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("users", UserService.getInstance().getAllUsers());
getServletContext()
.getRequestDispatcher(createViewPath("all-users"))
.forward(req, resp);
}
}
<file_sep>package dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class UserSessionDto {
private long userId;
private String userRole;
}
<file_sep>package servlet;
import dto.UserSessionDto;
import entity.MyCollection;
import service.CatalogService;
import service.CountryService;
import service.MyCollectionService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static util.ServletUtil.createViewPath;
@WebServlet(urlPatterns = "/country-collection", name = "CountryCollection")
public class CountryCollectionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
long countryId = Long.valueOf(req.getParameter("id"));
long userId = ((UserSessionDto) req.getSession().getAttribute("currentUser")).getUserId();
req.setAttribute("country", CountryService.getInstance().getCountryById(countryId));
req.setAttribute("themes", MyCollectionService.getInstance().getThemesInCollectionByUserId(userId, countryId));
req.setAttribute("series" , MyCollectionService.getInstance().getSeriesInCollectionByUserId(userId, countryId));
req.setAttribute("coins", MyCollectionService.getInstance().getCoinsInCollectionByUserId(userId, countryId));
getServletContext()
.getRequestDispatcher(createViewPath("country-collection"))
.forward(req, resp);
}
}
<file_sep>package service;
import dao.CollectionDao;
import dto.ViewCoinInCollectionByCountryDto;
import dto.ViewSeriesInCollectionByCountryDto;
import dto.ViewThemesInCollectionByCountryDto;
import java.util.List;
import java.util.stream.Collectors;
public final class MyCollectionService {
private static MyCollectionService INSTANCE = null;
private MyCollectionService() {}
public static MyCollectionService getInstance() {
if (INSTANCE == null) {
synchronized (MyCollectionService.class) {
if (INSTANCE == null) {
INSTANCE = new MyCollectionService();
}
}
}
return INSTANCE;
}
public void addCoinToCellection(long userId, long coinDescriptionId, long amount) {
CollectionDao.getInstance().addCoinToCollection(userId, coinDescriptionId, amount);
}
public void updateCoinInCollection(long userId, long coinDescriptionId, long amount) {
CollectionDao.getInstance().updateCoinAmountInCollection(userId, coinDescriptionId, amount);
}
public List<ViewCoinInCollectionByCountryDto> getCoinsInCollectionByUserId(long userId, long countryId) {
return CollectionDao.getInstance().findCoinsInCollectionByCountry(userId, countryId)
.stream()
.map(coin -> new ViewCoinInCollectionByCountryDto(
coin.getSeries().getId(),
coin.getId(),
coin.getName(),
coin.getAmount()))
.collect(Collectors.toList());
}
public List<ViewThemesInCollectionByCountryDto> getThemesInCollectionByUserId(long userId, long countryId) {
return CollectionDao.getInstance().findThemesInCollectionByCountry(userId, countryId).stream()
.map(theme -> new ViewThemesInCollectionByCountryDto(theme.getId(),
theme.getName(),
theme.getAmount()))
.collect(Collectors.toList());
}
public List<ViewSeriesInCollectionByCountryDto> getSeriesInCollectionByUserId(long userId, long countryId) {
return CollectionDao.getInstance().findSeriesInCollectionByCountry(userId, countryId).stream()
.map(series -> new ViewSeriesInCollectionByCountryDto(series.getId(),
series.getName(),
series.getTheme().getId(),
series.getAmount()))
.collect(Collectors.toList());
}
}
<file_sep>package servlet;
import service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/user-search", name = "UserSearch")
public class UserSearchServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
req.setAttribute("user", UserService.getInstance().getUserFullInfoByUserName(username));
req.setAttribute("userRoles", UserService.getInstance().getAllUserRoles());
resp.sendRedirect(req.getHeader("Referer"));
}
}
<file_sep>package dao;
import com.mysql.jdbc.Statement;
import connection.ConnectionManager;
import entity.CoinDescription;
import entity.Metal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public final class CoinDescriptionDao {
private static final String COINDESCRIPTION_TABLE_NAME = "cd";
private static final String METAL_TABLE_NAME = "m";
private static CoinDescriptionDao INSTANCE = null;
private CoinDescriptionDao() {}
public static CoinDescriptionDao getInstance() {
if (INSTANCE == null) {
synchronized (CoinDescriptionDao.class) {
if (INSTANCE == null) {
INSTANCE = new CoinDescriptionDao();
}
}
}
return INSTANCE;
}
public CoinDescription create(CoinDescription coinDescription) {
try (Connection connection = ConnectionManager.getConnection()) {
try (PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO coinDescription (coin_id, metal_id, denomination, mintage, weight, diameter, image_obverse, image_reverse) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
preparedStatement.setLong(1, coinDescription.getCoin().getId());
preparedStatement.setLong(2, coinDescription.getMetal().getId());
preparedStatement.setLong(3, coinDescription.getDenomination());
preparedStatement.setLong(4, coinDescription.getMintage());
preparedStatement.setDouble(5, coinDescription.getWeight());
preparedStatement.setDouble(6, coinDescription.getDiameter());
preparedStatement.setString(7, coinDescription.getImageObverse());
preparedStatement.setString(8, coinDescription.getImageReverse());
preparedStatement.executeUpdate();
ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
if (generatedKeys.next()) {
coinDescription.setId(generatedKeys.getLong(1));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return coinDescription;
}
public List<CoinDescription> findCoinDescriptionByCoinId(long coinId) {
List<CoinDescription> coinDescription = new ArrayList<>();
try (Connection connection = ConnectionManager.getConnection()) {
try (PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT * FROM coindescription cd JOIN metal m ON cd.metal_id = m.id AND cd.coin_id = ?;")) {
preparedStatement.setLong(1, coinId);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
coinDescription.add(createCoinDescriptionForCatalogFromResultSet(resultSet));
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return coinDescription;
}
private CoinDescription createCoinDescriptionForCatalogFromResultSet(ResultSet resultSet) throws SQLException {
CoinDescription coinDescription = new CoinDescription();
coinDescription.setId(resultSet.getLong(COINDESCRIPTION_TABLE_NAME + ".id"));
coinDescription.setMetal(new Metal(resultSet.getLong(METAL_TABLE_NAME + ".id"),
resultSet.getString(METAL_TABLE_NAME + ".name")));
coinDescription.setDenomination(resultSet.getLong(COINDESCRIPTION_TABLE_NAME + ".denomination"));
coinDescription.setWeight(resultSet.getDouble(COINDESCRIPTION_TABLE_NAME + ".weight"));
coinDescription.setDiameter(resultSet.getDouble(COINDESCRIPTION_TABLE_NAME + ".diameter"));
coinDescription.setMintage(resultSet.getLong(COINDESCRIPTION_TABLE_NAME + ".mintage"));
coinDescription.setImageObverse(resultSet.getString(COINDESCRIPTION_TABLE_NAME + ".image_obverse"));
coinDescription.setImageReverse(resultSet.getString(COINDESCRIPTION_TABLE_NAME + ".image_reverse"));
return coinDescription;
}
}
<file_sep>package dao;
import com.mysql.jdbc.Statement;
import connection.ConnectionManager;
import entity.Metal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public final class MetalDao {
private static final String METAL_TABLE_NAME = "metal";
private static MetalDao INSTANCE = null;
private MetalDao() {}
public static MetalDao getInstance() {
if (INSTANCE == null) {
synchronized (CountryDao.class) {
if (INSTANCE == null) {
INSTANCE = new MetalDao();
}
}
}
return INSTANCE;
}
public Metal create(Metal metal) {
try (Connection connection = ConnectionManager.getConnection()) {
try (PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO metal (name) VALUES (?)", Statement.RETURN_GENERATED_KEYS)) {
preparedStatement.setString(1, metal.getName());
preparedStatement.executeUpdate();
ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
if (generatedKeys.next()) {
metal.setId(generatedKeys.getLong(1));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return metal;
}
public List<Metal> findAll() {
List<Metal> metal = new ArrayList<>();
try (Connection connection = ConnectionManager.getConnection()) {
try (PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT * FROM metal;")) {
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
metal.add(createMetalFromResultSet(resultSet));
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return metal;
}
private Metal createMetalFromResultSet(ResultSet resultSet) throws SQLException {
return new Metal(
resultSet.getLong(METAL_TABLE_NAME + ".id"),
resultSet.getString(METAL_TABLE_NAME + ".name"));
}
}
<file_sep>package service;
import dto.ViewCatalogCoinsByCountryDto;
public final class CatalogService {
private static CatalogService INSTANCE = null;
private CatalogService() {}
public static CatalogService getInstance() {
if (INSTANCE == null) {
synchronized (CatalogService.class) {
if (INSTANCE == null) {
INSTANCE = new CatalogService();
}
}
}
return INSTANCE;
}
public ViewCatalogCoinsByCountryDto getCatalogCoinsByCountry(long countryId) {
ViewCatalogCoinsByCountryDto catalog = new ViewCatalogCoinsByCountryDto();
catalog.setThemes(ThemeService.getInstance().getThemesByCountry(countryId));
catalog.setSeries(SeriesService.getInstance().getSeriesByCountry(countryId));
catalog.setCoins(CoinService.getInstance().getCoinsByCountry(countryId));
return catalog;
}
}
<file_sep>login.username=Username
login.button=Sign in
login.email=E-mail
login.password=<PASSWORD>
login.registration=Registration
header.home=Home<file_sep>package servlet;
import service.CountryService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static util.ServletUtil.createViewPath;
@WebServlet(urlPatterns = "/catalog", name = "CatalogServlet")
public class CatalogServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("countries", CountryService.getInstance().getAllCountries());
getServletContext()
.getRequestDispatcher(createViewPath("catalog"))
.forward(req, resp);
}
}
<file_sep>package dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ViewUserLoginInfoDto {
private long id;
private String email;
private String password;
private String userRole;
}
<file_sep>package entity;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class Language {
public static Map<String, Locale> LANG = new HashMap<>();
static {
LANG.put("eng", new Locale("en", "US"));
LANG.put("rus", new Locale("ru", "RU"));
}
public static Locale getLocale(String lang) {
return LANG.get(lang);
}
}<file_sep>package servlet;
import dto.UserSessionDto;
import service.MyCollectionService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/add-coin-to-collection", name = "AddCoinToCollection")
public class AddCoinToCollectionServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
UserSessionDto userSessionDto = (UserSessionDto) req.getSession().getAttribute("currentUser");
long amount = Long.valueOf(req.getParameter("coinAmount"));
System.out.println(amount);
long coinDescriptionId = Long.valueOf(req.getParameter("coinDescriptionId"));
System.out.println(coinDescriptionId);
if (amount >= 0) {
MyCollectionService.getInstance().addCoinToCellection(userSessionDto.getUserId(), coinDescriptionId, amount);
} else {
req.setAttribute("error", "INVALID COIN AMOUNT ENTERED");
req.setAttribute("errorCoinId", coinDescriptionId);
}
resp.sendRedirect(req.getHeader("Referer"));
}
}
<file_sep>package dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.HashMap;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class TestDto {
private HashMap<Long, Long> cdIdAmount;
}
<file_sep>package service;
import dao.SeriesDao;
import dto.ViewAllSeriesByCountryDto;
import dto.ViewAllSeriesDto;
import entity.Series;
import entity.Theme;
import java.util.List;
import java.util.stream.Collectors;
public final class SeriesService {
private static SeriesService INSTANCE = null;
private SeriesService() {}
public static SeriesService getInstance() {
if (INSTANCE == null) {
synchronized (SeriesService.class) {
if (INSTANCE == null) {
INSTANCE = new SeriesService();
}
}
}
return INSTANCE;
}
public List<ViewAllSeriesByCountryDto> getSeriesByCountry(long countryId) {
return SeriesDao.getInstance().findAllByCountry(countryId).stream()
.map(seriesEntity -> new ViewAllSeriesByCountryDto(seriesEntity.getId(), seriesEntity.getName(), seriesEntity.getTheme().getId()))
.collect(Collectors.toList());
}
public List<ViewAllSeriesDto> getAllSeries() {
return SeriesDao.getInstance().findAll().stream()
.map(seriesEntity -> new ViewAllSeriesDto(seriesEntity.getId(), seriesEntity.getName(), seriesEntity.getTheme().getId()))
.collect(Collectors.toList());
}
public void addSeries(String seriesName, long themeId) {
Series series = new Series();
series.setName(seriesName);
Theme theme = new Theme();
theme.setId(themeId);
series.setTheme(theme);
SeriesDao.getInstance().create(series);
}
}
<file_sep>package entity;
public enum UserRole {
USER, ADMINISTRATOR, MODERATOR
}
<file_sep>package dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ViewCoinInCollectionByCountryDto {
private long seriesId;
private long coinId;
private String coinName;
private long amount;
}
<file_sep>package servlet;
import dto.ViewCoinForAddingDto;
import service.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import static util.ServletUtil.createViewPath;
@WebServlet(urlPatterns = "/add-coin", name = "AddCoin")
public class AddCoinServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("series", SeriesService.getInstance().getAllSeries());
getServletContext()
.getRequestDispatcher(createViewPath("add-coin"))
.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ViewCoinForAddingDto dto = new ViewCoinForAddingDto(
Long.valueOf(req.getParameter("seriesId")),
req.getParameter("coinName"),
LocalDate.parse(req.getParameter("releaseDate"), DateTimeFormatter.ofPattern("yyyy-MM-dd")),
req.getParameter("designer"),
req.getParameter("mintedBy"),
req.getParameter("descriptionObverse"),
req.getParameter("descriptionReverse"));
CoinService.getInstance().addCoin(dto);
resp.sendRedirect(req.getHeader("Referer"));
}
}
<file_sep>package dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ViewCatalogCoinsByCountryDto {
private List<ViewAllThemesByCountryDto> themes;
private List<ViewAllSeriesByCountryDto> series;
private List<ViewAllCoinsByCountryDto> coins;
}
<file_sep>package service;
import dao.UserDao;
import dto.*;
import entity.User;
import entity.UserRole;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public final class UserService {
private static UserService INSTANCE = null;
private UserService() {}
public static UserService getInstance() {
if (INSTANCE == null) {
synchronized (UserService.class) {
if (INSTANCE == null) {
INSTANCE = new UserService();
}
}
}
return INSTANCE;
}
public List<ViewUserBasicInfoDto> getAllUsers() {
return UserDao.getInstance().findAll().stream()
.map(userEntity -> new ViewUserBasicInfoDto(userEntity.getId(),
userEntity.getLogin(),
userEntity.getEmail(),
userEntity.getUserRole().toString()))
.collect(Collectors.toList());
}
public ViewUserLoginInfoDto getUserLoginInfoByEmail(String email) {
User user = UserDao.getInstance().findByEmail(email).orElse(null);
if (user != null) {
return new ViewUserLoginInfoDto(user.getId(), user.getEmail(), user.getPassword(), user.getUserRole().toString());
} else {
return null;
}
}
public ViewUserFullInfoDto getUserFullInfoByUserName(String username) {
User user = UserDao.getInstance().findByUserName(username).orElse(null);
if (user != null) {
return new ViewUserFullInfoDto(user.getId(), user.getLogin(), user.getEmail(), user.getUserRole().toString());
} else {
return null;
}
}
public ViewUserFullInfoDto getUserFullInfoByUserId(long userId) {
User user = UserDao.getInstance().findByUserId(userId).orElse(null);
if (user != null) {
return new ViewUserFullInfoDto(user.getId(), user.getLogin(), user.getEmail(), user.getUserRole().toString());
} else {
return null;
}
}
public long createNewUser(CreateNewUserDto dto) {
return UserDao.getInstance().create(new User(dto.getLogin(), dto.getPassword(), dto.getEmail(), dto.getRole())).getId();
}
public UserSessionDto getUserSessionInfo(String inputEmail, String inputPassword) {
ViewUserLoginInfoDto userLoginInfoDto = getUserLoginInfoByEmail(inputEmail);
if (userLoginInfoDto != null) {
if (userLoginInfoDto.getPassword().equals(inputPassword)) {
return new UserSessionDto(userLoginInfoDto.getId(), userLoginInfoDto.getUserRole());
}
}
return null;
}
public void changeUserRole(long userId, String newUserRole) {
UserDao.getInstance().changeUserRole(userId, newUserRole);
}
public void deleteUser(long userId) {
UserDao.getInstance().deleteUserSale(userId);
UserDao.getInstance().deleteUserCoinDescription(userId);
UserDao.getInstance().deleteUser(userId);
}
public List<String> getAllUserRoles() {
return Arrays.stream(UserRole.values()).map(Enum::toString).collect(Collectors.toList());
}
}
<file_sep>package dao;
import com.mysql.jdbc.Statement;
import connection.ConnectionManager;
import entity.News;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public final class NewsDao {
private static final String NEWS_TABLE_NAME = "n";
private static NewsDao INSTANCE = null;
private NewsDao() {}
public static NewsDao getInstance() {
if (INSTANCE == null) {
synchronized (NewsDao.class) {
if (INSTANCE == null) {
INSTANCE = new NewsDao();
}
}
}
return INSTANCE;
}
public News create(News news) {
try (Connection connection = ConnectionManager.getConnection()) {
try (PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO news (headline, news, releasedate) VALUES (?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
preparedStatement.setString(1, news.getHeadline());
preparedStatement.setString(2, news.getText());
preparedStatement.setString(3, news.getReleaseDate().toString());
preparedStatement.executeUpdate();
ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
if (generatedKeys.next()) {
news.setId(generatedKeys.getLong(1));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return news;
}
public List<News> findAllNews() {
List<News> news = new ArrayList<>();
try (Connection connection = ConnectionManager.getConnection()) {
try (PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT * FROM news n;")) {
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
news.add(createNewsFromResultSet(resultSet));
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return news;
}
private News createNewsFromResultSet(ResultSet resultSet) throws SQLException {
String release = resultSet.getString(NEWS_TABLE_NAME + ".releasedate");
LocalDateTime releaseDate = LocalDateTime.parse(release, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));
return new News(resultSet.getLong(NEWS_TABLE_NAME + ".id"),
resultSet.getString(NEWS_TABLE_NAME + ".headline"),
resultSet.getString(NEWS_TABLE_NAME + ".news"),
releaseDate);
}
public void delete(News news) {
try (Connection connection = ConnectionManager.getConnection()) {
try (PreparedStatement preparedStatement = connection.prepareStatement(
"DELETE FROM news WHERE id = ?")) {
preparedStatement.setLong(1, news.getId());
preparedStatement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
<file_sep>package service;
import dao.CoinDao;
import dao.CoinDescriptionDao;
import dto.*;
import entity.Coin;
import entity.Metal;
import entity.Series;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
public final class CoinService {
private static CoinService INSTANCE = null;
private CoinService() {}
public static CoinService getInstance() {
if (INSTANCE == null) {
synchronized (CoinService.class) {
if (INSTANCE == null) {
INSTANCE = new CoinService();
}
}
}
return INSTANCE;
}
public List<ViewAllCoinsByCountryDto> getCoinsByCountry(long countryId) {
return CoinDao.getInstance().findAllCoinByCountry(countryId).stream()
.map(coinEntity -> new ViewAllCoinsByCountryDto(coinEntity.getId(), coinEntity.getName(),
coinEntity.getSeries().getId()))
.collect(Collectors.toList());
}
public ViewCoinByIdDto getCoinFullInfo(long coinId) {
Coin coin = CoinDao.getInstance().findCoinById(coinId);
return new ViewCoinByIdDto(coin.getSeries().getTheme().getCountry().getName(),
coin.getSeries().getTheme().getName(),
coin.getSeries().getName(),
coin.getName(),
coin.getReleaseDate().format(DateTimeFormatter.ofPattern("dd MMMM yyyy")),
coin.getDesigner(),
coin.getMintedBy(),
CoinDescriptionService.getInstance().getAllCoinDescriptionsByCoinId(coinId),
coin.getDescriptionObverse(),
coin.getDescriptionRevers());
}
public List<ViewCoinBaseInfoDto> getAllCoinsId() {
return CoinDao.getInstance().findAllCoins().stream()
.map(coin -> new ViewCoinBaseInfoDto(coin.getId(), coin.getName()))
.collect(Collectors.toList());
}
public void addCoin(ViewCoinForAddingDto dto) {
Series series = new Series();
series.setId(dto.getId());
Coin coin = new Coin(dto.getCoinName(),
series,
dto.getReleaseDate(),
dto.getDesigner(),
dto.getMintedBy(),
dto.getDescriptionObverse(),
dto.getDescriptionReverse());
coin.setSeries(series);
CoinDao.getInstance().create(coin);
}
}
| 15ed1deb6f484d6fd4907bd681848741bfb4696e | [
"Java",
"SQL",
"INI"
] | 26 | SQL | SVZR/CourseProjectJD1 | f7e32237b71826ad674aa42cf3a9623f1c49e789 | 0f43fc1f1a05125064dfc4154eb9cf0b3c93cbc9 |
refs/heads/master | <repo_name>humminglab/id2_client_sdk<file_sep>/modules/irot/makefile
include ../../make.settings
.PHONY: lib
$(info $(CONFIG_LS_ID2_ROT_TYPE))
lib:
ifeq ($(CONFIG_LS_ID2_ROT_TYPE), SE)
make -C se
else
make -C demo
endif
clean:
make clean -C se
make clean -C demo
<file_sep>/modules/id2/inc/module/mdu_id2.h
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef __MDU_ID2_H__
#define __MDU_ID2_H__
#include "id2_client.h"
#ifdef __cplusplus
extern "C"
#endif
#define ID2_AUTH_TYPE_CHALLENGE 0
#define ID2_AUTH_TYPE_TIMESTAMP 1
/**
* @brief module id2 init.
*
* @return @see error code definitions.
*/
irot_result_t mdu_id2_init(void);
/**
* @brief module id2 cleanup.
*
* @return @see error code definitions.
*/
irot_result_t mdu_id2_cleanup(void);
/**
* @brief get the id2 sdk version from module.
*
* @param[out] version: the hexadecimal version number.
*
* @return @see error code definitions.
*/
irot_result_t mdu_id2_get_version(uint32_t* version);
/**
* @brief get ID2 ID String.
*
* @param[out] id: the ID2 buffer, containing ID2 ID string.
* @param[in] len: the ID2 buffer size, should be more than ID2_ID_LEN.
*
* @return @see error code definitions.
*/
irot_result_t mdu_id2_get_id(uint8_t* id, uint32_t len);
/**
* @brief get the authentication code with the challenge mode.
*
* @param[in] type: auth code type, challenge or timestamp.
* @param[in] random: random string, terminated with '\0'.
* @param[in] extra: extra string, optional, no more than 512 bytes.
* @param[in] extra_len: the length of extra string.
* @param[out] auth_code: the output buffer, containing authcode string.
* @param[inout] auth_code_len: in - the buffer size, more than 256 bytes.
* out - the actual length.
*
* @return @see error code definitions.
*/
irot_result_t mdu_id2_get_auth_code(uint32_t type, const char* random,
const uint8_t* extra, uint32_t extra_len,
uint8_t* auth_code, uint32_t* auth_code_len);
/**
* @brief decrypt the cipher data with id2 key.
*
* @param[in] in: input hexadecimal data.
* @param[in] in_len: lenth of the input data, less than ID2_MAX_CRYPT_LEN bytes.
* @param[out] out: output buffer, containing decrypted hexadecimal data.
* @param[inout] out_len: in - the buffer size; out - the actual length.
*
* @return @see error code definitions.
*/
irot_result_t mdu_id2_decrypt(const uint8_t* in,
uint32_t in_len, uint8_t* out, uint32_t* out_len);
/**
* @brief get the device challenge, less than ID2_MAX_DEVICE_RANDOM_LEN bytes.
*
* @param[out] random: output buffer, containing device challenge string.
* @param[inout] random_len: in - the output buffer size; out - the actual length.
*
* @return @see error code definitions.
*/
irot_result_t mdu_id2_get_device_challenge(uint8_t* random, uint32_t* random_len);
/**
* @brief verify the auth code from server.
*
* @param[in] auth_code: auth code string of server.
* @param[in] auth_code_len: the length of auth code.
* @param[in] device_random: device challenge string.
* @param[in] device_random_len: the length of device challenge.
* @param[in] server_extra: extra string of server.
* @param[in] server_extra_len: the length of extra.
*
* @return @see id2 error code definitions.
*/
irot_result_t mdu_id2_verify_server(
const uint8_t* auth_code, uint32_t auth_code_len,
const uint8_t* device_random, uint32_t device_random_len,
const uint8_t* server_extra, uint32_t server_extra_len);
/* @brief derive device secret based on id2.
*
* @param[in] seed: seed string, terminated with '\0', less than ID2_MAX_SEED_LEN.
* @param[out] secret: output buffer, containing secret string.
* @param[inout] secret_len: in - the length of secret buffer, should be more than ID2_DERIV_SECRET_LEN bytes.
* out - the actual secret string length.
*
* @return @see id2 error code definitions.
*/
irot_result_t mdu_id2_get_secret(const char* seed, uint8_t* secret, uint32_t* secret_len);
#ifdef __cplusplus
}
#endif
#endif /* __MDU_ID2_H__ */
<file_sep>/modules/id2/module/atcmd/mdu_id2_quec.c
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
#include "id2_priv.h"
#include "module/mdu_driver.h"
static void *handle = NULL;
irot_result_t mdu_id2_init(void)
{
irot_result_t ret;
ret = mdu_open_session(&handle);
if (ret != IROT_SUCCESS) {
id2_log_error("module open session fail, %d\n", ret);
return ret;
}
id2_log_info("not implemented!\n");
return IROT_ERROR_NOT_IMPLEMENTED;
}
irot_result_t mdu_id2_cleanup(void)
{
irot_result_t ret;
ret = mdu_close_session(handle);
if (ret != IROT_SUCCESS) {
id2_log_error("module close session fail, %d\n", ret);
return ret;
}
id2_log_info("not implemented!\n");
return IROT_ERROR_NOT_IMPLEMENTED;
}
irot_result_t mdu_id2_get_version(uint32_t* version)
{
id2_log_info("not implemented!\n");
return IROT_ERROR_NOT_IMPLEMENTED;
}
irot_result_t mdu_id2_get_id(uint8_t* id, uint32_t len)
{
id2_log_info("not implemented!\n");
return IROT_ERROR_NOT_IMPLEMENTED;
}
irot_result_t mdu_id2_get_auth_code(uint32_t type, const char* random,
const uint8_t* extra, uint32_t extra_len,
uint8_t* auth_code, uint32_t* auth_code_len)
{
id2_log_info("not implemented!\n");
return IROT_ERROR_NOT_IMPLEMENTED;
}
irot_result_t mdu_id2_decrypt(const uint8_t* in,
uint32_t in_len, uint8_t* out, uint32_t* out_len)
{
id2_log_info("not implemented!\n");
return IROT_ERROR_NOT_IMPLEMENTED;
}
irot_result_t mdu_id2_get_device_challenge(uint8_t* random, uint32_t* random_len)
{
id2_log_info("not implemented!\n");
return IROT_ERROR_NOT_IMPLEMENTED;
}
irot_result_t mdu_id2_verify_server(
const uint8_t* auth_code, uint32_t auth_code_len,
const uint8_t* device_random, uint32_t device_random_len,
const uint8_t* server_extra, uint32_t server_extra_len)
{
id2_log_info("not implemented!\n");
return IROT_ERROR_NOT_IMPLEMENTED;
}
irot_result_t mdu_id2_get_secret(const char* seed, uint8_t* secret, uint32_t* secret_len)
{
id2_log_info("not implemented!\n");
return IROT_ERROR_NOT_IMPLEMENTED;
}
<file_sep>/makefile
include ./make.settings
OSA_PATH := modules/osa
HAL_PATH := modules/hal
ID2_PATH := modules/id2
IROT_PATH := modules/irot
ITLS_PATH := modules/itls
CRYPTO_PATH := modules/crypto
APP_PATH := app
LIB_PATH := out/libs
BIN_PATH := out/bin
all:
ifeq ($(CONFIG_ID2_MDU), y)
mkdir -p $(LIB_PATH)
mkdir -p $(BIN_PATH)
@echo "Building osa..."
@make -C $(OSA_PATH)
cp -r $(OSA_PATH)/libls_osa.a $(LIB_PATH)
@echo "Building id2..."
@make -C $(ID2_PATH)
cp -r $(ID2_PATH)/libid2.a $(LIB_PATH)
@echo "Building id2 app..."
@make -C $(APP_PATH)
cp $(APP_PATH)/id2_app/id2_app $(BIN_PATH)
else
mkdir -p $(LIB_PATH)
mkdir -p $(BIN_PATH)
@echo "Building osa..."
@make -C $(OSA_PATH)
cp -r $(OSA_PATH)/libls_osa.a $(LIB_PATH)
@echo "Building hal..."
@make -C $(HAL_PATH)
cp -r $(HAL_PATH)/libls_hal.a $(LIB_PATH)
@echo "Building crypto..."
@make -C $(CRYPTO_PATH)
cp -r $(CRYPTO_PATH)/libicrypt.a $(LIB_PATH)
@echo "Building id2..."
@make -C $(ID2_PATH)
cp -r $(ID2_PATH)/libid2.a $(LIB_PATH)
@echo "Building irot..."
@make -C $(IROT_PATH)
cp -r $(IROT_PATH)/libkm.a $(LIB_PATH)
@echo "Building itls..."
@make -C $(ITLS_PATH)
cp -r $(ITLS_PATH)/libitls.a $(LIB_PATH)
@echo "Building id2 app..."
@make -C $(APP_PATH)
cp $(APP_PATH)/hal_app/hal_app $(BIN_PATH)
cp $(APP_PATH)/id2_app/id2_app $(BIN_PATH)
cp $(APP_PATH)/itls_app/itls_app $(BIN_PATH)
endif
clean:
rm -rf out
@make clean -C $(OSA_PATH)
@make clean -C $(HAL_PATH)
@make clean -C $(ID2_PATH)
@make clean -C $(IROT_PATH)
@make clean -C $(ITLS_PATH)
@make clean -C $(CRYPTO_PATH)
@make clean -C $(APP_PATH)
<file_sep>/modules/id2/makefile
include ../../make.rules
include ../../make.settings
ifeq ($(CONFIG_LS_ID2_ROT_TYPE), MDU)
CFLAGS += -I./inc
CFLAGS += -I../../include/osa
CFLAGS += -I../../include/id2
CFLAGS += -DCONFIG_ID2_MDU
ifeq ($(CONFIG_LS_ID2_DEBUG), Y)
CFLAGS += -DCONFIG_ID2_DEBUG
endif
SRCS += module/core/id2_client.c
SRCS += module/atcmd/mdu_id2_quec.c
SRCS += module/driver/template/mdu_driver.c
else #CONFIG_LS_ID2_ROT_TYPE
CFLAGS += -I./inc
CFLAGS += -I../../include/osa
CFLAGS += -I../../include/id2
CFLAGS += -I../../include/irot
CFLAGS += -I../../include/crypto
ifeq ($(CONFIG_LS_ID2_DEBUG), Y)
CFLAGS += -DCONFIG_ID2_DEBUG
endif
ifeq ($(CONFIG_LS_ID2_OTP), Y)
CFLAGS += -DCONFIG_ID2_OTP
endif
ifeq ($(CONFIG_LS_ID2_KEY_TYPE), 3DES)
CFLAGS += -DCONFIG_ID2_KEY_TYPE=ID2_KEY_TYPE_3DES
else ifeq ($(CONFIG_LS_ID2_KEY_TYPE), RSA)
CFLAGS += -DCONFIG_ID2_KEY_TYPE=ID2_KEY_TYPE_RSA
else ifeq ($(CONFIG_LS_ID2_KEY_TYPE), AES)
endif
SRCS += src/core/id2_client.c
SRCS += src/core/otp.c
SRCS += src/plat/id2_plat.c
SRCS += src/utils/id2_util.c
endif #CONFIG_LS_ID2_ROT_TYPE
OBJS := $(patsubst %.cxx,%.o,$(patsubst %.c,%.o,$(SRCS)))
OUT := libid2.a
$(OUT): $(OBJS)
$(AR) rc $(OUT) $(OBJS)
$(RANLIB) $(OUT)
%.o: %.c
$(CC) -c $(CFLAGS) $< -o $*.o
clean:
rm -f $(OBJS) .elf $(OUT)
<file_sep>/app/makefile
include ../make.settings
.PHONY: bin
bin:
ifeq ($(CONFIG_ID2_MDU), y)
make -C id2_app
else
make -C hal_app
make -C id2_app
make -C itls_app
endif
clean:
make clean -C hal_app
make clean -C id2_app
make clean -C itls_app
<file_sep>/README.md
# README for ID² Client SDK
<br />
IoT设备身份认证ID²(Internet Device ID),是一种物联网设备的可信身份标识,具备不可篡改、不可伪造、全球唯一的安全属性,是实现万物互联、服务流转的关键基础设施。<br />
<br />
ID² Client SDK是用于设备端开发和调试,帮助开发者快速接入ID²开放平台。此SDK, 支持三种载体Demo, SE(Secure Element)和MDU(安全模组):<br />
- Demo载体:用于ID²设备端功能的演示,正式产品,需切换到安全载体(Soft-KM, SE, TEE)。<br />
- SE载体:外挂安全芯片,ID²预烧录在SE芯片上。<br />
- MDU载体:安全模组,ID²密钥和SDK在模组中,主控通过A&T指令调用ID²的功能。
> |—— app:加解密硬件适配(HAL)接口和ID²接口的测试程序。<br />
> |—— doc:相关文档,如ID²指令规范。<br />
> |—— include:头文件目录。<br />
> |—— makefile:总的编译脚本。<br />
> |—— make.rules:编译配置,可配置编译工具链和编译参数。<br />
> |—— make.settings:ID²配置,如调试信息、空发功能和载体选择。<br />
> |—— modules:ID²和ID²依赖的模块。<br />
> |—— sample:示例代码。
<a name="cGT85"></a>
# 快速开始
描述在Ubuntu上编译和运行ID²Client SDK;其他编译环境,请参考makefile进行编译适配。
<a name="v7uOl"></a>
## 编译环境:
使用Ubuntu 14.04以上版本。
<a name="j7xHp"></a>
## 编译配置:
- make.rules:
> CROSS_COMPILE: 编译使用的工具链。<br />
> CFLAGS:编译工具链的编译参数。<br />
- make.settings:
> CONFIG_LS_ID2_DEBUG:ID²调试信息的开关。<br />
> CONFIG_LS_ID2_OTP:ID²密钥在使用时动态下发功能的开关。<br />
> CONFIG_LS_ID2_ROT_TYPE:ID²的安全载体的类型,SE/Demo/MDU。<br />
> CONFIG_LS_ID2_KEY_TYPE:ID²的密钥类型,3DES/RSA/AES。<br />
<a name="gG44j"></a>
## 编译SDK:
在SDK目录,运行如下命令:
> $ make clean <br />
> $ make <br />
编译成功,生成的静态库和应用程序统一放在SDK的out目录。
<a name="pPX46"></a>
## 运行程序:
在SDK目录,运行如下命令:
> ./out/bin/id2_app
测试成功(仅设备端接口测试,非真实交互验证),日志显示如下:
> <br />
> <LS_LOG> id2_client_get_id 649: ID2: 000FFFFFDB1D8DC78DDCB800 <br />
> <LS_LOG> id2_client_generate_authcode 170: <br />
> ============ ID2 Validation Json Message ============: <br />
> { <br />
> "reportVersion": "1.0.0", <br />
> "sdkVersion": "2.0.0", <br />
> "date": "Aug 23 2019 18:17:13", <br />
> "testContent": [{ <br />
> ....... <br />
> }] <br />
> } <br />
> <LS_LOG> id2_client_generate_authcode 186: =====>ID2 Client Generate AuthCode End. <br />
<a name="MUmQg"></a>
# 其他:
更多文档,如设备端适配和自主验证,请查阅官网文档:
https://help.aliyun.com/document_detail/101295.html
<br />
<file_sep>/modules/id2/module/core/id2_client.c
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include "id2_priv.h"
#include "id2_client.h"
#include "module/mdu_id2.h"
#define ID2_AUTH_CODE_BUF_LEN 256
static uint8_t s_id2_client_inited = 0;
static void _dump_id2_conf_info(void)
{
ls_osa_print("ID2 Client Build Time: %s %s\n", __DATE__, __TIME__);
ls_osa_print("-------------------------------------------\n");
#if defined(CONFIG_ID2_DEBUG)
ls_osa_print("CONFIG_ID2_DEBUG is defined!\n");
#else
ls_osa_print("CONFIG_ID2_DEBUG is not defined!\n");
#endif
if (CONFIG_ID2_MDU_TYPE == ID2_MDU_TYPE_QUECTEL) {
ls_osa_print("CONFIG_ID2_MDU_TYPE: %s\n", "ID2_MDU_TYPE_QUECTEL");
}
ls_osa_print("-------------------------------------------\n");
}
int is_id2_client_inited(void)
{
return s_id2_client_inited;
}
irot_result_t id2_client_init(void)
{
irot_result_t ret;
id2_log_debug("[id2_client_init enter.]\n");
_dump_id2_conf_info();
ret = mdu_id2_init();
if (ret != IROT_SUCCESS) {
id2_log_error("module init fail, %d\n", ret);
return ret;
}
s_id2_client_inited = 1;
return IROT_SUCCESS;
}
irot_result_t id2_client_cleanup(void)
{
irot_result_t ret;
id2_log_debug("[id2_client_cleanup enter.]\n");
ret = mdu_id2_cleanup();
if (ret != IROT_SUCCESS) {
id2_log_error("module cleanup fail, %d\n", ret);
return ret;
}
s_id2_client_inited = 0;
return IROT_SUCCESS;
}
irot_result_t id2_client_get_version(uint32_t* version)
{
irot_result_t ret;
id2_log_debug("[id2_client_get_version enter.]\n");
if (version == NULL) {
id2_log_error("invalid input arg.\n");
return IROT_ERROR_BAD_PARAMETERS;
}
ret = mdu_id2_get_version(version);
if (ret != IROT_SUCCESS) {
id2_log_error("module get version fail, %d\n", ret);
return ret;
}
return IROT_SUCCESS;
}
irot_result_t id2_client_get_id(uint8_t* id, uint32_t* len)
{
irot_result_t ret;
id2_log_debug("[id2_client_get_id enter.]\n");
if (id == NULL || len == NULL) {
id2_log_error("id or len is NULL\n");
return IROT_ERROR_BAD_PARAMETERS;
}
if (*len < ID2_ID_LEN) {
id2_log_error("short buffer, %d\n", *len);
*len = ID2_ID_LEN;
return IROT_ERROR_SHORT_BUFFER;
}
ret = mdu_id2_get_id(id, ID2_ID_LEN);
if (ret != IROT_SUCCESS) {
id2_log_error("module get id fail, %d\n", ret);
return ret;
}
*len = ID2_ID_LEN;
return IROT_SUCCESS;
}
irot_result_t id2_client_get_challenge_auth_code(const char* server_random,
const uint8_t* extra, uint32_t extra_len,
uint8_t* auth_code, uint32_t* auth_code_len)
{
irot_result_t ret;
id2_log_debug("[id2_client_get_challenge_auth_code enter.]\n");
if (auth_code == NULL || auth_code_len == NULL ||
server_random == NULL) {
id2_log_error("invalid input args\n");
return IROT_ERROR_BAD_PARAMETERS;
}
if (strlen(server_random) == 0 ||
strlen(server_random) > ID2_MAX_SERVER_RANDOM_LEN) {
id2_log_error("invalid server random length, %d\n", strlen(server_random));
return IROT_ERROR_BAD_PARAMETERS;
}
/* check extra */
if (extra_len > ID2_MAX_EXTRA_LEN || (
extra != NULL && extra_len == 0)) {
id2_log_error("invalid extra data length, %d\n", extra_len);
return IROT_ERROR_EXCESS_DATA;
}
/* check authcode */
if (*auth_code_len < ID2_AUTH_CODE_BUF_LEN) {
id2_log_error("auth code short buffer, %d %d\n",
*auth_code_len, ID2_AUTH_CODE_BUF_LEN);
*auth_code_len = ID2_AUTH_CODE_BUF_LEN;
return IROT_ERROR_SHORT_BUFFER;
}
ret = mdu_id2_get_auth_code(ID2_AUTH_TYPE_CHALLENGE,
server_random, extra, extra_len, auth_code, auth_code_len);
if (ret != IROT_SUCCESS) {
id2_log_error("module get auth code fail, %d\n", ret);
return ret;
}
return IROT_SUCCESS;
}
irot_result_t id2_client_get_timestamp_auth_code(const char* timestamp,
const uint8_t* extra, uint32_t extra_len,
uint8_t* auth_code, uint32_t* auth_code_len)
{
irot_result_t ret;
id2_log_debug("[id2_client_get_timestamp_auth_code enter.]\n");
if (auth_code == NULL || auth_code_len == NULL ||
timestamp == NULL) {
id2_log_error("invalid input args.\n");
return IROT_ERROR_BAD_PARAMETERS;
}
/* check extra */
if (extra_len > ID2_MAX_EXTRA_LEN || (
extra != NULL && extra_len == 0)) {
id2_log_error("invalid extra data length, %d.\n", extra_len);
return IROT_ERROR_EXCESS_DATA;
}
/* check authcode */
if (*auth_code_len < ID2_AUTH_CODE_BUF_LEN) {
id2_log_error("auth code short buffer, %d %d.\n",
*auth_code_len, ID2_AUTH_CODE_BUF_LEN);
*auth_code_len = ID2_AUTH_CODE_BUF_LEN;
return IROT_ERROR_SHORT_BUFFER;
}
ret = mdu_id2_get_auth_code(ID2_AUTH_TYPE_TIMESTAMP,
timestamp, extra, extra_len, auth_code, auth_code_len);
if (ret != IROT_SUCCESS) {
id2_log_error("module get auth code fail, %d\n", ret);
return ret;
}
return IROT_SUCCESS;
}
irot_result_t id2_client_decrypt(const uint8_t* in, uint32_t in_len, uint8_t* out, uint32_t* out_len)
{
irot_result_t ret;
id2_log_debug("[id2_client_decrypt enter.]\n");
if (in == NULL || in_len == 0 || out == NULL || out_len == NULL) {
id2_log_error("invalid input args.\n");
return IROT_ERROR_BAD_PARAMETERS;
}
if (in_len > ID2_MAX_CRYPT_LEN) {
id2_log_error("invalid input data length, %d.\n", in_len);
return IROT_ERROR_EXCESS_DATA;
}
ret = mdu_id2_decrypt(in, in_len, out, out_len);
if (ret != IROT_SUCCESS) {
id2_log_error("module id2 decrypt, %d\n", ret);
return ret;
}
return IROT_SUCCESS;
}
irot_result_t id2_client_get_device_challenge(uint8_t* random, uint32_t* random_len)
{
irot_result_t ret;
id2_log_debug("[id2_client_get_device_challenge enter.]\n");
if (random == NULL || random_len == NULL || *random_len == 0) {
id2_log_error("invalid input args.\n");
return IROT_ERROR_BAD_PARAMETERS;
}
ret = mdu_id2_get_device_challenge(random, random_len);
if (ret != IROT_SUCCESS) {
id2_log_error("module get device challenge fail, %d\n", ret);
return ret;
}
return IROT_SUCCESS;
}
irot_result_t id2_client_verify_server(
const uint8_t* auth_code, uint32_t auth_code_len,
const uint8_t* device_random, uint32_t device_random_len,
const uint8_t* server_extra, uint32_t server_extra_len)
{
irot_result_t ret;
id2_log_debug("[id2_client_verify_server enter.]\n");
if (auth_code == NULL || auth_code_len == 0) {
id2_log_error("invalid input args.\n");
return IROT_ERROR_BAD_PARAMETERS;
}
if (device_random != NULL && device_random_len == 0) {
id2_log_error("invalid device random length.\n");
return IROT_ERROR_BAD_PARAMETERS;
}
if (server_extra_len > ID2_MAX_EXTRA_LEN || (
server_extra != NULL && server_extra_len == 0)) {
id2_log_error("invalid server extra length, %d.\n", server_extra_len);
return IROT_ERROR_EXCESS_DATA;
}
ret = mdu_id2_verify_server(auth_code, auth_code_len,
device_random, device_random_len, server_extra, server_extra_len);
if (ret != IROT_SUCCESS) {
id2_log_error("module id2 verify server fail, %d\n", ret);
return ret;
}
return IROT_SUCCESS;
}
irot_result_t id2_client_get_secret(const char* seed, uint8_t* secret, uint32_t* secret_len)
{
irot_result_t ret;
uint32_t in_len;
id2_log_debug("[id2_client_get_secret enter.]\n");
if (seed == NULL || secret == NULL || secret_len == NULL) {
id2_log_error("invalid input args.\n");
return IROT_ERROR_BAD_PARAMETERS;
}
in_len = strlen(seed);
if (in_len == 0) {
id2_log_error("seed is null.\n");
return IROT_ERROR_BAD_PARAMETERS;
}
if (in_len > ID2_MAX_SEED_LEN) {
id2_log_error("seed is excess data.\n");
return IROT_ERROR_EXCESS_DATA;
}
if (*secret_len < ID2_DERIV_SECRET_LEN) {
id2_log_error("short buffer, %d.\n", *secret_len);
*secret_len = ID2_DERIV_SECRET_LEN;
return IROT_ERROR_SHORT_BUFFER;
}
ret = mdu_id2_get_secret(seed, secret, secret_len);
if (ret != IROT_SUCCESS) {
id2_log_error("module get secret fail, %d\n", ret);
return ret;
}
return IROT_SUCCESS;
}
irot_result_t id2_client_get_prov_stat(bool* is_prov)
{
uint8_t id2[ID2_ID_LEN];
uint32_t len = ID2_ID_LEN;
irot_result_t ret;
id2_log_debug("[id2_client_get_prov_stat enter.]\n");
if (!is_id2_client_inited()) {
id2_log_error("id2 not inited\n");
return IROT_ERROR_GENERIC;
}
if (is_prov == NULL) {
id2_log_error("invalid input arg\n");
return IROT_ERROR_BAD_PARAMETERS;
}
ret = mdu_id2_get_id(id2, len);
if (ret != IROT_SUCCESS) {
id2_log_error("module get id fail, %d\n", ret);
return ret;
}
*is_prov = true;
id2_log_info("id2 prov state: %s\n", *is_prov == true ? "true" : "false");
return IROT_SUCCESS;
}
irot_result_t id2_client_get_otp_auth_code(const uint8_t* token, uint32_t token_len,
uint8_t* auth_code, uint32_t* len)
{
(void)token;
(void)token_len;
(void)auth_code;
(void)len;
id2_log_info("not supported!!\n");
return IROT_ERROR_NOT_SUPPORTED;
}
irot_result_t id2_client_load_otp_data(const uint8_t* otp_data, uint32_t len)
{
(void)otp_data;
(void)len;
id2_log_info("not supported!!\n");
return IROT_ERROR_NOT_SUPPORTED;
}
irot_result_t id2_client_derive_key(const char* seed, uint8_t* key, uint32_t key_len)
{
(void)seed;
(void)key;
(void)key_len;
id2_log_info("not supported!!\n");
return IROT_ERROR_NOT_SUPPORTED;
}
irot_result_t id2_client_set_id2_and_key(const char* id2, int key_type, const char* key_value)
{
id2_log_info("not supported!\n");
return IROT_ERROR_NOT_SUPPORTED;
}
<file_sep>/modules/id2/inc/module/mdu_driver.h
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef __MDU_DRIVER_H__
#define __MDU_DRIVER_H__
#include "id2_client.h"
#ifdef __cplusplus
extern "C"
#endif
/**
* @brief open session and connect to module.
*
* @param handle
*
* @return @see error code definitions.
*/
irot_result_t mdu_open_session(void **handle);
/**
* @brief transmit AT command to module.
*
* @param handle
* @param req_buf request command buffer.
* @param req_len request command length.
* @param rsp_buf response command buffer.
* @param rsp_len input with response buffer length, output with real response length.
*
* @return @see error code definitions.
*/
irot_result_t mdu_transmit_command(void *handle, const uint8_t *req_buf, uint32_t req_len, uint8_t *rsp_buf, uint32_t *rsp_len);
/**
* @brief close session and disconnect to module.
*
* @param handle
*
* @return @see error code definitions.
*/
irot_result_t mdu_close_session(void *handle);
#ifdef __cplusplus
}
#endif
#endif /* __HAL_DRIVER_H__ */
<file_sep>/modules/id2/module/driver/template/mdu_driver.c
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
#include "id2_priv.h"
#include "module/mdu_driver.h"
irot_result_t mdu_open_session(void** handle)
{
return IROT_SUCCESS;
}
irot_result_t mdu_transmit_command(void* handle, const uint8_t* req_buf, const uint32_t req_len, uint8_t* rsp_buf, uint32_t* rsp_len)
{
id2_log_info("mdu transmit not implemented !!!\n");
memset(rsp_buf, 0x00, *rsp_len);
*rsp_len = 0x10;
return IROT_SUCCESS;
}
irot_result_t mdu_close_session(void* handle)
{
return IROT_SUCCESS;
}
<file_sep>/app/id2_app/app_entry.c
/*
* Copyright (C) 2017-2019 Alibaba Group Holding Limited
*/
#include "id2_test.h"
/* Hex String, getting from id2 console */
#define ID2_CIPHER_DATA "34632fec4a366aa384579b50c207a33612e4e8d9b543"
int main(int argc, char *argv[])
{
int ret;
uint32_t cipher_len = 0;
char *cipher_data = ID2_CIPHER_DATA;
if (argc >= 2) {
if (!strcmp(argv[1], "-set_data")) {
cipher_data = argv[2];
}
}
ret = id2_client_unit_test();
if (ret < 0) {
ID2_DBG_LOG("id2 client unit test fail!!\n");
return -1;
}
cipher_len = strlen(cipher_data);
ret = id2_client_generate_authcode();
if (ret < 0) {
ID2_DBG_LOG("id2 client generate authcode fail!!\n");
return -1;
}
cipher_len = strlen(cipher_data);
if (cipher_len > ID2_ID_LEN * 2) {
ret = id2_client_decrypt_data(cipher_data, cipher_len);
if (ret < 0) {
ID2_DBG_LOG("id2 client decrypt data fail!!\n");
return -1;
}
}
return 0;
}
| 262fd31d4a5db923432405689c4ab03214ddf734 | [
"Markdown",
"C",
"Makefile"
] | 11 | Makefile | humminglab/id2_client_sdk | ea60893ae301c68c20723628b4bd0341e698c0fd | e5ab167b6019feb0983c4a64b58229c244c2b996 |
refs/heads/master | <repo_name>JackieTien97/SOA_11<file_sep>/src/cn/edu/nju/jw/schema/学生信息类型.java
package cn.edu.nju.jw.schema;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import cn.edu.nju.schema.个人信息类型;
/**
* <p>学生信息类型 complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="学生信息类型">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="学号" type="{http://jw.nju.edu.cn/schema}学号类型"/>
* <element name="个人信息" type="{http://www.nju.edu.cn/schema}个人信息类型"/>
* <element name="课程列表" type="{http://jw.nju.edu.cn/schema}课程列表类型"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "\u5b66\u751f\u4fe1\u606f\u7c7b\u578b", propOrder = {
"\u5b66\u53f7",
"\u4e2a\u4eba\u4fe1\u606f",
"\u8bfe\u7a0b\u5217\u8868"
})
public class 学生信息类型 {
@XmlElement(required = true)
protected String 学号;
@XmlElement(required = true)
protected 个人信息类型 个人信息;
@XmlElement(required = true)
protected 课程列表类型 课程列表;
/**
* 获取学号属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String get学号() {
return 学号;
}
/**
* 设置学号属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void set学号(String value) {
this.学号 = value;
}
/**
* 获取个人信息属性的值。
*
* @return
* possible object is
* {@link 个人信息类型 }
*
*/
public 个人信息类型 get个人信息() {
return 个人信息;
}
/**
* 设置个人信息属性的值。
*
* @param value
* allowed object is
* {@link 个人信息类型 }
*
*/
public void set个人信息(个人信息类型 value) {
this.个人信息 = value;
}
/**
* 获取课程列表属性的值。
*
* @return
* possible object is
* {@link 课程列表类型 }
*
*/
public 课程列表类型 get课程列表() {
return 课程列表;
}
/**
* 设置课程列表属性的值。
*
* @param value
* allowed object is
* {@link 课程列表类型 }
*
*/
public void set课程列表(课程列表类型 value) {
this.课程列表 = value;
}
}
<file_sep>/src/homework/client/ScoreService.java
package homework.client;
import com.sun.xml.internal.ws.api.message.Headers;
import com.sun.xml.internal.ws.developer.WSBindingProvider;
import group8.service.*;
import homework.resolver.ComplexResolver;
import javax.xml.namespace.QName;
import javax.xml.ws.Holder;
public class ScoreService {
private static final String AUTH_NS = "http://nju.edu.cn/service/";
public void addScore(ArrayOfXsdAnyType listType, String email, String password) {
ScoreManagementService service = new ScoreManagementService();
service.setHandlerResolver(new ComplexResolver());
ScoreManagement scoreManage = service.getScoreManagement();
WSBindingProvider bp = (WSBindingProvider)scoreManage;
bp.setOutboundHeaders(Headers.create(new QName(AUTH_NS,"email"),email),
Headers.create(new QName(AUTH_NS,"password"),password));
Holder<ArrayOfXsdAnyType> param = new Holder<>(listType);
try {
scoreManage.addScoreOperation(listType);
} catch (InputFault inputFault) {
inputFault.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
public void deleteScore(ArrayOfXsdAnyType listType, String email, String password) {
ScoreManagementService service = new ScoreManagementService();
service.setHandlerResolver(new ComplexResolver());
ScoreManagement scoreManage = service.getScoreManagement();
WSBindingProvider bp = (WSBindingProvider)scoreManage;
bp.setOutboundHeaders(Headers.create(new QName(AUTH_NS,"email"),email),
Headers.create(new QName(AUTH_NS,"password"),password));
try {
scoreManage.deleteScoreOperation(listType);
} catch (InputFault inputFault) {
inputFault.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
public void queryScore(String sid, String email, String password) {
ScoreManagementService service = new ScoreManagementService();
service.setHandlerResolver(new ComplexResolver());
ScoreManagement scoreManage = service.getScoreManagement();
WSBindingProvider bp = (WSBindingProvider)scoreManage;
bp.setOutboundHeaders(Headers.create(new QName(AUTH_NS,"email"),email),
Headers.create(new QName(AUTH_NS,"password"),password));
try {
scoreManage.queryScoreOperation(sid);
} catch (InputFault inputFault) {
inputFault.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
public void modifyScore(ArrayOfXsdAnyType courseScore, String email, String password) {
ScoreManagementService service = new ScoreManagementService();
service.setHandlerResolver(new ComplexResolver());
ScoreManagement scoreManage = service.getScoreManagement();
WSBindingProvider bp = (WSBindingProvider)scoreManage;
bp.setOutboundHeaders(Headers.create(new QName(AUTH_NS,"email"),email),
Headers.create(new QName(AUTH_NS,"password"),password));
try {
scoreManage.modifyScoreOperation(courseScore);
} catch (InputFault inputFault) {
inputFault.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
}
<file_sep>/src/group8/service/StudentInfoManagement.java
package group8.service;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
/**
* This class was generated by Apache CXF 3.2.3
* 2018-04-04T17:03:10.066+08:00
* Generated source version: 3.2.3
*
*/
@WebService(targetNamespace = "http://group8.group8.service.example", name = "StudentInfoManagement")
@XmlSeeAlso({ObjectFactory.class, group8.service.fault.ObjectFactory.class, group8.service.model.ObjectFactory.class, group8.sax.ObjectFactory.class})
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface StudentInfoManagement {
@WebMethod
@WebResult(name = "retrieveStudentInfoOperationReturn", targetNamespace = "http://group8.group8.service.example", partName = "retrieveStudentInfoOperationReturn")
public group8.service.model.StudentInfo retrieveStudentInfoOperation(
@WebParam(partName = "studentToken", name = "studentToken1", targetNamespace = "http://group8.group8.service.example")
String studentToken
) throws SAXException, InputFault;
@WebMethod
@WebResult(name = "modifyStudentInfoOperationReturn", targetNamespace = "http://group8.group8.service.example", partName = "modifyStudentInfoOperationReturn")
public String modifyStudentInfoOperation(
@WebParam(partName = "studentToken", name = "studentToken", targetNamespace = "http://group8.group8.service.example")
String studentToken,
@WebParam(partName = "studentInfo", name = "studentInfo", targetNamespace = "http://group8.group8.service.example")
group8.service.model.StudentInfo studentInfo
) throws SAXException, InputFault;
}
<file_sep>/src/cn/edu/nju/jw/schema/账号认证类型.java
package cn.edu.nju.jw.schema;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>账号认证类型 complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="账号认证类型">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="邮箱" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="密码" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "\u8d26\u53f7\u8ba4\u8bc1\u7c7b\u578b", propOrder = {
"\u90ae\u7bb1",
"\u5bc6\u7801"
})
public class 账号认证类型 {
@XmlElement(required = true)
protected String 邮箱;
@XmlElement(required = true)
protected String 密码;
/**
* 获取邮箱属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String get邮箱() {
return 邮箱;
}
/**
* 设置邮箱属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void set邮箱(String value) {
this.邮箱 = value;
}
/**
* 获取密码属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String get密码() {
return 密码;
}
/**
* 设置密码属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void set密码(String value) {
this.密码 = value;
}
}
<file_sep>/src/cn/edu/nju/schema/部门信息类型.java
package cn.edu.nju.schema;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>部门信息类型 complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="部门信息类型">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="部门编号" type="{http://www.nju.edu.cn/schema}部门编号类型"/>
* <element name="部门名称" type="{http://www.nju.edu.cn/schema}部门名称类型"/>
* <element name="部门电话" type="{http://www.nju.edu.cn/schema}部门电话类型"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "\u90e8\u95e8\u4fe1\u606f\u7c7b\u578b", propOrder = {
"\u90e8\u95e8\u7f16\u53f7",
"\u90e8\u95e8\u540d\u79f0",
"\u90e8\u95e8\u7535\u8bdd"
})
public class 部门信息类型 {
@XmlElement(required = true)
protected String 部门编号;
@XmlElement(required = true)
protected String 部门名称;
@XmlElement(required = true)
protected String 部门电话;
/**
* 获取部门编号属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String get部门编号() {
return 部门编号;
}
/**
* 设置部门编号属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void set部门编号(String value) {
this.部门编号 = value;
}
/**
* 获取部门名称属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String get部门名称() {
return 部门名称;
}
/**
* 设置部门名称属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void set部门名称(String value) {
this.部门名称 = value;
}
/**
* 获取部门电话属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String get部门电话() {
return 部门电话;
}
/**
* 设置部门电话属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void set部门电话(String value) {
this.部门电话 = value;
}
}
<file_sep>/src/group8/service/ObjectFactory.java
package group8.service;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
import group8.service.fault.InputFault;
import group8.service.model.StudentInfo;
import group8.sax.SAXException;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the group8.group8.group8.service package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _StudentToken_QNAME = new QName("http://group8.group8.service.example", "studentToken");
private final static QName _StudentInfo_QNAME = new QName("http://group8.group8.service.example", "studentInfo");
private final static QName _ModifyStudentInfoOperationReturn_QNAME = new QName("http://group8.group8.service.example", "modifyStudentInfoOperationReturn");
private final static QName _Fault_QNAME = new QName("http://group8.group8.service.example", "fault");
private final static QName _Fault1_QNAME = new QName("http://group8.group8.service.example", "fault1");
private final static QName _StudentToken1_QNAME = new QName("http://group8.group8.service.example", "studentToken1");
private final static QName _RetrieveStudentInfoOperationReturn_QNAME = new QName("http://group8.group8.service.example", "retrieveStudentInfoOperationReturn");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: group8.group8.group8.service
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://group8.group8.service.example", name = "studentToken")
public JAXBElement<String> createStudentToken(String value) {
return new JAXBElement<String>(_StudentToken_QNAME, String.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link StudentInfo }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://group8.group8.service.example", name = "studentInfo")
public JAXBElement<StudentInfo> createStudentInfo(StudentInfo value) {
return new JAXBElement<StudentInfo>(_StudentInfo_QNAME, StudentInfo.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://group8.group8.service.example", name = "modifyStudentInfoOperationReturn")
public JAXBElement<String> createModifyStudentInfoOperationReturn(String value) {
return new JAXBElement<String>(_ModifyStudentInfoOperationReturn_QNAME, String.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SAXException }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://group8.group8.service.example", name = "fault")
public JAXBElement<SAXException> createFault(SAXException value) {
return new JAXBElement<SAXException>(_Fault_QNAME, SAXException.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link InputFault }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://group8.group8.service.example", name = "fault1")
public JAXBElement<InputFault> createFault1(InputFault value) {
return new JAXBElement<InputFault>(_Fault1_QNAME, InputFault.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://group8.group8.service.example", name = "studentToken1")
public JAXBElement<String> createStudentToken1(String value) {
return new JAXBElement<String>(_StudentToken1_QNAME, String.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link StudentInfo }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://group8.group8.service.example", name = "retrieveStudentInfoOperationReturn")
public JAXBElement<StudentInfo> createRetrieveStudentInfoOperationReturn(StudentInfo value) {
return new JAXBElement<StudentInfo>(_RetrieveStudentInfoOperationReturn_QNAME, StudentInfo.class, null, value);
}
}
<file_sep>/src/group8/model/StudentIDAuthMsg.java
package group8.model;
public class StudentIDAuthMsg {
public String id;
public String pwd;
}
<file_sep>/src/cn/edu/nju/schema/个人信息类型.java
package cn.edu.nju.schema;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>个人信息类型 complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="个人信息类型">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="姓名" type="{http://www.nju.edu.cn/schema}姓名类型"/>
* <element name="性别" type="{http://www.nju.edu.cn/schema}性别类型"/>
* <element name="身份证号码" type="{http://www.nju.edu.cn/schema}身份证号码类型"/>
* <element name="部门信息" type="{http://www.nju.edu.cn/schema}部门信息类型"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "\u4e2a\u4eba\u4fe1\u606f\u7c7b\u578b", propOrder = {
"\u59d3\u540d",
"\u6027\u522b",
"\u8eab\u4efd\u8bc1\u53f7\u7801",
"\u90e8\u95e8\u4fe1\u606f"
})
public class 个人信息类型 {
@XmlElement(required = true)
protected 姓名类型 姓名;
@XmlElement(required = true)
@XmlSchemaType(name = "string")
protected 性别类型 性别;
@XmlElement(required = true)
protected String 身份证号码;
@XmlElement(required = true)
protected 部门信息类型 部门信息;
/**
* 获取姓名属性的值。
*
* @return
* possible object is
* {@link 姓名类型 }
*
*/
public 姓名类型 get姓名() {
return 姓名;
}
/**
* 设置姓名属性的值。
*
* @param value
* allowed object is
* {@link 姓名类型 }
*
*/
public void set姓名(姓名类型 value) {
this.姓名 = value;
}
/**
* 获取性别属性的值。
*
* @return
* possible object is
* {@link 性别类型 }
*
*/
public 性别类型 get性别() {
return 性别;
}
/**
* 设置性别属性的值。
*
* @param value
* allowed object is
* {@link 性别类型 }
*
*/
public void set性别(性别类型 value) {
this.性别 = value;
}
/**
* 获取身份证号码属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String get身份证号码() {
return 身份证号码;
}
/**
* 设置身份证号码属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void set身份证号码(String value) {
this.身份证号码 = value;
}
/**
* 获取部门信息属性的值。
*
* @return
* possible object is
* {@link 部门信息类型 }
*
*/
public 部门信息类型 get部门信息() {
return 部门信息;
}
/**
* 设置部门信息属性的值。
*
* @param value
* allowed object is
* {@link 部门信息类型 }
*
*/
public void set部门信息(部门信息类型 value) {
this.部门信息 = value;
}
}
<file_sep>/src/group8/model/DeleteScore.java
package group8.model;
public class DeleteScore {
public String sid;
public String cid;
public String scoreType;
}
<file_sep>/src/group8/model/Department.java
package group8.model;
public class Department {
private String departmentId;
private String departmentName;
private String departmentClass;
}
<file_sep>/src/group8/service/ScoreManagement.java
package group8.service;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
/**
* This class was generated by Apache CXF 3.2.3
* 2018-04-04T17:02:39.086+08:00
* Generated source version: 3.2.3
*
*/
@WebService(targetNamespace = "http://group8.group8.service", name = "ScoreManagement")
@XmlSeeAlso({group8.service.fault.ObjectFactory.class, group8.service.model.ObjectFactory.class, ObjectFactory.class, group8.sax.ObjectFactory.class})
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface ScoreManagement {
@WebMethod
@WebResult(name = "queryScoreOperationReturn", targetNamespace = "http://group8.group8.service", partName = "queryScoreOperationReturn")
public ArrayOfXsdAnyType queryScoreOperation(
@WebParam(partName = "sidList", name = "sidList", targetNamespace = "http://group8.group8.service")
String sidList
) throws SAXException, InputFault;
@WebMethod
@WebResult(name = "deleteScoreOperationReturn", targetNamespace = "http://group8.group8.service", partName = "deleteScoreOperationReturn")
public group8.service.model.RequestResult deleteScoreOperation(
@WebParam(partName = "deleteScoreList", name = "deleteScoreList", targetNamespace = "http://group8.group8.service")
ArrayOfXsdAnyType deleteScoreList
) throws SAXException, InputFault;
@WebMethod
@WebResult(name = "modifyScoreOperationReturn", targetNamespace = "http://group8.group8.service", partName = "modifyScoreOperationReturn")
public group8.service.model.RequestResult modifyScoreOperation(
@WebParam(partName = "modifyScoreList", name = "modifyScoreList", targetNamespace = "http://group8.group8.service")
ArrayOfXsdAnyType modifyScoreList
) throws SAXException, InputFault;
@WebMethod
@WebResult(name = "addScoreOperationReturn", targetNamespace = "http://group8.group8.service", partName = "addScoreOperationReturn")
public group8.service.model.RequestResult addScoreOperation(
@WebParam(partName = "addScoreList", name = "addScoreList", targetNamespace = "http://group8.group8.service")
ArrayOfXsdAnyType addScoreList
) throws SAXException, InputFault;
}
<file_sep>/src/group8/fault/InputFaultType.java
package group8.fault;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "InputFaultType")
public class InputFaultType {
@XmlAttribute
protected String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
<file_sep>/src/homework/resolver/ComplexResolver.java
package homework.resolver;
import homework.handler.AuthIdentityHandler;
import homework.handler.LogHandler;
import homework.handler.StudentModifyHandler;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;
import java.util.ArrayList;
import java.util.List;
public class ComplexResolver implements HandlerResolver{
@Override
public List<Handler> getHandlerChain(PortInfo portInfo) {
List<Handler> handlers = new ArrayList<>();
handlers.add(new LogHandler());
handlers.add(new AuthIdentityHandler());
handlers.add(new StudentModifyHandler());
return handlers;
}
}
<file_sep>/src/group8/sax/package-info.java
@javax.xml.bind.annotation.XmlSchema(namespace = "http://sax.xml.org", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package group8.sax;
<file_sep>/src/cn/edu/nju/jw/schema/PswErrorException.java
package cn.edu.nju.jw.schema;
import javax.xml.ws.WebFault;
/**
* This class was generated by Apache CXF 3.2.3
* 2018-04-04T16:53:07.067+08:00
* Generated source version: 3.2.3
*/
@WebFault(name = "AuthFault", targetNamespace = "http://jw.nju.edu.cn/schema")
public class PswErrorException extends Exception {
private cn.edu.nju.jw.schema.AuthFaultType authFault;
public PswErrorException() {
super();
}
public PswErrorException(String message) {
super(message);
}
public PswErrorException(String message, java.lang.Throwable cause) {
super(message, cause);
}
public PswErrorException(String message, cn.edu.nju.jw.schema.AuthFaultType authFault) {
super(message);
this.authFault = authFault;
}
public PswErrorException(String message, cn.edu.nju.jw.schema.AuthFaultType authFault, java.lang.Throwable cause) {
super(message, cause);
this.authFault = authFault;
}
public cn.edu.nju.jw.schema.AuthFaultType getFaultInfo() {
return this.authFault;
}
}
<file_sep>/src/cn/edu/nju/jw/schema/权限级别.java
package cn.edu.nju.jw.schema;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>权限级别的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
* <p>
* <pre>
* <simpleType name="权限级别">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="老师"/>
* <enumeration value="研究生"/>
* <enumeration value="本科生"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "\u6743\u9650\u7ea7\u522b")
@XmlEnum
public enum 权限级别 {
老师,
研究生,
本科生;
public String value() {
return name();
}
public static 权限级别 fromValue(String v) {
return valueOf(v);
}
}
<file_sep>/src/homework/handler/StudentModifyHandler.java
package homework.handler;
import group8.model.Score;
import group8.service.InputFault;
import group8.service.SAXException;
import group8.service.StudentInfoManagement;
import group8.service.StudentInfoManagementService;
import homework.resolver.DefaultResolver;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class StudentModifyHandler implements SOAPHandler<SOAPMessageContext> {
@Override
public Set<QName> getHeaders() {
return null;
}
@Override
public boolean handleMessage(SOAPMessageContext context) {
if (!(Boolean) context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY)) {
StudentInfoManagementService serviceImplService = new StudentInfoManagementService();
serviceImplService.setHandlerResolver(new DefaultResolver());
StudentInfoManagement service = serviceImplService.getStudentInfoManagement();
try {
SOAPBody soapBody = context.getMessage().getSOAPBody();
Node courseScoreList = soapBody.getFirstChild();
NodeList courseScores = courseScoreList.getChildNodes();
for (int i = 0; i < courseScores.getLength(); i++) {
Node courseScore = courseScores.item(i);
String cid = courseScore.getAttributes().getNamedItem("课程编号").getTextContent();
String ctype = courseScore.getAttributes().getNamedItem("成绩性质").getTextContent();
NodeList scores = courseScore.getChildNodes();
for (int j = 0; j < scores.getLength(); j++) {
Node score = scores.item(j);
String sid = score.getChildNodes().item(0).getTextContent();
String scoreStr = score.getChildNodes().item(1).getTextContent();
Score courseScoreType = new Score();
courseScoreType.cid = cid;
courseScoreType.type = ctype;
List<Score> scoreTypes = new ArrayList<>();
Score scoreType = new Score();
scoreType.score = Integer.parseInt(scoreStr);
scoreTypes.add(scoreType);
service.modifyStudentInfoOperation(sid, service.retrieveStudentInfoOperation(sid));
}
}
} catch (InputFault inputFault) {
inputFault.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (SOAPException e) {
e.printStackTrace();
}
}
return true;
}
@Override
public boolean handleFault(SOAPMessageContext context) {
return true;
}
@Override
public void close(MessageContext context) {
}
}
| a11bee0ce513d6e46b2581cba08605fd38808aa1 | [
"Java"
] | 17 | Java | JackieTien97/SOA_11 | 8c4e3b6085469108eca30ecd3c1e1501ebde054e | a67bd3d2acc9626d1e3fd2ec1b19841fd2c54e79 |
refs/heads/master | <repo_name>clevedkm/cdkm_angular_ecran<file_sep>/src/controllers/ecran1.js
angular.module('ecransBNP', ["ngTable", 'angularUtils.directives.dirPagination'])
.controller('ecran1_BNP_Controller', function ($scope){
var elementCountry = this;
elementCountry.countrys =[
{name:'France', all: 0, none: 0, custom: 0 },
{name:'Allemagne', all: 0, none: 0, custom: 0 },
{name:'Congo', all: 0, none: 0, custom: 0 },
{name:'Belgique', all: 0, none: 0, custom: 0 },
{name:'Italie', all: 0, none: 0, custom: 0 },
{name:'Espagne', all: 0, none: 0, custom: 0 },
{name:'Pologne', all: 0, none: 0, custom: 0 },
{name:'Luxembourg', all: 0, none: 0, custom: 0 },
{name:'Luxembourg', all: 0, none: 0, custom: 0 },
{name:'Luxembourg', all: 0, none: 0, custom: 0 },
];
elementCountry.nomberCountry = function (){
var count = 0;
for(var i = 1; i <= elementCountry.countrys.length; i++){
count = i;
}
return count;
};
$scope.sort = function(keyName){
$scope.sortKey = keyName;
$scope.reverse = !$scope.reverse;
};
}); | 12ee74fbdfac15341910b16a4aa38fd040d8bf5a | [
"JavaScript"
] | 1 | JavaScript | clevedkm/cdkm_angular_ecran | 19be55b01e125abd526eff278486ab22db90b876 | 2b7deed02ca732381376e47b41f18177ee77ed17 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
//
public function md5test()
{
echo "接收端 >>>>"; echo '</br>';
echo '<pre>';print_r($_GET);echo '</pre>';
$key = "1905"; // 计算签名的KEY
//验签
$data = $_GET['data']; //接收到的数据
$signature = $_GET['signature']; //发送端的签名
// 计算签名
echo "接收到的签名:". $signature;echo '</br>';
$s = md5($data.$key);
echo '接收端计算的签名:'. $s;echo '</br>';
//与接收到的签名 比对
if($s == $signature)
{
echo "验签通过";
}else{
echo "验签失败";
}
echo '1234';
}
public function check2()
{
$key = "1905"; // 计算签名的key
echo '<pre>';print_r($_POST);
//接收数据 和 签名
$json_data = $_POST['data'];
$sign = $_POST['sign'];
//计算签名
$sign2 = md5($json_data.$key);
echo "接收端计算的签名:".$sign2;echo "<br>";
// 比较接收到的签名
if($sign2==$sign){
echo "验签成功";
}else{
echo "验签失败";
}
}
//私钥解密
public function rsadescypt1()
{
$enc_data_str = $_GET['data'];
echo "</br>";
echo "接收到的base64的密文:".$enc_data_str;echo "</br>";
$base64_decode_str = base64_decode($enc_data_str);
echo "base64decode 密文:".$base64_decode_str;echo "</br>";
//解密
$pub_key = trim(file_get_contents(storage_path('keys/pub.key')));
// echo $pub_key;
openssl_public_decrypt($base64_decode_str,$dec_data,$pub_key);
echo "解密数据:".$dec_data;echo "</br>";
}
//对称加密
public function aes(){
$str='huangxiaobo1111'; //待加密的数据
$method='AES-256-CBC'; //加密方式
$key='<KEY>'; //加密的密钥
$iv='jingtdjopvrfhutd'; //必须为16位
//加密函数进行加密
$enc=openssl_encrypt($str,$method,$key,OPENSSL_RAW_DATA,$iv);
//不可读模式转换成可读模式
$str_base=base64_encode($enc);
//转换为可传输数据类型
$str_url=urlencode($str_base);
$url='http://1905server.com/sign/aes?str='.$str_url;
$g=file_get_contents($url);
echo $g;
// $d=openssl_decrypt($enc,$method,$key,OPENSSL_RAW_DATA,$iv);
// echo $d;
}
} | ae1fef961ac9924121687b8b02c6d0a1e8972674 | [
"PHP"
] | 1 | PHP | 429324527/passport | bfffcfd0af79ce0dfbe2da4baa279cfad54db8f6 | cd96cf171018bd63a7b034f2fa25e261592b89d7 |
refs/heads/master | <file_sep>using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
using System;
using System.Collections.Specialized;
namespace Elmah
{
public class NameValueCollectionSerializer : SerializerBase<object>
{
private static readonly NameValueCollectionSerializer instance = new NameValueCollectionSerializer();
public static NameValueCollectionSerializer Instance
{
get { return instance; }
}
public override object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var bsonType = context.Reader.GetCurrentBsonType();
if (bsonType == BsonType.Null)
{
context.Reader.ReadNull();
return null;
}
var nvc = new NameValueCollection();
var stringSerializer = new StringSerializer();
context.Reader.ReadStartArray();
while (context.Reader.ReadBsonType() != BsonType.EndOfDocument)
{
context.Reader.ReadStartArray();
var key = (string)stringSerializer.Deserialize(context, args);
var val = (string)stringSerializer.Deserialize(context, args);
context.Reader.ReadEndArray();
nvc.Add(key, val);
}
context.Reader.ReadEndArray();
return nvc;
}
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
{
if (value == null)
{
context.Writer.WriteNull();
return;
}
var nvc = (NameValueCollection)value;
var stringSerializer = new StringSerializer();
context.Writer.WriteStartArray();
foreach (var key in nvc.AllKeys)
{
foreach (var val in nvc.GetValues(key))
{
context.Writer.WriteStartArray();
stringSerializer.Serialize(context, args, key);
stringSerializer.Serialize(context, args, val);
context.Writer.WriteEndArray();
}
}
context.Writer.WriteEndArray();
}
}
} | 6f75d6228d29fb63141720cf7aeec9996511ff92 | [
"C#"
] | 1 | C# | bart-antiope/elmah-mongodb | 379fd17e9100677d8c80dc113a57f941a229c8ab | 51778bc330c078080b068e47623d3211d67dfad2 |
refs/heads/master | <file_sep># Android Rich Text
The project is mostly in draft state. Let it serve as an example for
accomplishing Rich Text capabilities by using Android's `EditText`.
Included in this small project is also an example for animating drawables
using `ImageSpan`. The example contains an intermediate loading animation
as well as a progress bar for when an image is being downloaded.<file_sep>package com.benbarkay.mobilizetest.richtext;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.SystemClock;
import android.text.Editable;
import android.text.Selection;
import android.text.SpanWatcher;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.text.style.StyleSpan;
import com.benbarkay.mobilizetest.util.Range;
import com.benbarkay.mobilizetest.util.Removable;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
public class RichTextEditable extends SpannableStringBuilder implements RichText {
public static class Factory extends Editable.Factory {
@Override
public Editable newEditable(CharSequence source) {
return new RichTextEditable();
}
}
@Override
public RichText style(Style style, boolean on) {
style(style, selection(), on);
return this;
}
@Override
public RichText style(Style style, Range range, boolean on) {
if (on) {
insertStyle(range, convertStyle(style));
} else {
removeStyle(range, convertStyle(style));
}
return this;
}
private int convertStyle(Style style) {
switch (style) {
case BOLD: return Typeface.BOLD;
case ITALIC: return Typeface.ITALIC;
}
return -1;
}
private Style convertStyle(int style) {
switch (style) {
case Typeface.BOLD: return Style.BOLD;
case Typeface.ITALIC: return Style.ITALIC;
}
return null;
}
private void insertStyle(Range range, int style) {
if (range.length() == 0) {
setSpan(new StyleSpan(style), range.getStart(), range.getEnd(), SPAN_COMPOSING);
} else {
int boldStart = range.getStart();
int boldEnd = range.getEnd();
Set<StyleSpan> relevantSpans = new HashSet<>();
relevantSpans.addAll(Arrays.asList(getSpans(range.getStart(), range.getStart(), StyleSpan.class)));
relevantSpans.addAll(Arrays.asList(getSpans(range.getStart(), range.getEnd(), StyleSpan.class)));
relevantSpans.addAll(Arrays.asList(getSpans(range.getEnd(), range.getEnd(), StyleSpan.class)));
for (StyleSpan styleSpan : relevantSpans) {
if (styleSpan.getStyle() == style) {
boldStart = Math.min(boldStart, getSpanStart(styleSpan));
boldEnd = Math.max(boldEnd, getSpanEnd(styleSpan));
removeSpan(styleSpan);
}
}
setSpan(new StyleSpan(style), boldStart, boldEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
private void removeStyle(Range range, int style) {
for (StyleSpan styleSpan : getSpans(range.getStart(), range.getEnd(), StyleSpan.class)) {
if (styleSpan.getStyle() == style) {
int spanStart = getSpanStart(styleSpan);
int spanEnd = getSpanEnd(styleSpan);
if (range.after(spanStart)) {
setSpan(new StyleSpan(style), spanStart, range.getStart(), SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (range.before(spanEnd)) {
setSpan(new StyleSpan(style), range.getEnd(), spanEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
}
removeSpan(styleSpan);
}
}
}
@Override
public RichText drawable(final Drawable drawable, int position, String text, final Handler handler) {
// This is required to keep the callback from being garbage collected -- drawables only
// keep a weak reference.
final AtomicReference<Drawable.Callback> callbackRef = new AtomicReference<>();
final ImageSpan imageSpan = new ImageSpan(drawable) {
Object cbRef = callbackRef;
};
insert(position, text);
setSpan(imageSpan, position, position + text.length(), 0);
Drawable.Callback callback = new Drawable.Callback() {
@Override
public void invalidateDrawable(Drawable who) {
int start = getSpanStart(imageSpan);
int end = getSpanEnd(imageSpan);
if (start != -1 && end != -1) {
setSpan(imageSpan, start, end, 0);
}
}
@Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
handler.postDelayed(what, when - SystemClock.uptimeMillis());
}
@Override
public void unscheduleDrawable(Drawable who, Runnable what) {
handler.removeCallbacks(what);
}
};
callbackRef.set(callback);
drawable.setCallback(callback);
return this;
}
@Override
public Collection<Style> activeStyles() {
return activeStyles(selection());
}
@Override
public Collection<Style> activeStyles(Range range) {
Collection<Style> styles = new HashSet<>();
for (StyleSpan styleSpan : getSpans(range.getStart(), range.getEnd(), StyleSpan.class)) {
Style style = convertStyle(styleSpan.getStyle());
if (style != null) {
int styleStart = getSpanStart(styleSpan);
int styleEnd = getSpanEnd(styleSpan);
if (range.length() == 0) {
int styleFlags = getSpanFlags(styleSpan);
if (!testFlag(styleFlags, SPAN_INCLUSIVE_INCLUSIVE) && !testFlag(styleFlags, SPAN_COMPOSING)) {
if ((range.getStart() == styleStart && !testFlag(styleFlags, SPAN_INCLUSIVE_EXCLUSIVE)) ||
(range.getEnd() == styleEnd && !testFlag(styleFlags, SPAN_EXCLUSIVE_INCLUSIVE))) {
continue;
}
}
} else if (styleStart > range.getStart() || styleEnd < range.getEnd()) {
continue;
}
styles.add(style);
}
}
return styles;
}
@Override
public Range selection() {
return new Range(
getSpanStart(Selection.SELECTION_START),
getSpanEnd(Selection.SELECTION_END)
);
}
@Override
public Removable selection(final SelectionListener listener) {
final SpanWatcher spanWatcher = new SpanWatcher() {
private int startPosition;
private Range range;
@Override
public void onSpanAdded(Spannable text, Object what, int start, int end) {
publishRange();
}
@Override
public void onSpanRemoved(Spannable text, Object what, int start, int end) {
publishRange();
}
@Override
public void onSpanChanged(Spannable text, Object what, int ostart, int oend, int nstart, int nend) {
if (what == Selection.SELECTION_START) {
startPosition = nstart;
} else if (what == Selection.SELECTION_END) {
range = new Range(startPosition, nstart);
publishRange();
}
}
private void publishRange() {
if (range != null) {
listener.selectionChanged(range);
}
}
};
setSpan(spanWatcher, 0, 0, SPAN_INCLUSIVE_INCLUSIVE);
return new Removable() {
@Override
public void remove() {
removeSpan(spanWatcher);
}
};
}
@Override
public SpannableStringBuilder replace(int start, int end, CharSequence tb, int tbstart, int tbend) {
super.replace(start, end, tb, tbstart, tbend);
if (tb.length() > 0) {
for (StyleSpan styleSpan : getSpans(start, end, StyleSpan.class)) {
int flags = getSpanFlags(styleSpan);
if (testFlag(flags, SPAN_COMPOSING)) {
style(convertStyle(styleSpan.getStyle()), new Range(start + tbstart, end + tbend), true);
setSpan(new StyleSpan(styleSpan.getStyle()), start + tbstart, end + tbend, SPAN_COMPOSING);
}
}
}
return this;
}
private boolean testFlag(int bitmask, int flag) {
return (bitmask & flag) == flag;
}
@Override
public RichTextEditable append(CharSequence text) {
return (RichTextEditable)super.append(text);
}
}
<file_sep>package com.benbarkay.mobilizetest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
public class MobilizeTestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
myToolbar.setTitle(R.string.compose_post);
setSupportActionBar(myToolbar);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.editor_frame, new TextEditorFragment(), "editor")
.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mobilize_test_menu, menu);
return true;
}
}
| cc9f8797b19addfbc15ed2c36daf9b62fa229f70 | [
"Markdown",
"Java"
] | 3 | Markdown | benbarkay/rich-text-example-android | 495d9b1b8a8eb86592080abd86ede23310f32098 | 73ca9b0084746c7f2f1db00c8cb8bab50a88506b |
refs/heads/master | <file_sep>var mongoose = require('mongoose');
//create price schema
var priceSchema = mongoose.Schema({
ticker: {
type: String
},
price: {
type: Number
},
percentChange: {
type: Number
},
create_date:{
type: Date,
}
});
var Price = module.exports = mongoose.model('Price', priceSchema); //make copy of schema and export to outside
//find quote history by ticker
module.exports.getQuotesByTicker = function(ticker, callback){
var query = {
ticker: ticker
};
Price.aggregate(
{$match: query},
{$project: {
_id:0,
ticker:1,
price:1,
percentChange:1,
create_date:1
}},
{$sort: {create_date: -1}}
)
.exec(callback);
};
//find quote by ticker and date
module.exports.getQuotesByTickerAndDate = function(ticker, date, callback){
var today = new Date();
var start = date;
var query = {
create_date: { $gte: start, $lt: today },
ticker: ticker
};
Price.aggregate(
{$match: query},
{$project: {
_id:0,
ticker:1,
price:1,
percentChange:1,
create_date:1
}},
{$sort: {create_date: 1}}
)
.exec(callback);
};
<file_sep>var passport = require('passport');
var express = require('express');
var jwt = require('jwt-simple');
var async = require('async');
// bundle our routes
var router = express.Router();
// get mongoose models
var User = require('../models/user');
var Basket = require('../models/basket');
var Term = require('../models/term');
var Price = require('../models/price');
// get db config file
var config = require('../config/database');
// pass passport for configuration
require('../config/passport')(passport);
// create a new user account
router.post('/signup', function(req, res) {
if (!req.body.name || !req.body.email || !req.body.password) {
res.json({success: false, msg: 'Please enter your name, email and password.'});
} else {
var newUser = new User({
name: req.body.name,
email: req.body.email,
password: <PASSWORD>
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'User already exists.'});
}
res.json({success: true, msg: 'Signup success!'});
});
}
});
// route to authenticate a user
router.post('/authenticate', function(req, res) {
User.findOne({
email: req.body.email
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
}
else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token, UserId: user._id, msg: 'Welcome back, ' + user.name + '!'});
}
else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
// get user profile
router.post('/profile/', function(req, res) {
var userid = req.body.userid;
User.getProfile(userid, function(err, profile){
if(err){
throw err;
}
var d = new Date (profile[0].create_date);
var date = d.toISOString().substring(0, 10);
res.json({success: true, name: profile[0].name, email: profile[0].email, "date joined": date});
});
});
// route to change email
router.post('/update-email', function(req, res) {
var email = req.body.email;
var newEmail = req.body.newEmail;
var password = <PASSWORD>;
User.findOne({
email: email
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Incorrect email. User not found.'});
}
else {
// check if password matches
user.comparePassword(password, function (err, isMatch) {
if (isMatch && !err) {
User.updateEmail(email, newEmail, {}, function(err, update){
if(err) {
return res.json({success: false, msg: 'Email already taken.'});
}
res.json({success: true, msg: "Your email is now updated to " + newEmail});
});
}
else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
// route to change password
router.post('/update-password', function(req, res) {
var email = req.body.email;
var oldPassword = req.body.oldPassword;
var newPassword = req.body.newPassword;
var newPassword2 = req.body.newPassword2;
User.findOne({
email: email
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Incorrect email. User not found.'});
}
else {
// check if password matches
user.comparePassword(oldPassword, function (err, isMatch) {
if (isMatch && !err) {
if(newPassword !== <PASSWORD>){
res.json({success: false, msg: "New password and confirm password do not match."});
}
else{
user.password = <PASSWORD>;
user.save(function(err){
if (err) { next(err) }
else {
res.json({success: true, msg: "Your password is now updated."});
}
})
}
}
else {
res.send({success: false, msg: 'Authentication failed. Wrong old password entered.'});
}
});
}
});
});
// get all baskets by user Id
router.post('/get-baskets/', function(req, res) {
var userid = req.body.userid;
Basket.getBasketsByUser(userid, function(err, baskets){
if(err){
throw err;
}
res.json(baskets);
});
});
// get one basket by basket Id
router.post('/get-basket/', function(req, res) {
var basketid = req.body.basketid;
Basket.getBasketById(basketid, function(err, basket){ // singular term used for result object
if(err){
throw err;
}
res.json(basket);
});
});
// update item array by basket Id
router.put('/update-basket/', function(req, res) {
var userid = req.body.userid;
var basketid = req.body.basketid;
var basketname = req.body.basketname;
Basket.matchBasketnameOnUpdate(userid, basketid, basketname, function(err, result){
var resultArray = result.map(function(u) { return JSON.stringify(u.nameMatchResult); });
var namematch = resultArray.join(",");
if(err){
throw err;
}
if(namematch === "true"){
res.json({success: false, msg: 'Watchlist name already exists'});
}else{
var basket = {
basketname: req.body.basketname,
item: req.body.item
};
Basket.updateBasket(basketid, basket, {}, function(err, basket){ // singular term used for result object
if(err){
throw err;
}
res.json({success: true, name: req.body.basketname, items: req.body.item, msg: 'Watchlist successfully updated'});
});
}
});
});
//delete one basket by Id
router.post('/delete-basket/', function(req, res){
var basketid = req.body.basketid;
Basket.deactivateBasket(basketid, {}, {}, function(err, basket){ //result object takes on singular term
if(err){
throw err;
}
res.json({success: true, msg: 'Watchlist successfully deleted'});
});
});
//restate one basket by Id
router.post('/restate-basket/', function(req, res){
var basketid = req.body.basketid;
Basket.activateBasket(basketid, {}, {}, function(err, basket){ //result object takes on singular term
if(err){
throw err;
}
res.json({success: true, msg: 'Watchlist successfully restated'});
});
});
router.post('/save-basket/', function(req, res) {
var userid = req.body.userid;
var basketname = req.body.basketname;
var item = req.body.item;
Basket.matchBasketnameOnSave(userid, basketname, function(err, result){
var resultArray = result.map(function(u) {
return JSON.stringify(u.nameMatchResult);
});
var namematch = resultArray.join(",");
if(err){
throw err;
}
if(namematch === "true"){
res.json({success: false, msg: 'Watchlist already exists'});
}else{
var newBasket = new Basket({
creator: userid,
basketname: basketname,
item: item
});
newBasket.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Watchlist already exists or session timed out. Please try again.'});
}
res.json({success: true, watchlist: basketname, item: item, msg:'Watchlist Created!'});
});
}
});
});
//calculate stock and weighted returns by user watchlists
router.get('/watchlist-returns/:id', function(req, res) {
var watchlistid = req.params.id;
var results = {};
var items;
var tickerArray =[];
var latestArray = [];
var startArray = [];
var equalWeight;
var stockReturns = [];
var watchlistReturns = [];
var createDate;
async.series([
//get watchlist items by watchlist
function(callback){
Basket.getBasketById(watchlistid, function(err, basket){
if (err) return callback (err);
if (basket.length == 0 ){
return callback (new Error ("Watchlist not found"));
}
createDate = basket[0].create_date;
items = basket[0].item.split(/[ .:;?!~,`"&|()<>{}\[\]\n\r/]+/);
equalWeight = 1/(items.length-1);
results = {
watchlistItems: items
};
callback();
});
},
//get tickers by watchlist company names
function(callback){
async.forEach(items, function(item, callback) {
Term.getTickerByCompany(item, function(err, tickers) {
if (err) callback (err);
if (tickers.length == 0 ){
callback (new Error ("Watchlist is empty"));
}
tickerArray.push(tickers[0].ticker);
results.watchlistTickers = tickerArray;
callback();
});
}, callback);
},
//get latest and start prices with tickers
function(callback){
async.parallel([
//get latest prices
function(callback){
async.forEach(tickerArray, function(ticker, callback) {
Price.getQuotesByTicker(ticker, function(err, latest) {
if (err) callback (err);
latestArray.push(latest[0].price);
results.latestPrices = latestArray;
callback();
});
}, callback);
},
//get start prices
function(callback){
async.forEach(tickerArray, function(ticker, callback) {
Price.getQuotesByTickerAndDate(ticker, createDate, function(err, start) {
if (err) callback (err);
startArray.push(start[0].price);
results.startPrices = startArray;
callback();
});
}, callback);
}
], callback);
},
//calculate stockReturns and watchlistReturns
function(callback){
for (i=0; i<items.length; i++){
stockReturns.push(((latestArray[i]/startArray[i]-1)*100).toFixed(2));
watchlistReturns.push(equalWeight*stockReturns[i]);
}
results.stockReturns = stockReturns;
results.watchlistReturns = watchlistReturns;
callback();
}
], function(err){
if (err) return (err);
res.json(results);
}); //end async
});//close API
// update alerts by user Id
router.put('/update-alerts/', function(req, res) {
var userid = req.body.userid;
var name = req.body.name;
var ticker = req.body.ticker;
var price = req.body.price;
var limit = req.body.limit;
User.updateAlerts(userid, name, ticker, price, limit, {}, function(err, alert){
if(err){
throw err;
}
res.json({success: true, name: req.body.name, "price set at ": req.body.price, limit: req.body.limit, msg: 'Alert successfully set'});
});
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
module.exports = router;
<file_sep># Betafish
betafish stuff
<file_sep>var mongoose = require('mongoose');
//create relationship schema
var productSchema = mongoose.Schema({
product: {
name: {type: String},
category: {type: String}
},
company: {
type: String,
},
user: {
type: String, ref: 'User'
},
create_date:{
type: Date,
default: Date.now //specific date of API call
}
});
var Product = module.exports = mongoose.model('Product', productSchema); //make copy of schema and export to outside
//count product upvotes last 30 days
module.exports.productCount30Days = function(callback){
var today = new Date();
var start = new Date().setDate(today.getDate()-30);
var startDate = new Date(start);
startDate.setHours(0,0,0);
var query = {
create_date: { $gte: startDate, $lte: today }
};
Product.aggregate(
{$match: query},
{$group: {
_id: {
company: "$company",
name: "$product.name",
},
counts: {$push: "$create_date"}
}},
{$project: {
_id:0,
product:"$_id",
productCount: {$size: "$counts"}
}},
{$sort: {productCount: -1}}
)
.exec(callback);
};
//count product upvotes last 90 days
module.exports.productCount90Days = function(callback){
var today = new Date();
var start = new Date().setDate(today.getDate()-90);
var startDate = new Date(start);
startDate.setHours(0,0,0);
var query = {
create_date: { $gte: startDate, $lte: today }
};
Product.aggregate(
{$match: query},
{$group: {
_id: {
company: "$company",
name: "$product.name",
},
counts: {$push: "$create_date"}
}},
{$project: {
_id:0,
product:"$_id",
productCount: {$size: "$counts"}
}},
{$sort: {productCount: -1}}
)
.exec(callback);
};
//product upvotes by user
module.exports.getProductsByUser = function(userid, callback){
var query = {
user: userid
};
Product.aggregate(
{$match: query},
{$project: {
_id:0,
user:1,
company:1,
"product.name":1,
"product.category":1
}}
)
.exec(callback);
};
//product upvotes by company
module.exports.getProductsByCompany = function(company, callback){
var query = {
company: company
};
Product.aggregate(
{$match: query},
{$project: {
_id:0,
company:1,
user:1,
"product.name":1,
"product.category":1
}}
)
.exec(callback);
};
<file_sep>var mongoose = require('mongoose');
//create term schema
var termSchema = mongoose.Schema({ //define schema props
name: {
type: String,
required: true //for validation
},
group: {
type: String,
required: true //for validation
},
ticker: {
type: String,
required: true //for validation
},
altTicker: {
type: String,
required: true //for validation
},
quote: {
lastPrice: {type: Number},
tradeTime: {type: Date},
percentChange: {type: Number}
},
info: {
type: String,
required: true //for validation
},
product: {
name: {type: Array},
category: {type: String},
pictureURL: {type: Array}
},
price: {
tradingDay: {type: Array},
close: {type: Array}
},
valuations: {
pricetoearnings: {
revenue: {type: Array},
date: {type: Array}
},
pricetobook: {
gp: {type: Array},
date: {type: Array}
},
dividendyield: {
op: {type: Array},
date: {type: Array}
}
},
financials: {
sales: {
revenue: {type: Array},
date: {type: Array}
},
grossprofit: {
gp: {type: Array},
date: {type: Array}
},
operatingprofit: {
op: {type: Array},
date: {type: Array}
},
netincome: {
ni: {type: Array},
date: {type: Array}
},
earningspershare: {
eps: {type: Array},
date: {type: Array}
},
bookvaluepershare: {
bps: {type: Array},
date: {type: Array}
},
dividendpershare: {
dps: {type: Array},
date: {type: Array}
},
},
sharesShort: {
settlementDate: {type: Array},
shortInterest: {type: Array},
sharesOutstanding: [{
tradingDay: {type: Date},
sharesCount: {type: Number}
}],
percentfloat: {type: Number}
},
create_date: {
type: Date,
default: Date.now //specific date of API call
}
});
var Term = module.exports = mongoose.model('Term', termSchema); //make copy of schema and export to outside
//get terms
module.exports.getTerms = function(callback, limit){ //set up a function for export
Term.find({}, '-_id', callback).limit(limit);
};
//get term tickers
module.exports.getTermNames = function(callback, limit){ //set up a function for export
Term.find({}, {_id:0, name:1}, callback).limit(limit);
};
//get nodes
module.exports.getNodes = function(callback, limit){ //set up a function for export
Term.aggregate(
{$match: {} },
{$project: {
_id:0,
group:"$group",
id:"$name"
}
})
.exec(callback);
};
//get term by name
module.exports.getTermsByName = function(id, callback){ //no limit cos there's only one object parsed, and use singular for object
var name = {name: id};
Term.find(name, '-_id', callback);//call collection, then create specific object with callback
};
//get d3 nodes by name
module.exports.getNodesByName = function(id, callback){ //no limit cos there's only one object parsed, and use singular term for object
var name = { name: id };
Term.aggregate(
{$match: name},
{$project: {
_id:0,
group:"$group",
id:"$name"
}
})
.exec(callback);
};
//update doc with EOD prices
module.exports.updatePrice = function(name, prices, options, callback){
var query = {name: name};
var tradingDay = prices.map(function(u) { return u.tradingDay; });
var close = prices.map(function(u) { return u.close; });
var update = {
"price.tradingDay": tradingDay,
"price.close": close
};
Term.findOneAndUpdate(query, update, options, callback);
};
//update doc with live quotes
module.exports.updateQuote = function(name, quote, options, callback){
var query = {name: name};
var tempLastPrice = quote.map(function(u) { return u.lastPrice; });
var tempTradeTime = quote.map(function(u) { return u.tradeTimestamp; });
var tempPercentChange = quote.map(function(u) { return u.percentChange; });
var lastPrice = tempLastPrice[0];
var tradeTime = tempTradeTime[0];
var percentChange = tempPercentChange[0];
var update = {
"quote.lastPrice": lastPrice,
"quote.tradeTime": tradeTime,
"quote.percentChange": percentChange
};
Term.findOneAndUpdate(query, update, options, callback);
};
//update doc with Quandl SFO annual revenues
module.exports.updateRevenue = function(name, dates, revenues, options, callback){
var query = {name: name};
var update = {
"financials.sales.revenue": revenues,
"financials.sales.date": dates
};
Term.findOneAndUpdate(query, update, options, callback);
};
//update doc with Quandl SFO annual EBIT
module.exports.updateGP = function(name, dates, gps, options, callback){
var query = {name: name};
var update = {
"financials.grossprofit.gp": gps,
"financials.grossprofit.date": dates
};
Term.findOneAndUpdate(query, update, options, callback);
};
//update doc with Quandl SFO annual EBIT
module.exports.updateOP = function(name, dates, ops, options, callback){
var query = {name: name};
var update = {
"financials.operatingprofit.op": ops,
"financials.operatingprofit.date": dates
};
Term.findOneAndUpdate(query, update, options, callback);
};
//update doc with Quandl SFO annual Net Income
module.exports.updateNI = function(name, dates, nis, options, callback){
var query = {name: name};
var update = {
"financials.netincome.ni": nis,
"financials.netincome.date": dates
};
Term.findOneAndUpdate(query, update, options, callback);
};
//update doc with Quandl SFO annual Earnings per diluted share
module.exports.updateEPS = function(name, dates, eps, options, callback){
var query = {name: name};
var update = {
"financials.earningspershare.eps": eps,
"financials.earningspershare.date": dates
};
Term.findOneAndUpdate(query, update, options, callback);
};
//update doc with Quandl SFO annual book value per share
module.exports.updateBPS = function(name, dates, bps, options, callback){
var query = {name: name};
var update = {
"financials.bookvaluepershare.bps": bps,
"financials.bookvaluepershare.date": dates
};
Term.findOneAndUpdate(query, update, options, callback);
};
//update doc with Quandl SFO annual dividend per share
module.exports.updateDPS = function(name, dates, dps, options, callback){
var query = {name: name};
var update = {
"financials.dividendpershare.dps": dps,
"financials.dividendpershare.date": dates
};
Term.findOneAndUpdate(query, update, options, callback);
};
//get revenues
module.exports.getRevenue = function(name, callback, limit){
var name = { name: name };
Term.aggregate(
{$match: name},
{$project: {
_id:0,
revenue: "$financials.sales.revenue"
}
})
.exec(callback);
};
//get eps
module.exports.getEarningsPerShare = function(name, callback, limit){
var name = { name: name };
Term.aggregate(
{$match: name},
{$project: {
_id:0,
eps: "$financials.earningspershare.eps"
}
})
.exec(callback);
};
//collect latest top gainers
module.exports.topGainers = function(callback){
Term.aggregate(
{$project: {
_id: 0,
term: "$name",
percentChange: "$quote.percentChange"
}},
{$sort: {percentChange: -1}}
)
.exec(callback);
};
//collect latest top losers
module.exports.topLosers = function(callback){
var query = {
$and: [
{name: { $not: /^C/ }},
{name: { $not: /^P/ }}
]
};
Term.aggregate(
{$match: query},
{$project: {
_id: 0,
term: "$name",
percentChange: "$quote.percentChange"
}},
{$sort: {percentChange: 1}}
)
.exec(callback);
};
//get all products
module.exports.getProducts = function(callback, limit){ //set up a function for export
var query = {
$and: [
{name: { $not: /^C/ }}
]
};
Term.aggregate(
{$match: query},
{$project: {
_id:0,
name:1,
"product.name":1,
"product.category":1
}}
)
.exec(callback);
};
//get randomized products
module.exports.getRandomProducts = function(callback, limit){ //set up a function for export
var query = {
$and: [
{name: { $not: /^C/ }}
]
};
Term.aggregate(
{$match: query},
{$project: {
_id:0,
name:1,
"product.name":1,
"product.category":1
}},
{ $sample : { size: 5 } }
)
.exec(callback);
};
//get products of one company
module.exports.getProductsByCompany = function(name, callback, limit){ //set up a function for export
var query = {
name: name,
$and: [
{name: { $not: /^C/ }}
]
};
Term.aggregate(
{$match: query},
{$project: {
_id:0,
name:1,
"product.name":1,
"product.category":1
}}
)
.exec(callback);
};
//get all tickers
module.exports.getTickers = function(callback, limit){
var query = {
$and: [
{name: { $not: /^C/ }},
{name: { $not: /^P/ }}
]
};
Term.aggregate(
{$match: query},
{$group: {
_id: "whatever",
tickerArray: {$push: "$ticker"},
companyArray: {$push: "$name"}
}},
{$project: {
_id:0,
tickerArray:1,
companyArray:1,
tickerCount: {$size: "$tickerArray"}
}}
)
.exec(callback);
};
//get one ticker
module.exports.getTickerByCompany = function(company, callback){
var query = {
name: company
};
Term.aggregate(
{$match: query},
{$project: {
_id:0,
name:1,
ticker:1
}}
)
.exec(callback);
};
<file_sep>module.exports = {
'secret': 'secret',
'database': process.env.MONGOLAB_URI ||
process.env.MONGODB_URI || 'mongodb://localhost/bftest'
};
/*connect to db
var uristring =
process.env.MONGOLAB_URI ||
process.env.MONGODB_URI ||
'mongodb://localhost/bftest';
mongoose.connect(uristring, function (err, res) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Connected to: ' + uristring);
}
});
*/
<file_sep>var mongoose = require('mongoose');
//create doc schema
var docSchema = mongoose.Schema({ //define schema props
Object1: {
type: String,
required: true //for validation
},
Object2: {
type: String,
required: true //for validation
},
Dissimdist: {
type: Number
},
Relationship: {
type: String
},
Traffic: {
Competitor: {
User: [{
userid: {type: String, ref: 'User'},
vote_type: {type: Number},
vote_count: {type: Number},
vote_date: {type: Date, default: Date.now},
user_comment: {type: String}
}]
},
Supplier: {
User: [{
userid: {type: String, ref: 'User'},
vote_type: {type: Number},
vote_count: {type: Number},
vote_date: {type: Date, default: Date.now},
user_comment: {type: String}
}]
},
Client: {
User: [{
userid: {type: String, ref: 'User'},
vote_type: {type: Number},
vote_count: {type: Number},
vote_date: {type: Date, default: Date.now},
user_comment: {type: String}
}]
},
Sister: {
User: [{
userid: {type: String, ref: 'User'},
vote_type: {type: Number},
vote_count: {type: Number},
vote_date: {type: Date, default: Date.now},
user_comment: {type: String}
}]
},
Subsidiary: {
User: [{
userid: {type: String, ref: 'User'},
vote_type: {type: Number},
vote_count: {type: Number},
vote_date: {type: Date, default: Date.now},
user_comment: {type: String}
}]
},
Parent: {
User: [{
userid: {type: String, ref: 'User'},
vote_type: {type: Number},
vote_count: {type: Number},
vote_date: {type: Date, default: Date.now},
user_comment: {type: String}
}]
},
},
News: {
Headlines: [{type: String}],
Dates: [{type: Date}],
Abstracts: [{type: String}]
},
create_date: {
type: Date,
default: Date.now
}
});
var Doc = module.exports = mongoose.model('Doc', docSchema); //make copy of schema and export to outside
//get docs
module.exports.getDocs = function(callback, limit){ //set up getDocs as a function for export
Doc.aggregate({
$project: {
_id:0,
Object1:1,
Object2:1,
Dissimdist:1,
Relationship:1,
}
})
.sort({ DissimDist:1 })
.exec(callback);
};
//get doc by object1
module.exports.getDocsByObject1 = function(id, callback){ //no limit cos there's only one object parsed, and use singular term for object
var object1 = {
Object1: id,
Dissimdist: { $lte: .75 },
Relationship: {$ne: "peer"}
};
Doc.aggregate(
{$match: object1},
{$sort: { DissimDist:1 }},
{$project: {
_id:0,
Object1:1,
Object2:1,
Dissimdist:1,
Relationship:1,
netCompetitor: {$sum: "$Traffic.Competitor.User.vote_type"},
netSupplier: {$sum: "$Traffic.Supplier.User.vote_type"},
netClient: {$sum: "$Traffic.Client.User.vote_type"},
netSister: {$sum: "$Traffic.Sister.User.vote_type"},
netSubsidiary: {$sum: "$Traffic.Subsidiary.User.vote_type"},
netParent: {$sum: "$Traffic.Parent.User.vote_type"},
totalCompetitor: {$sum:
"$Traffic.Competitor.User.vote_count"},
totalSupplier: {$sum:
"$Traffic.Supplier.User.vote_count"},
totalClient: {$sum:
"$Traffic.Client.User.vote_count"},
totalSister: {$sum:
"$Traffic.Sister.User.vote_count"},
totalSubsidiary: {$sum:
"$Traffic.Subsidiary.User.vote_count"},
totalParent: {$sum:
"$Traffic.Parent.User.vote_count"}
}},
{$project: {
_id:0,
source:"$Object1",
target:"$Object2",
value: {$cond: {
if: {
$ne: [{$sum: [
"$totalCompetitor", "$totalSupplier", "$totalClient", "$totalSister", "$totalSubsidiary", "$totalParent"
]} ,0]
},
then: {
$multiply: [
{$divide: [5, "$Dissimdist"]},
{$sum: [
"$totalCompetitor", "$totalSupplier", "$totalClient", "$totalSister", "$totalSubsidiary", "$totalParent"
]}
]},
else: "$Dissimdist"
}},
totalVotes: {$sum: [
"$totalCompetitor", "$totalSupplier", "$totalClient", "$totalSister", "$totalSubsidiary", "$totalParent"
]},
relationship: {$cond: {
if: {
$gte: [{$sum: [
"$totalCompetitor", "$totalSupplier", "$totalClient", "$totalSister", "$totalSubsidiary", "$totalParent"
]} , 30]
},
then: {
Competitor: "$netCompetitor",
Supplier: "$netSupplier",
Client: "$netClient",
Sister: "$netSister",
Subsidiary: "$netSubsidiary",
Parent: "$netParent"
},
else: "$Relationship"
}}
}}
)
.exec(callback);
};
//get doc by object2
module.exports.getDocsByObject2 = function(id, callback){ //no limit cos there's only one object parsed, and use singular term for object
var object2 = {
Object2: id,
Dissimdist: { $lte: .75 },
Relationship: {$ne: "peer"}
};
Doc.aggregate(
{$match: object2},
{$sort: { DissimDist:1 }},
{$project: {
_id:0,
Object1:1,
Object2:1,
Dissimdist:1,
Relationship:1,
netCompetitor: {$sum: "$Traffic.Competitor.User.vote_type"},
netSupplier: {$sum: "$Traffic.Supplier.User.vote_type"},
netClient: {$sum: "$Traffic.Client.User.vote_type"},
netSister: {$sum: "$Traffic.Sister.User.vote_type"},
netSubsidiary: {$sum: "$Traffic.Subsidiary.User.vote_type"},
netParent: {$sum: "$Traffic.Parent.User.vote_type"},
totalCompetitor: {$sum:
"$Traffic.Competitor.User.vote_count"},
totalSupplier: {$sum:
"$Traffic.Supplier.User.vote_count"},
totalClient: {$sum:
"$Traffic.Client.User.vote_count"},
totalSister: {$sum:
"$Traffic.Sister.User.vote_count"},
totalSubsidiary: {$sum:
"$Traffic.Subsidiary.User.vote_count"},
totalParent: {$sum:
"$Traffic.Parent.User.vote_count"}
}},
{$project: {
_id:0,
source:"$Object2",
target:"$Object1",
value: {$cond: {
if: {
$ne: [{$sum: [
"$totalCompetitor", "$totalSupplier", "$totalClient", "$totalSister", "$totalSubsidiary", "$totalParent"
]} ,0]
},
then: {
$multiply: [
{$divide: [5, "$Dissimdist"]},
{$sum: [
"$totalCompetitor", "$totalSupplier", "$totalClient", "$totalSister", "$totalSubsidiary", "$totalParent"
]}
]},
else: "$Dissimdist"
}},
totalVotes: {$sum: [
"$totalCompetitor", "$totalSupplier", "$totalClient", "$totalSister", "$totalSubsidiary", "$totalParent"
]},
relationship: {$cond: {
if: {
$gte: [{$sum: [
"$totalCompetitor", "$totalSupplier", "$totalClient", "$totalSister", "$totalSubsidiary", "$totalParent"
]} , 30]
},
then: {
Competitor: "$netCompetitor",
Supplier: "$netSupplier",
Client: "$netClient",
Sister: "$netSister",
Subsidiary: "$netSubsidiary",
Parent: "$netParent"
},
else: "$Relationship"
}}
}}
)
.exec(callback);
};
//create target array by object1
module.exports.getTargetsByObject1 = function(id, callback){ //no limit cos there's only one object parsed, and use singular term for object
var object1 = {
Object1: id,
Dissimdist: { $lte: .75 },
Relationship: {$ne: "peer"}
};
Doc.aggregate(
{$match: object1},
{$sort: { DissimDist:1 }},
{$group: {_id:0, targets: { $push: "$Object2"}}},
{$unwind: "$targets"},
{$project: {_id:0, targets:1}}
)
.exec(callback);
};
//get targets only by object2
module.exports.getTargetsByObject2 = function(id, callback){ //no limit cos there's only one object parsed, and use singular term for object
var object2 = {
Object2: id,
Dissimdist: { $lte: .75 },
Relationship: {$ne: "peer"}
};
Doc.aggregate(
{$match: object2},
{$sort: { DissimDist:1 }},
{$group: {_id:0, targets: { $push: "$Object1"}}},
{$unwind: "$targets"},
{$project: {_id:0, targets:1}}
)
.exec(callback);
};
//upvote Competitor
module.exports.upvoteCompetitor = function(source, target, userid, comment, options, callback){
var query = {Object1: source, Object2: target};
var update = {
$push: {"Traffic.Competitor.User": {
userid: userid,
vote_type: 1,
vote_count: 1,
$currentDate: {vote_date: true},
user_comment: comment
}}
};
Doc.findOneAndUpdate(query, update, options, callback);
};
//downvote Competitor
module.exports.downvoteCompetitor = function(source, target, userid, comment, options, callback){
var query = {Object1: source, Object2: target};
var update = {
$push: {"Traffic.Competitor.User": {
userid: userid,
vote_type: -1,
vote_count: 1,
$currentDate: {vote_date: true},
user_comment: comment
}}
};
Doc.findOneAndUpdate(query, update, options, callback);
};
//upvote Supplier
module.exports.upvoteSupplier = function(source, target, userid, comment, options, callback){
var query = {Object1: source, Object2: target};
var update = {
$push: {"Traffic.Supplier.User": {
userid: userid,
vote_type: 1,
vote_count: 1,
$currentDate: {vote_date: true},
user_comment: comment
}}
};
Doc.findOneAndUpdate(query, update, options, callback);
};
//downvote Supplier
module.exports.downvoteSupplier = function(source, target, userid, comment, options, callback){
var query = {Object1: source, Object2: target};
var update = {
$push: {"Traffic.Supplier.User": {
userid: userid,
vote_type: -1,
vote_count: 1,
$currentDate: {vote_date: true},
user_comment: comment
}}
};
Doc.findOneAndUpdate(query, update, options, callback);
};
//upvote Client
module.exports.upvoteClient = function(source, target, userid, comment, options, callback){
var query = {Object1: source, Object2: target};
var update = {
$push: {"Traffic.Client.User": {
userid: userid,
vote_type: 1,
vote_count: 1,
$currentDate: {vote_date: true},
user_comment: comment
}}
};
Doc.findOneAndUpdate(query, update, options, callback);
};
//downvote Client
module.exports.downvoteClient = function(source, target, userid, comment, options, callback){
var query = {Object1: source, Object2: target};
var update = {
$push: {"Traffic.Client.User": {
userid: userid,
vote_type: -1,
vote_count: 1,
$currentDate: {vote_date: true},
user_comment: comment
}}
};
Doc.findOneAndUpdate(query, update, options, callback);
};
//upvote Sister
module.exports.upvoteSister = function(source, target, userid, comment, options, callback){
var query = {Object1: source, Object2: target};
var update = {
$push: {"Traffic.Sister.User": {
userid: userid,
vote_type: 1,
vote_count: 1,
$currentDate: {vote_date: true},
user_comment: comment
}}
};
Doc.findOneAndUpdate(query, update, options, callback);
};
//downvote Sister
module.exports.downvoteSister = function(source, target, userid, comment, options, callback){
var query = {Object1: source, Object2: target};
var update = {
$push: {"Traffic.Sister.User": {
userid: userid,
vote_type: -1,
vote_count: 1,
$currentDate: {vote_date: true},
user_comment: comment
}}
};
Doc.findOneAndUpdate(query, update, options, callback);
};
//upvote Subsidiary
module.exports.upvoteSubsidiary = function(source, target, userid, comment, options, callback){
var query = {Object1: source, Object2: target};
var update = {
$push: {"Traffic.Subsidiary.User": {
userid: userid,
vote_type: 1,
vote_count: 1,
$currentDate: {vote_date: true},
user_comment: comment
}}
};
Doc.findOneAndUpdate(query, update, options, callback);
};
//downvote Subsidiary
module.exports.downvoteSubsidiary = function(source, target, userid, comment, options, callback){
var query = {Object1: source, Object2: target};
var update = {
$push: {"Traffic.Subsidiary.User": {
userid: userid,
vote_type: -1,
vote_count: 1,
$currentDate: {vote_date: true},
user_comment: comment
}}
};
Doc.findOneAndUpdate(query, update, options, callback);
};
//upvote Parent
module.exports.upvoteParent = function(source, target, userid, comment, options, callback){
var query = {Object1: source, Object2: target};
var update = {
$push: {"Traffic.Parent.User": {
userid: userid,
vote_type: 1,
vote_count: 1,
$currentDate: {vote_date: true},
user_comment: comment
}}
};
Doc.findOneAndUpdate(query, update, options, callback);
};
//downvote Parent
module.exports.downvoteParent = function(source, target, userid, comment, options, callback){
var query = {Object1: source, Object2: target};
var update = {
$push: {"Traffic.Parent.User": {
userid: userid,
vote_type: -1,
vote_count: 1,
$currentDate: {vote_date: true},
user_comment: comment
}}
};
Doc.findOneAndUpdate(query, update, options, callback);
};
//get vote traffic by Object1
module.exports.getDocTrafficByObject1 = function(source, callback){ //no limit cos there's only one object parsed, and use singular term for object
var query = {
Object1: source,
Relationship: {$ne: "peer"},
Relationship: {$ne: ""}
};
Doc.aggregate(
{$match: query},
{$project: {
_id:0,
Object1:1,
Object2:1,
Relationship:1,
netCompetitor: {$sum: "$Traffic.Competitor.User.vote_type"},
netSupplier: {$sum: "$Traffic.Supplier.User.vote_type"},
netClient: {$sum: "$Traffic.Client.User.vote_type"},
netSister: {$sum: "$Traffic.Sister.User.vote_type"},
netSubsidiary: {$sum: "$Traffic.Subsidiary.User.vote_type"},
netParent: {$sum: "$Traffic.Parent.User.vote_type"},
totalCompetitor: {$sum:
"$Traffic.Competitor.User.vote_count"},
totalSupplier: {$sum:
"$Traffic.Supplier.User.vote_count"},
totalClient: {$sum:
"$Traffic.Client.User.vote_count"},
totalSister: {$sum:
"$Traffic.Sister.User.vote_count"},
totalSubsidiary: {$sum:
"$Traffic.Subsidiary.User.vote_count"},
totalParent: {$sum:
"$Traffic.Parent.User.vote_count"}
}},
{$project: {
_id:0,
source:"$Object1",
target:"$Object2",
defaultRelationship: "$Relationship",
Competitor: "$netCompetitor",
Supplier: "$netSupplier",
Client: "$netClient",
Sister: "$netSister",
Subsidiary: "$netSubsidiary",
Parent: "$netParent",
totalVotes: {$sum: [
"$totalCompetitor", "$totalSupplier", "$totalClient", "$totalSister", "$totalSubsidiary", "$totalParent"
]}
}}
)
.exec(callback);
};
//get vote traffic by Object2
module.exports.getDocTrafficByObject2 = function(source, callback){ //no limit cos there's only one object parsed, and use singular term for object
var query = {
Object2: source,
Relationship: {$ne: "peer"},
Relationship: {$ne: ""}
};
Doc.aggregate(
{$match: query},
{$project: {
_id:0,
Object1:1,
Object2:1,
Relationship:1,
netCompetitor: {$sum: "$Traffic.Competitor.User.vote_type"},
netSupplier: {$sum: "$Traffic.Supplier.User.vote_type"},
netClient: {$sum: "$Traffic.Client.User.vote_type"},
netSister: {$sum: "$Traffic.Sister.User.vote_type"},
netSubsidiary: {$sum: "$Traffic.Subsidiary.User.vote_type"},
netParent: {$sum: "$Traffic.Parent.User.vote_type"},
totalCompetitor: {$sum:
"$Traffic.Competitor.User.vote_count"},
totalSupplier: {$sum:
"$Traffic.Supplier.User.vote_count"},
totalClient: {$sum:
"$Traffic.Client.User.vote_count"},
totalSister: {$sum:
"$Traffic.Sister.User.vote_count"},
totalSubsidiary: {$sum:
"$Traffic.Subsidiary.User.vote_count"},
totalParent: {$sum:
"$Traffic.Parent.User.vote_count"}
}},
{$project: {
_id:0,
source:"$Object2",
target:"$Object1",
defaultRelationship: "$Relationship",
Competitor: "$netCompetitor",
Supplier: "$netSupplier",
Client: "$netClient",
Sister: "$netSister",
Subsidiary: "$netSubsidiary",
Parent: "$netParent",
totalVotes: {$sum: [
"$totalCompetitor", "$totalSupplier", "$totalClient", "$totalSister", "$totalSubsidiary", "$totalParent"
]}
}}
)
.exec(callback);
};
//get vote traffic by Source and Target
module.exports.getDocTrafficBySourceAndTarget = function(source, target, callback){ //no limit cos there's only one object parsed, and use singular term for object
var query = {
Object1: source,
Object2: target,
Relationship: {$ne: "peer"},
Relationship: {$ne: ""}
};
Doc.aggregate(
{$match: query},
{$project: {
_id:0,
Object1:1,
Object2:1,
Relationship:1,
netCompetitor: {$sum: "$Traffic.Competitor.User.vote_type"},
netSupplier: {$sum: "$Traffic.Supplier.User.vote_type"},
netClient: {$sum: "$Traffic.Client.User.vote_type"},
netSister: {$sum: "$Traffic.Sister.User.vote_type"},
netSubsidiary: {$sum: "$Traffic.Subsidiary.User.vote_type"},
netParent: {$sum: "$Traffic.Parent.User.vote_type"},
totalCompetitor: {$sum:
"$Traffic.Competitor.User.vote_count"},
totalSupplier: {$sum:
"$Traffic.Supplier.User.vote_count"},
totalClient: {$sum:
"$Traffic.Client.User.vote_count"},
totalSister: {$sum:
"$Traffic.Sister.User.vote_count"},
totalSubsidiary: {$sum:
"$Traffic.Subsidiary.User.vote_count"},
totalParent: {$sum:
"$Traffic.Parent.User.vote_count"}
}},
{$project: {
_id:0,
source:"$Object1",
target:"$Object2",
defaultRelationship: "$Relationship",
Competitor: "$netCompetitor",
Supplier: "$netSupplier",
Client: "$netClient",
Sister: "$netSister",
Subsidiary: "$netSubsidiary",
Parent: "$netParent",
totalVotes: {$sum: [
"$totalCompetitor", "$totalSupplier", "$totalClient", "$totalSister", "$totalSubsidiary", "$totalParent"
]}
}}
)
.exec(callback);
};
//get vote traffic by Target and Source
module.exports.getDocTrafficByTargetAndSource = function(source, target, callback){ //no limit cos there's only one object parsed, and use singular term for object
var query = {
Object2: source,
Object1: target,
Relationship: {$ne: "peer"},
Relationship: {$ne: ""}
};
Doc.aggregate(
{$match: query},
{$project: {
_id:0,
Object1:1,
Object2:1,
Relationship:1,
netCompetitor: {$sum: "$Traffic.Competitor.User.vote_type"},
netSupplier: {$sum: "$Traffic.Supplier.User.vote_type"},
netClient: {$sum: "$Traffic.Client.User.vote_type"},
netSister: {$sum: "$Traffic.Sister.User.vote_type"},
netSubsidiary: {$sum: "$Traffic.Subsidiary.User.vote_type"},
netParent: {$sum: "$Traffic.Parent.User.vote_type"},
totalCompetitor: {$sum:
"$Traffic.Competitor.User.vote_count"},
totalSupplier: {$sum:
"$Traffic.Supplier.User.vote_count"},
totalClient: {$sum:
"$Traffic.Client.User.vote_count"},
totalSister: {$sum:
"$Traffic.Sister.User.vote_count"},
totalSubsidiary: {$sum:
"$Traffic.Subsidiary.User.vote_count"},
totalParent: {$sum:
"$Traffic.Parent.User.vote_count"}
}},
{$project: {
_id:0,
source:"$Object2",
target:"$Object1",
defaultRelationship: "$Relationship",
Competitor: "$netCompetitor",
Supplier: "$netSupplier",
Client: "$netClient",
Sister: "$netSister",
Subsidiary: "$netSubsidiary",
Parent: "$netParent",
totalVotes: {$sum: [
"$totalCompetitor", "$totalSupplier", "$totalClient", "$totalSister", "$totalSubsidiary", "$totalParent"
]}
}}
)
.exec(callback);
};
//update doc news
module.exports.updateNews = function(source, target, headlines, dates, abstracts, options, callback){
var query = {Object1: source, Object2: target};
var update = {
"News.Headlines": headlines,
"News.Dates": dates,
"News.Abstracts": abstracts
};
Doc.findOneAndUpdate(query, update, options, callback);
};
<file_sep>var mongoose = require('mongoose');
var ObjectId = require('mongoose').Types.ObjectId;
// set up a basket model
var basketSchema = mongoose.Schema({
creator: {
type: String, ref: 'User',
required: true
},
basketname: {
type: String,
required: true
},
item: {
type: String
},
active: {
type: Boolean,
default: true
},
default: {
type: Boolean,
default: false
},
create_date: {
type: Date,
default: Date.now //specific date of API call
},
lastModified: {
type: Date
}
});
var Basket = module.exports = mongoose.model('Basket', basketSchema); //make copy of schema and export to outside
//get baskets by user
module.exports.getBasketsByUser = function(id, callback){ //no limit cos there's only one object parsed, and use singular term for object
var query = {creator: id};
Basket.aggregate(
{$match: query},
{$project: {
_id:1,
creator:1,
basketname:1,
item:1,
active:1
}
})
.exec(callback);
};
//get one basket
module.exports.getBasketById = function(id, callback){
var query = {_id: id};
Basket.find(query, '-_id', callback);
};
//update basket
module.exports.updateBasket = function(id, basket, options, callback){ //set up updateRelationship as a function for export, no limit cos only one object is parsed, use singular term for object
var query = {_id: id};
var update = {
basketname: basket.basketname,
item: basket.item, //defined for each document prop
$currentDate: {
lastModified: true
}};
Basket.findOneAndUpdate(query, update, options, callback); //function params as defined by vars above
};
//delete basket
module.exports.deactivateBasket = function(id, update, options, callback){ //set up updateRelationship as a function for export, no limit cos only one object is parsed, use singular term for object
var query = {_id: id};
var update = {active: false};
Basket.findOneAndUpdate(query, update, options, callback); //function params as defined by vars above
};
//restate basket
module.exports.activateBasket = function(id, update, options, callback){ //set up updateRelationship as a function for export, no limit cos only one object is parsed, use singular term for object
var query = {_id: id};
var update = {active: true};
Basket.findOneAndUpdate(query, update, options, callback); //function params as defined by vars above
};
//match basketname on update
module.exports.matchBasketnameOnUpdate = function(userid, basketid, name, callback){ //no limit cos there's only one object parsed, and use singular term for object
var query = {
creator: userid,
_id: {$ne: ObjectId(basketid)},
active: true
};
Basket.aggregate(
{$match: query},
{$project: {
_id:0,
creator: 1,
namematch: {
$cond: [ {$ne: ["$basketname", name]}, false, true ]
}
}},
{$group: {
_id: "$creator",
namematches: {$push: "$namematch"},
}},
{$project: {
_id:0,
nameMatchResult: {$anyElementTrue: ["$namematches"]}
}}
)
.exec(callback);
};
//match basketname on save
module.exports.matchBasketnameOnSave = function(userid, name, callback){ //no limit cos there's only one object parsed, and use singular term for object
var query = {
creator: userid,
active: true
};
Basket.aggregate(
{$match: query},
{$project: {
_id:0,
creator: 1,
namematch: {
$cond: [ {$ne: ["$basketname", name]}, false, true ]
}
}},
{$group: {
_id: "$creator",
namematches: {$push: "$namematch"},
}},
{$project: {
_id:0,
nameMatchResult: {$anyElementTrue: ["$namematches"]}
}}
)
.exec(callback);
};
<file_sep>var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var mongoose = require('mongoose');
var morgan = require('morgan');
var cors = require('cors');
var config = require('./config/database');
// connect to database
mongoose.connect(config.database);
//define api routes
var routes = require('./routes/index');
var user = require('./routes/user');
var api = require('./routes/api');
// Init App
var app = express();
app.set('port', (process.env.PORT || 5000));
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// log to console
app.use(morgan('dev'));
//CORS Middleware
app.use(cors());
// Passport init
app.use(passport.initialize());
//connect the routes
app.use('/', routes);
app.use('/user', user);
app.use('/api', api);
//Set Port
app.listen(app.get('port'), function() {
console.log('listening on port ', app.get('port'));
});
| ce48f386ba8677de6bd1b5b5d961a22ca3927ecf | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | cecilang/Betafish | 7c67253f5c9a960e6b74f5d5c7fa9d4a61dd4295 | 29da6a270bdec92deb86d0ba689a447f80fb925e |
refs/heads/master | <file_sep>using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace Company.Function
{
public static class TimerTriggerCSharp1
{
[FunctionName("TimerTriggerCSharp1")]
[return: ServiceBus("queue", Connection = "SERVICEBUS_CONNECTION")]
public static string ServiceBusOutput([TimerTrigger("* 0/5 * * * *")]TimerInfo myTimer, ILogger log)
{
string output = $"C# Timer trigger function executed at: {DateTime.Now}";
log.LogInformation(output);
return output;
}
}
}
| 7757b53bec0fce9fcb85099ff0089dbd0d3eac23 | [
"C#"
] | 1 | C# | cachai2/functions-vnet-tutorial | 48e3446140d3d2136af5439765a443cb32e1932a | 12ff51924a6c2a221e0aec581455a0e5a50b5b2f |
refs/heads/main | <repo_name>antonioam82/PDF-Image-Extract<file_sep>/README.md
# PDF-Image-Extract
<file_sep>/pdf_image_extractor.py
import fitz
import io
import os
from PIL import Image
import zipfile
def ns(c):
while c!=("s") and c!=("n"):
print(chr(7));c=input("Escribe solo \'n\' o \'s\' según su opción: ")
return(c)
def check_dir():
while True:
direc = input("Introducir directorio: ")
if os.path.isdir(direc):
break
else:
print("DIRECTORIO NO VÁLIDO.")
return direc
def check_file():
while True:
filen = input("Introduce archivo PDF: ")
if filen in os.listdir() and filen.endswith(".pdf"):
break
else:
print("ARCHIVO NO VÁLIDO.")
return filen
while True:
print("------------------PDF IMAGE EXTRACTOR------------------\n")
dire = check_dir()
os.chdir(dire)
file = check_file()
images = []
pdf_file = fitz.open(file)
print('{} Páginas'.format(len(pdf_file)))
for page_index in range(len(pdf_file)):
page = pdf_file[page_index]
image_list = page.getImageList()
print('{} imágenes encontradas en la página {}'.format(len(image_list),page_index))
for image_index, img in enumerate(page.getImageList(), start=1):
xref = img[0]
base_image = pdf_file.extractImage(xref)
image_bytes = base_image["image"]
image_ext = base_image["ext"]
image = Image.open(io.BytesIO(image_bytes))
image_name = (f"image{page_index+1}_{image_index}.{image_ext}")
image.save(open(image_name,"wb"))
images.append(image_name)
folder_name, ex = os.path.splitext(file)
with zipfile.ZipFile(folder_name+".zip","w") as zfile:
for i in images:
zfile.write(i)
os.remove(i)
zfile.close()
print("\nCreado archivo \'{}\'.".format(folder_name+".zip"))
conti = ns(input("¿Continuar(n/s)?: "))
if conti == "n":
break
<file_sep>/pdf_image_extractor2.py
from tkinter import *
from tkinter import filedialog, messagebox
#import tkinter.scrolledtext as slt
import zipfile
import Pmw
import io
import os
import threading
from PIL import Image
import fitz
class app():
def __init__(self):
self.root = Tk()
self.root.title('PDF Image Extractor')
self.root.geometry('774x420')
self.root.configure(bg='light slate gray')
self.current_dir = StringVar()
self.canvas = Canvas(self.root,width=157,height=290)
self.canvas.place(x=603,y=100)
self.scrollbar = Scrollbar(self.canvas,orient=VERTICAL)
self.scrollbar.pack(side=RIGHT,fill=Y)
self.selected_pages = []
self.name = ""
self.to_zip = []
self.pdf_file = ""
self.pages_box = Listbox(self.canvas,width=23,height=17)
self.pages_box.pack()
self.pages_box.config(yscrollcommand = self.scrollbar.set)
self.scrollbar.config(command = self.pages_box.yview)
self.currentDir = Entry(self.root,width=132,textvariable=self.current_dir)
self.currentDir.place(x=0,y=0)
#self.display = slt.ScrolledText(self.root,width=70,height=18,bg='dark green',fg='lawn green')
#self.display.place(x=10,y=30)
self.display = Pmw.ScrolledText(self.root,text_width=70,text_height=16,hscrollmode='none',vscrollmode='dynamic',
text_background='dark green',text_foreground='lawn green')
self.display.place(x=10,y=30)
self.pgeslabel = Label(self.root,text="PAGES:",bg='light slate gray',fg='white')
self.pgeslabel.place(x=600,y=38)
self.num_pages = IntVar()
self.pges = Entry(self.root,width=18,bg='black',fg='light green',textvariable=self.num_pages)
self.pges.place(x=649,y=38)
self.num_pages.set(0)
self.pdf_name = StringVar()
self.listlabel = Label(self.root,text="LIST OF PAGES:",bg='light slate gray',fg='white')
self.listlabel.place(x=601,y=77)
self.pdfName = Entry(self.root,width=45,bg='black',fg='light green',font=('arial',14),textvariable=self.pdf_name)
self.pdfName.place(x=95,y=333)
self.btnSearch = Button(self.root,text="SEARCH PDF",bg="gold3",width=10,command=self.load_pdf)
self.btnSearch.place(x=10,y=333)
self.btnExtract = Button(self.root, text="EXPORT TO CURRENT DIR",bg="PaleGreen1",width=39,command=lambda:self.init_extract(False))
self.btnExtract.place(x=10,y=377)
self.btnExtractZip = Button(self.root,text="EXPORT TO ZIP",bg="PaleGreen1",width=38,command=lambda:self.init_extract(True))
self.btnExtractZip.place(x=318,y=377)
self.btnSelect = Button(self.root,text="SELECT PAGE",width=21,bg="gold3",command=self.select_page)
self.btnSelect.place(x=604,y=377)
self.btnClear = Button(self.root,text="CLEAR ALL",width=82,bg="light gray",command=self.clear_all)
self.btnClear.place(x=10,y=291)
self.get_dir()
self.root.mainloop()
def get_dir(self):
self.current_dir.set(os.getcwd())
def clear_all(self):
self.selected_pages = []
self.display.delete('1.0',END)
def load_pdf(self):
pdf_root = filedialog.askopenfilename(initialdir="/",title="SELECT PDF", filetypes=(("PDF files","*.pdf"),("all files","*.*")))
self.pages_box.delete(0, END)
if pdf_root != "":
try:
self.name = (pdf_root.split("/")[-1])
self.display.appendtext('PDF TITTLE: {}.\n'.format(self.name))
os.chdir("/".join(pdf_root.split("/")[:-1]))
self.pdf_file = fitz.open(pdf_root)
self.pdf_name.set(self.name)
self.num_pages.set(len(self.pdf_file))
self.view_pages()
self.get_dir()
except Exception as e:
self.display.appendtext('\n{}.\n'.format(str(e)))
messagebox.showwarning("ERROR","Can't open the file.")
def view_pages(self):
for i in range(self.num_pages.get()):
self.pages_box.insert(END,"PAGE: {}\n".format(i+1))
self.pages_box.insert(END,"ALL PAGES")
def select_page(self):
try:
pdf_index = self.pages_box.curselection()[0]
if pdf_index not in self.selected_pages:
if pdf_index == self.num_pages.get():
for i in range(self.num_pages.get()):
self.selected_pages.append(i)
dis_text = "ALL PAGES SELECTED\n"
else:
dis_text = "SELECTED PAGE {}\n".format(pdf_index+1)
self.selected_pages.append(pdf_index)
self.selected_pages.sort()
self.display.appendtext(dis_text)
except:
if self.pdf_file == "":
messagebox.showwarning("ERROR","Search a PDF file.")
else:
messagebox.showwarning("ERROR","Select page\s to extract from.")
def make_zip(self):
if self.name != "":
final_name,ex = os.path.splitext(self.name)
with zipfile.ZipFile(final_name+".zip",'w') as zip_file:
for i in self.to_zip:
zip_file.write(i)
os.remove(i)
zip_file.close()
#self.display.insert(END,"CREATED ZIP FILE.")
self.display.appendtext("\nCREATED ZIP FILE {}".format(final_name+".zip\n"))
self.display.appendtext("\nTASK COMPLETED.\n")
self.to_zip = []
def extract(self,z):
if len(self.selected_pages) > 0:
for p in self.selected_pages:
page = self.pdf_file[p]
image_list = page.getImageList()
if len(image_list)>0:
count = 0
for image_index, img in enumerate(image_list, start=1):
xref = img[0]
base_image = self.pdf_file.extractImage(xref)
image_bytes = base_image["image"]
image_ext = base_image["ext"]
image = Image.open(io.BytesIO(image_bytes))
image_name = ("image{}_{}.{}".format(p+1,count,image_ext))
self.to_zip.append(image_name)
image.save(open(image_name,"wb"))
self.display.appendtext("Extracted image {} from page {}.\n".format(count,p+1))
count+=1
else:
self.display.appendtext("No images on page {}.\n".format(p+1))
if z==True:
self.make_zip()
else:
self.display.appendtext("\nTASK COMPLETED.\n")
self.selected_pages = []
def init_extract(self,tz):
t = threading.Thread(target=self.extract(tz))
t.start()
if __name__=="__main__":
app()
| 7274766e9e2aedb5d287fb24c07e045bde1f2c16 | [
"Markdown",
"Python"
] | 3 | Markdown | antonioam82/PDF-Image-Extract | 9723d61dc754eb1cfd8b8f5359b3cc065a86980e | 0804438671de7ee7a21d1dcdcae34443940e748e |
refs/heads/main | <repo_name>Devanshu801/inventory<file_sep>/src/inventory/FurnitureDecorator.java
package inventory;
public class FurnitureDecorator implements shopkeeper {
protected shopkeeper shopkeeper;
public FurnitureDecorator(shopkeeper s) {
this.shopkeeper = s;
}
public void ischildsafe() {
this.shopkeeper.ischildsafe();
}
}
| a3685231ca9845d8c903ea03dad000442011a39a | [
"Java"
] | 1 | Java | Devanshu801/inventory | c55aba8e699bc3937042864aeb096f453a75410d | f00ad7c812720eb0d3f12c2fdb48ba85398b79a6 |
refs/heads/master | <file_sep>from typing import List, Union
import torch
import torch.nn as nn
from torch.nn.utils import spectral_norm
import torch.nn.functional as F
import torchvision
class Generator(nn.Module):
'''
Generator network
'''
def __init__(self, out_channels: int = 3, latent_dimensions: int = 128,
channels_factor: Union[int, float] = 1, number_of_classes: int = 365) -> None:
'''
Constructor method
:param out_channels: (int) Number of output channels (1 = grayscale, 3 = rgb)
:param latent_dimensions: (int) Latent dimension size
:param channels_factor: (int, float) Channel factor to adopt the channel size in each layer
:param number_of_classes: (int) Number of classes in class tensor
'''
super(Generator, self).__init__()
# Save parameters
self.latent_dimensions = latent_dimensions
# Init linear input layers
self.input_path = nn.ModuleList([
LinearBlock(in_features=latent_dimensions, out_features=256, feature_size=365),
LinearBlock(in_features=256, out_features=256, feature_size=4096),
nn.Sequential(spectral_norm(nn.Linear(in_features=256, out_features=int(512 // channels_factor) * 4 * 4)),
nn.LeakyReLU(negative_slope=0.2))
])
# Init main residual path
self.main_path = nn.ModuleList([
GeneratorResidualBlock(in_channels=int(512 // channels_factor), out_channels=int(512 // channels_factor),
feature_channels=513, number_of_classes=number_of_classes),
GeneratorResidualBlock(in_channels=int(512 // channels_factor), out_channels=int(512 // channels_factor),
feature_channels=513, number_of_classes=number_of_classes),
GeneratorResidualBlock(in_channels=int(512 // channels_factor), out_channels=int(256 // channels_factor),
feature_channels=257, number_of_classes=number_of_classes),
SelfAttention(channels=int(256 // channels_factor)),
GeneratorResidualBlock(in_channels=int(256 // channels_factor), out_channels=int(128 // channels_factor),
feature_channels=129, number_of_classes=number_of_classes),
GeneratorResidualBlock(in_channels=int(128 // channels_factor), out_channels=int(64 // channels_factor),
feature_channels=65, number_of_classes=number_of_classes)
])
# Init final block
self.final_block = nn.Sequential(
nn.UpsamplingBilinear2d(scale_factor=2),
nn.BatchNorm2d(int(64 // channels_factor)),
spectral_norm(nn.Conv2d(in_channels=int(64 // channels_factor), out_channels=int(64 // channels_factor),
kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)),
nn.LeakyReLU(negative_slope=0.2),
spectral_norm(
nn.Conv2d(in_channels=int(64 // channels_factor), out_channels=out_channels, kernel_size=(1, 1),
stride=(1, 1), padding=(0, 0), bias=False))
)
def forward(self, input: torch.Tensor, features: List[torch.Tensor],
masks: List[torch.Tensor] = None, class_id: torch.Tensor = None) -> torch.Tensor:
'''
Forward pass
:param input: (torch.Tensor) Input latent tensor
:param features: (List[torch.Tensor]) List of vgg16 features
:return: (torch.Tensor) Generated output image
'''
# Init depth counter
depth_counter = len(features) - 1
# Input path
for index, layer in enumerate(self.input_path):
if index == 0:
# Mask feature
feature = features[depth_counter] * masks[depth_counter]
output = layer(input, feature)
depth_counter -= 1
elif index == 1:
# Mask feature
feature = features[depth_counter] * masks[depth_counter]
output = layer(output, feature)
depth_counter -= 1
else:
output = layer(output)
# Reshaping
output = output.view(output.shape[0], int(output.shape[1] // (4 ** 2)), 4, 4)
# Main path
for layer in self.main_path:
if isinstance(layer, SelfAttention):
output = layer(output)
else:
# Mask feature and concat mask
feature = features[depth_counter]
mask = masks[depth_counter]
feature = torch.cat((feature * mask, mask), dim=1)
output = layer(output, feature, class_id)
depth_counter -= 1
# Final block
output = self.final_block(output)
return output.sigmoid()
class Discriminator(nn.Module):
'''
Discriminator network
'''
def __init__(self, in_channels: int = 3, channel_factor: Union[int, float] = 1, number_of_classes: int = 365):
'''
Constructor mehtod
:param in_channels: (int) Number of input channels (grayscale = 1, rgb =3)
:param channel_factor: (int, float) Channel factor to adopt the channel size in each layer
'''
# Call super constructor
super(Discriminator, self).__init__()
# Init layers
self.layers = nn.Sequential(
DiscriminatorResidualBlock(in_channels=in_channels, out_channels=int(64 // channel_factor)),
DiscriminatorResidualBlock(in_channels=int(64 // channel_factor), out_channels=int(128 // channel_factor)),
DiscriminatorResidualBlock(in_channels=int(128 // channel_factor), out_channels=int(256 // channel_factor)),
SelfAttention(channels=int(256 // channel_factor)),
DiscriminatorResidualBlock(in_channels=int(256 // channel_factor), out_channels=int(256 // channel_factor)),
SelfAttention(channels=int(256 // channel_factor)),
DiscriminatorResidualBlock(in_channels=int(256 // channel_factor), out_channels=int(256 // channel_factor)),
DiscriminatorResidualBlock(in_channels=int(256 // channel_factor), out_channels=int(256 // channel_factor)),
DiscriminatorResidualBlock(in_channels=int(256 // channel_factor), out_channels=int(256 // channel_factor)),
)
# Init classification layer
self.classification = spectral_norm(
nn.Linear(in_features=int(256 // channel_factor) * 2 * 2, out_features=1, bias=False))
# Init embedding layer
self.embedding = spectral_norm(nn.Embedding(num_embeddings=number_of_classes,
embedding_dim=int(256 // channel_factor) * 2 * 2))
self.embedding.weight.data.uniform_(-0.1, 0.1)
def forward(self, input: torch.Tensor, class_id: torch.Tensor) -> torch.Tensor:
'''
Forward pass
:param input: (torch.Tensor) Input image to be classified, real or fake. Image shape (batch size, 1 or 3, height, width)
:return: (torch.Tensor) Output prediction of shape (batch size, 1)
'''
# Main path
output = self.layers(input)
# Reshape output into two dimensions
output = output.flatten(start_dim=1)
# Perform embedding
output_embedding = self.embedding(class_id)
output_embedding = (output.unsqueeze(dim=1) * output_embedding).sum(dim=1)
# Classification path
output = self.classification(output)
return output + output_embedding
class VGG16(nn.Module):
'''
Implementation of a pre-trained VGG 16 model which outputs intermediate feature activations of the model.
'''
def __init__(self, path_to_pre_trained_model: str = None) -> None:
'''
Constructor
:param pretrained: (bool) True if the default pre trained vgg16 model pre trained in image net should be used
'''
# Call super constructor
super(VGG16, self).__init__()
# Load model
if path_to_pre_trained_model is not None:
self.vgg16 = torch.load(path_to_pre_trained_model)
else:
self.vgg16 = torchvision.models.vgg16(pretrained=False)
# Convert feature module into model list
self.vgg16.features = nn.ModuleList(list(self.vgg16.features))
# Convert classifier into module list
self.vgg16.classifier = nn.ModuleList(list(self.vgg16.classifier))
def forward(self, input: torch.Tensor) -> List[torch.Tensor]:
'''
Forward pass of the model
:param input: (torch.Tenor) Input tensor of shape (batch size, channels, height, width)
:return: (List[torch.Tensor]) List of intermediate features in ascending oder w.r.t. the number VGG layer
'''
# Adopt grayscale to rgb if needed
if input.shape[1] == 1:
output = input.repeat_interleave(3, dim=1)
else:
output = input
# Normalize image
output = (output - output.mean(dim=1, keepdim=True)) / (output.std(dim=1, keepdim=True) + 1e-08)
output = output * torch.tensor([0.229, 0.224, 0.225], device=output.device).view(1, 3, 1, 1)
output = output + torch.tensor([0.485, 0.456, 0.406], device=output.device).view(1, 3, 1, 1)
# Init list for features
features = []
# Feature path
for layer in self.vgg16.features:
output = layer(output)
if isinstance(layer, nn.MaxPool2d):
features.append(output)
# Average pool operation
output = self.vgg16.avgpool(output)
# Flatten tensor
output = output.flatten(start_dim=1)
# Classification path
for index, layer in enumerate(self.vgg16.classifier):
output = layer(output)
if index == 3 or index == 6:
features.append(output)
return features
class SelfAttention(nn.Module):
'''
Self attention module proposed in: https://arxiv.org/pdf/1805.08318.pdf.
'''
def __init__(self, channels: int) -> None:
'''
Constructor
:param channels: (int) Number of channels to be utilized
'''
# Call super constructor
super(SelfAttention, self).__init__()
# Init convolutions
self.query_convolution = spectral_norm(
nn.Conv2d(in_channels=channels, out_channels=channels // 8, kernel_size=(1, 1), stride=(1, 1),
padding=(0, 0), bias=False))
self.key_convolution = spectral_norm(
nn.Conv2d(in_channels=channels, out_channels=channels // 8, kernel_size=(1, 1), stride=(1, 1),
padding=(0, 0), bias=False))
self.value_convolution = spectral_norm(
nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=(1, 1), stride=(1, 1),
padding=(0, 0), bias=False))
# Init gamma parameter
self.gamma = nn.Parameter(0.1 * torch.ones(1, dtype=torch.float32))
def forward(self, input: torch.Tensor) -> torch.Tensor:
'''
Forward pass
:param input: (torch.Tensor) Input tensor
:return: (torch.Tensor) Output tensor
'''
# Save input shape
batch_size, channels, height, width = input.shape
# Mappings
query_mapping = self.query_convolution(input)
key_mapping = self.key_convolution(input)
value_mapping = self.value_convolution(input)
# Reshape and transpose query mapping
query_mapping = query_mapping.view(batch_size, -1, height * width).permute(0, 2, 1)
# Reshape key mapping
key_mapping = key_mapping.view(batch_size, -1, height * width)
# Calc attention maps
attention = F.softmax(torch.bmm(query_mapping, key_mapping), dim=1)
# Reshape value mapping
value_mapping = value_mapping.view(batch_size, -1, height * width)
# Attention features
attention_features = torch.bmm(value_mapping, attention)
# Reshape to original shape
attention_features = attention_features.view(batch_size, channels, height, width)
# Residual mapping and gamma multiplication
output = self.gamma * attention_features + input
return output
class GeneratorResidualBlock(nn.Module):
'''
Residual block
'''
def __init__(self, in_channels: int, out_channels: int, feature_channels: int,
number_of_classes: int = 365) -> None:
'''
Constructor
:param in_channels: (int) Number of input channels
:param out_channels: (int) Number of output channels
:param number_of_classes: (int) Number of classes in class tensor
:param feature_channels: (int) Number of feature channels
'''
# Call super constructor
super(GeneratorResidualBlock, self).__init__()
# Init main operations
self.main_block = nn.ModuleList([
spectral_norm(nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)),
ConditionalBatchNorm(num_features=out_channels, number_of_classes=number_of_classes),
nn.LeakyReLU(negative_slope=0.2),
nn.UpsamplingBilinear2d(scale_factor=2),
spectral_norm(nn.Conv2d(in_channels=out_channels, out_channels=out_channels,
kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)),
ConditionalBatchNorm(num_features=out_channels, number_of_classes=number_of_classes),
nn.LeakyReLU(negative_slope=0.2)
])
# Init residual mapping
self.residual_mapping = nn.Sequential(
nn.UpsamplingBilinear2d(scale_factor=2),
spectral_norm(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=(1, 1), stride=(1, 1),
padding=(0, 0), bias=False)))
# Init convolution for mapping the masked features
self.masked_feature_mapping = spectral_norm(
nn.Conv2d(in_channels=feature_channels, out_channels=out_channels,
kernel_size=(3, 3), stride=(1, 1), padding=(1, 1),
bias=False))
def forward(self, input: torch.Tensor, masked_features: torch.Tensor, class_id: torch.Tensor) -> torch.Tensor:
'''
Forward pass
:param input: (torch.Tensor) Input tensor
:param masked_features: (torch.Tensor) Masked feature tensor form vvg16
:param class_id: (torch.Tensor) Class one-hot vector
:return: (torch.Tensor) Output tensor
'''
# Main path
output = input
for layer in self.main_block:
if isinstance(layer, ConditionalBatchNorm):
output = layer(output, class_id)
else:
output = layer(output)
# Residual mapping
output_residual = self.residual_mapping(input)
output_main = output + output_residual
# Feature path
mapped_features = self.masked_feature_mapping(masked_features)
# Addition step
output = output_main + mapped_features
return output
class LinearBlock(nn.Module):
def __init__(self, in_features: int, out_features: int, feature_size: int) -> None:
'''
Constructor
:param in_features: (int) Number of input features
:param out_features: (int) Number of output features
:param feature_size: (int) Number of channels including in the feature vector
'''
# Call super constructor
super(LinearBlock, self).__init__()
# Init linear layer and activation
self.main_block = nn.Sequential(
spectral_norm(nn.Linear(in_features=in_features, out_features=out_features, bias=False)),
nn.LeakyReLU(negative_slope=0.2)
)
# Init mapping the masked features
self.masked_feature_mapping = nn.Linear(in_features=feature_size, out_features=out_features, bias=False)
def forward(self, input: torch.Tensor, masked_features: torch.Tensor) -> torch.Tensor:
'''
Forward pass
:param input: (torch.Tensor) Input tensor
:param masked_features: (torch.Tensor) Masked feature tensor form vvg16
:return: (torch.Tensor) Output tensor
'''
# Main path
output_main = self.main_block(input)
# Feature path
mapped_features = self.masked_feature_mapping(masked_features)
# Addition step
output = output_main + mapped_features
return output
class DiscriminatorResidualBlock(nn.Module):
'''
Simple residual block for the discriminator model.
'''
def __init__(self, in_channels: int, out_channels: int) -> None:
'''
Constructor
:param in_channels: (int) Number of input channels
:param out_channels: (int) Number of output channels
'''
# Call super constructor
super(DiscriminatorResidualBlock, self).__init__()
# Init operation of the main part
self.main_block = nn.Sequential(
spectral_norm(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=(3, 3), padding=(1, 1),
stride=(1, 1), bias=False)),
nn.LeakyReLU(negative_slope=0.2),
spectral_norm(
nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=(3, 3), padding=(1, 1),
stride=(1, 1), bias=False)),
nn.LeakyReLU(negative_slope=0.2)
)
# Init residual mapping
self.residual_mapping = spectral_norm(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=(1, 1), padding=(0, 0),
stride=(1, 1), bias=False))
# Init downsmapling
self.downsampling = nn.AvgPool2d(kernel_size=(2, 2))
def forward(self, input: torch.Tensor) -> torch.Tensor:
'''
Forward pass
:param input: (torch.Tensor) Input tensor of shape (batch size, in channels, height, width)
:return: (torch.Tensor) Output tensor of shape (batch size, in channels, height / 2, width / 2)
'''
# Main path
output = self.main_block(input)
# Residual mapping
output_residual = self.residual_mapping(input)
output = output + output_residual
# Downsampling
output = self.downsampling(output)
return output
class ConditionalBatchNorm(nn.Module):
"""
This class implements conditional batch normalization as used in:
https://arxiv.org/pdf/1707.00683.pdf
"""
def __init__(self, num_features: int, number_of_classes: int = 365) -> None:
"""
Constructor method
:param num_features: (int) Number of features
:param number_of_classes: (int) Number of classes in class tensor
"""
# Call super constructor
super(ConditionalBatchNorm, self).__init__()
# Init linear layers to predict the affine parameters
self.linear_scale = nn.Linear(in_features=number_of_classes, out_features=num_features, bias=False)
self.linear_bias = nn.Linear(in_features=number_of_classes, out_features=num_features, bias=False)
# Apply spectral norm
self.linear_scale = spectral_norm(self.linear_scale)
self.linear_bias = spectral_norm(self.linear_bias)
def forward(self, input: torch.Tensor, class_id: torch.Tensor) -> torch.Tensor:
"""
Forward pass
:param input: (torch.Tensor) 4d input feature map
:param class_id: (torch.Tensor) Class one-hot vector
:return: (torch.Tensor) Normalized output tensor
"""
# Perform normalization
output = (input - input.mean(dim=1, keepdim=True)) / (input.std(dim=1, keepdim=True) + 1e-08)
# Get affine parameters
scale = self.linear_scale(class_id)
bias = self.linear_bias(class_id)
scale = scale.view(scale.shape[0], scale.shape[-1], 1, 1)
bias = bias.view(bias.shape[0], bias.shape[-1], 1, 1)
# Apply affine parameters
output = scale * output + bias
return output
<file_sep>from typing import List, Tuple
import torch
import torch.nn.functional as F
import numpy as np
from skimage.draw import random_shapes
import os
import json
def get_masks_for_training(
mask_shapes: List[Tuple] =
[(64, 128, 128), (128, 64, 64), (256, 32, 32), (512, 16, 16), (512, 8, 8), (4096,), (365,)],
device: str = 'cpu', add_batch_size: bool = False,
p_random_mask: float = 0.3) -> List[torch.Tensor]:
'''
Method returns random masks similar to 3.2. of the paper
:param mask_shapes: (List[Tuple]) Shapes of the features generated by the vgg16 model
:param device: (str) Device to store tensor masks
:param add_batch_size: (bool) If true a batch size is added to each mask
:param p_random_mask: (float) Probability that a random mask is generated else no mask is utilized
:return: (List[torch.Tensor]) Generated masks for each feature tensor
'''
# Select layer where no masking is used. Every output from the deeper layers get mapped out. Every higher layer gets
# masked by a random shape
selected_layer = np.random.choice(range(7))
# Make masks
masks = []
random_mask = None
random_mask_used = False
spatial_varying_masks = np.random.rand() < p_random_mask
for index, mask_shape in enumerate(reversed(mask_shapes)):
# Full mask on case
if index < selected_layer:
if len(mask_shape) > 1:
# Save mask to list
masks.append(torch.zeros((1, mask_shape[1], mask_shape[2]), dtype=torch.float32, device=device))
else:
# Save mask to list
masks.append(torch.zeros(mask_shape, dtype=torch.float32, device=device))
# No mask case
elif index == selected_layer:
if len(mask_shape) > 1:
# Save mask to list
masks.append(torch.ones((1, mask_shape[1], mask_shape[2]), dtype=torch.float32, device=device))
else:
# Save mask to list
masks.append(torch.ones(mask_shape, dtype=torch.float32, device=device))
# Random mask cases
elif index > selected_layer and random_mask is None:
if len(mask_shape) > 2:
# Get random mask
if spatial_varying_masks:
random_mask_used = True
random_mask = random_shapes(mask_shape[1:],
min_shapes=1,
max_shapes=4,
min_size=min(8, mask_shape[1] // 2),
allow_overlap=True)[0][:, :, 0]
# Random mask to torch tensor
random_mask = torch.tensor(random_mask, dtype=torch.float32, device=device)[None, :, :]
# Change range of mask to [0, 1]
random_mask = (random_mask == 255.0).float()
else:
# Make no mask
random_mask = torch.zeros(mask_shape[1:], dtype=torch.float32, device=device)[None, :, :]
# Save mask to list
masks.append(random_mask)
else:
if spatial_varying_masks:
# Save mask to list
masks.append(torch.randint(low=0, high=2, size=mask_shape, dtype=torch.float32, device=device))
else:
random_mask = torch.zeros(mask_shape, dtype=torch.float32, device=device)
masks.append(random_mask)
else:
# Save mask to list
if random_mask_used:
masks.append(F.upsample_nearest(random_mask[None, :, :, :], size=mask_shape[1:]).float().to(device)[0])
else:
masks.append(torch.ones(mask_shape[1:], dtype=torch.float32, device=device)[None, :, :])
# Add batch size dimension
if add_batch_size:
for index in range(len(masks)):
masks[index] = masks[index].unsqueeze(dim=0)
# Reverse order of masks to match the features of the vgg16 model
masks.reverse()
return masks
def get_masks_for_validation(mask_shapes: List[Tuple] =
[(64, 128, 128), (128, 64, 64), (256, 32, 32), (512, 16, 16), (512, 8, 8), (4096,),
(365,)], device: str = 'cpu', add_batch_size: bool = False) -> List[torch.Tensor]:
return get_masks_for_inference(layer_index_to_choose=np.random.choice(range(len(mask_shapes))),
mask_shapes=mask_shapes, device=device, add_batch_size=add_batch_size)
def get_masks_for_inference(layer_index_to_choose: int, mask_shapes: List[Tuple] =
[(64, 128, 128), (128, 64, 64), (256, 32, 32), (512, 16, 16), (512, 8, 8), (4096,),
(365,)], device: str = 'cpu', add_batch_size: bool = False) -> List[torch.Tensor]:
# Init list for masks
masks = []
# Loop over all shapes
for index, mask_shape in enumerate(reversed(mask_shapes)):
if index == layer_index_to_choose:
if len(mask_shape) > 1:
# Save mask to list
masks.append(torch.ones((1, mask_shape[1], mask_shape[2]), dtype=torch.float32, device=device))
else:
# Save mask to list
masks.append(torch.ones(mask_shape, dtype=torch.float32, device=device))
else:
if len(mask_shape) > 1:
# Save mask to list
masks.append(torch.zeros((1, mask_shape[1], mask_shape[2]), dtype=torch.float32, device=device))
else:
# Save mask to list
masks.append(torch.zeros(mask_shape, dtype=torch.float32, device=device))
# Add batch size dimension
if add_batch_size:
for index in range(len(masks)):
masks[index] = masks[index].unsqueeze(dim=0)
# Reverse order of masks to match the features of the vgg16 model
masks.reverse()
return masks
def normalize_0_1_batch(input: torch.tensor) -> torch.tensor:
'''
Normalize a given tensor to a range of [-1, 1]
:param input: (Torch tensor) Input tensor
:return: (Torch tensor) Normalized output tensor
'''
input_flatten = input.view(input.shape[0], -1)
return ((input - torch.min(input_flatten, dim=1)[0][:, None, None, None]) / (
torch.max(input_flatten, dim=1)[0][:, None, None, None] -
torch.min(input_flatten, dim=1)[0][:, None, None, None]))
def normalize_m1_1_batch(input: torch.tensor) -> torch.tensor:
'''
Normalize a given tensor to a range of [-1, 1]
:param input: (Torch tensor) Input tensor
:return: (Torch tensor) Normalized output tensor
'''
input_flatten = input.view(input.shape[0], -1)
return 2 * ((input - torch.min(input_flatten, dim=1)[0][:, None, None, None]) / (
torch.max(input_flatten, dim=1)[0][:, None, None, None] -
torch.min(input_flatten, dim=1)[0][:, None, None, None])) - 1
class Logger(object):
"""
Class to log different metrics
"""
def __init__(self) -> None:
self.metrics = dict()
self.hyperparameter = dict()
def log(self, metric_name: str, value: float) -> None:
"""
Method writes a given metric value into a dict including list for every metric
:param metric_name: (str) Name of the metric
:param value: (float) Value of the metric
"""
if metric_name in self.metrics:
self.metrics[metric_name].append(value)
else:
self.metrics[metric_name] = [value]
def save_metrics(self, path: str) -> None:
"""
Static method to save dict of metrics
:param metrics: (Dict[str, List[float]]) Dict including metrics
:param path: (str) Path to save metrics
:param add_time_to_file_name: (bool) True if time has to be added to filename of every metric
"""
# Save dict of hyperparameter as json file
with open(os.path.join(path, 'hyperparameter.txt'), 'w') as json_file:
json.dump(self.hyperparameter, json_file)
# Iterate items in metrics dict
for metric_name, values in self.metrics.items():
# Convert list of values to torch tensor to use build in save method from torch
values = torch.tensor(values)
# Save values
torch.save(values, os.path.join(path, '{}.pt'.format(metric_name)))
<file_sep>from typing import List, Tuple
import torch
import torch.nn as nn
class SemanticReconstructionLoss(nn.Module):
'''
Implementation of the proposed semantic reconstruction loss
'''
def __init__(self, weight_factor: float = 0.1) -> None:
'''
Constructor
'''
# Call super constructor
super(SemanticReconstructionLoss, self).__init__()
# Save parameter
self.weight_factor = weight_factor
# Init max pooling operations. Since the features have various dimensions, 2d & 1d max pool as the be init
self.max_pooling_2d = nn.MaxPool2d(2)
self.max_pooling_1d = nn.MaxPool1d(2)
def __repr__(self):
'''
Get representation of the loss module
:return: (str) String including information
'''
return '{}, weights factor={}, maxpool kernel size{}' \
.format(self.__class__.__name__, self.weight_factor, self.max_pooling_1d.kernel_size)
def forward(self, features_real: List[torch.Tensor], features_fake: List[torch.Tensor],
masks: List[torch.Tensor]) -> torch.Tensor:
'''
Forward pass
:param features_real: (List[torch.Tensor]) List of real features
:param features_fake: (List[torch.Tensor]) List of fake features
:return: (torch.Tensor) Loss
'''
# Check lengths
assert len(features_real) == len(features_fake) == len(masks)
# Init loss
loss = torch.tensor([0.0], dtype=torch.float32, device=features_real[0].device)
# Calc full loss
for feature_real, feature_fake, mask in zip(features_real, features_fake, masks):
# Downscale features
if len(feature_fake.shape) == 4:
feature_real = self.max_pooling_2d(feature_real)
feature_fake = self.max_pooling_2d(feature_fake)
mask = self.max_pooling_2d(mask)
else:
feature_real = self.max_pooling_1d(feature_real.unsqueeze(dim=1))
feature_fake = self.max_pooling_1d(feature_fake.unsqueeze(dim=1))
mask = self.max_pooling_1d(mask.unsqueeze(dim=1))
# Normalize features
union = torch.cat((feature_real, feature_fake), dim=0)
feature_real = (feature_real - union.mean()) / union.std()
feature_fake = (feature_fake - union.mean()) / union.std()
# Calc l1 loss of the real and fake feature conditionalized by the corresponding mask
loss = loss + torch.mean(torch.abs((feature_real - feature_fake) * mask))
# Average loss with number of features
loss = loss / len(features_real)
return self.weight_factor * loss
class DiversityLoss(nn.Module):
'''
Implementation of the mini-batch diversity loss
'''
def __init__(self, weight_factor: float = 0.1) -> None:
'''
Constructor
'''
# Call super constructor
super(DiversityLoss, self).__init__()
# Save parameter
self.weight_factor = weight_factor
# Init l1 loss module
self.l1_loss = nn.L1Loss(reduction='mean')
# Init epsilon for numeric stability
self.epsilon = 1e-08
def __repr__(self):
'''
Get representation of the loss module
:return: (str) String including information
'''
return '{}, weights factor={}'.format(self.__class__.__name__, self.weight_factor)
def forward(self, images_fake: torch.Tensor, latent_inputs: torch.Tensor) -> torch.Tensor:
'''
Forward pass
:param images_real: (torch.Tensor) Mini-batch of real images
:param latent_inputs: (torch.Tensor) Random latent input tensor
:return: (torch.Tensor) Loss
'''
# Check batch sizes
assert images_fake.shape[0] > 1
# Divide mini-batch of images into two paris
images_fake_1 = images_fake[:images_fake.shape[0] // 2]
images_fake_2 = images_fake[images_fake.shape[0] // 2:]
# Divide latent inputs into two paris
latent_inputs_1 = latent_inputs[:latent_inputs.shape[0] // 2]
latent_inputs_2 = latent_inputs[latent_inputs.shape[0] // 2:]
# Calc loss
loss = self.l1_loss(latent_inputs_1, latent_inputs_2) / (
self.l1_loss(images_fake_1, images_fake_2) + self.epsilon)
return self.weight_factor * loss
class LSGANGeneratorLoss(nn.Module):
'''
Implementation of the least squares gan loss for the generator network
'''
def __init__(self) -> None:
# Call super constructor
super(LSGANGeneratorLoss, self).__init__()
def __repr__(self):
'''
Get representation of the loss module
:return: (str) String including information
'''
return str(self.__class__.__name__)
def forward(self, images_fake: torch.Tensor) -> torch.Tensor:
'''
Forward pass
:param images_fake: (torch.Tensor) Fake images generated
:return: (torch.Tensor) Loss
'''
return 0.5 * torch.mean((images_fake - 1.0) ** 2)
class LSGANDiscriminatorLoss(nn.Module):
'''
Implementation of the least squares gan loss for the discriminator network
'''
def __init__(self) -> None:
# Call super constructor
super(LSGANDiscriminatorLoss, self).__init__()
def __repr__(self):
'''
Get representation of the loss module
:return: (str) String including information
'''
return str(self.__class__.__name__)
def forward(self, images_real: torch.Tensor, images_fake: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
'''
Forward pass. Loss parts are not summed up to not retain the whole backward graph later.
:param images_real: (torch.Tensor) Real images
:param images_fake: (torch.Tensor) Fake images generated
:return: (torch.Tensor) Loss real part and loss fake part
'''
return 0.5 * torch.mean((images_real - 1.0) ** 2), 0.5 * torch.mean(images_fake ** 2)
<file_sep># Semantic Pyramid for Image Generation
**Unofficel** [PyTorch](https://pytorch.org/) implementation of the paper [Semantic Pyramid for Image Generation](https://arxiv.org/pdf/2003.06221.pdf) by [<NAME>](https://github.com/assafshocher) & <NAME>.

[Source](https://arxiv.org/pdf/2003.06221.pdf). Proposed results of the paper.
## Model architecture

[Source](https://arxiv.org/pdf/2003.06221.pdf)
The full architecture consists of three parts. First, the object recognition model which is implemented as a
pre-trained VGG 16 network. Secondly, the residual generator network which is partly based on the generator architecture
of the [SAGAN](https://arxiv.org/pdf/1805.08318.pdf).
And thirdly, the residual discriminator network which is also based on the
[SAGAN](https://arxiv.org/pdf/1805.08318.pdf).
## Dataset
To download and extract the [places365](http://places2.csail.mit.edu/download.html) dataset from the official website
run the following script
```
sh download_places365.sh
```
## Pre-trained VGG 16 model
To download and convert the VGG 16 model pre-trained on the places dataset run the following command
```
sh download_pretrained_vgg16.sh
```
This script downloads the official pre-trained caffe models from the
[places365 repository](https://github.com/CSAILVision/places365). Afterwards, the caffe model gets converted with the
help of the [caffemodel2pytorch](https://github.com/vadimkantorov/caffemodel2pytorch) repo created by
[<NAME>](https://github.com/vadimkantorov).
## Usage
To train or test the GAN simply run the main script `python main.py`. This main script takes multiple arguments.
Argument | Default value | Info
--- | --- | ---
`--train` | False | Flag to perform training
`--test` | False | Flag to perform testing
`--batch_size` | 20 | Batch size to be utilized
`--lr` | 1e-04 | Learning rate to use
`--channel_factor` | 1 | Channel factor adopts the number of channels utilized in the U-Net
`--device` | 'cuda' | Device to use (cuda recommended)
`--gpus_to_use` | '0' | Indexes of the GPUs to be use
`--use_data_parallel` | False | Use multiple GPUs
`--load_generator_network` | None | Path of the generator network to be loaded (.pt)
`--load_discriminator_network` | None | Path of the discriminator network to be loaded (.pt)
`--load_pretrained_vgg16` | 'pre_trained_models/vgg_places_365.pt' | Path of the pre-trained VGG 16 to be loaded (.pt)
`--path_to_places365` | 'places365_standard' | Path to places365 dataset
`--epochs` | 50 | Epochs to perform while training
While training logs and models gets save automatically to the `saved_data` file. Inference plots also gets saved in the
same folder.
## Results
With limited compute budget I was not able to reproduce the results form the paper. The plot, shown below, was after approximately 24h of training on a single Nvidia Tesla V100. After 24h the whole performance dropped again. However, due to the limited computing power, I was only able to train 48h.

<file_sep>torch>= 1.1.0
torchvision>= 0.4.2
matplotlib>= 3.0.3
numpy>= 1.16.2
tqdm>= 4.31.1
scikit-image>= 0.14.2
scipy>= 1.0.0
Pillow>= 4.3.0
pandas>= 0.24.2
h5py>= 2.10.0
protobuf>=3.15.6 | 29b27807891d3c932ebd355af8f50bf8a92f7f61 | [
"Markdown",
"Python",
"Text"
] | 5 | Python | killsking/Semantic_Pyramid_for_Image_Generation | 3649d4b04ca3f3e80594962355a22fcce9d30fe7 | 5ffe408dad63d77945958967848382c8dfac8767 |
refs/heads/master | <repo_name>LyndonArmitage/socketTest<file_sep>/src/com/lyndonarmitage/socketTest/BasicServer.java
package com.lyndonarmitage.socketTest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created with IntelliJ IDEA.
* Created By: <NAME>
* Date: 22/01/13
*/
public class BasicServer {
public static final int serverPort = 2001; // fixed number for now
public static void main(String args[]) {
System.out.println("Starting Server...");
BasicServer server = new BasicServer();
System.out.println("Server exited."); // Lyndon: This will never output. See note below about bad practice
}
public BasicServer() {
runServer();
}
/**
* Attempt to run the server.<br />
* This will block the current thread we are on
*/
private void runServer() {
try {
ServerSocket serverSocket = new ServerSocket(serverPort);
Socket clientSocket;
BufferedReader in;
PrintWriter out;
while (true) { // Lyndon: I think this is bad practice but the example I based this off of does this.
System.out.println("Waiting for client.");
clientSocket = serverSocket.accept(); // blocking
System.out.println("Client connection from: " + clientSocket.getInetAddress().getHostAddress());
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
processClient(in, out);
clientSocket.close();
System.out.println("Client connection close.\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Process a client and their commands.
*
* @param in the input coming from the client
* @param out the output going to the client
*/
private void processClient(BufferedReader in, PrintWriter out) {
String line;
boolean done = false;
try {
while (!done) {
line = in.readLine();
if (line == null) {
done = true;
} else {
System.out.println("Client message: " + line);
if (line.trim().equals("bye")) {
done = true; // close client connection
}
processCommand(line, out);
}
}
} catch (Exception E) {
E.printStackTrace();
}
}
/**
* Process the command and return the correct output to the client.
*
* @param command the command
* @param out server output to the client
*/
private void processCommand(String command, PrintWriter out) {
if (!command.equals("bye")) {
out.println("echo: " + command);
}
}
}
| 398b17df18c41b4708a94d7975abc98ade509daf | [
"Java"
] | 1 | Java | LyndonArmitage/socketTest | bbec8d65d400aed88566772ab23c3ab7821452ac | 42c0d21509bbcd0913e19c6c1a1827e85c469766 |
refs/heads/master | <file_sep>/*
* MinimaxPlayer.h
*
* Created on: Apr 17, 2015
* Author: wong
*/
#ifndef MINIMAXPLAYER_H
#define MINIMAXPLAYER_H
#include "OthelloBoard.h"
#include "Player.h"
#include <vector>
/**
* This class represents an AI player that uses the Minimax algorithm to play the game
* intelligently.
*/
class MinimaxPlayer : public Player {
public:
/**
* @param symb This is the symbol for the minimax player's pieces
*/
MinimaxPlayer(char symb);
/**
* Destructor
*/
virtual ~MinimaxPlayer();
/**
* @param b The board object for the current state of the board
* @param col Holds the return value for the column of the move
* @param row Holds the return value for the row of the move
*/
void get_move(OthelloBoard* b, int& col, int& row);
/*
A helper struct that contains a board, and the column and row
of the latest move
*/
struct TreeNode
{
int col;
int row;
OthelloBoard b;
};
/**
* @return A copy of the MinimaxPlayer object
* This is a virtual copy constructor
*/
MinimaxPlayer* clone();
private:
/*
The function takes the current board and returns
an vector of TreeNodes containing all successors that can be reached in
one move
*/
std::vector<TreeNode> successor(OthelloBoard b, char symb);
/*
The maximizing function. Returns the MaxValue of a board.
*/
int MaxValue(OthelloBoard b);
/*
The miimizing function. Returns the MaxValue of a board.
*/
int MinValue(OthelloBoard b);
/**
This function takes the current board, and returns the "goodness"
The goodness is in regards to the maximizing player.
The maximizing player is whoever moves first.
**/
int utility(OthelloBoard b);
/*
Determines if a board is in a end state.
It is if neither player can make a move
*/
bool GameOver(OthelloBoard b);
};
#endif
<file_sep>################################
# Intro to AI - Assignment 1 #
# <NAME> #
# <NAME> #
################################
# NOTE: This code only works with Python3
import sys
import timeit
import os
import queue
class State(object):
def __init__(self, misRight, canRight, misLeft, canLeft, boat, parent, level):
self.misRight = misRight
self.canRight = canRight
self.misLeft = misLeft
self.canLeft = canLeft
self.parent = parent
self.boat = boat
self.level = level
def __repr__(self):
return "left bank: %s %s right bank: %s %s boat: %s" % (self.misLeft, self.canLeft, self.misRight, self.canRight, self.boat)
def __eq__(self, other):
if self.misRight == other.misRight \
and self.misLeft == other.misLeft \
and self.canRight == other.canRight \
and self.canLeft == other.canLeft \
and self.boat == other.boat:
return True
else:
return False
def __lt__(self, other):
if self.misLeft < other.misLeft and self.canLeft < other.canLeft:
return True
else:
return False
def __hash__(self):
return hash((self.misLeft, self.misRight, self.canLeft, self.canRight, self.boat))
# Checks for a valid state.
# If missionaries are present on a bank, then there cannot be more missionaries
def isValid(self):
valid = False
# if there are missionaries on the right, and there are more cannibals
if (self.misRight > 0) and (self.misRight < self.canRight):
valid = False
# if there are missionaries on the left, and there are more cannibals
elif (self.misLeft > 0) and (self.misLeft < self.canLeft):
valid = False
# if any of the values are negative
elif self.misLeft < 0 or self.canLeft < 0 or self.misRight < 0 or self.canRight < 0:
valid = False
else:
valid = True
# print(self)
return valid
def load_data(file):
left_bank = []
right_bank = []
first_line = 1
file = open(file, 'r')
# loop through each line in the file
for line in file:
# tokenize the line
line = line.replace("\n", "").split(',')
# convert the line to numbers and not strings
# //line = map(int, line)
if (first_line):
left_bank = list(map(int,line[0:3]))
first_line = 0
else:
right_bank = list(map(int,line[0:3]))
# check boat position and create state
if (right_bank[2] == 1):
state = State(right_bank[0], right_bank[1], left_bank[0], left_bank[1], 'right', None, 0)
else:
state = State(right_bank[0], right_bank[1], left_bank[0], left_bank[1], 'left', None, 0)
return state
def breadth_first(initial_state, goal_state):
visited = set()
fringe = []
# push first node into queue
fringe.append(initial_state)
while(fringe):
# gets the FIRST element in the fringe
current_node = fringe.pop(0)
# check if current node is goal
if (current_node == goal_state):
path = solution(current_node, initial_state)
return (path, len(visited))
if current_node not in visited:
visited.add(current_node)
valid_children = expand(current_node)
for state in valid_children:
fringe.append(state)
return None
def depth_first(initial_state, goal_state):
visited = set()
fringe = []
# push first node into queue
fringe.append(initial_state)
while(fringe):
# gets the LAST element in the fringe
current_node = fringe.pop()
# check if current node is goal
if (current_node == goal_state):
path = solution(current_node, initial_state)
return (path, len(visited))
if current_node not in visited:
visited.add(current_node)
valid_children = expand(current_node)
valid_children = list(reversed(valid_children))
for state in valid_children:
fringe.append(state)
return None
def iterative_deepening(initial_state, goal_state):
visited = set()
fringe = []
limit = 0
goal_found = 0
nodes = 0
while(len(visited) < 600):
# push first node into queue
fringe.append(initial_state)
while(fringe):
# gets the LAST element in the fringe
current_node = fringe.pop()
# check if current node is goal
if (current_node == goal_state):
path = solution(current_node, initial_state)
return (path, nodes)
if current_node not in visited:
visited.add(current_node)
# if the current level is less than the iterator
# we want to expand
if (current_node.level < limit):
valid_children = expand(current_node)
valid_children = list(reversed(valid_children))
for state in valid_children:
fringe.append(state)
nodes += len(visited)
visited.clear()
limit = limit + 1
def astar(initial_state, goal_state):
visited = set()
fringe = queue.PriorityQueue()
fringe.put((getScore(initial_state, goal_state), initial_state))
while(fringe):
# Get the element from the top of the queue, that has the lowest priority
current_node = fringe.get()[1]
# check if current node is goal
if (current_node == goal_state):
path = solution(current_node, initial_state)
return (path, len(visited))
if(current_node not in visited):
visited.add(current_node)
valid_children = expand(current_node)
for state in valid_children:
fringe.put((getScore(state, goal_state), state))
def getScore(cur, goal):
score = 0
# A lower score will mean that it is closer to the solution
score += goal.misLeft - cur.misLeft
score += goal.canLeft - cur.canLeft
return score
def expand(current):
valid_children = []
if (current.boat == 'right'):
# print("expanding w/ boat on right")
# move one missionary
child = State(current.misRight - 1, current.canRight, current.misLeft + 1, current.canLeft, 'left', current, current.level + 1)
if (child.isValid()):
valid_children.append(child)
# move two missionaries
child = State(current.misRight - 2, current.canRight, current.misLeft + 2, current.canLeft, 'left', current, current.level + 1)
if (child.isValid()):
valid_children.append(child)
# move one cannibal
child = State(current.misRight, current.canRight - 1, current.misLeft, current.canLeft + 1, 'left', current, current.level + 1)
if (child.isValid()):
valid_children.append(child)
# move one cannibal and one missionary
child = State(current.misRight - 1, current.canRight - 1, current.misLeft + 1, current.canLeft + 1, 'left', current, current.level + 1)
if (child.isValid()):
valid_children.append(child)
# move two cannibals
child = State(current.misRight, current.canRight - 2, current.misLeft, current.canLeft + 2, 'left', current, current.level + 1)
if (child.isValid()):
valid_children.append(child)
elif (current.boat == 'left'):
# print("expanding w/ boat on left")
# move one missionary
child = State(current.misRight + 1, current.canRight, current.misLeft - 1, current.canLeft, 'right', current, current.level + 1)
if (child.isValid()):
valid_children.append(child)
# move two missionaries
child = State(current.misRight + 2, current.canRight, current.misLeft - 2, current.canLeft, 'right', current, current.level + 1)
if (child.isValid()):
valid_children.append(child)
# move one cannibal
child = State(current.misRight, current.canRight + 1, current.misLeft, current.canLeft - 1, 'right', current, current.level + 1)
if (child.isValid()):
valid_children.append(child)
# move one cannibal and one missionary
child = State(current.misRight + 1, current.canRight + 1, current.misLeft - 1, current.canLeft - 1, 'right', current, current.level + 1)
if (child.isValid()):
valid_children.append(child)
# move two cannibals
child = State(current.misRight, current.canRight + 2, current.misLeft, current.canLeft - 2, 'right', current, current.level + 1)
if (child.isValid()):
valid_children.append(child)
return valid_children
def solution(finalState, initial):
currentState = finalState
path = []
path.append(finalState)
while currentState.parent != initial:
currentState = currentState.parent
path.insert(0, currentState)
return path
def main(args):
# Ensure enough arguments are present
if len(args) != 5:
print ("Incorrect number of command lind arguments provided.")
print ("Usage: starting_state goal_state mode output_file")
return
# Save file name
starting_state = args[1]
goal_state = args[2]
mode = args[3]
output = open(args[4], 'w')
initial = load_data(starting_state)
goal = load_data(goal_state)
validModes = set(["bfs", "dfs", "iddfs", "astar"])
if mode not in validModes:
print ("Please specify a valid mode from ", validModes)
exit
if mode == "bfs":
(solutionPath, nodes) = breadth_first(initial, goal)
time = timeit.timeit(stmt="breadth_first(initial, goal)", setup="from __main__ import breadth_first, initial, goal", number=1)
elif mode == "dfs":
(solutionPath, nodes) = depth_first(initial, goal)
time = timeit.timeit(stmt="depth_first(initial, goal)", setup="from __main__ import depth_first, initial, goal", number=1)
elif mode == 'iddfs':
(solutionPath, nodes) = iterative_deepening(initial, goal)
time = timeit.timeit(stmt="iterative_deepening(initial, goal)", setup="from __main__ import iterative_deepening, initial, goal", number=1)
elif mode == 'astar':
(solutionPath, nodes) = astar(initial, goal)
time = timeit.timeit(stmt="astar(initial, goal)", setup="from __main__ import astar, initial, goal", number=1)
if solutionPath != None:
print("Nodes visited: ", nodes)
print("Solution path:")
for step in solutionPath:
print(step, file=output)
print(step)
print("Time: " + str(time))
else:
print("No solution was found")
if __name__ == "__main__":
starting_state = sys.argv[1]
goal_state = sys.argv[2]
initial = load_data(starting_state)
goal = load_data(goal_state)
main(sys.argv)
<file_sep>/*
* MinimaxPlayer.cpp
*
* Created on: Apr 17, 2015
* Author: wong
*/
#include <iostream>
#include <assert.h>
#include "MinimaxPlayer.h"
using std::vector;
MinimaxPlayer::MinimaxPlayer(char symb) :
Player(symb) {
}
MinimaxPlayer::~MinimaxPlayer() {
}
int MinimaxPlayer::utility(OthelloBoard b) {
return (b.count_score(b.get_p1_symbol()) - b.count_score(b.get_p2_symbol()));
}
std::vector<OthelloBoard*> MinimaxPlayer::successor(OthelloBoard b, char symbol) {
std::vector<OthelloBoard*> validMoves;
for(int row = 0; row < b.get_num_rows(); row++) {
for(int col = 0; col < b.get_num_cols(); col++) {
if(b.is_legal_move(col, row, symbol) && b.is_cell_empty(col, row)) {
OthelloBoard *temp = new OthelloBoard(b);
temp->play_move(col, row, symbol);
temp->set_row(row);
temp->set_col(col);
validMoves.push_back(temp);
}
}
}
return validMoves;
}
int MinimaxPlayer::max_value(OthelloBoard b) {
if(!b.has_legal_moves_remaining(b.get_p1_symbol()) && !b.has_legal_moves_remaining(b.get_p2_symbol())) {
return utility(b);
}
std::vector<OthelloBoard*> children;
int maximum = -100;
char symbol = b.get_p1_symbol();
children = successor(b, symbol);
for(int i = 0; i < children.size(); i++) {
maximum = std::max(maximum, min_value(*children[i]));
}
return maximum;
}
int MinimaxPlayer::min_value(OthelloBoard b) {
if(!b.has_legal_moves_remaining(b.get_p1_symbol()) && !b.has_legal_moves_remaining(b.get_p2_symbol())) {
return utility(b);
}
std::vector<OthelloBoard*> children;
int minimum = 100;
char symbol = b.get_p2_symbol();
children = successor(b, symbol);
for(int i = 0; i < children.size(); i++) {
minimum = std::min(minimum, max_value(*children[i]));
}
return minimum;
}
void MinimaxPlayer::get_move(OthelloBoard* b, int& col, int& row) {
int best_row = -1;
int best_col = -1;
int best_min = 100;
std::vector<OthelloBoard*> first_children = successor(*b, get_symbol());
for (int i = 0; i < first_children.size(); i++) {
int value = max_value(*first_children[i]);
if (value < best_min) {
best_min = value;
best_row = first_children[i]->get_row();
best_col = first_children[i]->get_col();
}
}
row = best_row;
col = best_col;
}
MinimaxPlayer* MinimaxPlayer::clone() {
MinimaxPlayer* result = new MinimaxPlayer(symbol);
return result;
}
<file_sep>/*
* MinimaxPlayer.cpp
*
* Created on: Apr 17, 2015
* Author: wong
*/
#include <iostream>
#include <assert.h>
#include <algorithm>
#include "MinimaxPlayer.h"
using std::vector;
MinimaxPlayer::MinimaxPlayer(char symb) :
Player(symb) {
}
MinimaxPlayer::~MinimaxPlayer() {
}
std::vector<MinimaxPlayer::TreeNode> MinimaxPlayer::successor(OthelloBoard b, char symb)
{
std::vector<MinimaxPlayer::TreeNode> validMoves;
for(int row = 0; row < b.get_num_rows(); row++)
{
for(int col = 0; col < b.get_num_cols(); col++)
{
if(b.is_legal_move(col, row, symb) && b.is_cell_empty(col, row))
{
OthelloBoard temp = b;
temp.play_move(col, row, symb);
TreeNode toAdd = {col, row, temp};
validMoves.push_back(toAdd);
}
}
}
return validMoves;
}
int MinimaxPlayer::MaxValue(OthelloBoard b)
{
std::vector<TreeNode> children;
if(GameOver(b))
{
return utility(b);
}
// Initalize v to "neg inifinity"
int v = -9999;
// p1 is always maximizing
char symb = b.get_p1_symbol();
children = successor(b, symb);
for(int i = 0; i < children.size(); i++)
{
v = std::max(v, MinValue(children[i].b));
}
return v;
}
int MinimaxPlayer::MinValue(OthelloBoard b)
{
std::vector<TreeNode> children;
if(GameOver(b))
{
return utility(b);
}
// Initalize v to "pos inifinity"
int v = 9999;
// p2 is always minimizing
char symb = b.get_p2_symbol();
children = successor(b, symb);
for(int i = 0; i < children.size(); i++)
{
v = std::min(v, MaxValue(children[i].b));
}
return v;
}
void MinimaxPlayer::get_move(OthelloBoard* b, int& col, int& row) {
TreeNode bestBoard = {-1, -1, *b};
int minBest = 9999;
int maxBest = -9999;
// Get first level of successors here.
std::vector<TreeNode> children = successor(*b, get_symbol());
for(int i = 0; i < children.size(); i++)
{
if(b->get_p1_symbol() == get_symbol())
{
int v = MinValue(children[i].b);
if(v > maxBest)
{
maxBest = v;
bestBoard = children[i];
}
}
// For the puroses of testing this assignment
// we will always end up in this block
else
{
int v = MaxValue(children[i].b);
if(v < minBest)
{
minBest = v;
bestBoard = children[i];
}
}
}
// play the col and row from the bestBoard
col = bestBoard.col;
row = bestBoard.row;
}
bool MinimaxPlayer::GameOver(OthelloBoard b)
{
if(!b.has_legal_moves_remaining(b.get_p2_symbol()) && !b.has_legal_moves_remaining(b.get_p1_symbol()))
{
return true;
}
else
{
return false;
}
}
int MinimaxPlayer::utility(OthelloBoard b)
{
int p1Score = b.count_score(b.get_p1_symbol());
int p2Score = b.count_score(b.get_p2_symbol());
return p1Score - p2Score;
}
MinimaxPlayer* MinimaxPlayer::clone() {
MinimaxPlayer* result = new MinimaxPlayer(symbol);
return result;
}
<file_sep>from __future__ import division
import sys
import os
import string
# NOTE: Python 2 :)
def getVocab(data):
result = set()
for line in data:
for word in line:
result.add(word)
return sorted(result)
def assign_vocab_probabilities(vocab, training, truth):
true_records = 0
false_records = 0
for value in truth:
if value == 1:
true_records += 1
else:
false_records += 1
result = {}
for index, entry in enumerate(vocab):
true_true_word_count = 0
false_true_word_count = 0
false_false_word_count = 0
true_false_word_count = 0
for sentence in training:
if sentence[index] == 1:
if sentence[-1] == 1:
true_true_word_count += 1
else:
true_false_word_count += 1
else:
if sentence[-1] == 1:
false_true_word_count += 1
else:
false_false_word_count += 1
probabilities = (true_true_word_count/true_records, false_true_word_count/true_records, true_false_word_count/false_records, false_false_word_count/false_records)
result[entry] = probabilities
return result, (true_records / len(truth), false_records / len(truth))
def testing_phase(sentences, trained_vocab, probabilities, vocab):
result = []
prob_class_true = probabilities[0]
prob_class_false = probabilities[1]
for sentence in sentences:
prob_true = prob_class_true
for index, word in enumerate(sentence):
if vocab[index] in trained_vocab:
if word == 1:
prob_true *= trained_vocab[vocab[index]][0]
else:
prob_true *= trained_vocab[vocab[index]][1]
prob_false = prob_class_false
for index, word in enumerate(sentence):
if vocab[index] in trained_vocab:
if word == 1:
prob_false *= trained_vocab[vocab[index]][2]
else:
prob_false *= trained_vocab[vocab[index]][3]
if prob_true >= prob_false:
result.append(1)
else:
result.append(0)
return result
def check_accuracy(calculated_truth, real_truth):
correct = 0
for i in range(len(real_truth)):
if calculated_truth[i] == real_truth[i]:
correct += 1
return correct / len(real_truth)
def getData(fileName):
data = []
dataTruth = []
deleteChars = string.punctuation + "1234567890"
with open(fileName) as f:
training = f.readlines()
for line in training:
temp = line.split('\t')
data.append(temp[0].translate(None, deleteChars).lower().split())
dataTruth.append(temp[1].strip())
dataTruth = list(map(int, dataTruth))
return data, dataTruth
def buildFeatureVector(vocab, sentences, truth):
result = []
truthIndex = 0
for sentence in sentences:
# feature vector of size M+1, where M is the size of the vocab
temp = [0 for _ in range(len(vocab))]
for word in sentence:
if word in vocab:
try:
index = vocab.index(word)
except:
continue
temp[index] = 1
temp[len(vocab) - 1] = truth[truthIndex]
result.append(temp)
truthIndex += 1
return result
def outputPreprocess(vocab, train, test):
os.system('rm preprocessed_train.txt')
os.system('rm preprocessed_test.txt')
trainFile = open("preprocessed_train.txt", 'w')
testFile = open("preprocessed_test.txt", 'w')
for word in vocab:
trainFile.write(word + ",")
testFile.write(word + ",")
trainFile.write("classlabel\n")
testFile.write("classlabel\n")
for feature in train:
for idx, i in enumerate(feature):
if idx == len(feature) - 1:
trainFile.write(str(i))
else:
trainFile.write(str(i) + ",")
trainFile.write("\n")
for feature in test:
for idx, i in enumerate(feature):
if idx == len(feature) - 1:
testFile.write(str(i))
else:
testFile.write(str(i) + ",")
testFile.write("\n")
def main(args):
vocab = []
trainingWords = []
testingWords = []
trainingTruth = []
testingTruth = []
training = []
testing = []
trainingSentences, trainingTruth = getData(args[1])
testingSentences, testingTruth = getData(args[2])
vocab = getVocab(trainingSentences)
training = buildFeatureVector(vocab, trainingSentences, trainingTruth)
testing = buildFeatureVector(vocab, testingSentences, testingTruth)
outputPreprocess(vocab, training, testing)
trained_vocab, (p_class_1, p_class_0) = assign_vocab_probabilities(vocab, training, trainingTruth)
training_classification = testing_phase(training, trained_vocab, (p_class_1, p_class_0), vocab)
testing_classification = testing_phase(testing, trained_vocab, (p_class_1, p_class_0), vocab)
result1 = check_accuracy(training_classification, trainingTruth)
result2 = check_accuracy(testing_classification, testingTruth)
# output results
output = open('results.txt', 'w')
output.write("Training Set (training, training): ")
output.write(str(result1) + '\n')
output.write("Testing Set (training, testing): ")
output.write(str(result2) + '\n')
if __name__ == "__main__":
main(sys.argv)
| 3c51d08d744e63fd5b62fc8cbb9a6c59d0f253ef | [
"Python",
"C++"
] | 5 | C++ | aoumar153/intro-to-ai | f3e15910b9836ed409f14321a5f493c88ea3f007 | e7e2fce93f78a2b6750965c1fe5f58440faabe0a |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Test2
{
class Program
{
static void Main(string[] args)
{
int[] vektor = new int[10] { 9, 3, 4, 2, 17, 32, 63, 54, 1, 8, };
int[] vektorKopje = vektor;
int Min1 = 999;
int Min2 = 999;
for (int i = 0; i < vektor.Length; i++)
{
if (vektor[i] < Min1)
{
Min1 = vektor[i];
}
}
for (int i = 0; i < vektor.Length; i++)
{
if (vektor[i] < Min2 && vektor[i] != Min1)
{
Min2 = vektor[i];
}
}
var list = vektor.ToList();
for (int k=0;k<list.Count;k++)
{
if(list[k]==Min1)
{
list.RemoveAt(k--);
}
if(list[k]==Min2)
{
list.RemoveAt(k--);
}
}
vektor = list.ToArray();
for (int j = 0; j < vektorKopje.Length; j++)
{
Console.Write(vektorKopje[j]);
Console.Write("\t");
}
Console.Write("\n");
Console.Write("\n");
Console.Write("Dy numrat me te vegjel te Vektorit jane:\t" + Min1 + " dhe " + Min2);
Console.Write("\n");
Console.Write("\n");
for (int i = 0; i < vektor.Length; i++)
{
Console.Write(vektor[i]);
Console.Write("\t");
}
}
}
}
<file_sep># test
# My first commit
| e5e53346744579fb1e9f49e3359b8348f690bb3e | [
"Markdown",
"C#"
] | 2 | C# | MedinaXhametaj/test | b96dd1178c0877624183c91d698d4aa49d33f88c | 2978f77d7888d0d777b0af1cdb8db4a144b0be42 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace naredbaUsing
{
class Program
{
static void Main(string[] args)
{
Console.Write("Unesite ime: ");
string ime = Console.ReadLine();
Console.Write("Unesite prezime: ");
string prezime = Console.ReadLine();
// Podatke upisujemo u datoteku
Console.WriteLine("\n-- Zapisujemo u datoteku...");
using (StreamWriter sw = new StreamWriter(@"D:\My Documents\NOOP\datoteka.txt"))
{
sw.WriteLine("Ime: { 0}", ime);
sw.WriteLine("Prezime: { 0}", prezime);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace objektiStreamReader
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(@"D:\My Documents\NOOP\datoteka.txt");
// Čitamo datoteku liniju po liniju
while (!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
// Zatvaramo datoteku
sr.Close();
Console.ReadKey();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace objektiStreamWriter
{
class Program
{
static void Main(string[] args)
{
Console.Write("Unesite ime: ");
string ime = Console.ReadLine();
Console.Write("Unesite prezime: ");
string prezime = Console.ReadLine();
StreamWriter sw = new StreamWriter(@"D:\My Documents\NOOP\datoteka.txt");
sw.WriteLine("Ime: { 0}", ime);
sw.WriteLine("Prezime: { 0}", prezime);
sw.Close();
}
}
}
| 1cb1a2db49fdff754ed834afdd12c35806278b4d | [
"C#"
] | 3 | C# | AntonioEreiz332/systemIOvjezbe | 8f203bd936c5d3882937bc1f96475aadea890f7b | 69409d710151331d51bb726fff886faaa4ee2edc |
refs/heads/master | <repo_name>RMedina19/Graficando_Covid19_Mx<file_sep>/02_script/art_rm_nexos.R
# 1. Cargar paquetes ----
require(tidyverse)
require(ggplot2)
require(readxl)
require(ggthemes)
require(lubridate)
require(geofacet)
require(RColorBrewer)
# 2. Establecer directorios ----
dir <- "~/GitHub/Graficando_Covid19_Mx"
setwd(dir)
inp <- "/01_datos/"
out <- "/03_gráficas/"
fiuffi <- "Elaboración propia con datos de la Secretaría de Salud\n@guzmart_ | @regi_medina | @lolo7no"
# Función para reconocer acentos
rm_accent <- function(str,pattern="all") {
if(!is.character(str))
str <- as.character(str)
pattern <- unique(pattern)
if(any(pattern=="Ç"))
pattern[pattern=="Ç"] <- "ç"
symbols <- c(
acute = "áéíóúÁÉÍÓÚýÝ",
grave = "àèìòùÀÈÌÒÙ",
circunflex = "âêîôûÂÊÎÔÛ",
tilde = "ãõÃÕñÑ",
umlaut = "äëïöüÄËÏÖÜÿ",
cedil = "çÇ"
)
nudeSymbols <- c(
acute = "aeiouAEIOUyY",
grave = "aeiouAEIOU",
circunflex = "aeiouAEIOU",
tilde = "aoAOnN",
umlaut = "aeiouAEIOUy",
cedil = "cC"
)
accentTypes <- c("´","`","^","~","¨","ç")
if(any(c("all","al","a","todos","t","to","tod","todo")%in%pattern)) # opcao retirar todos
return(chartr(paste(symbols, collapse=""), paste(nudeSymbols, collapse=""), str))
for(i in which(accentTypes%in%pattern))
str <- chartr(symbols[i],nudeSymbols[i], str)
return(str)
}
# 3. Cargar datos ----
d <- read_excel(paste0(dir, inp, "covid_mex_20200401.xlsx"),
col_types = c("numeric", "text", "text", "numeric", "date", "text", "text", "date", "date", "numeric", "date", "numeric", "date")) %>%
mutate(ent = str_replace_all(ent, "\r", " "),
ent = str_remove_all(ent, "\n"),
ent = rm_accent(ent)) %>%
filter(!inconsistencia_omision==1)
load(paste0(dir, inp, "mxhexmap.RData"))
mxhexmap$state_abbr <- ifelse(mxhexmap$state_abbr=="DF",
"CDMX",as.character(mxhexmap$state_abbr))
# 4. Transformaciones de los datos----
data_fecha <- d %>%
group_by(
fecha_corte
) %>%
summarise(
n = n()
)
data_fecha_acumulado <- data_fecha %>%
mutate(
n = cumsum(n),
fecha_corte = ymd(fecha_corte),
pais = "México"
)
data_fecha_sintomas <- d %>%
group_by(
fecha_inicio
) %>%
summarise(
n = n()
) %>%
mutate(
n_acumulada = cumsum(n)
)
# DATA CURVA EPIDÉMICA COMPARADA
data_ent <- d %>%
group_by(
ent
) %>%
summarise(
n = n()
) %>%
mutate(
cve_ent = case_when(
ent == "AGUASCALIENTES" ~ "01",
ent == "BAJA CALIFORNIA" ~ "02",
ent == "BAJA CALIFORNIA SUR" ~ "03",
ent == "CAMPECHE" ~ "04",
ent == "CHIAPAS" ~ "07",
ent == "CHIHUAHUA" ~ "08",
ent == "<NAME>" ~ "09",
ent == "COAHUILA" ~ "05",
ent == "COLIMA" ~ "06",
ent == "DURANGO" ~ "10",
ent == "GUANAJUATO" ~ "11",
ent == "GUERRERO" ~ "12",
ent == "HIDALGO" ~ "13",
ent == "JALISCO" ~ "14",
ent == "MEXICO" ~ "15",
ent == "MICHOACAN" ~ "16",
ent == "MORELOS" ~ "17",
ent == "NAYARIT" ~ "18",
ent == "<NAME>" ~ "19",
ent == "OAXACA" ~ "20",
ent == "PUEBLA" ~ "21",
ent == "QUERETARO" ~ "22",
ent == "<NAME>" ~ "23",
ent == "<NAME>" ~ "24",
ent == "SINALOA" ~ "25",
ent == "SONORA" ~ "26",
ent == "TABASCO" ~ "27",
ent == "TAMAULIPAS" ~ "28",
ent == "TLAXCALA" ~ "29",
ent == "VERACRUZ" ~ "30",
ent == "YUCATAN" ~ "31",
ent == "ZACATECAS" ~ "32",
)
) %>%
left_join(mxhexmap %>% rename(cve_ent=ent))
data_world <- read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv") %>%
filter(`Country/Region`=="Spain" | `Country/Region`== "Italy" |
`Country/Region`== "France" | `Country/Region` == "Germany" | `Country/Region`== "US") %>%
filter(is.na(`Province/State`)) %>%
select(-"Province/State", -Lat, -Long) %>%
rename("pais" = "Country/Region") %>%
pivot_longer(-pais,
names_to = "fecha_corte",
values_to = "n") %>%
group_by(pais, fecha_corte) %>%
summarise(n = sum(n, na.rm = T)) %>%
ungroup() %>%
mutate(fecha_corte = mdy(fecha_corte),
pais = case_when(
str_starts(pais, "Fr")~ "Francia",
str_starts(pais, "Ger")~ "Alemania",
str_starts(pais, "It")~ "Italia",
str_starts(pais, "Sp")~ "España",
str_starts(pais, "U")~ "EEUU",
)) %>%
select(pais, fecha_corte, n) %>%
bind_rows(data_fecha_acumulado) %>%
complete(fecha_corte, pais) %>%
replace(., is.na(.), 0) %>%
filter(n>0)%>%
group_by(pais) %>%
mutate(Día = as.numeric(fecha_corte-min(fecha_corte)),
max = max(n))%>%
ungroup()
# 5. Visualizaciones ----
fiuf <- "Número de casos confirmados de COVID-19 en México\npor fecha de corte"
fiuff <- paste0("Actualización: ", str_sub(max(data_fecha_acumulado$fecha_corte), end = -1))
# Total de nuevos casos confirmados por día
ggplot(data_fecha_acumulado,
aes(x = as.Date(fecha_corte),
y = n,
label = n)) +
geom_line() + geom_label(size=5) +
scale_x_date(date_breaks = "1 day",
limits = c(
min(as.Date(data_fecha_acumulado$fecha_corte)-0.7),
max(as.Date(data_fecha_acumulado$fecha_corte)+0.8)
),
expand = c(0,0)) +
theme_minimal() +
labs(title=fiuf,
subtitle=fiuff,
caption=fiuffi,
x="",
y="Número de casos acumulados") +
theme(plot.title = element_text(size = 35, face = "bold"),
plot.subtitle = element_text(size = 25),
plot.caption = element_text(size = 20),
strip.text = element_text(size = 15),
panel.spacing.x = unit(3, "lines"),
text = element_text(family = "Arial Narrow"),
axis.text.x = element_text(size = 12, angle = 90, vjust = 0.5),
axis.title.y = element_text(size = 15),
axis.text.y = element_text(size = 15))
ggsave(filename = paste0(dir, out,
str_replace_all(str_sub(max(data_fecha_acumulado$fecha_corte), end = -1), "-", "_"),
"_01_acumulados.png"), width = 15, height = 10, dpi = 100)
# Total de personas con primeros síntomas por día
fiuf <- "Número de casos confirmados de COVID-19 en México\npor fecha de síntomas"
ggplot(data_fecha_sintomas,
aes(x = as.Date(fecha_inicio),
y = n_acumulada,
label = ifelse(
fecha_inicio==max(data_fecha_sintomas$fecha_inicio), n_acumulada, ""
))) +
geom_text(size=6, vjust = -0.5, hjust = 1) + geom_line() +
scale_x_date(date_breaks = "1 day",
limits = c(
min(as.Date(data_fecha_sintomas$fecha_inicio)-0.7),
max(as.Date(data_fecha_sintomas$fecha_inicio)+0.7)
),
expand = c(0,0)) +
theme_minimal() +
labs(title=fiuf,
subtitle=fiuff,
caption=fiuffi,
x="Fecha de inicio de síntomas",
y="Número de casos acumulados") +
theme(plot.title = element_text(size = 35, face = "bold"),
plot.subtitle = element_text(size = 25),
plot.caption = element_text(size = 20),
strip.text = element_text(size = 15),
panel.spacing.x = unit(3, "lines"),
text = element_text(family = "Arial Narrow"),
axis.text.x = element_text(size = 12, angle = 90, vjust = 0.5),
axis.title.x = element_text(size = 15),
axis.title.y = element_text(size = 15),
axis.text.y = element_text(size = 15))
ggsave(filename = paste0(dir, out,
str_replace_all(str_sub(max(d$fecha_corte), end = -1), "-", "_"),
"_02_sintomas.png"), width = 15, height = 10, dpi = 100)
# Casos acumulados por entidad en mapa de calor
fiuf <- "Número de casos confirmados de COVID-19 en México\npor entidad federativa"
ggplot(data_ent,
aes(long, lat, group=ent,
fill=as.integer(n))) +
geom_polygon(color = "gray") +
geom_text(aes(label=paste0(state_abbr, "\n[ ",n, " ]"),
x=cent_x,y=cent_y)) +
theme_void() +
scale_fill_gradient("",
low = brewer.pal(n = 9, "Reds")[1],
high = brewer.pal(n = 9, "Reds")[9]) +
labs(title=fiuf,
subtitle=fiuff,
caption=fiuffi,
x="",
y="") +
theme(plot.title = element_text(size = 35, face = "bold"),
plot.subtitle = element_text(size = 25),
plot.caption = element_text(size = 20),
strip.text = element_text(size = 15),
panel.spacing.x = unit(3, "lines"),
text = element_text(family = "Arial Narrow"),
axis.text.x = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_blank()) +
coord_fixed()
ggsave(filename = paste0(
out, str_replace_all(str_sub(max(d$fecha_corte), end = -1), "-", "_"), "_03_ent.png"
), width = 15, height = 10, dpi = 100)
fiuf <- "Número de casos acumulados en distintos países\ndesde el primer caso confirmado en el país"
ggplot(data_world,
aes(x = Día,
y = n,
color = pais,
label = ifelse(
fecha_corte==max(fecha_corte),
paste0(pais, "\n",
format(max, big.mark = ",")), ""
))) +
geom_line(lineend = "round",
size = 1) +
geom_text_repel(color="black") +
labs(title = fiuf,
subtitle = fiuff,
caption = fiuffi,
colour = "",
x = "Días desde el primer caso confirmado en el país",
y = "") +
theme_minimal() +
theme(plot.title = element_text(size = 35, face = "bold"),
plot.subtitle = element_text(size = 25),
plot.caption = element_text(size = 20),
strip.text = element_text(size = 15),
panel.spacing.x = unit(3, "lines"),
text = element_text(family = "Arial Narrow"),
axis.text.x = element_text(size = 15, vjust = 0.5),
axis.text.y = element_text(size = 13),
legend.position = "none",
legend.text = element_text(size = 18))
ggsave(filename = paste0(dir, out,
str_replace_all(str_sub(max(d$fecha_corte), end = -1), "-", "_"),
"_04_mundial.png"), width = 15, height = 10, dpi = 100)
<file_sep>/README.md
# Recomendaciones para visualizaciones gráficas de datos
En este repositorio encontrarán una pequeña serie de recomendaciones para mejorar las prácticas de visualización de datos con información sobre el avance del Covid-19 en México.
| ac894b8c6f097502a68cfa2fb28244321b432afb | [
"Markdown",
"R"
] | 2 | R | RMedina19/Graficando_Covid19_Mx | f8bb3b412b30626f98cbe6af8910337a0d2d7102 | 56ab5e566e4b491732dc8b62ba75f13e26c2f5cd |
refs/heads/main | <file_sep># -*- coding: utf-8 -*-
"""
Created on Sun May 23 17:45:26 2021
@author: ASHUTOSH
"""
from pandas import read_csv
import sys
import math
dataset = read_csv('18-04-2019-TO-16-04-2021RELIANCEALLN.csv', header=0)
def calculate_slope(index, slope_length):
# print(index,"to",index+slope_length-1)
return math.degrees(math.atan(
(dataset.iloc[index + slope_length - 1]['Close Price'] - dataset.iloc[index]['Close Price']) / slope_length))
def calculate_profit(slope_length, input_angle, output_angle):
profit = 0.0
buy_indices = []
sell_indices = []
buy_price_indices = []
sell_price_indices = []
for index, row in dataset.iterrows():
if index + slope_length <= len(dataset.index):
if calculate_slope(index, slope_length) >= input_angle:
# pass
buy_price = dataset.iloc[index + slope_length - 1]['Close Price']
buy_indices.append(index + slope_length - 1)
buy_price_indices.append(buy_price)
sell_price = 0.0
for index_sell, row_sell in dataset.iterrows():
if index_sell > (index + slope_length - 1):
if index_sell + slope_length <= len(dataset.index):
if calculate_slope(index_sell, slope_length) <= ((-1) * output_angle):
sell_price = dataset.iloc[index_sell + slope_length - 1]['Close Price']
sell_indices.append(index_sell + slope_length - 1)
sell_price_indices.append(sell_price)
break
profit += (sell_price - buy_price)
return profit, buy_indices, sell_indices, buy_price_indices, sell_price_indices
slope_angles = [30]
slope_lengths = [20]
max_profit = sys.float_info.min
min_cash = sys.float_info.max
max_slope_length = max_input_angle = max_output_angle = 0
cash = 100000
optimum_buy_indices = []
optimum_sell_indices = []
optimum_buy_price_indices = []
optimum_sell_price_indices = []
for slope_length in slope_lengths:
for input_angle in slope_angles:
for output_angle in slope_angles:
profit, buy_indices, sell_indices, buy_price_indices, sell_price_indices = calculate_profit(slope_length,
input_angle,
output_angle)
if profit > max_profit:
max_profit = profit
max_slope_length = slope_length
max_input_angle = input_angle
max_output_angle = output_angle
optimum_buy_indices = buy_indices
optimum_sell_indices = sell_indices
optimum_buy_price_indices = buy_price_indices
optimum_sell_price_indices = sell_price_indices
print('max profit = ', max_profit)
print('optimum slope length = ', max_slope_length)
print('optimum input angle = ', max_input_angle)
print('optimum output angle = ', max_output_angle)
print('optimum buy indices = ', optimum_buy_indices)
print('optimum sell indices = ', optimum_sell_indices)
def countX(lst, x):
count = 0
for ele in lst:
if (ele == x):
count = count + 1
return count
cash_list = []
for i in range(494):
if i in optimum_buy_indices:
# print('bought')
cash -= optimum_buy_price_indices[optimum_buy_indices.index(i)]
cash_list.append(cash)
elif i in optimum_sell_indices:
# print('sold')
times = countX(optimum_sell_indices, i)
# print(times)
cash += (optimum_sell_price_indices[optimum_sell_indices.index(i)] * times)
print(min(cash_list))
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun May 23 12:54:25 2021
@author: ASHUTOSH
"""
from pandas import read_csv
import sys
import math
dataset = read_csv('18-04-2019-TO-16-04-2021RELIANCEALLN.csv', header=0)
def calculate_slope(index, slope_length):
# print(index,"to",index+slope_length-1)
return math.degrees(math.atan(
(dataset.iloc[index + slope_length - 1]['Close Price'] - dataset.iloc[index]['Close Price']) / slope_length))
def calculate_profit(slope_length, input_angle, output_angle):
profit = 0.0
for index, row in dataset.iterrows():
if index + slope_length <= len(dataset.index):
if calculate_slope(index, slope_length) >= input_angle:
# pass
buy_price = dataset.iloc[index + slope_length - 1]['Close Price']
sell_price = 0.0
for index_sell, row_sell in dataset.iterrows():
if index_sell > (index + slope_length - 1):
if index_sell + slope_length <= len(dataset.index):
if calculate_slope(index_sell, slope_length) <= ((-1) * output_angle):
sell_price = dataset.iloc[index_sell + slope_length - 1]['Close Price']
break
profit += (sell_price - buy_price)
return profit
slope_angles = [30, 45]
slope_lengths = [5, 20]
max_profit = sys.float_info.min
max_slope_length = max_input_angle = max_output_angle = 0
for slope_length in slope_lengths:
for input_angle in slope_angles:
for output_angle in slope_angles:
profit = calculate_profit(slope_length, input_angle, output_angle)
if profit > max_profit:
max_profit = profit
max_slope_length = slope_length
max_input_angle = input_angle
max_output_angle = output_angle
print('max profit = ', max_profit)
print('optimum slope length = ', max_slope_length)
print('optimum input angle = ', max_input_angle)
print('optimum output angle = ', max_output_angle)
<file_sep># stock
My attempt at stock price prediction
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu May 20 10:42:44 2021
@author: ASHUTOSH
"""
from math import sqrt
from numpy import concatenate
from matplotlib import pyplot
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
import pandas as pd
# convert series to supervised learning
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
n_vars = 1 if type(data) is list else data.shape[1]
df = DataFrame(data)
cols, names = list(), list()
# input sequence (t-n, ... t-1)
for i in range(n_in, 0, -1):
cols.append(df.shift(i))
names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
# forecast sequence (t, t+1, ... t+n)
for i in range(0, n_out):
cols.append(df.shift(-i))
if i == 0:
names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
else:
names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
# put it all together
agg = concat(cols, axis=1)
agg.columns = names
# drop rows with NaN values
if dropnan:
agg.dropna(inplace=True)
return agg
# load dataset
dataset = read_csv('18-04-2019-TO-16-04-2021RELIANCEALLN.csv', header=0, index_col=2)
dataset=dataset.drop(columns=['Series','Symbol'])
print(dataset.head())
# print(dataset.index)
dataset['Year'] = pd.DatetimeIndex(dataset.index).year
dataset['Month'] = pd.DatetimeIndex(dataset.index).month
dataset['Week'] = pd.DatetimeIndex(dataset.index).week
dataset['Day'] = pd.DatetimeIndex(dataset.index).day
dataset['Dayofweek'] = pd.DatetimeIndex(dataset.index).day_name()
dataset['Dayofyear'] = pd.DatetimeIndex(dataset.index).dayofyear
dataset['Is_month_end'] = pd.DatetimeIndex(dataset.index).is_month_end
dataset['Is_month_start'] = pd.DatetimeIndex(dataset.index).is_month_start
dataset['Is_quarter_end'] = pd.DatetimeIndex(dataset.index).is_quarter_end
dataset['Is_quarter_start'] = pd.DatetimeIndex(dataset.index).is_quarter_start
dataset['Is_year_end'] = pd.DatetimeIndex(dataset.index).is_year_end
dataset['Is_year_start'] = pd.DatetimeIndex(dataset.index).is_year_start
switcher={
'Monday':0,
'Tuesday':1,
'Wednesday':2,
'Thursday':3,
'Friday':4,
'Saturday':5,
'Sunday':6
}
for i in range(0,len(dataset)):
prev=dataset['Dayofweek'][i]
dataset['Dayofweek'][i]=switcher.get(dataset['Dayofweek'][i],"Invalid day")
values = dataset.values
# integer encode direction
encoder = LabelEncoder()
values[:,23] = encoder.fit_transform(values[:,23])
# ensure all data is float
values = values.astype('float32')
# normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
# specify the number of lag hours
n_days = 10
n_features = 24
# frame as supervised learning
reframed = series_to_supervised(scaled, n_days, 1)
print(reframed.shape)
# split into train and test sets
values = reframed.values
# values1=values[:400,:]
# values2=values[400:,:]
# print(values[:400,:])
# # n_train_hours = 365 * 24
train = values[:395, :]
test = values[395:, :]
# split into input and outputs
n_obs = n_days * n_features
train_X, train_y = train[:, :n_obs], train[:, -n_features]
test_X, test_y = test[:, :n_obs], test[:, -n_features]
print(train_X.shape, len(train_X), train_y.shape)
# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], n_days, n_features))
test_X = test_X.reshape((test_X.shape[0], n_days, n_features))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)
# design network
model = Sequential()
model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(train_X, train_y, epochs=50, batch_size=72, validation_data=(test_X, test_y), verbose=2, shuffle=False)
# plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()
# make a prediction
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], n_days*n_features))
# invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, -23:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
print('prediction=')
print(inv_yhat)
# invert scaling for actual
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, -23:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:,0]
print('actual=')
print(inv_y)
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)<file_sep># import packages
import pandas as pd
import numpy as np
# to plot within notebook
import matplotlib.pyplot as plt
# %matplotlib inline
# setting figure size
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 20, 10
# for normalizing data
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 1))
# read the file
df = pd.read_csv('18-04-2019-TO-16-04-2021RELIANCEALLN.csv')
# print the head
df.head()
# setting index as date
df['Date'] = pd.to_datetime(df.Date, format='%d-%b-%Y')
df.index = df['Date']
# plot
plt.figure(figsize=(16, 8))
plt.plot(df['Close Price'], label='Close Price history')
print('\n Shape of the data:')
print(df.shape)
data = df.sort_index(ascending=True, axis=0)
new_data = pd.DataFrame(index=range(0, len(df)), columns=['Date', 'Close Price'])
for i in range(0, len(data)):
new_data['Date'][i] = data['Date'][i]
new_data['Close Price'][i] = data['Close Price'][i]
# NOTE: While splitting the data into train and validation set, we cannot use random splitting since that will destroy the time component. So here we have set the last year’s data into validation and the 4 years’ data before that into train set.
# splitting into train and validation
train = new_data[:395]
valid = new_data[395:]
# shapes of training set
print('\n Shape of training set:')
print(train.shape)
# shapes of validation set
print('\n Shape of validation set:')
print(valid.shape)
# In the next step, we will create predictions for the validation set and check the RMSE using the actual values.
# making predictions
preds = []
for i in range(0, valid.shape[0]):
a = train['Close Price'][len(train) - 248 + i:].sum() + sum(preds)
b = a / 248
preds.append(b)
# checking the results (RMSE value)
rms = np.sqrt(np.mean(np.power((np.array(valid['Close Price']) - preds), 2)))
print('\n RMSE value on validation set:')
print(rms)
# plot
valid['Predictions'] = 0
valid['Predictions'] = preds
plt.plot(train['Close Price'])
plt.plot(valid[['Close Price', 'Predictions']])
# sorting
data = df.sort_index(ascending=True, axis=0)
# creating a separate dataset
new_data = pd.DataFrame(index=range(0, len(df)),
columns=['Date', 'Close Price', 'Turnover', 'No. of Trades', '% Dly Qt to Traded Qty'])
for i in range(0, len(data)):
new_data['Date'][i] = data['Date'][i]
new_data['Close Price'][i] = data['Close Price'][i]
new_data['Turnover'][i] = data['Turnover'][i]
new_data['No. of Trades'][i] = data['No. of Trades'][i]
new_data['% Dly Qt to Traded Qty'][i] = data['% Dly Qt to Traded Qty'][i]
new_data['Year'] = pd.DatetimeIndex(new_data['Date']).year
new_data['Month'] = pd.DatetimeIndex(new_data['Date']).month
new_data['Week'] = pd.DatetimeIndex(new_data['Date']).week
new_data['Day'] = pd.DatetimeIndex(new_data['Date']).day
new_data['Dayofweek'] = pd.DatetimeIndex(new_data['Date']).day_name()
new_data['Dayofyear'] = pd.DatetimeIndex(new_data['Date']).dayofyear
new_data['Is_month_end'] = pd.DatetimeIndex(new_data['Date']).is_month_end
new_data['Is_month_start'] = pd.DatetimeIndex(new_data['Date']).is_month_start
new_data['Is_quarter_end'] = pd.DatetimeIndex(new_data['Date']).is_quarter_end
new_data['Is_quarter_start'] = pd.DatetimeIndex(new_data['Date']).is_quarter_start
new_data['Is_year_end'] = pd.DatetimeIndex(new_data['Date']).is_year_end
new_data['Is_year_start'] = pd.DatetimeIndex(new_data['Date']).is_year_start
new_data.head()
switcher = {
'Monday': 0,
'Tuesday': 1,
'Wednesday': 2,
'Thursday': 3,
'Friday': 4,
'Saturday': 5,
'Sunday': 6
}
for i in range(0, len(new_data)):
prev = new_data['Dayofweek'][i]
new_data['Dayofweek'][i] = switcher.get(new_data['Dayofweek'][i], "Invalid day")
# if(new_data['Dayofweek'][i]=="Invalid day"):
# print(prev)
print(new_data.head())
new_data['mon_fri'] = 0
for i in range(0, len(new_data)):
if (new_data['Dayofweek'][i] == 0 or new_data['Dayofweek'][i] == 4):
new_data['mon_fri'][i] = 1
else:
new_data['mon_fri'][i] = 0
print(new_data.head())
# split into train and validation
train = new_data[:395]
valid = new_data[395:]
x_train = train.drop(['Date', 'Close Price'], axis=1)
y_train = train['Close Price']
x_valid = valid.drop(['Date', 'Close Price'], axis=1)
y_valid = valid['Close Price']
# implement linear regression
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(x_train, y_train)
# make predictions and find the rmse
preds = model.predict(x_valid)
rms = np.sqrt(np.mean(np.power((np.array(y_valid) - np.array(preds)), 2)))
rms
# plot
valid['Predictions'] = 0
valid['Predictions'] = preds
valid.index = new_data[395:].index
train.index = new_data[:395].index
plt.plot(train['Close Price'])
plt.plot(valid[['Close Price', 'Predictions']])
# importing libraries
from sklearn import neighbors
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 1))
# scaling data
x_train_scaled = scaler.fit_transform(x_train)
x_train = pd.DataFrame(x_train_scaled)
x_valid_scaled = scaler.fit_transform(x_valid)
x_valid = pd.DataFrame(x_valid_scaled)
# using gridsearch to find the best parameter
params = {'n_neighbors': [2, 3, 4, 5, 6, 7, 8, 9]}
knn = neighbors.KNeighborsRegressor()
model = GridSearchCV(knn, params, cv=5)
# fit the model and make predictions
model.fit(x_train, y_train)
preds = model.predict(x_valid)
# rmse
rms = np.sqrt(np.mean(np.power((np.array(y_valid) - np.array(preds)), 2)))
rms
# plot
valid['Predictions'] = 0
valid['Predictions'] = preds
plt.plot(valid[['Close Price', 'Predictions']])
plt.plot(train['Close Price'])
from pmdarima import auto_arima
data = df.sort_index(ascending=True, axis=0)
train = data[:395]
valid = data[395:]
training = train['Close Price']
validation = valid['Close Price']
model = auto_arima(training, start_p=1, start_q=1,max_p=3, max_q=3, m=12,start_P=0, seasonal=True,d=1, D=1, trace=True,error_action='ignore',suppress_warnings=True)
model.fit(training)
forecast = model.predict(n_periods=99)
forecast = pd.DataFrame(forecast,index = valid.index,columns=['Prediction'])
rms=np.sqrt(np.mean(np.power((np.array(valid['Close Price'])-np.array(forecast['Prediction'])),2)))
rms
#plot
plt.plot(train['Close Price'])
plt.plot(valid['Close Price'])
plt.plot(forecast['Prediction'])
#importing prophet
from fbprophet import Prophet
#creating dataframe
new_data = pd.DataFrame(index=range(0,len(df)),columns=['Date', 'Close Price'])
for i in range(0,len(data)):
new_data['Date'][i] = data['Date'][i]
new_data['Close Price'][i] = data['Close Price'][i]
new_data['Date'] = pd.to_datetime(new_data.Date,format='%Y-%m-%d')
new_data.index = new_data['Date']
#preparing data
new_data.rename(columns={'Close Price': 'y', 'Date': 'ds'}, inplace=True)
#train and validation
train = new_data[:395]
valid = new_data[395:]
#fit the model
model = Prophet()
model.fit(train)
#predictions
close_prices = model.make_future_dataframe(periods=len(valid))
forecast = model.predict(close_prices)
#rmse
forecast_valid = forecast['yhat'][395:]
rms=np.sqrt(np.mean(np.power((np.array(valid['y'])-np.array(forecast_valid)),2)))
rms
#plot
valid['Predictions'] = 0
valid['Predictions'] = forecast_valid.values
plt.plot(train['y'])
plt.plot(valid[['y', 'Predictions']])
#plot
valid['Predictions'] = 0
valid['Predictions'] = forecast_valid.values
plt.plot(train['y'])
plt.plot(valid[['y', 'Predictions']])
#importing required libraries
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
#creating dataframe
data = df.sort_index(ascending=True, axis=0)
new_data = pd.DataFrame(index=range(0,len(df)),columns=['Date', 'Close Price'])
for i in range(0,len(data)):
new_data['Date'][i] = data['Date'][i]
new_data['Close Price'][i] = data['Close Price'][i]
#setting index
new_data.index = new_data.Date
new_data.drop('Date', axis=1, inplace=True)
#creating train and test sets
dataset = new_data.values
train = dataset[0:395,:]
valid = dataset[395:,:]
#converting dataset into x_train and y_train
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(dataset)
x_train, y_train = [], []
for i in range(60,len(train)):
x_train.append(scaled_data[i-60:i,0])
y_train.append(scaled_data[i,0])
x_train, y_train = np.array(x_train), np.array(y_train)
x_train = np.reshape(x_train, (x_train.shape[0],x_train.shape[1],1))
# create and fit the LSTM network
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1],1)))
model.add(LSTM(units=50))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(x_train, y_train, epochs=1, batch_size=1, verbose=2)
#predicting 246 values, using past 60 from the train data
inputs = new_data[len(new_data) - len(valid) - 60:].values
inputs = inputs.reshape(-1,1)
inputs = scaler.transform(inputs)
X_test = []
for i in range(60,inputs.shape[0]):
X_test.append(inputs[i-60:i,0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))
closing_price = model.predict(X_test)
closing_price = scaler.inverse_transform(closing_price)
rms=np.sqrt(np.mean(np.power((valid-closing_price),2)))
rms
#for plotting
train = new_data[:395]
valid = new_data[395:]
valid['Predictions'] = closing_price
plt.plot(train['Close Price'])
plt.plot(valid[['Close Price','Predictions']])
| 392c71880f6230cca23613fd76f357af30ed81d8 | [
"Markdown",
"Python"
] | 5 | Python | asht123dd/stock | 0766bc2f286e4362e590e41e4efef0fc97d35e3e | db1b3859b072e6a12ed59016bc442c657cb0e361 |
refs/heads/master | <file_sep># ssh agent forwarding
#eval `ssh-agent` >/dev/null 2>&1
#find ~/.ssh -type f -name '*_rsa' | xargs ssh-add > /dev/null 2>&1
#find ~/.ssh -type f -name '*.pem' | xargs ssh-add > /dev/null 2>&1
# Oh My ZSH!
source ~/.oh-my-zshrc
source ~/.zprompt
setprompt
#--------------------------------------------------------------------------------------
PATH=/usr/local/bin:$PATH:/usr/local/scripts:~/scripts
# include any bashrc stuff we don't want to version control
[[ -e ~/.initSwaaatz ]] && source ~/.initSwaaatz
[[ -e ~/.dotfiles/lib/zsh-autoenv/autoenv.zsh ]] && source ~/.dotfiles/lib/zsh-autoenv/autoenv.zsh
for script in `ls ~/.dotfiles/initscripts`; do source ~/.dotfiles/initscripts/$script; done
#--------------------------------------------------------------------------------------
# OS X
if [[ `uname` == "Darwin" ]]; then
alias ls='ls -G '
alias grep='grep --color=always'
alias showhidden="defaults write com.apple.Finder AppleShowAllFiles YES && killall Finder"
alias hidehidden="defaults write com.apple.Finder AppleShowAllFiles NO && killall Finder"
# homebrew
which brew >/dev/null 2>&1 || ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
which wget >/dev/null 2>&1 || brew install wget
# Various Plugins
[[ ! -e /usr/local/share/zsh/site-functions/_aws ]] && (brew install awscli >/dev/null 2>&1 || brew link --overwrite awscli)
. /usr/local/share/zsh/site-functions/_aws 2>/dev/null
else
[[ -d /home/linuxbrew ]] && eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)
fi
# Ctrl-S is a pain in the ass
stty -ixon
# CONVENIENCE
alias ltr='ls -ltr'
function grepv () { grep "$@" | grep -v --color grep }
function psgrep () { ps aux | grep "$@" | grep -v --color grep }
function fromnow (){ date -v+$1 "+%Y-%m-%d" }
function suniq(){ sort | uniq <&3 }
alias vedit='vim ~/.vimrc'
# output formatting
BOLD="\e[1m"
ITALIC="\e[3m"
PLAIN="\e[0m"
GREEN="\e[32m"
RED_BOLD="\e[01;31m"
function shdo () {
FULLCMD=($*)
CMD="$1" ARGS=${FULLCMD[@]:1}
echo -en "\e[01m* $CMD $ARGS\e[0m"
NUMTABS=$((`tput cols`/8 - 2))
echo -ne "\r"
for X in {1..$NUMTABS}
do
echo -ne "\t"
done
echo -e " \e[0;1m[ \e[32m`date +%T` \e[0;1m]\e[0m"
eval $CMD $ARGS
RC=$?
if [ $RC -eq 0 ]
then
echo -e "[ ${GREEN}OK${PLAIN} ]"
else
echo -e "[ ${RED_BOLD}FAIL${PLAIN} ] ($RC)"
fi
}
test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh"
export GOPATH=$HOME/work
autoload -U compinit && compinit -u
<file_sep>alias ansibleedit="vim $0"
alias ansiblerefresh="source $0"
function whatsmyip () { ansible -i /dev/null localhost -mipify_facts 2>/dev/null | grep public_ip | awk '{print $2}' | sed 's/"//g' }
#[[ ! -e ~/.ansible.hosts ]] && touch ~/.ansible.hosts
#export ANSIBLE_INVENTORY=~/.ansible.hosts
#alias ahost='cat ~/.ansible.hosts'
#alias ahostedit='vim ~/.ansible.hosts'
#function ahostselect (){
# if [[ -z $1 ]]; then
# ls -l ~/.ansible.hosts
# else
# ln -sf $HOME/.ansible.hosts.$1 $HOME/.ansible.hosts
# fi
#}
# For Reference:
# MAC Ansible Installed: /usr/local/Cellar/ansible/1.9.4/libexec/lib/python2.7/site-packages/ansible
<file_sep>#!/bin/bash
control_c()
{
exit
}
trap control_c SIGINT
destroy_vagrant(){
echo -e "\e[1;31mDestroying $1\e[m. (hit Ctrl+C to cancel)"
sleep 3
vagrant destroy -f
}
TEMP=`getopt -o m:p:r:d --long match:,playbook:,restore:,destroy,no-provision -n "$0" -- "$@"`
eval set -- "$TEMP"
usage () {
ISERROR=$1
echo -e "\[31;1mERROR:\e[;0m SoMeErRoRmEsSaGe!"
echo -e "\t\e[1;1musage: `basename $0`\e[0m [ OPTION ]"
exit $ISERROR
}
MATCH=""
PLAYBOOK=""
RESTORE=""
DESTROY=0
NO_PROVISION=0
while true ; do
case "$1" in
-m|--match) MATCH=$2 ; shift 2 ;;
-p|--playbook) PLAYBOOK=$2 ; shift 2 ;;
-r|--restore) RESTORE=$2 ; shift 2 ;;
-d|--destroy) DESTROY=1 ; shift ;;
--no-provision) NO_PROVION=1 ; shift ;;
--) shift ; break ;;
esac
done
LIMIT=""
# RESET / RESTORE
REPO_DIR_LOCAL=$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )
for VAGRANT_DIR in `find $REPO_DIR_LOCAL/vagrants -type f -name Vagrantfile | sort -r | xargs dirname`; do
# check if VM is a match
if [[ "$VAGRANT_DIR" =~ "$MATCH" ]]; then
echo -e "\e[1;4mWorking on vagrant\e[m: \e[92m`basename $VAGRANT_DIR`\e[m"
cd $VAGRANT_DIR
vagrant halt
# what is the VM name?
VM_NAME=$(grep --color=no -r vb.name Vagrantfile | sed 's/.*"\([^"]*\)".*/\1/')
# if snapshot to restore was specified
if [[ ! -z $RESTORE ]]; then
echo -e "\e[1;1mRestoring snapshot\e[m: \e[92m$RESTORE\e[m"
VBoxManage snapshot $VM_NAME restore $RESTORE
# elif
# ANY OTHER REASONS TO OVERRIDE DESTROY=1?
else
# are we forcing destruction of the VM?
if [[ $DESTROY -eq 1 ]]; then
destroy_vagrant $VM_NAME
else
# if we have any snapshots, restore the latest
LATEST_SNAPSHOT=$(VBoxManage snapshot $VM_NAME list 2>/dev/null | grep --color=no Name | tail -n1 | awk '{print $2}')
if [[ ! -z $LATEST_SNAPSHOT ]]; then
echo -e "\e[1;1mRestoring latest snapshot\e[m: \e[92m$LATEST_SNAPSHOT\e[m"
VBoxManage snapshot $VM_NAME restorecurrent
# elif
# ANY OTHER REASONS NOT TO DESTROY?
else
# else, just destroy it
destroy_vagrant $VM_NAME
fi
fi
fi
# now bring it on back
vagrant up
echo
fi
done
# PROVISION
if [[ $NO_PROVION -ne 1 ]]; then
if [[ ! -z $MATCH ]]; then
LIMIT="--limit localhost,$MATCH"
fi
ansible-playbook $REPO_DIR_LOCAL/playbooks/vagrant/provision.yml $LIMIT
fi
if [[ ! -z $PLAYBOOK && -e $REPO_DIR_LOCAL/playbooks/vagrant/${PLAYBOOK}.yml ]]; then
ansible-playbook $REPO_DIR_LOCAL/playbooks/vagrant/${PLAYBOOK}.yml $LIMIT
fi
<file_sep>#!/bin/bash -x
pushd `dirname $0` >/dev/null
CURRDIR=`pwd`
ln -sf $CURRDIR/swartz_files/vimrc ~/.vimrc
ln -sf $CURRDIR/swartz_files/gitconfig ~/.gitconfig
ln -sf $CURRDIR/swartz_files/zshrc ~/.zshrc
ln -sf $CURRDIR/swartz_files/zprompt ~/.zprompt
ln -sf $CURRDIR/swartz_files/oh-my-zshrc ~/.oh-my-zshrc
mkdir -p ~/.dotfiles 2>/dev/null
ln -sf $CURRDIR/swartz_files/initscripts ~/.dotfiles/initscripts
ln -sf $CURRDIR/scripts ~/scripts
[[ ! -e ~/.vim/bundle/Vundle.vim ]] && git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
zsh_dir=/usr/local/share/zsh/site-functions
#for completion in `ls $CURRDIR/swartz_files/zsh/site-functions`; do
# [[ ! -L $zsh_dir/$completion ]] &&
# ln -sf $CURRDIR/swartz_files/zsh/site-functions/$completion $zsh_dir/$completion
#done
<file_sep>alias vagrantedit="vim $0"
alias vagrantrefresh="source $0"
function vid (){
IDS="`vagrant global-status | grep virtualbox | sed 's/\(.*\)virtualbox.*/\1/'`"
if [[ ! -z "$1" || `echo $IDS | wc -l` -gt 1 ]]; then
ID=`echo $IDS | /usr/bin/grep $1 2>/dev/null`
else
ID=`echo $IDS | head -n1`
fi
echo $ID | awk '{print $1}'
}
function vu (){ vagrant up $(vid $1) }
function vh (){ vagrant halt $(vid $1) }
function vd (){ vagrant destroy $(vid $1) -f }
function vp (){ vagrant provision $(vid $1) }
function vssh (){ vagrant ssh $(vid $1) 2> >(grep -v "Connection.*closed") }
function vsshcmd (){ vagrant ssh $(vid $1) -c $2 2> >(grep -v "Connection.*closed") }
alias vg="vagrant global-status | sed '/^[^\w]$/q'"
alias vup="vu"
alias vhalt="vh"
alias vdestroy="vd"
alias vprovision="vp"
alias vcmd="vc"
alias vupall='for VAG in $(vg|grep running| awk "{print $1}"|tr "\n" " "); do vagrant up $VAG; done'
alias vhaltall='for VAG in $(vg|grep running|awk "{print $1}"|tr "\n" " "); do vagrant halt $VAG; done'
alias vpall='for VAG in $(vg|grep running|awk "{print $1}"| tr "\n" " "); do vagrant provision $VAG; done'
alias vdall='for VAG in $(vg|grep running|awk "{print $1}"| tr "\n" " "); do vagrant destroy $VAG; done'
<file_sep># TERRAFORM
alias terraformedit="vim $0"
alias tfedit=terraformedit
alias terraformrefresh="source $0"
alias tfrefresh=terraformrefresh
alias ta="terraform remote pull && terraform apply && terraform remote push"
alias td="terraform remote pull && terraform destroy -force && terraform remote push"
alias tp="terraform plan"
alias to="terraform output"
alias tg="terraform get -update"
alias tfrm='rm **/.terraform/terraform.tfstate'
alias tfrmrf='rm -rf **/.terraform'
function tf-getresources(){
grep -r '^resource' . | awk '{print $2 $3}' | sed -e 's/"/ /g' -e 's/^ //g' -e 's/ / /g'| sort | uniq
}
function tf-getvars(){
tffiles=$(ls **.tf | tr '\n' ' ')
[[ ! -z $1 ]] && tffiles=$1
grep -r '\bvar\.[a-z_]*' $(echo $tffiles)| sed -e 's/[^}]*\(\${var\.[^}]*}\)/\1 /g' -e 's/}.*{/} ${/g' -e 's/}[^{]*$/}/g' -e 's/ \${count.index}//g' -e 's/^[^\$]*.*var.\([a-z_]*\).*/\1/g' | sort | uniq
}
<file_sep>#!/usr/bin/python
import argparse
from os import path,listdir
from mutagen.id3 import ID3
from mutagen.flac import FLAC
from mutagen.mp3 import MP3
def validate_flac( flac_file ):
#try:
flac_data = FLAC( flac_file )
f = open("/tmp/deployMusic.log", "a")
albumartist = str(flac_data["albumartist"])[3:-2]
title = str(flac_data["title"])[3:-2]
tracknumber = str(flac_data["tracknumber"])[3:-2]
f.write( albumartist + " -- " + tracknumber + " - " + title + "\n")
f.close()
#except:
# return False
return True
def validate_mp3( mp3_file ):
try:
mp3_data = MP3( mp3_file )
except:
return False
return True
def validate_audio( audio_file, extension ):
if extension == "mp3":
return validate_mp3( audio_file )
elif extension == "flac":
return validate_flac( audio_file )
else:
return False
def validate_all( all_files, extension ):
for audio_file in all_files:
if not validate_audio( audio_file, extension ):
return False
return True
def get_files( dir_path, extension ):
dir_files = { 'audio': [], 'other': [] }
for item in listdir( dir_path ):
current_file = dir_path + '/' + item
# is file - analyze
if path.isfile( current_file ):
if current_file.rsplit( '.', 1 )[1] == extension:
dir_files['audio'].append( current_file )
else:
dir_files['other'].append( current_file )
# is directory - recursive case
else:
subdir_files = get_files( current_file, extension )
dir_files['audio'].extend( subdir_files['audio'] )
dir_files['other'].extend( subdir_files['other'] )
return dir_files
# process command line argument
parser = argparse.ArgumentParser( description='Get the directory' )
parser.add_argument( 'dir_in' )
arguments = parser.parse_args()
dir_in = arguments.dir_in
# are we looking for flac or mp3?
if "TOFLAC" in dir_in:
extension = "flac"
validate_fn = "validate_flac"
elif "TOMP3" in dir_in:
extension = "mp3"
validate_fn = "validate_mp3"
# get files in directory
dir_in_files = get_files( dir_in, extension )
f = open( "/tmp/deployMusic.log", 'a' )
for in_file in dir_in_files[ 'audio' ]:
f.write( in_file )
if validate_audio( in_file, extension ):
f.write( " - VALID!\n" )
else:
f.write( " - INVALID!\n" )
answer = "YES" if validate_all( dir_in_files['audio'], extension ) else "NO"
f.write( "\n\nAll files valid? " + answer )
f.write( "\n" )
f.close
<file_sep># RUBY
#alias rubyedit="vim $0"
#alias rubyrefresh="source $0"
#export PATH="$HOME/.rbenv/bin:$PATH"
#eval "$(rbenv init -)"
#alias rbinstall="RUBY_CONFIGURE_OPTS=--with-readline-dir=`brew --prefix readline` rbenv install"
#
#alias rubocopper="rubocop -SDa"
<file_sep>alias zshedit="vim $0"
alias zshrefresh="source $0"
# keyboard behavior# {{{
bindkey ';5D' backward-word
bindkey ';5C' forward-word
bindkey "^[[3~" delete-char
bindkey "^[3;5~" delete-char
# create a zkbd compatible hash;
# to add other keys to this hash, see: man 5 terminfo
typeset -A key
key[Home]=${terminfo[khome]}
key[End]=${terminfo[kend]}
key[Insert]=${terminfo[kich1]}
key[Delete]=${terminfo[kdch1]}
key[Up]=${terminfo[kcuu1]}
key[Down]=${terminfo[kcud1]}
key[Left]=${terminfo[kcub1]}
key[Right]=${terminfo[kcuf1]}
key[PageUp]=${terminfo[kpp]}
key[PageDown]=${terminfo[knp]}
# setup key accordingly
[[ -n "${key[Home]}" ]] && bindkey "${key[Home]}" beginning-of-line
[[ -n "${key[End]}" ]] && bindkey "${key[End]}" end-of-line
[[ -n "${key[Insert]}" ]] && bindkey "${key[Insert]}" overwrite-mode
[[ -n "${key[Delete]}" ]] && bindkey "${key[Delete]}" delete-char
[[ -n "${key[Up]}" ]] && bindkey "${key[Up]}" up-line-or-history
[[ -n "${key[Down]}" ]] && bindkey "${key[Down]}" down-line-or-history
[[ -n "${key[Left]}" ]] && bindkey "${key[Left]}" backward-char
[[ -n "${key[Right]}" ]] && bindkey "${key[Right]}" forward-char
# Finally, make sure the terminal is in application mode, when zle is
# active. Only then are the values from $terminfo valid.
if (( ${+terminfo[smkx]} )) && (( ${+terminfo[rmkx]} )); then
function zle-line-init () {
printf '%s' "${terminfo[smkx]}"
}
function zle-line-finish () {
printf '%s' "${terminfo[rmkx]}"
}
zle -N zle-line-init
zle -N zle-line-finish
fi
# }}}
# ZSH
setopt correct
HISTFILE=$HOME/.zhistory # enable history saving on shell exit
setopt APPEND_HISTORY # append rather than overwrite history file.
HISTSIZE=99999999 # lines of history to maintain memory
SAVEHIST=99999999 # lines of history to maintain in history file.
setopt HIST_EXPIRE_DUPS_FIRST # allow dups, but expire old ones when I hit HISTSIZE
setopt EXTENDED_HISTORY # save timestamp and runtime information
setopt interactivecomments # allow comments on command line
setopt noequals # don't evaluate = as command substitution
alias cp='nocorrect cp '
alias mv='nocorrect mv '
alias mkdir='nocorrect mkdir '
alias ssh='nocorrect ssh '
alias vi='vim'
alias l='ls -1'
alias ll='ls -l'
alias lla='ls -lhA'
alias ls='ls -G'
alias watch='watch --color'
alias zedit="vim ~/.zshrc"
alias zrefresh="source ~/.zshrc"
alias ohmyzedit="vim ~/.oh-my-zshrc"
<file_sep>source ~/.initBanner.sh 2>/dev/null
<file_sep>alias dockeredit="vim $0"
alias dedit=dockeredit
alias dockerrefresh="source $0"
alias drefresh=dockerrefresh
function dlogin() {
docker login -u dswartz
}
[[ -z "$DOCKER_PORT" ]] && DOCKER_PORT=2222
function docker-run {
OS=$1
NAME=$2
docker run -h $OS --name $NAME -p$DOCKER_PORT:22 -it -d -v $HOME/git/ansible:/tmp/ansible dswartz/2fifty6:$OS
DOCKER_PORT=$((DOCKER_PORT+1))
}
function docker-centos {
OS="centos"; [[ -z $1 ]] && NAME=$OS || NAME=$1
docker-run $OS $NAME
}
function docker-fedora {
OS="fedora"; [[ -z $1 ]] && NAME=$OS || NAME=$1
docker-run $OS $NAME
}
function docker-debian {
OS="debian"; [[ -z $1 ]] && NAME=$OS || NAME=$1
docker-run $OS $NAME
}
function docker-ubuntu {
OS="ubuntu"; [[ -z $1 ]] && NAME=$OS || NAME=$1
docker-run $OS $NAME
}
alias dcentos=docker-centos
alias dfedora=docker-fedora
alias ddebian=docker-debian
alias dubuntu=docker-ubuntu
function dnames { docker ps -a --format '{{.Names}}' }
function dports { docker ps -a --format '{{.Ports}}' }
function dids { docker ps -a --format '{{.ID}}' }
function dall {
for did in $(dids); do
docker inspect $did
done
}
function dkillall {
for did in $(dids); do
(docker kill $did; docker rm $did >/dev/null) 2>/dev/null
done
}
<file_sep>#!/bin/bash
# This can be used to generate ansible yml files ad-hoc or in bulk
# vim plugin:
# https://github.com/chase/vim-ansible-yaml
create_file () {
NEWFILE=$1
cat > $NEWFILE<<END
---
# file: $NEWFILE
# TODO
# vim:ft=ansible
END
}
for NEWFILE in "$@"; do create_file $NEWFILE; done
<file_sep># AWS
alias awsedit="vim $0"
alias awsrefresh="source $0"
[[ ! -e ~/.dotfiles/aws ]] && mkdir -p ~/.dotfiles/aws
#[[ ! -x /usr/local/share/zsh/site-functions/_envselect ]] &&
# sudo cat > /usr/local/share/zsh/site-functions/_envselect <<EOF
##compdef envselect
#compadd \$(command ls -1 ~/.dotfiles/aws 2>/dev/null --color=none |
# sed -e 's/ /\\\\ /g' -e 's/.*aws://g')
#EOF
function envselect(){
if [[ -z $1 ]]; then
ls -l ~/.autoenv.zsh
else
AUTOENV_PATH=~/.dotfiles/aws/$1/.autoenv.zsh
if [[ -e $AUTOENV_PATH ]]; then
ln -sf $AUTOENV_PATH ~/.autoenv.zsh
source ~/.autoenv.zsh
else
echo "No match for $AUTOENV_PATH"
fi
fi
}
alias enva='env | grep --color=no AWS'
function awsdefault (){
export AWS_DEFAULT_PROFILE=$1
}
# ALB{{{
function target-group-health (){
aws elbv2 describe-target-health --target-group-arn $1 | jq -r '.TargetHealthDescriptions[].TargetHealth.State'
}
# }}}
# ASG{{{
function rmasg () {
ASG_NAME=$1
aws autoscaling delete-auto-scaling-group --auto-scaling-group-name $ASG_NAME --force-delete
}
function lsasg () {
aws autoscaling describe-auto-scaling-groups|jq -r '.AutoScalingGroups[].AutoScalingGroupName'
}
function rmlc () {
LC_NAME=$1
aws autoscaling delete-launch-configuration --launch-configuration-name $LC_NAME
}
function lslc () {
aws autoscaling describe-launch-configurations | jq -r '.LaunchConfigurations[].LaunchConfigurationName'
}
# }}}
# EC2{{{
export RUNNING_INSTANCE_FILTER="Name=instance-state-name,Values=running"
alias describe-ami='aws ec2 describe-images --image-ids '
alias describe-ec2='aws ec2 describe-instances --instance-ids '
alias ec2ids="aws ec2 describe-instances --instance-ids"
function ami-jqtags(){
jq -r '.Images[].Tags[] | .Key + "\t\t" + .Value'
}
function ec2-jqid(){
jq -r '.Reservations[].Instances[].InstanceId'
}
function ec2-jqname(){
jq -r '.Reservations[].Instances[].Tags[] | select(.Key=="Name") | .Value'
}
function ec2-jqprivateip(){
jq -r ".Reservations[].Instances[].NetworkInterfaces[].PrivateIpAddresses[0].PrivateIpAddress"
}
function ec2-jqpublicip(){
jq -r ".Reservations[].Instances[].PublicIpAddress"
}
function ec2-jqvolumes(){
jq -r '.Reservations[].Instances[].BlockDeviceMappings[] | .DeviceName + "\t" + .Ebs.VolumeId'
}
function ec2-jqvolumeids(){
jq -r '.Reservations[].Instances[].BlockDeviceMappings[].Ebs.VolumeId'
}
function ec2-byname (){
aws ec2 describe-instances --filters "Name=tag:Name,Values=$1" $RUNNING_INSTANCE_FILTER
}
function ec2-namebyid (){
aws ec2 describe-instances --instance-ids $1 |
ec2-jqname
}
function ec2-idbyname (){
ec2-byname $1 |
ec2-jqid
}
function ec2-ipbyname (){
aws ec2 describe-instances --filters "Name=tag:Name,Values=$1" $RUNNING_INSTANCE_FILTER |
ec2-jqprivateip
}
function ec2-byvpc (){
aws ec2 describe-instances --filters "Name=vpc-id,Values=$1" $RUNNING_INSTANCE_FILTER
}
function ec2-ipbyvpc (){
aws ec2 describe-instances --filters "Name=vpc-id,Values=$1" $RUNNING_INSTANCE_FILTER |
ec2-jqprivateip
}
function ec2-ipbynamevpc (){
aws ec2 describe-instances --filters "Name=tag:Name,Values=$1" "Name=vpc-id,Values=$2" $RUNNING_INSTANCE_FILTER |
ec2-jqprivateip
}
function ec2-publicipbyname (){
aws ec2 describe-instances --filters "Name=tag:Name,Values=$1" $RUNNING_INSTANCE_FILTER |
ec2-jqpublicip
}
function ec2-publicipbynamevpc (){
aws ec2 describe-instances --filters "Name=tag:Name,Values=$1" "Name=vpc-id,Values=$2" $RUNNING_INSTANCE_FILTER |
ec2-jqpublicip
}
function ec2-namebyip (){
aws ec2 describe-instances --filters "Name=private-ip-address,Values=$1" $RUNNING_INSTANCE_FILTER | jq -r '.Reservations[].Instances[].Tags[] | select(.Key=="Name") | .Value'
}
function ec2-snapshotbyid (){
aws ec2 describe-snapshots --snapshot-ids $*
}
# }}}
# ELB{{{
function elb-jqname(){
jq -r '.LoadBalancerDescriptions[].LoadBalancerName'
}
function elb-jqstate(){
jq -r '.InstanceStates[].State'
}
function elb-jqhealth(){
jq -r '.LoadBalancerDescriptions[].HealthCheck.Target'
}
function elb-getstatebyname(){
ELB_NAME=$1
aws elb describe-instance-health --load-balancer-name $ELB_NAME | elb-jqstate
}
function elb-gethealthbyname(){
ELB_NAME=$1
aws elb describe-load-balancers --load-balancer-name $ELB_NAME | elb-jqhealth
}
function lselb(){
aws elb describe-load-balancers | elb-jqname
}
function rmelb(){
ELB_NAME=$1
aws elb delete-load-balancer --load-balancer-name $ELB_NAME
}
# }}}
# Cloudwatch{{{
function cloudwatch-jqmetric(){
jq -r '.Metrics[] | .Dimensions[].Value + "-" + .MetricName' | sort
}
# }}}
# IAM{{{
function iam-instance-profile (){
aws iam get-instance-profile --instance-profile-name $1
}
function iam-jqprofilerole (){
jq -r '.InstanceProfile.Roles[].RoleName'
}
# }}}
# RDS
function rds-instances (){
aws rds describe-db-instances $*
}
function rds-jqname (){
jq -r '.DBInstances[].DBInstanceIdentifier'
}
function rds-jqarn (){
jq -r '.DBInstances[].DBInstanceArn'
}
# keypairs{{{
function mkkeypair (){
KEY_NAME=$1
[[ ! -z $2 ]] && REGION=$2 || REGION=us-east-1
aws ec2 create-key-pair --key-name $KEY_NAME --region $REGION |
ruby -e "require 'json'; puts JSON.parse(STDIN.read)['KeyMaterial']" > ~/.ssh/$KEY_NAME.pem &&
chmod 600 ~/.ssh/$KEY_NAME.pem
}
function rmkeypair (){
KEY_NAME=$1
[[ ! -z $2 ]] && REGION=$2 || REGION=us-east-1
aws ec2 delete-key-pair --key-name $KEY_NAME --region $REGION &&
rm ~/.ssh/$KEY_NAME.pem
}
# }}}
# VPC{{{
function vpc-byname (){
aws ec2 describe-vpcs --filters Name=tag:Name,Values=$1
}
function vpc-jqid (){
jq -r '.Vpcs[].VpcId'
}
#}}}
<file_sep>#!/bin/bash
# Mem
TOTAL=`free | grep Mem | awk '{print $2}'`
USED=`free | grep Mem | awk '{print $3}'`
FREE=`free | grep Mem | awk '{print $4}'`
# buffers/cache
UNAVAIL=`free | grep '\-/+' | awk '{print $3}'`
AVAIL=`free | grep '\-/+' | awk '{print $4}'`
# Swap
SWAP=`free | grep Swap | awk '{print $3}'`
CACHED=$(( $AVAIL - $FREE ))
# Do it!
printf "|| Available: %2d%% || Cached: %2d%% ||\n" $((100*AVAIL/TOTAL)) $((100*CACHED/TOTAL))
printf "|| Unavailable: %2d%% || Used: %2d%% ||\n" $((100*UNAVAIL/TOTAL)) $((100*USED/TOTAL))
if [[ $SWAP -ne 0 ]]; then
printf "|| Swapped: %2d%% ||\n" $((100*SWAP/TOTAL))
fi
<file_sep>#!/bin/bash
ANSIBLE_HOST="$1"
ANSIBLE_SSH_USER="$2"
ANSIBLE_SSH_PASS=""
ANSIBLE_SUDO_PASS=""
usage () {
echo -e "\e[31;1mERROR:\e[;0m no hostname specified!"
echo -e "\t\e[1;1musage: `basename $0`\e[0m HOST [ sshuser ]"
exit 1
}
# get ssh host; must be passed in
[[ -z "$ANSIBLE_HOST" ]] && usage
# get ssh user
while [[ -z "$ANSIBLE_SSH_USER" ]]; do
echo -n "ssh username: "
read ANSIBLE_SSH_USER
done
if [[ "$ANSIBLE_SSH_USER" == "vagrant" ]]; then
ANSIBLE_SSH_PASS="<PASSWORD>"
ANSIBLE_SUDO_PASS="<PASSWORD>"
fi
# get ssh password
while [[ -z "$ANSIBLE_SSH_PASS" ]]; do
echo -n "ssh password: "
read -s ANSIBLE_SSH_PASS
echo
done
# get sudo password
while [[ -z "$ANSIBLE_SUDO_PASS" ]]; do
echo -n "sudo password: "
read -s ANSIBLE_SUDO_PASS
echo
done
# generate temporary inventory file
TEMP_INVENTORY="`mktemp /tmp/ansinvXXXXXXXX`"
# make sure temporary inventory file lifetime is the execution of this script
function cleanup {
rm -rf "$TEMP_INVENTORY"
}
trap cleanup EXIT
# generate temporary inventory file contents
cat > $TEMP_INVENTORY<<END
ansiblehost ansible_ssh_host=$ANSIBLE_HOST ansible_connection=ssh ansible_ssh_user=$ANSIBLE_SSH_USER ansible_ssh_pass=$ANSIBLE_SSH_PASS ansible_sudo_pass=$ANSIBLE_SUDO_PASS
[ansibles]
ansiblehost
END
# get directory of repo (current script)
LOCAL_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
REMOTE_DIR=$( echo $LOCAL_DIR | sed "s/\/home\/$(whoami)/\/home\/$ANSIBLE_SSH_USER/" )
ansible-playbook -i $TEMP_INVENTORY $REMOTE_DIR/playbooks/ansiblize.yml --extra-vars="local_dir=$LOCAL_DIR remote_dir=$REMOTE_DIR"
[[ $? -eq 0 ]] && echo "Successfully ansiblized $ANSIBLE_SSH_USER@$ANSIBLE_HOST" || echo "Failed to ansiblize $ANSIBLE_SSH_USER@$ANSIBLE_HOST"
<file_sep>#!/bin/bash
SECONDS=$1
echo "Sleeping for $SECONDS seconds..."
for (( i = 0; i < $SECONDS; i++ )); do
SECONDS_LEFT=$(( $SECONDS - $i ))
printf "\r \r"
echo -n "Time left: $SECONDS_LEFT seconds"
[[ $SECONDS_LEFT -gt 0 ]] && sleep 1
done
printf "\r \r"
echo "OK!"
<file_sep>alias kitchenedit="vim $0"
alias kitchenrefresh="source $0"
[[ ! -e ~/.oh-my-zsh/custom/plugins/kitchen ]] && git clone https://github.com/pelletiermaxime/test-kitchen-zsh-plugin.git ~/.oh-my-zsh/custom/plugins/kitchen
function rekitchen (){
kitchen destroy $* && kitchen converge $*
}
alias klist="kitchen list 2>/dev/null"
alias klogin="kitchen login 2>/dev/null"
alias kl=klist
alias kc="kitchen converge 2>/dev/null"
alias kk="kitchen converge 2>/dev/null"
alias kd="kitchen destroy 2>/dev/null"
export EDITOR=`which vim`
<file_sep># GIT
alias gti=git
alias gt=git
alias got=git
alias gitedit="vim $0"
alias gitrefresh="source $0"
alias gb="git branch"
alias gbr="git branch -r"
alias gi="git"
alias gita="git"
alias gitp="git"
alias st="git status"
alias stt="git status -s"
alias pull="git pull --all"
alias fetch="git fetch --all"
function gcommit(){
git commit -m"$1"
}
function gpushamend(){
git commit --amend --no-edit && git show && sleep 1 && git push --force
}
function modall(){
FILES="$(git status -s| sed 's/^R .*-> //'|sed 's/^[ ]*[A-Z]*[ ]*//'|sort|uniq|grep -v '??')"
if [[ ! -z "$@" ]]; then
FILES="$(echo $FILES | grep --color=no "$@")"
fi
if [[ ! -z "$FILES" ]]; then
FILES="$(echo $FILES | tr "\n" " ")"
vim $(echo $FILES)
fi
}
function mod (){
FILES="$(git status | grep --color=no modified | sed 's/\(.*\)modified:\([\ ]*\)\(.*\)/\3/')"
FILES=$(echo $FILES | sort | uniq)
if [[ ! -z "$@" ]]; then
FILES="$(echo $FILES | grep --color=no "$@")"
fi
if [[ ! -z "$FILES" ]]; then
FILES="$(echo $FILES | tr "\n" " ")"
vim $(echo $FILES)
fi
}
function pullall(){
currbranch=$(git branch | grep '*' --color=no | awk '{print $2}')
for branch in `git branch | sed 's/\*//'`; do echo "updating $branch..."; git co $branch; git pull; echo; done
git co $currbranch
}
alias pa=pullall
function giturl(){
git config -l | grep url | sed 's/.*:\/\///'
}
function gitprev (){
currbranch=$(git branch | grep '*' --color=no | awk '{print $2}')
git diff origin/$currbranch..$currbranch
}
alias gprev=gitprev
function gitmergeprev (){
currbranch=$(git branch | grep '*' --color=no | awk '{print $2}')
mbranch=`echo $currbranch | sed -e 's/test/dev/' -e 's/prod/test/'`
git diff $currbranch..$mbranch
}
alias gmprev=gitmergeprev
#[[ ! -e /usr/local/share/zsh/site-functions/_2fifty6 ]] &&
# cat > /usr/local/share/zsh/site-functions/_2fifty6 <<EOF
##compdef 2fifty6
#compadd \$(command echo 'checkout commit push rm')
#EOF
function 2fifty6(){
SUBCMD=$1
BRANCH=$2
CURRBRANCH=$(git branch --no-color|grep \* --color=no | awk '{print $2}')
# default branch is current
[[ -z $BRANCH ]] && BRANCH=$CURRBRANCH
case $SUBCMD in
"push")
# git push remote local:remote
git push 2fifty6 $BRANCH:$BRANCH
;;
"rm")
# if deleting current branch, check out develop first
if [[ $BRANCH == $CURRBRANCH ]]; then
git checkout develop
fi
[[ ! -z $(git branch | grep "\b${BRANCH}\b") ]] && git branch -D $BRANCH
[[ ! -z $(git branch -r | "grep 2fifty6/${BRANCH}") ]] && git push 2fifty6 :$BRANCH
;;
"co"|"checkout"|"branch")
git co -b $BRANCH --track rean/develop
;;
"commit")
git commit -m"$CURRBRANCH $2"
;;
*)
echo "wtf?"
;;
esac
}
#function stashrebase(){
# git stash
# git rebase -i HEAD~2
# git stash pop
#}
#alias str="stashrebase"
| 706a8c0af4d85aba5250da4d30510703d21cda6d | [
"Python",
"Shell"
] | 18 | Shell | 2fifty6/config | 7a56097f61de6ca1ef90b8ad40f08d0bed2eec35 | 111ae2f53edad8984bf3051dec78a445ed1e2def |
refs/heads/master | <repo_name>mboukhlouf/OSRS-Hiscores-Checker<file_sep>/OSRS Hiscores Checker/CheckingLib/Helper.cs
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace CheckingLib
{
public static class Helper
{
public static String EncodeFormUrlContent(IDictionary<String, String> Parameters)
{
String data = "";
KeyValuePair<String, String> Parameter;
using (IEnumerator<KeyValuePair<String, String>> e = Parameters.GetEnumerator())
{
while (e.MoveNext())
{
Parameter = e.Current;
data += $"{Parameter.Key}={Parameter.Value}&";
}
}
return data;
}
}
}
<file_sep>/OSRS Hiscores Checker/Runescape/OSRS/User.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Runescape.OSRS
{
public class User
{
public string Username { get; set; }
public Skill[] Skills { get; set; }
public User()
{
Username = "";
Skills = new Skill[24];
}
public User(string username)
{
Username = username;
Skills = new Skill[24];
}
public void ParseSkillsFromText(string text)
{
string[] tokens = text.Split("\n");
if(tokens.Length < 24)
{
throw new ParsingException($"Expecting atleast 24 tokens, but found {tokens.Length}.");
}
for(int i = 0; i < 24; i++)
{
Skills[i] = new Skill(tokens[i]);
}
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append(Username + ",");
for(int i = 0; i < Skills.Length; i++)
{
builder.Append($"{Skills[i].Level},{Skills[i].Xp}");
if (i != Skills.Length - 1)
builder.Append(",");
}
return builder.ToString();
}
}
}
<file_sep>/OSRS Hiscores Checker/CheckingLib/Variables.cs
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace CheckingLib
{
public class Variables : Dictionary<string, string>
{
public Variables()
{
}
public String Transform(String Input)
{
String output = Input;
Regex regex = new Regex("%([A-Za-z0-9]+)%");
MatchCollection matches = regex.Matches(Input);
foreach (Match match in matches)
{
if (ContainsKey(match.Groups[1].Value))
{
output = Regex.Replace(output, match.Groups[0].Value, this[match.Groups[1].Value]);
}
}
return output;
}
}
}
<file_sep>/OSRS Hiscores Checker/CheckingLib/Checker.cs
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net.Http.Headers;
namespace CheckingLib
{
public class Checker : IDisposable
{
private bool disposed = false;
private readonly HttpClientHandler ClientHandler;
private readonly HttpClient Client;
public readonly Variables Variables;
public IWebProxy Proxy
{
get
{
return ClientHandler.Proxy;
}
set
{
ClientHandler.UseProxy = value != null;
ClientHandler.Proxy = value;
}
}
public CookieContainer Cookies
{
get
{
return ClientHandler.CookieContainer;
}
set
{
ClientHandler.CookieContainer = value;
}
}
public Checker()
{
ClientHandler = new HttpClientHandler();
Client = new HttpClient(ClientHandler);
ClientHandler.UseDefaultCredentials = true;
ClientHandler.UseCookies = true;
ClientHandler.CookieContainer = new CookieContainer();
ClientHandler.AllowAutoRedirect = false;
Variables = new Variables();
}
public async Task<Response> ExecuteAsync(Step Step)
{
var Message = new HttpRequestMessage()
{
Method = new HttpMethod(Step.Method),
RequestUri = new Uri(Variables.Transform(Step.Url)),
Content = new StringContent(Variables.Transform(Step.PostData ?? ""))
};
foreach (KeyValuePair<String, String> header in Step.Headers)
{
Message.Headers.Add(header.Key, Variables.Transform(header.Value));
}
if (!String.IsNullOrEmpty(Step.ContentType))
Message.Content.Headers.ContentType = new MediaTypeHeaderValue(Step.ContentType);
using (HttpResponseMessage httpResponse = await Client.SendAsync(Message))
using (HttpContent content = httpResponse.Content)
{
Dictionary<string, string[]> headers = new Dictionary<string, string[]>();
// Adding response headers
foreach(var header in httpResponse.Headers)
{
headers.Add(header.Key, (string[])header.Value);
}
// Adding content headres
foreach(var header in content.Headers)
{
foreach(var value in header.Value)
{
headers.Add(header.Key, (string[])header.Value);
}
}
Response response = new Response()
{
Version = httpResponse.Version.ToString(),
StatusCode = (int)httpResponse.StatusCode,
ReasonPhrase = httpResponse.ReasonPhrase,
Body = await content.ReadAsStringAsync(),
Headers = headers
};
Message.Dispose();
return response;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
}
Client.Dispose();
ClientHandler.Dispose();
disposed = true;
}
~Checker()
{
Dispose(false);
}
}
}
<file_sep>/OSRS Hiscores Checker/Program.cs
using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using Runescape.OSRS;
using CheckingLib;
using System.Threading.Tasks;
namespace OSRS_Hiscores_Checker
{
class Program
{
private static Config config;
private static Queue<User> users;
private static Queue<WebProxy> proxies;
private static bool finished = false;
private static int threadsFinished = 0;
private static Speedometer speedometer;
private static int totalUsers;
private static int errorsCount = 0;
private static Step step = new Step()
{
Url = "https://secure.runescape.com/m=hiscore_oldschool/index_lite.ws?player=%USERNAME%",
Method = "GET",
Headers = new Dictionary<string, string>()
{
{ "User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" },
{ "Accept", "*/*" },
{ "Accept-Language", "en-US,en;q=0.9" }
}
};
static void Main(string[] args)
{
if (!File.Exists("config.json"))
{
Console.WriteLine("Coudln't find config.json file.");
Config config = new Config();
File.WriteAllText("config.json", config.ToJson());
Console.WriteLine("A config.json file was just created, please fill it and run the program again.");
Console.Read();
return;
}
String configJson = File.ReadAllText("config.json");
config = Config.ParseFromJson(configJson);
Console.WriteLine(config);
// Parsing users
users = new Queue<User>();
String[] combos = File.ReadAllLines(config.InputFile);
foreach (String combo in combos)
{
if (combo.Trim() != "")
{
try
{
users.Enqueue(new User(combo));
}
catch (Exception)
{
}
}
}
totalUsers = users.Count;
Console.WriteLine($"Found {users.Count} users.");
// Parsing proxies
if (config.ProxiesFile != "")
{
proxies = new Queue<WebProxy>();
String[] _proxies = File.ReadAllLines(config.ProxiesFile);
foreach (String proxy in _proxies)
{
if (proxy.Trim() != "")
{
try
{
proxies.Enqueue(ParseProxy(proxy));
}
catch (Exception)
{
}
}
}
}
if (proxies == null)
Console.WriteLine($"No proxy will be used.");
else
{
Console.WriteLine($"Found {proxies.Count} proxies.");
}
if (config.Threads > combos.Length)
{
config.Threads = combos.Length;
}
Task[] tasks = new Task[config.Threads];
Console.WriteLine($"Starting {config.Threads} threads.");
speedometer = new Speedometer();
speedometer.Start();
UpdateStatus();
for (int i = 0; i < config.Threads; i++)
{
tasks[i] = new Task(CheckAsync);
tasks[i].Start();
}
while (!finished)
{
Console.Read();
}
}
private static Object obj = new Object();
private static async void CheckAsync()
{
while (users.Count > 0)
{
Checker checker = new Checker();
User user;
WebProxy proxy = null;
lock (obj)
{
user = users.Dequeue();
if (proxies != null)
{
proxy = proxies.Dequeue();
proxies.Enqueue(proxy);
}
}
checker.Proxy = proxy;
try
{
checker.Variables["USERNAME"] = user.Username;
String text = (await checker.ExecuteAsync(step)).Body;
if(text.Contains("Page not found"))
{
errorsCount++;
lock(obj)
File.AppendAllText(config.ErrorsFile, user.Username + ", error: Page not found." + "\n");
}
else
{
user.ParseSkillsFromText(text);
lock (obj)
File.AppendAllText(config.OutputFile, user.ToString() + "\n");
}
}
catch (Exception e)
{
lock (obj)
{
errorsCount++;
File.AppendAllText(config.ErrorsFile, user.Username + ", error: " + e.Message + "\n");
}
users.Enqueue(user);
}
lock (obj)
speedometer.Progress++;
UpdateStatus();
}
lock (obj)
{
threadsFinished++;
if (threadsFinished == config.Threads)
{
finished = true;
Console.WriteLine("Done!");
}
}
}
private static void UpdateStatus()
{
Console.Title = $"Progress: {speedometer.Progress}/{totalUsers} users | Speed: {speedometer.GetProgressPerHour()} users/hour | Errors: {errorsCount}";
}
private static WebProxy ParseProxy(String str)
{
String[] parts = str.Trim().Split(":");
if (parts.Length != 2)
throw new Exception("Proxy not in format.");
String host = parts[0];
int port;
try
{
port = int.Parse(parts[1]);
}
catch (Exception)
{
throw new Exception("Problem in port.");
}
return new WebProxy(host, port);
}
}
}
<file_sep>/OSRS Hiscores Checker/Runescape/OSRS/Skill.cs
using System;
namespace Runescape.OSRS
{
public class Skill
{
public int Rank { get; set; }
public int Level { get; set; }
public int Xp { get; set; }
public Skill()
{
}
public Skill(int rank, int level, int xp)
{
Rank = rank;
Level = level;
Xp = xp;
}
public Skill(string text)
{
ParseFromString(text);
}
public void ParseFromString(string text)
{
String[] tokens = text.Split(",");
if(tokens.Length != 3)
{
throw new ParsingException($"Expecting 3 tokens in {text}, found {tokens.Length}.");
}
try
{
Rank = int.Parse(tokens[0]);
Level = int.Parse(tokens[1]);
Xp = int.Parse(tokens[2]);
}
catch(Exception e)
{
throw new ParsingException($"Exception at parsing values from \"{text}\".", e);
}
}
}
}
<file_sep>/OSRS Hiscores Checker/CheckingLib/Step.cs
using System;
using System.Collections.Generic;
namespace CheckingLib
{
public class Step
{
public String Url { get; set; }
public String Method { get; set; }
public String PostData { get; set; }
public Dictionary<String, String> Headers { get; set; }
public String ContentType { get; set; }
public Step()
{
}
}
}
| 0d62defb3f7c04debfff40eb6598f21bbb7586f8 | [
"C#"
] | 7 | C# | mboukhlouf/OSRS-Hiscores-Checker | 656fa145d90604542e2f7088021561145f55117e | 08cff3f8612476dd4e72f87bc9c051276ec2784d |
refs/heads/master | <repo_name>carlos99/file_uploader_project<file_sep>/config/routes.rb
Rails.application.routes.draw do
mount ImageUploader::UploadEndpoint => "/images/upload"
resources :posts
root to: "posts#index"
end
<file_sep>/config/initializers/shrine.rb
require "shrine/storage/s3"
require "shrine/storage/file_system"
s3_options = {
access_key_id: ENV['ACCESS_KEY_ID'],
secret_access_key: ENV['SECRET_ACCESS_KEY'],
region: ENV['BUCKET_REGION'],
bucket: ENV['BUCKET_NAME'],
endpoint: ENV["AWS_HOST"],
}
Shrine.storages = {
cache: Shrine::Storage::S3.new(prefix: "cache", upload_options: {acl: "public-read"}, **s3_options),
store: Shrine::Storage::S3.new(prefix: "store", upload_options: {acl: "public-read"}, **s3_options),
}
Shrine.plugin :activerecord
Shrine.plugin :direct_upload
Shrine.plugin :restore_cached_data
Shrine.plugin :cached_attachment_data # for forms
| faa13b4b194cfba963a7810a053a4d2898abaf2a | [
"Ruby"
] | 2 | Ruby | carlos99/file_uploader_project | fb910bc7ec820bd984634c679015468fbfe8c139 | 9a9cc7606fd19f86232573bf73f71350d3cfbcd3 |
refs/heads/master | <repo_name>SamLookingGlass/Express-CRUD<file_sep>/index.js
const express = require('express');
const hbs = require('hbs');
const wax = require('wax-on');
const axios = require('axios')
const baseURL = "https://petstore.swagger.io/v2"; // --> note 1
/* 1. SETUP EXPRESS */
let app = express();
// 1B. SETUP VIEW ENGINE
app.set('view engine', 'hbs');
// 1C. SETUP STATIC FOLDER
app.use(express.static('public'));
// 1D. SETUP WAX ON (FOR TEMPLATE INHERITANCE)
wax.on(hbs.handlebars);
wax.setLayoutPath('./views/layouts')
// 1E. ENABLE FORMS
app.use(express.urlencoded({extended:false}));
// 2. ROUTES
app.get('/', (req,res)=>{
res.render('base')
})
app.get('/pets', async (req,res)=>{
// --> note 2
let response = await axios.get(baseURL + '/pet/findByStatus', {
params:{
'status':'available'
},
})
res.render('all_pets',{
'all_pets': response.data // --> note 3
})
})
// 3. RUN SERVER
app.listen(3000, ()=>console.log("Server started")) | b1ad16c2baa6e85914234bf1f7228ec17d5a32b2 | [
"JavaScript"
] | 1 | JavaScript | SamLookingGlass/Express-CRUD | c9ac1b7d0466a852207a6be4f42ff83093676730 | dc4cac43f026c37d11bade74c16cc2185244d37d |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CaCuocBongDa.Models.Storage;
namespace CaCuocBongDa.Models
{
public class DataContextDB
{
public CaCuocDataContext cacuoc = new CaCuocDataContext();
public DataContextDB()
{
cacuoc.CommandTimeout = 2000;
}
public string InsertOrUpdateAcc(string xml, int type)
{
try
{
cacuoc.CaCuoc_InsertOrUpdate(xml, type);
return "";
}
catch (Exception ex)
{
return ex.Message;
}
}
public List<CaCuoc_GetTaiKhoanResult> GetTaiKhoan(int id, string user, int type)
{
return cacuoc.CaCuoc_GetTaiKhoan(id, user, type).ToList();
}
public string InsertOrUpdateMatch(string xml, int type)
{
try
{
cacuoc.CaCuoc_InsertOrUpdateMatch(xml, type);
return "";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace CaCuocBongDa.Models.Libraries
{
public class MemberShip
{
#region Create an MD5 Hash
/// <summary>
/// C# sample code to create an MD5 hash.
/// </summary>
/// <param name="input"></param>
/// <returns>MD5 hash</returns>
public string GetMD5Hash(string userName, string password)
{
string result = string.Empty;
string input = userName + password;
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("X2").ToUpper());
}
result = s.ToString();
return result;
}
#endregion
#region Khoi tao va giai ma~ MD5 co' key
/// <summary>
/// Ham ma~ hoa MD5
/// </summary>
/// <param name="clearText">ky tu. can ma~ hoa'</param>
/// <returns></returns>
public string EncryptMD5(string clearText)
{
string EncryptionKey = "paytv";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
/// <summary>
/// Ham` giai ma~ MD5
/// </summary>
/// <param name="cipherText">ky tu. MD5 can` giai ma~</param>
/// <returns></returns>
public string DecryptMD5(string cipherText)
{
string EncryptionKey = "paytv";
cipherText = cipherText.Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CaCuocBongDa.Models;
using CaCuocBongDa.Models.Libraries;
using Newtonsoft.Json.Linq;
namespace CaCuocBongDa.Controllers
{
public class AccountController : Controller
{
DataContextDB ccDB = new DataContextDB();
MemberShip mem = new MemberShip();
[Authorize]
public ActionResult Index()
{
return View();
}
public ActionResult Login(string ReturnUrl)
{
ViewBag.Title = "Đăng Nhập";
if (ReturnUrl == null)
ViewData["url"] = "/";
else
ViewData["url"] = ReturnUrl;
return View();
}
[HttpPost]
public ActionResult KiemTraDangNhap(User user)
{
var data = ccDB.GetTaiKhoan(0, user.TenTaiKhoan, 3);
var code = 0;
if (data.Count == 0)
{
code = 2;
}
else
{
if (data[0].Password.Trim() == mem.GetMD5Hash(user.TenTaiKhoan, user.MatKhau))
{
if (data[0].IsActive == 1)
{
FormsAuthentication.SetAuthCookie(user.TenTaiKhoan,user.Checked);
code = 1;
}
}
}
return Json(new
{
code
});
}
public ActionResult Register()
{
return View();
}
[Authorize]
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}
/// <summary>
/// Set Authentication cho MVC
/// </summary>
/// <param name="result">ket qua login tu` jquery. 1. Thanh cong</param>
/// <param name="user">Ten user</param>
/// <param name="Checked">Co su dung checked luu lai khong? True, false</param>
[AllowAnonymous]
public void SetLogin(int result, string user, bool Checked)
{
if (result == 1)
{
FormsAuthentication.SetAuthCookie(user.ToLower(), Checked);
}
}
[HttpPost]
public string DangKyTaiKhoan(User user)
{
try
{
var xml = "<T UserName='"+user.TenTaiKhoan+"' Password='"+mem.GetMD5Hash(user.TenTaiKhoan,user.MatKhau)+"' Email='"+user.Email+"' FullName='"+user.HoVaTen+"' />";
ccDB.InsertOrUpdateAcc(xml,1);
return "";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}
<file_sep>var myApp = angular.module('ca-cuoc', ['ngMessages','ngResource']);
myApp.controller('mainController', [
'$scope', '$filter', '$http', function($scope, $filter, $http,$resource) {
$scope.TenTaiKhoan = '';
$scope.MatKhau = '';
$scope.Login = function() {
var $btn = $('#btnDangky');
$btn.button('loading');
var Data = {
TenTaiKhoan: $scope.TenTaiKhoan,
MatKhau: $scope.MatKhau,
Checked: true
};
$http({
traditional: true,
method: 'POST',
url: '/Account/KiemTraDangNhap',
data: JSON.stringify(Data),
contentType: "application/json",
dataType: "json"
}).then(function successCallback(response) {
if (response.data.code == 1) {
$(location).attr('href', '/');
} else if(response.data.code==0){
toastr['error']('Chưa cống nạp tiền mà đòi vô ah!');
}else if (response.data.code == 2) {
toastr['error']('Rất tiếc tài khoản không tồn tại nhé !');
}
//$('#btnDangNhap').prop('disabled', false);
$btn.button('reset');
}).then(function errorCallback(response) {
toastr["error"](response.data);
$('#btnDangNhap').prop('disabled', false);
$btn.button('reset');
});
};
}
]);
myApp.controller('registerController', [
'$scope', '$filter', '$http', function($scope, $filter, $http) {
$scope.TenTaiKhoan = '';
$scope.HoVaTen = '';
$scope.Email = '';
$scope.MatKhau = '';
$scope.DangKy= function() {
//$('#btnDangky').prop('disabled', true);
var $btn = $('#btnDangky');
$btn.button('loading');
var format = /[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
if (format.test($scope.TenTaiKhoan)) {
toastr["error"]("Tên tài khoản không hợp lệ");
return;
}
var Data = {
Email: $scope.Email,
TenTaiKhoan: $scope.TenTaiKhoan,
HoVaTen: $scope.HoVaTen,
MatKhau: $scope.MatKhau
};
$http({
traditional: true,
method: 'POST',
url: '/Account/DangKyTaiKhoan',
data:JSON.stringify(Data),
contentType: "application/json",
dataType: "json"
}).then(function successCallback(response) {
if (response.data !== "")
toastr["error"](response.data);
else {
toastr["success"](
'Bạn đã đăng ký thành công, vui lòng yêu cầu kích hoạt trước khi sử dụng! Chào thân ái và quyết thắng');
setTimeout(function() {
$(location).attr('href', '/dang-nhap');
},
5000);
}
$btn.button('reset');
},
function errorCallback(response) {
toastr["error"](response.data);
$btn.button('reset');
});
}
}
]);<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace CaCuocBongDa
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
//Dang Nhap
routes.MapRoute(name: "Dang-Nhap", url: "dang-nhap", defaults: new { controller = "Account", action = "Login" });
routes.MapRoute(name: "Dang-Xuat", url: "dang-xuat", defaults: new { controller = "Account", action = "Logout" });
routes.MapRoute(name: "Dang-Ky", url: "dang-ky", defaults: new { controller = "Account", action = "Register" });
routes.MapRoute(name: "Lock-Screen", url: "Lock-Screen", defaults: new { controller = "Account", action = "Lock_Screen" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Index", id = UrlParameter.Optional }
);
}
}
} | fd17ec3a511274ba114a6dc760c29de0f2682df9 | [
"JavaScript",
"C#"
] | 5 | C# | trananh1992/CaCuocBongDa | 365924a4264e316aecd41f785fe302fc319620cd | 1cc10c79d9c408dcc72cceec3b2cf9fadb4b62fa |
refs/heads/master | <file_sep>console.log("cupcake loaded");
function Cupcake(id, imagename, x, y){
var textures = [];
for(var i=0; i<10; ++i)textures.push(PIXI.Texture.fromFrame(imagename + (i+1) + ".png"));
for(var i=0; i<10; ++i)textures.push(PIXI.Texture.fromFrame(imagename + (i+1) + "b.png"));
PIXI.extras.MovieClip.call(this, textures);
this.id = id-1;
this.anchor = new Point(0.5, 0.5);
this.position = new Point(x,y);
this.gotoAndStop(this.id);
this.interactive = true;
this.click = this.click.bind(this);
};
Cupcake.prototype = Object.create(PIXI.extras.MovieClip.prototype);
Cupcake.prototype.contructor = Cupcake;
Cupcake.prototype.blur = 0;
Cupcake.prototype.click = function(event){
console.log("Click cupcake",this.id,event.data.global);
this.id = this.id < 9 ? this.id+1 : 0;
console.log("cupcake new id",this.id);
this.gotoAndStop(this.id+this.blur);
}
<file_sep>function Event(type, data){
this.type = type; // String name
this.data = data; // wahtevs
}
Event.prototype.type = null;
Event.prototype.data = null;
Event.prototype.stopPropagation = false;
Event.prototype.target = null;
Event.ASSETS_LOADED = "ASSETS_LOADED";
Event.RESIZE = "RESIZE";
Event.CHANGE_BACKGROUND = "CHANGE_BACKGROUND";
<file_sep>console.log("Game loaded");
function Game(background){
PIXI.Container.call(this);
//this.anchor = new Point(0.5,0.5);
this.background = background;
var c1 = new Cupcake(1,"cupcakes", 200, 520);
this.addChild(c1);
c1 = new Cupcake(2,"cupcakes", 900, 520);
this.addChild(c1);
c1 = new CharacterMC("SunMoon", ["sun","moon"], 600, 100);
this.addChild(c1);
c1 = new Carousel(30,30);
this.addChild(c1);
c1.drawEllipse();
this.resize = this.resize.bind(this);
Events.Dispatcher.addEventListener(Event.RESIZE, this.resize);
// stage.interactive = true;
// this.onMouseDown = this.onMouseDown.bind(this);
// stage.on('mousedown', this.onMouseDown);
// this.onMouseMove = this.onMouseMove.bind(this);
// stage.on('mousemove', this.onMouseMove);
// this.onMouseOut = this.onMouseOut.bind(this);
// stage.on('mouseout', this.onMouseOut);
// this.onMouseUp = this.onMouseUp.bind(this);
// stage.on('mouseup', this.onMouseUp);
}
Game.prototype = Object.create(PIXI.Container.prototype);
Game.prototype.constructor = Game;
// Game.prototype.onMouseDown = function(event){
// console.log("onMouseDown",event.data.global);
// this.startPoint = new Point(event.data.global.x,event.data.global.y);
// }
// Game.prototype.onMouseMove = function(event){
// //console.log("onMouseMove",event.data.global);
// }
// Game.prototype.onMouseOut = function(event){
// console.log("onMouseOut",event.data.global);
// }
// Game.prototype.onMouseUp = function(event){
// console.log("onMouseUp",event.data.global);
// this.endPoint = new Point(event.data.global.x,event.data.global.y);
// this.distX = Math.abs(this.startPoint.x-this.endPoint.x);
// this.distY = Math.abs(this.startPoint.y-this.endPoint.y);
// console.log("Distance x,y",this.distX,this.distY)
// }
/**
* Pin 0,0 or this container to topleft of background
* @param {Object} event
*/
Game.prototype.resize = function(event){
var data = event.data;
var topleft = new Point(this.background.position.x,this.background.position.y);
topleft.x -= this.background.width/2;
topleft.y -= this.background.height/2;
this.position = topleft;
}
<file_sep>console.log("Character loaded");
function CharacterMC(name, images, x, y){
this.name = name;
var textures = [];
for(var i in images){
textures.push(new PIXI.Texture.fromFrame(images[i]+".png"));
}
PIXI.extras.MovieClip.call(this, textures);
this.gotoAndStop(0);
this.anchor = new Point(0.5, 0.5);
this.position = new Point(x,y);
this.interactive = true;
this.resize = this.resize.bind(this);
Events.Dispatcher.addEventListener(Event.RESIZE, this.resize);
this._fadeOut = this._fadeOut.bind(this);
this._fadeIn = this._fadeIn.bind(this);
}
CharacterMC.prototype = Object.create(PIXI.extras.MovieClip.prototype);
CharacterMC.prototype.constructor = CharacterMC;
CharacterMC.prototype.curImg = 0;
CharacterMC.prototype.swapSpeed = 0.01;
/**
* Called internally to swap the backgrounds.
*/
CharacterMC.prototype._fadeOut = function(){
this.alpha -= this.swapSpeed;
if(this.alpha <= 0){
this.alpha = 0;
globalTicker.remove(this._fadeOut);
this.gotoAndStop(this.curImg);
globalTicker.add(this._fadeIn);
}
}
CharacterMC.prototype._fadeIn = function(){
if(this.alpha + this.swapSpeed*4 < 1){
this.alpha += this.swapSpeed*4;
}
else{
this.alpha = 1;
globalTicker.remove(this._fadeIn);
}
}
CharacterMC.prototype.click = function(event){
console.log("click");
Events.Dispatcher.dispatchEvent(new Event(Event.CHANGE_BACKGROUND));
this.curImg = 1-this.curImg;
globalTicker.add(this._fadeOut);
}
CharacterMC.prototype.mousedown = function(event){
console.log("click s");
}
CharacterMC.prototype.resize = function(event){
// this.position.x = event.data.size.x/2;
}
<file_sep>console.log("GameManager loaded");
function GameManager(){
this.layers = [];
this.layers[GameManager.BACKGROUND] = new PIXI.Container();
this.layers[GameManager.GAME] = new PIXI.Container();
this.layers[GameManager.CONSOLE] = new PIXI.Container();
}
GameManager.BACKGROUND = "background";
GameManager.GAME = "game";
GameManager.CONSOLE = "console";
GameManager.prototype.layers = null;
GameManager.prototype.gameBackground = null;
GameManager.prototype.game = null;
GameManager.prototype.console = null;
/**
* Add all our layers to the main stage so we can see stuff!
*/
GameManager.prototype.onAssetsLoaded = function(){
// Add our layers to the main stage
stage.addChild(this.layers[GameManager.BACKGROUND]);
stage.addChild(this.layers[GameManager.GAME]);
stage.addChild(this.layers[GameManager.CONSOLE]);
// Create the things to go in the layers and add them.
this._createBackground();
this._createGame();
this._createConsole();
}
/**
* Create the actual Game: most of the code to handle paying the game goes in there!
*/
GameManager.prototype._createGame = function(){
this.game = new Game(this.gameBackground);
this.layers[GameManager.GAME].addChild(this.game);
}
/**
* Create the game background with some images.
* Later, we can listen out for any request by the GAME to change background.
*/
GameManager.prototype._createBackground = function(){
// Create a background manager with a couple of images to play with.
this.gameBackground = new GameBackground(["assets/bgDay.jpg","assets/bgNight.jpg"]);
// gameBackground should be able to do its own cross-fades etc because it *is*
// a PIXI.Container: we can manage it as a single item.
this.layers[GameManager.BACKGROUND].addChild(this.gameBackground);
/*
// test backgrounds
var that = this;
setTimeout(function(){
that.gameBackground.change(GameBackground.DAY, GameBackground.NIGHT);
},2000);
setTimeout(function(){
that.gameBackground.change(GameBackground.NIGHT, GameBackground.DAY);
},6000);
*/
}
/**
* Create the GameConsole and add to our list of things on the stage, so we can see it.
*/
GameManager.prototype._createConsole = function(){
this.console = new GameConsole();
this.layers[GameManager.CONSOLE].addChild(this.console);
}
<file_sep>console.log("GameLoader loaded");
function GameLoader(){
PIXI.loaders.Loader.call(this);
}
GameLoader.prototype = Object.create(PIXI.loaders.Loader.prototype);
GameLoader.prototype.constructor = GameLoader;
/**
* Call the game when ready using callback.
* @param {Object} callback
*/
GameLoader.prototype.loadAssets = function(callback){
var assets = [ "assets/bgDay.jpg",
"assets/bgNight.jpg",
"assets/cupcakes.json",
"assets/sun_moon.json"];
console.log("GameLoader load:", assets);
this.add(assets);
this.once('complete', callback);
this.on('progress', this.onProgress);
this.load();
}
/**
* Logs progress of loading to the console
* @param {Object} data
*/
GameLoader.prototype.onProgress = function(data){
console.log("Loading progress:", data.progress);
}
| 1eccad656a3f4abda643852e3610d345293c11a1 | [
"JavaScript"
] | 6 | JavaScript | maserlin/BC | 31b63b287ef869f8fc244816997610ec7e755032 | 3f44828251bd10be8276d6287af73d2a26105deb |
refs/heads/master | <file_sep>$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'pp'
require 'directors_database'
# Find a way to accumulate the :worldwide_grosses and return that Integer
# using director_data as input
def gross_for_director(director_data)
movies = director_data[:movies]
gross_earnings = movies.map{|y| y[:worldwide_gross]}.reduce(:+)
# gross_earnings = 0
# row_index = 0
# while row_index < movies.count do
# movie = movies[row_index]
# gross_earnings += movie[:worldwide_gross]
# row_index += 1
# end
# gross_earnings
end
# Write a method that, given an NDS creates a new Hash
# The return value should be like:
#
# { directorOne => allTheMoneyTheyMade, ... }
def directors_totals(nds)
result = {}
nds.each do |director|
result[director[:name]] = gross_for_director(director)
end
result
end
| b44840f81f6ae15435358725fc83d8f644ea068f | [
"Ruby"
] | 1 | Ruby | forksofpower/programming-univbasics-nds-nds-to-insight-with-methods-austin-web-030920 | 43811496abaa8ca7c784d7610ccc7f0213b349df | da176cfc0bd728131b3e5cb84516b6d241adc126 |
refs/heads/main | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
class RegionController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
//
}
public function show() {
$locations = DB::table('locations')
->where('level', 'reg')
->get()
;
return $locations;
}
}
<file_sep># PH Locations
RESTful API for PH locations
## Platform
Built using [Lumen](https://lumen.laravel.com/docs).
| 8a88de173fcc9874b7c4487977de05d7d00da252 | [
"Markdown",
"PHP"
] | 2 | PHP | makgyber/phlocation | 7d95f131e1a5dac9dcbec82f145ec74d0102d565 | d56d20af33b8dd56bcd49ee816a4ad9055a3f94f |
refs/heads/master | <file_sep>#UDPPingClient.py
from __future__ import division
import time
import sys
from socket import *
#initialize some variables
myMax = 0
myMin = 1
mySum = 0
myNum = int(sys.argv[3])
numLost = 0
#Sends N number of datagrams
for pings in range(myNum):
#Create a UDP socket
clientSocket = socket(AF_INET, SOCK_DGRAM)
#Set 1 second timeout value
clientSocket.settimeout(1)
#Ping to server
message = 'wooooooooo'
#Server address
addr = ('127.0.0.1', 12000)
#Send ping and track send time
start = time.time()
clientSocket.sendto(message, addr)
#If data is received back from server, print
try:
data, server = clientSocket.recvfrom(1024)
end = time.time()
now = time.strftime("%c")
rtt = end - start
#determine RTT
if rtt > myMax:
myMax = rtt
if rtt < myMin:
myMin = rtt
mySum = mySum + rtt
#Print stuff
print 'Reply from %s: Ping %d %s' %(str(addr), pings+1, now)
print 'RTT: %f' %(rtt)
#If data is not received back from server, print it has timed out and track number of packets lost
except timeout:
print 'Request timed out'
numLost = numLost + 1
#Some math and printing for after all packets have been sent
myAvg = mySum / myNum
myLoss = (numLost / myNum) * 100
lossMsg = str(myLoss) + '%'
print 'Max = %f Min = %f Average = %f Packet Loss = %s' %(myMax, myMin, myAvg, lossMsg)<file_sep>#UDPPingServer.py
import random, time
from socket import *
#Create a UDP socket
serverSocket = socket(AF_INET, SOCK_DGRAM)
#Assign IP address and port number to socket
serverSocket.bind(('', 12000))
#The loop runs forever
while True:
#Generate random number in the range of 0 to 10
rand = random.randint(0, 10)
#Receive the client packet along with the address it is coming from
message, address = serverSocket.recvfrom(1024)
#simulate a delay between .1 to .5 seconds
rand2 = random.randint(1,5)/10.0
time.sleep(rand2)
# If rand is less than 4, we consider the packet lost and do not respond
if rand < 4:
continue
#Otherwise, the server responds
serverSocket.sendto(message, address) | ce19a386f35028b3b59dee84c4f285530860fce5 | [
"Python"
] | 2 | Python | Lo-Camillo/UDPPingClient | 007d614bf02bb6c8328f54c228779bcf46c055eb | 14dd9a02e87341b6b872db927f134fd939d8b66c |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.Compression;
using DosyaZipleDonustur.webReferans;
using System.Web.Services;
using System.Web;
using System.Diagnostics;
using System.Xml.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Spire.Doc;
namespace DosyaZipleDonustur
{
class Program
{
static void Main(string[] args)
{
// Ziple();
//MultiZiple();
// Unzip();
}
static void Ziple()
{
string inputPath = "C:/Users/Administrator/Desktop/metinDeneme.docx";
Spire.Doc.Document document = new Spire.Doc.Document();
document.LoadFromFile(inputPath);
//Convert Word to PDF
document.SaveToFile("metin.PDF", FileFormat.PDF);
byte[] array = File.ReadAllBytes("metin.PDF");
webReferans.WebService1 ws = new webReferans.WebService1();
byte[] zipByteArray = ws.ZipThat("metin.pdf", array);
File.WriteAllBytes("C:/Users/Administrator/Desktop/test.zip", zipByteArray);
Console.WriteLine("İşlem Başarılı .");
Console.ReadLine();
}
static void MultiZiple()
{
string inputPath1 = "C:/Users/Administrator/Desktop/metinDeneme.docx";
string inputPath2 = "C:/Users/Administrator/Desktop/metinDeneme2.docx";
Spire.Doc.Document doc1 = new Spire.Doc.Document();
Spire.Doc.Document doc2 = new Spire.Doc.Document();
doc1.LoadFromFile(inputPath1);
doc2.LoadFromFile(inputPath2);
doc1.SaveToFile("metin1.PDF", FileFormat.PDF);
doc2.SaveToFile("metin2.PDF", FileFormat.PDF);
byte[] metin1_Array = File.ReadAllBytes("metin1.PDF");
byte[] metin2_Array = File.ReadAllBytes("metin2.PDF");
webReferans.WebService1 ws = new webReferans.WebService1();
byte[] multiZipArray = ws.ZipMulti("metin1.PDF", "metin2.PDF", metin1_Array, metin2_Array);
File.WriteAllBytes("C:/Users/Administrator/Desktop/testMultiZip.zip", multiZipArray);
}
static void Unzip()
{
//string startPath = "C:/Users/Administrator/Desktop/start";
//string zipPath = "C:/Users/Administrator/Desktop/testMultiZip.zip";
//string extractPath = "C:/Users/Administrator/Desktop/extract";
//System.IO.Compression.ZipFile.CreateFromDirectory(startPath, zipPath);
//System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
String ZipPath = "C:/Users/Administrator/Desktop/testMultiZip.zip";
String extractPath = "C:/Users/Administrator/Desktop/extract";
ZipFile.ExtractToDirectory(ZipPath, extractPath);
}
}
}
| 7697171a4f94903535aae0e1da7718ab76c89a29 | [
"C#"
] | 1 | C# | mecozb/Compress-Decompress-using-with-WebService | 687a1106133373309b13117d5e2f100617049b65 | ba8a910960677b96bcf038f288a2aded0d4fbacd |
refs/heads/master | <repo_name>yangxqiao/ROS_conversation_engine<file_sep>/conversation_engine/commanding_motors.py
#!/usr/bin/env python
import rospy
from std_msgs.msg import Float64MultiArray
if __name__ == '__main__':
rospy.init_node('joints_command_example')
# create a publisher
head_pub = rospy.Publisher('/qt_robot/head_position/command', Float64MultiArray, queue_size=1)
right_pub = rospy.Publisher('/qt_robot/right_arm_position/command', Float64MultiArray, queue_size=1)
left_pub = rospy.Publisher('/qt_robot/left_arm_position/command', Float64MultiArray, queue_size=1)
# wait for publisher/subscriber connections
wtime_begin = rospy.get_time()
while (right_pub.get_num_connections() == 0) :
rospy.loginfo("waiting for subscriber connections")
if rospy.get_time() - wtime_begin > 10.0:
rospy.logerr("Timeout while waiting for subscribers connection!")
sys.exit()
rospy.sleep(1)
rate = rospy.Rate(0.5)
toggle = False
while not rospy.is_shutdown():
rospy.loginfo("publishing motor commnad...")
try:
if toggle:
head = [20 ,0]
rarm = [90 ,0 , -70]
larm = [-90 ,0 , -70]
else:
head = [-20 ,0]
rarm = [90 ,0 , -10]
larm = [-90 ,0 , -10]
head_pub.publish(Float64MultiArray(data=head))
right_pub.publish(Float64MultiArray(data=rarm))
left_pub.publish(Float64MultiArray(data=larm))
toggle = not toggle
except rospy.ROSInterruptException:
rospy.logerr("could not publish motor commnad!")
rate.sleep()<file_sep>/conversation_engine/commanding_head.py
#!/usr/bin/env python
import rospy
import os
from std_msgs.msg import MultiArrayDimension
from std_msgs.msg import Float64MultiArray
import subprocess
def move_head(HeadYaw, HeadPitch):
ref = Float64MultiArray()
ref.data.append(HeadYaw)
ref.data.append(HeadPitch)
# head_pub.publish(ref)
strmsg = "{}".format(ref)
os.system('rostopic pub --once /qt_robot/head_position/command std_msgs/Float64MultiArray "'+strmsg+"\"")
if __name__ == '__main__':
# rospy.init_node('moving_head_example', anonymous=True)
# head_pub = rospy.Publisher('/qt_robot/head_position/command', std_msgs/Float64MultiArray, queue_size=1)
try:
move_head(2.0, -20.0)
move_head(2.0, 25.0)
# rospy.spin()
except rospy.ROSInterruptException:
pass<file_sep>/README.md
# ROS_conversation_engine
This directory is used for testing Qt robot's functionalities
<file_sep>/conversation_engine/reading_head_position.py
#!/usr/bin/env python
import rospy
import numpy as np
from qt_nuitrack_app.msg import Faces
from std_msgs.msg import String
from std_msgs.msg import Float64MultiArray
class PositionInfo:
def __init__(self):
self.coordinate_x = 0.5
self.coordinate_y = 0.5
self.current_head_pos = np.array([0, 0])
self.step_size = 10
self.threshold = 1e-6
def get_coordinate_x(self):
return self.coordinate_x
def get_coordinate_y(self):
return self.coordinate_y
def set_coordinate_x(self, new_position):
self.coordinate_x = (new_position[0] + new_position[1]) / 2
def set_coordinate_y(self, new_position):
self.coordinate_y = (new_position[0] + new_position[1]) / 2
def process_new_head_position(self):
desired_face_location = np.array([0.5, 0.5])
actual_face_location = np.array([self.coordinate_x, self.coordinate_y])
diff_face_loc = desired_face_location - actual_face_location
if abs(diff_face_loc[0]) > self.threshold and abs(diff_face_loc[1]) > self.threshold:
self.current_head_pos[0] += self.step_size * diff_face_loc[0]
self.current_head_pos[1] -= self.step_size * diff_face_loc[1]
publish_data = self.current_head_pos
if self.current_head_pos[0] > 45:
publish_data[0] = 45
elif self.current_head_pos[0] < -45:
publish_data[0] = -45
if self.current_head_pos[1] > 20:
publish_data[1] = 20
elif self.current_head_pos[1] < -20:
self.current_head_pos[1] = -20
head_pub.publish(Float64MultiArray(data=publish_data))
def callback(msg):
strmsg_left = "Left eye: (%.4f, %.4f)" % (msg.faces[0].left_eye[0], msg.faces[0].left_eye[1])
strmsg_right = "Right eye: (%.4f, %.4f)" % (msg.faces[0].right_eye[0], msg.faces[0].right_eye[1])
my_position.set_coordinate_x([msg.faces[0].left_eye[0], msg.faces[0].right_eye[0]])
my_position.set_coordinate_y([msg.faces[0].left_eye[0], msg.faces[0].right_eye[1]])
strmsg_x = "The coordinate_x of the head: %.4f" % my_position.get_coordinate_x()
strmsg_y = "The coordinate_y of the head: %.4f" % my_position.get_coordinate_y()
def show_expression(file_path):
emotionShow_pub = rospy.Publisher('/qt_robot/emotion/show', String, queue_size=1)
emotionShow_pub.publish(file_path)
def play_gesture(file_path):
gesturePlay_pub = rospy.Publisher('/qt_robot/gesture/play', String, queue_size=1)
gesturePlay_pub.publish(file_path)
if __name__ == '__main__':
rospy.init_node('joints_command_example')
head_pub = rospy.Publisher('/qt_robot/head_position/command', Float64MultiArray, queue_size=1)
# wait for publisher/subscriber connections
wtime_begin = rospy.get_time()
while (head_pub.get_num_connections() == 0) :
rospy.loginfo("waiting for subscriber connections")
if rospy.get_time() - wtime_begin > 10.0:
rospy.logerr("Timeout while waiting for subscribers connection!")
sys.exit()
rospy.sleep(1)
rate = rospy.Rate(0.5)
count = 0
my_position = PositionInfo()
rospy.loginfo("publishing motor commnad...")
try:
rospy.Subscriber('/qt_nuitrack_app/faces', Faces, callback)
except rospy.ROSInterruptException:
rospy.logerr("could not publish motor commnad!")
rospy.spin()
rate.sleep()<file_sep>/conversation_engine/move_head_back.py
#!/usr/bin/env python
import rospy
from qt_motors_controller.srv import *
def move_head_back():
home('HeadPitch')
home('HeadYaw')
if __name__ == '__main__':
rospy.init_node('move_head_back')
move_back_head_pub = rospy.ServiceProxy('/qt_robot/motors/home', home)
rospy.wait_for_service('/qt_robot/motors/home')
rospy.loginfo("ready...")
try:
move_head_back()
rospy.loginfo("finish.")
except rospy.ROSInterruptException:
pass<file_sep>/conversation_engine/reading_joints.py
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import JointState
def joint_states_callback(msg):
strmsg = ""
for i, joint_name in enumerate(msg.name):
strmsg += "%s: %.2f, " % (joint_name, msg.position[i])
rospy.loginfo(strmsg)
if __name__ == '__main__':
rospy.init_node('joints_example')
rospy.Subscriber('/qt_robot/joints/state', JointState, joint_states_callback)
rospy.spin()
<file_sep>/conversation_engine/gaze_controller.py
import rospy
from std_msgs.msg import Float64MultiArray
from std_msgs.msg import Bool
from sensor_msgs import JointState
class StatusInfo:
def __init__(self):
self._is_speaking = False
self._human_pos_x = 0.5
self._human_pos_y = 0.5
self._robot_head_pitch = 0
self._robot_head_yaw = 0
def set_is_speaking(self, msg):
self._is_speaking = msg.data
def set_skeleton(self, msg):
self._human_pos_x = (msg.faces[0].left_eye[0] + msg.faces[0].right_eye[0]) * 0.5
self._human_pos_y = (msg.faces[0].left_eye[1] + msg.faces[0].right_eye[1]) * 0.5
def set_sensor_msg(self, msg):
self._robot_head_pitch = msg.position[0]
self._robot_head_yaw = msg.position[1]
@property
def human_pos_x(self):
return self._human_pos_x
@property
def human_pos_y(self):
return self._human_pos_y
@property
def is_speaking(self):
return self._is_speaking
@property
def robot_head_pitch(self):
return self._robot_head_pitch
@property
def robot_head_Yaw(self):
return self._robot_head_Yaw
def run(msg):
# finite state machine for publishing the correct angle
# Requirement:
# Not totally predictable/ random
# Using establish design choices
# Defferentiate between speaking and listening
while not rospy.is_shutdown():
# start timing
# case I: QT is speaking
if QT_status_info.is_speaking:
# perform Intimacy-modulating gaze aversions
# Length: M = 1.14s, SD = 0.27s
# Time between consecutive gaze aversions: M = 7.21s, SD = 1.88s
# What we need:
# QT's current head position
# pick an absolute angle and call the process_new_head_position()
# perform gaze tracing
pass
# case II: QT is listening
else:
# perform floor management gaze aversions
# Length: M = 2.3s, SD = 1.1s
# Start time in relation to the start of the next utterance: M = -1.03s, SD = 0.39s
# perform Intimacy-modulating gaze aversions
# Length: M = 1.96s, SD = 0.32s
# Time between consecutive gaze aversions: M = 4.75s, SD = 1.39s
pass
if __name__ == '__main__':
rospy.init_node('gaze_behavior_controller')
# create the publisher
qtHeadMotor_pub = rospy.Publisher('/qt_robot/head_position/command',
Float64MultiArray,
queue_size=1)
# create three subscribers
QT_status_info = StatusInfo()
rospy.Subscriber('speaker', Bool, QT_status_info.set_is_speaking)
rospy.Subscriber('/qt_nuitrack_app/faces', Faces, QT_status_info.set_skeleton)
rospy.Subscriber('/qt_robot/joints/state', JointState, QT_status_info.set_sensor_msg)
# wait for publisher/subscriber connections
wtime_begin = rospy.get_time()
while (head_pub.get_num_connections() == 0) :
rospy.loginfo("waiting for subscriber connections")
if rospy.get_time() - wtime_begin > 10.0:
rospy.logerr("Timeout while waiting for subscribers connection!")
sys.exit()
rospy.sleep(1)
rospy.loginfo("ready...")
try:
QT_status_info.run()
except rospy.ROSInterruptException:
rospy.logerr("could not successfully subscribe!")
rospy.spin()
rate.sleep()
| cb82a84e095144d79393aa79b76ee0143f88ebe0 | [
"Markdown",
"Python"
] | 7 | Python | yangxqiao/ROS_conversation_engine | 6d4781b4ed6497b35d42299875af94bd4e7b6440 | 9b0c9cf0b193e6135874c131906e8e05085656d8 |
refs/heads/master | <repo_name>altieresbianchi/cashbackapi<file_sep>/config/custom-express.js
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
const pool = require('./pool-factory');
const connectionMiddleware = require('../src/middleware/connection');
// Middleware connect
app.use(connectionMiddleware(pool));
//Formidable
const formidableMiddleware = require('express-formidable');
app.use(formidableMiddleware());
// Rotas
const routes = require('../src/routes');
// Connect all our routes to our application
app.use('/api/', routes);
//app.use(routes);
//middleware de tratamento de erro
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: err.toString() });
});
module.exports = app;<file_sep>/README.md
# Cashback API
API Cashback.
# Linguagem
**Node.js**
# Banco de dados
**MySql**<br/>
Obs.: Os dados (script CREATE TABLES e DER em Workbench se encontram na pasta documents).
# Ambiente Demonstração
- **Localhost:** http://localhost:8080/api
- **Remoto:** https://cashbackapi.herokuapp.com/api
# Collection Postman
https://www.getpostman.com/collections/c20c6a727886b1d6f22e
Configuração do Environment:
- **BASE_DOMAIN** *(URL do ambiente)*
- **TOKEN** *(Token gerado no login)*
# Endpoints
**Home**
- **GET** **/v1/** *(Endpoint base)*
**Login**
- **POST** **/v1/login** *(Login de revendedor (Parâmetros: cpf, senha))*
**Revendedor**
- **GET** **/v1/revendedores/** *(Lista de revendedores cadastrados)*
- **GET** **/v1/revendedores/:cpf** *(Busca revendedor pelo cpf)*
- **GET** **/v1/revendedores/:cpf/cashback** *(Busca o cashback total do revendedor pelo cpf)*
- **POST** **/v1/revendedores/** *(Cadastra um novo revendedor (Parâmetros: cpf, nome, email, senha))*
- **PUT** **/v1/revendedores/:cpf** *(Edita um revendedor (Parâmetros: nome, email, senha))*
- **DELETE** **/v1/revendedores/:cpf** *(Exclui um revendedor)*
**Compra**
- **GET** **/v1/compras/** *(Lista de compras cadastradas)*
- **GET** **/v1/compras/:codigo** *(Busca compra pelo código)*
- **POST** **/v1/compras/** *(Cadastra uma nova compra (Parâmetros: codigo, cpf, valor, data))*
- **PUT** **/v1/compras/:codigo** *(Edita uma compra (Parâmetros: valor, status, data))*
- **DELETE** **/v1/compras/:codigo** *(Exclui uma compra)*
**Cashback**
- **GET** **/v1/cashback/:cpf** *(Retorna o saldo de cashback do revendedor buscando pelo CPF na API externa fornecida pelo solicitante)*
<file_sep>/src/controllers/loginController.js
const jwt = require('jsonwebtoken');
const config = require('config');
// FUNCOES ---
function formatResult(res, code, message, data) {
return res.status(code).json({
"statusCode": code,
"message": message,
"data": data,
});
}
exports.postLogin = function(req, res, next) {
var cpf = req.fields.cpf;
var senha = req.fields.senha;
// console.log('Cpf: ' + cpf + ' - Senha: ' + senha);
var query = 'SELECT cpf, nome, email, DATE_FORMAT(data_cadastro, "%Y-%m-%d %H:%m") as dataCadastro FROM revendedor WHERE cpf = ? AND senha = ?';
req.connection.query(query, [cpf, senha], (err, [item]) => {
if(err) {
formatResult(res, 500, err, null);
} else if(!item) {
formatResult(res, 401, 'Login ou senha incorretos!', null);
} else {
// Gera o token
var token = jwt.sign({ cpf: cpf }, config.get('myJwtPrivateKey'), {
expiresIn: 900 // Expira em 15 min
});
// Seta o token no obj
item['token'] = token;
// Result
formatResult(res, 200, 'Login realizado com sucesso!', item);
}
});
};
<file_sep>/src/routes/compra.js
const models = require('express').Router();
//Require controller modules.
var controller = require('../controllers/compraController');
// Rotas
models.get('/', controller.getList);
models.get('/:codigo', controller.getById);
models.post('/', controller.postCreate);
models.put( '/:codigo', controller.putUpdate);
models.delete('/:codigo', controller.deleteById);
module.exports = models;<file_sep>/index.js
const app = require('./config/custom-express');
/*
const expressSwagger = require('express-swagger-generator')(app);
let options = {
swaggerDefinition: {
info: {
description: 'API Chasback - Teste prático',
title: 'Swagger',
version: '1.0.0',
},
//host: 'localhost:8080',
host: 'cashbackapi.herokuapp.com',
basePath: '/api/',
produces: [
"application/json",
"application/xml"
],
schemes: ['http', 'https'],
securityDefinitions: {
JWT: {
type: 'apiKey',
in: 'header',
name: 'Authorization',
description: "",
}
}
},
basedir: __dirname, //app absolute path
files: ['./src/routes/*.js', './src/controllers/*.js'] //Path to the API handle folder
};
expressSwagger(options)
*/
// Inicia o server
var porta = process.env.PORT || 8080;
app.listen(porta, () => {
console.log('server started');
});<file_sep>/src/controllers/revendedorController.js
// FUNCOES ---
function formatResult(res, code, message, data, errors) {
return res.status(code).json({
"statusCode": code,
"message": message,
"data": data,
"errors": errors,
});
}
exports.getList = function(req, res) {
var query = "SELECT cpf, nome, email, DATE_FORMAT(data_cadastro, '%Y-%m-%d %H:%m') as dataCadastro, " +
" DATE_FORMAT(data_atualizacao, '%Y-%m-%d %H:%m') as dataAtualizacao " +
" FROM revendedor ORDER BY nome";
// não me importa de onde vem a conexão, só preciso de uma conexão!
req.connection.query(query, (err, list) => {
if(err) {
formatResult(res, 500, err, null);
} else if(!list) {
formatResult(res, 404, "Registros não encontrados", null);
} else {
formatResult(res, 200, "Dados retornados com sucesso", list);
}
// não preciso me preocupar em devolver a conexão para o pool
});
};
exports.getById = function(req, res, next) {
// param
var cpf = (req.params.cpf ? req.params.cpf.replace(/[^0-9]/g, '') : null);
var query = "SELECT cpf, nome, email, DATE_FORMAT(data_cadastro, '%Y-%m-%d %H:%m') as dataCadastro, " +
" DATE_FORMAT(data_atualizacao, '%Y-%m-%d %H:%m') as dataAtualizacao " +
" FROM revendedor WHERE cpf = ?";
// não me importa de onde vem a conexão, só preciso de uma conexão!
req.connection.query(query, [cpf], (err, [item]) => {
if(err) {
formatResult(res, 500, err, null);
} else if(!item) {
formatResult(res, 404, "Registro não encontrado", null);
} else {
formatResult(res, 200, "Dados retornados com sucesso", item);
}
// não preciso me preocupar em devolver a conexão para o pool
});
};
exports.getCashback = function(req, res, next) {
// param
var cpf = (req.params.cpf ? req.params.cpf.replace(/[^0-9]/g, '') : null);
var query = 'SELECT IF(SUM(valor) IS NULL, 0, SUM(valor)) as cashback FROM compra WHERE cpf = ?';
//console.log('query: ' + query)
req.connection.query(query, [cpf], (err, [result]) => {
if(err) {
formatResult(res, 500, err, null);
} else {
formatResult(res, 200, 'Total cashback retornado com sucesso!', result);
}
});
}
exports.postCreate = function(req, res, next) {
var cpf = (req.fields.cpf ? req.fields.cpf.replace(/[^0-9]/g, '') : null);
var nome = (req.fields.nome ? req.fields.nome : null);
var email = (req.fields.email ? req.fields.email : null);
var senha = (req.fields.senha ? req.fields.senha : null);
// console.log('Nome: ' + nome + ' - Cpf: ' + cpf + ' - Email: ' + email + ' - Senha: ' + senha);
// console.log(cpf.length)
// Valida o form
var errors = [];
if(!cpf) {
errors.push("Informe o CPF");
} else if(cpf.length < 11) {
errors.push("O CPF deve conter 11 dígitos");
}
if(!nome) {
errors.push("Informe o nome completo");
}
if(!email) {
errors.push("Informe o email");
}
if(!senha) {
errors.push("Informe a senha");
}
// console.log(errors)
if(errors && errors.length > 0) {
formatResult(res, 409, 'Há dados inválidos no formulário enviado', null, errors);
} else {
var query = 'SELECT cpf FROM revendedor WHERE cpf = ?';
req.connection.query(query, [cpf], (err, [item]) => {
if(err) {
formatResult(res, 500, err, null);
} else if(item) {
formatResult(res, 409, 'CPF já cadastrado', null);
} else {
var query = 'INSERT INTO revendedor(cpf, nome, email, senha, data_cadastro, data_atualizacao) VALUES (?, ?, ?, ?, ?, ?)';
var params = [cpf, nome, email, senha, new Date(), new Date()];
// console.log(query);
// não me importa de onde vem a conexão, só preciso de uma conexão!
req.connection.query(query, params, (err, result) => {
// console.log(item)
if(err) {
formatResult(res, 500, err, null);
} else {
formatResult(res, 200, 'Registro criado com sucesso', null);
}
// não preciso me preocupar em devolver a conexão para o pool
});
}
});
}
};
exports.putUpdate = function(req, res, next) {
// param
var cpf = (req.params.cpf ? req.params.cpf.replace(/[^0-9]/g, '') : null);
// Campos
var nome = (req.fields.nome ? req.fields.nome : null);
var email = (req.fields.email ? req.fields.email : null);
var senha = (req.fields.senha ? req.fields.senha : null);
// console.log('Nome: ' + nome + ' - Cpf: ' + cpf + ' - Email: ' + email + ' - Senha: ' + senha);
var query = 'SELECT cpf FROM revendedor WHERE cpf = ?';
// var params = {cpf: cpf};
// não me importa de onde vem a conexão, só preciso de uma conexão!
req.connection.query(query, [cpf], (err, [item]) => {
if(err) {
formatResult(res, 500, err, null);
} else if(!item) {
formatResult(res, 404, "CPF não encontrado", null);
} else {
// Valida o form
var errors = [];
if(!nome) {
errors.push("Informe o nome completo");
}
if(!email) {
errors.push("Informe o email");
}
if(!senha) {
errors.push("Informe a senha");
}
// console.log(errors)
if(errors && errors.length > 0) {
formatResult(res, 409, 'Há dados inválidos no formulário enviado', null, errors);
} else {
var query = "UPDATE revendedor SET nome=?, email=?, senha=?, data_atualizacao=? WHERE cpf=?";
var params = [nome, email, senha, new Date(), cpf];
// console.log(query);
// não me importa de onde vem a conexão, só preciso de uma conexão!
req.connection.query(query, params, (err, result) => {
if(err) {
formatResult(res, 500, err, null);
} else {
formatResult(res, 200, "Registro atualizado com sucesso", null);
}
});
}
}
});
};
exports.deleteById = function(req, res, next) {
// param
var cpf = (req.params.cpf ? req.params.cpf.replace(/[^0-9]/g, '') : null);
//console.log('Request cpf:', cpf);
var query = 'DELETE FROM revendedor WHERE cpf = ?';
// var params = {cpf: cpf};
console.log(query);
// não me importa de onde vem a conexão, só preciso de uma conexão!
req.connection.query(query, [cpf], (err, result) => {
// console.log(item)
if(err) {
formatResult(res, 500, err, null);
} else {
formatResult(res, 200, "Registro excluído com sucesso", null);
}
// não preciso me preocupar em devolver a conexão para o pool
});
};
<file_sep>/src/controllers/compraController.js
var moment = require('moment');
// FUNCOES ---
function formatResult(res, code, message, data, errors) {
return res.status(code).json({
"statusCode": code,
"message": message,
"data": data,
"errors": errors,
});
}
exports.getList = function(req, res) {
var query = "SELECT codigo, cpf, valor, porcentagem, "
+ " ((valor * porcentagem) / 100) AS cashback, "
+ " status, IF(status = 1, 'Aprovado', 'Em validação') AS statusDesc, "
+ " DATE_FORMAT(data_compra, '%Y-%m-%d') as dataCompra, "
+ " DATE_FORMAT(data_atualizacao, '%Y-%m-%d %H:%i') as dataAtualizacao "
+ " FROM compra ORDER BY data_compra DESC ";
// não me importa de onde vem a conexão, só preciso de uma conexão!
req.connection.query(query, (err, list) => {
if(err) {
formatResult(res, 500, err, null);
} else if(!list) {
formatResult(res, 404, "Registros não encontrados", null);
} else {
formatResult(res, 200, "Dados retornados com sucesso", list);
}
// não preciso me preocupar em devolver a conexão para o pool
});
};
exports.getById = function(req, res, next) {
// param
var codigo = req.params.codigo;
console.log('Request codigo:', codigo);
// res.send('Request Id:', req.params.id)
var query = "SELECT codigo, cpf, valor, porcentagem, "
+ " ((valor * porcentagem) / 100) AS cashback, "
+ " status, IF(status = 1, 'Aprovado', 'Em validação') AS statusDesc, "
+ " DATE_FORMAT(data_compra, '%Y-%m-%d') as dataCompra, "
+ " DATE_FORMAT(data_atualizacao, '%Y-%m-%d %H:%i') as dataAtualizacao "
+ " FROM compra WHERE codigo = ? ";
// não me importa de onde vem a conexão, só preciso de uma conexão!
req.connection.query(query, [codigo], (err, [item]) => {
if(err) {
formatResult(res, 500, err, null);
} else if(!item) {
formatResult(res, 404, "Registro não encontrado", null);
} else {
formatResult(res, 200, "Dados retornados com sucesso", item);
}
// não preciso me preocupar em devolver a conexão para o pool
});
};
exports.postCreate = function(req, res, next) {
var codigo = (req.fields.codigo ? req.fields.codigo : null);
var cpf = (req.fields.cpf ? req.fields.cpf.replace(/[^0-9]/g, '') : null);
var valor = (req.fields.valor ? req.fields.valor : null);
var data = (req.fields.data ? req.fields.data : null);
var status = 0; // Em validacao
// Valida o CPF
if(cpf == '15350946056') {
status = 1; // Aprovado
}
// console.log(cpf);
/*
Rota para cadastrar uma nova compra exigindo no mínimo
código,
valor,
data e
CPF do
revendedor(a).
Todos os cadastros são salvos com o status “Em validação” exceto quando o
CPF do revendedor(a) for 153.509.460-56, neste caso o status é salvo como “Aprovado”;
*/
// console.log('Codigo: ' + codigo + ' - Cpf: ' + cpf + ' - Valor: ' + valor + ' - Data: ' + data);
// Valida o form
var errors = [];
if(!codigo) {
errors.push("Informe o código da compra");
}
if(!cpf) {
errors.push("Informe o CPF do revendedor");
} else if(cpf.length < 11) {
errors.push("O CPF deve conter 11 dígitos");
}
if(!valor) {
errors.push("Informe o valor da compra");
}
if(!data) {
errors.push("Informe a data da compra");
}
if(!moment(data, "YYYY-MM-DD", true).isValid()) {
errors.push("Data da compra inválida. O formato deve ser AAAA-MM-DD.");
}
if(errors && errors.length > 0) {
formatResult(res, 409, 'Há dados inválidos no formulário enviado', null, errors);
} else {
var query = 'SELECT cpf FROM revendedor WHERE cpf = ?';
req.connection.query(query, [cpf], (err, [result]) => {
if(err) {
formatResult(res, 500, err, null);
} else if(!result) {
formatResult(res, 404, 'Revendedor não encontrado', null);
} else {
var query = 'SELECT codigo FROM compra WHERE codigo = ?';
req.connection.query(query, [codigo], (err, [item]) => {
if(err) {
formatResult(res, 500, err, null);
} else if(item) {
formatResult(res, 409, 'Compra já cadastrada', null);
} else {
var query = 'SELECT SUM(valor) as valor FROM compra WHERE cpf = ? ';
//console.log('query: ' + query)
req.connection.query(query, [cpf], (err, [result]) => {
if(err) {
formatResult(res, 500, err, null);
} else {
// Calcula a porcentagem
var porcentagem = 10;
if(result.valor) {
if(result.valor > 1000 && result.valor <= 1500 ) {
porcentagem = 15;
} else if(result.valor > 15000) {
porcentagem = 20;
}
}
console.log('Valor: ' + result.valor + ' - %: ' + porcentagem);
var query = 'INSERT INTO compra (codigo, cpf, valor, porcentagem, status, data_compra, data_atualizacao) VALUES (?, ?, ?, ?, ?, ?, ?)';
var params = [codigo, cpf, valor, porcentagem, status, data, new Date()];
// console.log(query);
req.connection.query(query, params, (err, result) => {
// console.log(item)
if(err) {
formatResult(res, 500, err, null);
} else {
formatResult(res, 200, 'Compra cadastrada com sucesso', null);
}
});
//return result;
}
});
}
});
}
});
}
};
exports.putUpdate = function(req, res, next) {
// param
var codigo = (req.params.codigo ? req.params.codigo : null);
// Dados
var valor = (req.fields.valor ? req.fields.valor : null);
var status = (req.fields.status ? (req.fields.status > 0 ? 1 : 0) : null);
var data = (req.fields.data ? req.fields.data : null);
//Valida o form
var errors = [];
if(!valor) {
errors.push("Informe o valor da compra");
}
if(status == null) {
errors.push("Informe o status da compra");
}
if(!data) {
errors.push("Informe a data da compra");
}
if(!moment(data, "YYYY-MM-DD", true).isValid()) {
errors.push("Data da compra inválida. O formato deve ser AAAA-MM-DD.");
}
if(errors && errors.length > 0) {
formatResult(res, 409, 'Há dados inválidos no formulário enviado', null, errors);
} else {
var query = 'SELECT cpf, status FROM compra WHERE codigo = ? ';
// não me importa de onde vem a conexão, só preciso de uma conexão!
req.connection.query(query, [codigo], (err, [result]) => {
if(err) {
formatResult(res, 500, err, null);
} else if(!result) {
formatResult(res, 404, "Registro não encontrado", null);
} else if(result.status == 1) {
formatResult(res, 403, "Não é permitido alterar uma compra já aprovada", null);
} else {
var query = 'SELECT SUM(valor) as valor FROM compra WHERE cpf = ? ';
//console.log('query: ' + query)
// não me importa de onde vem a conexão, só preciso de uma conexão!
req.connection.query(query, [result.cpf], (err, [result]) => {
if(err) {
formatResult(res, 500, err, null);
} else {
// Calcula a porcentagem
var porcentagem = 10;
if(result.valor) {
if(result.valor > 1000 && result.valor <= 1500 ) {
porcentagem = 15;
} else if(result.valor > 15000) {
porcentagem = 20;
}
}
console.log('Valor: ' + result.valor + ' - %: ' + porcentagem);
var query = "UPDATE compra SET valor=?, status=?, porcentagem=?, data_compra=?, data_atualizacao=? WHERE codigo=?";
var params = [valor, status, porcentagem, data, new Date(), codigo];
//console.log(query);
req.connection.query(query, params, (err, result) => {
// console.log(item)
if(err) {
formatResult(res, 500, err, null);
} else {
formatResult(res, 200, "Registro atualizado com sucesso", null);
}
});
}
});
}
});
}
};
exports.deleteById = function(req, res, next) {
// param
var codigo = req.params.codigo;
console.log('Delete codigo:', codigo);
var query = 'SELECT status FROM compra WHERE codigo = ? ';
// não me importa de onde vem a conexão, só preciso de uma conexão!
req.connection.query(query, [codigo], (err, [result]) => {
if(err) {
formatResult(res, 500, err, null);
} else if(!result) {
formatResult(res, 404, "Registro não encontrado", null);
} else if(result.status == 1) {
formatResult(res, 403, "Não é permitido excluir uma compra já aprovada", null);
} else {
var query = 'DELETE FROM compra WHERE status = 0 AND codigo = ?';
req.connection.query(query, [codigo], (err, result) => {
if(err) {
formatResult(res, 500, err, null);
} else {
formatResult(res, 200, "Registro excluído com sucesso", null);
}
});
}
// não preciso me preocupar em devolver a conexão para o pool
});
};
<file_sep>/documents/CREATE_TABLES.sql
-- MySQL Script generated by MySQL Workbench
-- Sat Jan 4 21:41:02 2020
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
-- -----------------------------------------------------
-- Schema cashback
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema cashback
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `cashback` DEFAULT CHARACTER SET utf8 ;
USE `cashback` ;
-- -----------------------------------------------------
-- Table `cashback`.`revendedor`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `cashback`.`revendedor` (
`cpf` VARCHAR(11) NOT NULL,
`nome` VARCHAR(60) NULL,
`email` VARCHAR(100) NULL,
`senha` VARCHAR(45) NULL,
`data_cadastro` TIMESTAMP NULL,
`data_atualizacao` TIMESTAMP NULL,
PRIMARY KEY (`cpf`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `cashback`.`compra`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `cashback`.`compra` (
`codigo` INT NOT NULL AUTO_INCREMENT,
`cpf` VARCHAR(11) NOT NULL,
`valor` DECIMAL(10,2) NULL,
`porcentagem` INT NULL,
`status` SMALLINT NULL COMMENT '0 - Em validação\n1 - Aprovado',
`data_compra` DATE NULL,
`data_atualizacao` TIMESTAMP NULL,
PRIMARY KEY (`codigo`),
INDEX `fk_compra_revendedor_idx` (`cpf` ASC),
CONSTRAINT `fk_compra_revendedor`
FOREIGN KEY (`cpf`)
REFERENCES `cashback`.`revendedor` (`cpf`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep>/src/middleware/auth.js
const jwt = require('jsonwebtoken');
const config = require('config');
module.exports = (req, res, next) => {
// Pega o token da header
var token = (req.headers['x-auth-token'] || req.headers['authorization']);
// console.log(req.headers);
if (!token) {
//return res.status(401).send({ auth: false, message: 'Token não informado.' });
return formatResult(res, 401, 'Token não informado.', null);
}
jwt.verify(token, config.get('myJwtPrivateKey'), function(err, decoded) {
if (err) {
//return res.status(500).send({ auth: false, message: 'Token inválido ou expirado.' });
return formatResult(res, 401, 'Token inválido.', null);
//return formatResult(res, 401, err, null);
}
// se tudo estiver ok, salva no request para uso posterior
req.cpf = decoded.cpf;
next();
});
}
function formatResult(res, code, message, data) {
return res.status(code).json({
"statusCode": code,
"message": message,
"data": data,
});
}<file_sep>/src/routes/index.js
const routes = require('express').Router();
const request = require("request");
const config = require('config');
// Auth
const auth = require('../middleware/auth');
// Require routes
const revendedor = require('./revendedor');
const compra = require('./compra');
// Require controller
var loginController = require('../controllers/loginController');
//Login
routes.post('/v1/login', loginController.postLogin);
// Rotas internas
routes.use('/v1/revendedores', revendedor);
routes.use('/v1/compras', auth, compra); // Todas as rotas com autenticacao
// Cashback acumulado
routes.get('/v1/cashback/:cpf', auth, (req, res) => {
try {
// Pega o CPF
var cpf = (req.params.cpf ? req.params.cpf.replace(/[^0-9]/g, '') : null);
//console.log(cpf)
//console.log(config.get('externalApiToken'))
// Opcoes chamada
const options = {
url: (config.get('externalApiUrl') + '?cpf=' + cpf),
headers: {
"token": config.get('externalApiToken')
}
};
// Chamada da API
request.get(options, (error, response, result) => {
if(error) {
res.status(500).json({
"statusCode": 500,
"message": "Falha ao buscar o cashback",
"data": error,
});
}
// Converte o resultado
var parsed = JSON.parse(result);
// Seta o retorno
res.status(parsed.statusCode).json({
"statusCode": parsed.statusCode,
"message": (parsed.body.message ? parsed.body.message : "Dados retornados com sucesso"),
"data": parsed.body,
});
});
} catch (ex) {
console.error(ex);
res.status(500).json({
"statusCode": 500,
"message": "Não foi possível completar a solicitação",
"data": ex.message,
});
}
});
// Home
routes.get('/v1/', (req, res) => {
res.status(200).json({
"statusCode": 200,
"message": "Cashback API - Teste prático.",
"data": null,
});
});
module.exports = routes;
| f26c69a707e3103402dcd9499c432b7f17ae0a90 | [
"JavaScript",
"SQL",
"Markdown"
] | 10 | JavaScript | altieresbianchi/cashbackapi | 9c91b0dbeff05063707c1f92c7b9ebc28b46723d | 1561461d2f7305070fccf06605b24a453caba73a |
refs/heads/master | <repo_name>wenjunGG/NetMQ<file_sep>/NetMQ/Simproduct.cs
using EasyNetQ;
using Model;
using System;
using System.Collections.Generic;
using System.Text;
namespace NetMQ
{
public static class Simproduct
{
public static void sim()
{
using (var bus = RabbitHutch.CreateBus("host=localhost"))
{
var input = "";
Console.WriteLine("Enter a message. 'Quit' to quit.");
while ((input = Console.ReadLine()) != "Quit")
{
bus.Publish(new TextMessage
{
Text = input
});
}
}
}
}
}
<file_sep>/Subscriber/Program.cs
using EasyNetQ;
using Model;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
using System.Threading;
namespace Subscriber
{
class Program
{
private static string EXCHANGE_NAME = "exchangefanout";
private static string ROUTEKEY = "k1fanout";
private static string CHANCEL_NAME = "chanelfamout";
private static string EXCHANGE_TYPE = "fanout";
static void Main(string[] args)
{
//using (var bus = RabbitHutch.CreateBus("host=localhost"))
//{
// //bus.Subscribe<TextMessage>("test11", HandleTextMessage);
// //Console.WriteLine("Listening for messages. Hit <return> to quit.");
// //Console.ReadLine();
// //异步
// // bus.SubscribeAsync<TextMessage>("subscribe_async_test", message =>
// // new WebClient().DownloadStringTask(new Uri("http://localhost:1338/?timeout=500"))
// //.ContinueWith(task =>
// // Console.WriteLine("Received: '{0}', Downloaded: '{1}'",
// // message.Text,
// // task.Result)));
// //请求响应
// //bus.Respond<TextMessage, TextMessage>(request =>
// //new TextMessage { Text = "Responding to " + HandleTextMessage(request.Text) });
//sendrecieve
// bus.Receive<TextMessage>("my.queue1", message => Console.WriteLine("MyMessage: {0}", message.Text));
// Console.ReadLine();
//}
// var factory = new ConnectionFactory() { HostName = "localhost" };
// using (var connection = factory.CreateConnection())
// {
// using (var channel = connection.CreateModel())
// {
// channel.QueueDeclare("hello", false, false, false, null);
// var consumer = new QueueingBasicConsumer(channel);
//#if demo1
// channel.BasicConsume("hello", true, consumer);//自动删除消息
//#else
// channel.BasicConsume("hello", true, consumer);//需要接受方发送ack回执,删除消息
//#endif
// Console.WriteLine(" [*] Waiting for messages." + "To exit press CTRL+C");
// while (true)
// {
// var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();//挂起的操作
//#if demo2
// channel.BasicAck(ea.DeliveryTag, false);//与channel.BasicConsume("hello", false, null, consumer);对应
//#endif
// var body = ea.Body;
// var message = Encoding.UTF8.GetString(body);
// Console.WriteLine(" [x] Received {0}", message);
// int dots = message.Split('.').Length - 1;
// Thread.Sleep(dots * 1000);
// Console.WriteLine(" [x] Done");
//#if demo2
// //channel.BasicAck(ea.DeliveryTag, false);//与channel.BasicConsume("hello", false, null, consumer);对应,这句话写道40行和49行运行结果就会不一样.写到这里会发生如果输出[x] Received {0}之后,没有输出 [x] Done之前,CTRL+C结束程序,那么message会自动发给另外一个客户端,当另外一个客户端收到message后,执行完49行的命令之后,服务器会删掉这个message
//#endif
// }
// }
// }
////广播模式
//ConnectionFactory factory = new ConnectionFactory() { HostName = "localhost" };
//using (IConnection Connection = factory.CreateConnection())
//{
// using (IModel channel = Connection.CreateModel())
// {
// channel.ExchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE);
// // channel.QueueDeclare(CHANCEL_NAME, false);//true, true, true, false, false, null);
// channel.QueueBind(CHANCEL_NAME, EXCHANGE_NAME, ROUTEKEY);
// channel.QueueDeclare(CHANCEL_NAME, false, false, false, null);
// var consumer = new QueueingBasicConsumer(channel);
// channel.BasicConsume(CHANCEL_NAME, false, consumer);
// Console.WriteLine(" [*] Waiting for messages." + "To exit press CTRL+C");
// while (true)
// {
// var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();//挂起的操作
// var body = ea.Body;
// var message = Encoding.UTF8.GetString(body);
// Console.WriteLine(" [x] Received {0}", message);
// }
// }
//}
//CustmerMq.InitCustmerMq();
//广播 success
Consumer.Con();
//最简单的模式
// SimConsumer.SimCon();
//send recieve
// RecieveConsumer.RecieveCon();
//复杂
// ComplexConsumer.ComplexCon();
}
static string HandleTextMessage(string mess)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Got message: {0}", mess);
Console.ResetColor();
return "ok";
}
}
}<file_sep>/NetMQ/SendProduct.cs
using EasyNetQ;
using Model;
using System;
using System.Collections.Generic;
using System.Text;
namespace NetMQ
{
public static class SendProduct
{
public static void sendPro()
{
using (var bus = RabbitHutch.CreateBus("host=localhost"))
{
var input = "";
Console.WriteLine("Enter a message. 'Quit' to quit.");
while ((input = Console.ReadLine()) != "Quit")
{
// Send Receive
bus.Send("my.queue2", new TextMessage { Text = "Hello Widgets!" });
}
}
}
}
}
<file_sep>/NetMQ/product.cs
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Text;
namespace NetMQ
{
public static class product
{
public static void pro()
{
//建立RabbitMQ连接和通道
ConnectionFactory connectionFactory = new ConnectionFactory
{
HostName = "127.0.0.1",
Port = 5672,
UserName = "guest",
Password = "<PASSWORD>",
Protocol = Protocols.DefaultProtocol,
AutomaticRecoveryEnabled = true, //自动重连
RequestedFrameMax = UInt32.MaxValue,
RequestedHeartbeat = UInt16.MaxValue //心跳超时时间
};
try
{
using (var connection = connectionFactory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
//创建一个新的,持久的交换区
channel.ExchangeDeclare("SISOExchange_fanout", ExchangeType.Fanout, true, false, null);
//创建一个新的,持久的队列, 没有排他性,与不自动删除
channel.QueueDeclare("SISOqueue_fanout", true, false, false, null);
// 绑定队列到交换区
channel.QueueBind("SISOqueue_fanout", "SISOExchange_fanout", "optionalRoutingKey_fanout");
// 设置消息属性
var properties = channel.CreateBasicProperties();
properties.DeliveryMode = 2; //消息是持久的,存在并不会受服务器重启影响
//准备开始推送
//发布的消息可以是任何一个(可以被序列化的)字节数组,如序列化对象,一个实体的ID,或只是一个字符串
var encoding = new UTF8Encoding();
for (var i = 0; i < 10; i++)
{
var msg = string.Format("这是消息 #{0}?", i + 1);
var msgBytes = encoding.GetBytes(msg);
//RabbitMQ消息模型的核心思想就是,生产者不把消息直接发送给队列。实际上,生产者在很多情况下都不知道消息是否会被发送到一个队列中。取而代之的是,生产者将消息发送到交换区。交换区是一个非常简单的东西,它一端接受生产者的消息,另一端将他们推送到队列中。交换区必须要明确的指导如何处理它接受到的消息。是放到一个队列中,还是放到多个队列中,亦或是被丢弃。这些规则可以通过交换区的类型来定义。
//可用的交换区类型有:direct,topic,headers,fanout。
//Exchange:用于接收消息生产者发送的消息,有三种类型的exchange:direct, fanout,topic,不同类型实现了不同的路由算法;
//RoutingKey:是RabbitMQ实现路由分发到各个队列的规则,并结合Binging提供于Exchange使用将消息推送入队列;
//Queue:是消息队列,可以根据需要定义多个队列,设置队列的属性,比如:消息移除、消息缓存、回调机制等设置,实现与Consumer通信;
channel.BasicPublish("SISOExchange_fanout", "optionalRoutingKey_fanout", properties, msgBytes);
}
channel.Close();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("消息发布!");
Console.ReadKey(true);
}
}
}
<file_sep>/NetMQ/ProducerMQ.cs
using RabbitMQ.Client;
using RabbitMQ.Client.Content;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace NetMQ
{
public static class ProducerMQ
{
public static void InitProducerMQ()
{
Uri uri = new Uri("amqp://127.0.0.1:5672/");
string exchange = "ex1";
string exchangeType = "direct";
string routingKey = "m1";
bool persistMode = true;
ConnectionFactory cf = new ConnectionFactory();
cf.UserName = "guest";
cf.Password = "<PASSWORD>";
//cf.VirtualHost = "dnt_mq";
cf.RequestedHeartbeat = 0;
cf.Endpoint = new AmqpTcpEndpoint(uri);
using (IConnection conn = cf.CreateConnection())
{
using (IModel ch = conn.CreateModel())
{
if (exchangeType != null)
{
ch.ExchangeDeclare(exchange, exchangeType);//,true,true,false,false, true,null);
ch.QueueDeclare("q1", false,false,false,null);//true, true, true, false, false, null);
ch.QueueBind("q1", "ex1", "m1", null);
}
var input = "";
Console.WriteLine("Enter a message. 'Quit' to quit.");
while ((input = Console.ReadLine()) != "Quit")
{
IMapMessageBuilder b = new MapMessageBuilder(ch);
IDictionary target = (IDictionary)b.Headers;
target["header"] = "hello world";
IDictionary targetBody = (IDictionary)b.Body;
targetBody["body"] = "daizhj";
if (persistMode)
{
((IBasicProperties)b.GetContentHeader()).DeliveryMode = 2;
}
ch.BasicPublish(exchange, routingKey,
(IBasicProperties)b.GetContentHeader(),
b.GetContentBody());
}
}
}
}
}
}
<file_sep>/Subscriber/SimConsumer.cs
using EasyNetQ;
using Model;
using System;
using System.Collections.Generic;
using System.Text;
namespace Subscriber
{
public static class SimConsumer
{
public static void SimCon()
{
using (var bus = RabbitHutch.CreateBus("host=localhost"))
{
bus.Subscribe<TextMessage>("test1", HandleTextMessage);
Console.WriteLine("Listening for messages. Hit <return> to quit.");
Console.ReadLine();
}
}
static void HandleTextMessage(TextMessage textMessage)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Got message: {0}", textMessage.Text);
Console.ResetColor();
}
}
}
<file_sep>/Subscriber/Consumer.cs
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.MessagePatterns;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Subscriber
{
public static class Consumer
{
public static void Con()
{
// 建立RabbitMQ连接和通道
var connectionFactory = new ConnectionFactory
{
HostName = "127.0.0.1",
Port = 5672,
UserName = "guest",
Password = "<PASSWORD>",
Protocol = Protocols.AMQP_0_9_1,
RequestedFrameMax = UInt32.MaxValue,
RequestedHeartbeat = UInt16.MaxValue
};
using (var connection = connectionFactory.CreateConnection())
using (var channel = connection.CreateModel())
{
// 这指示通道不预取超过1个消息
channel.BasicQos(0, 1, false);
//创建一个新的,持久的交换区
channel.ExchangeDeclare("SISOExchange_fanout", ExchangeType.Fanout, true, false, null);
//创建一个新的,持久的队列
channel.QueueDeclare("sample-queue_fanout", true, false, false, null);
//绑定队列到交换区
channel.QueueBind("SISOqueue_fanout", "SISOExchange_fanout", "optionalRoutingKey_fanout");
using (var subscription = new Subscription(channel, "SISOqueue_fanout", false))
{
Console.WriteLine("等待消息...");
var encoding = new UTF8Encoding();
while (channel.IsOpen)
{
BasicDeliverEventArgs eventArgs;
var success = subscription.Next(2000, out eventArgs);
if (success == false) continue;
var msgBytes = eventArgs.Body;
var message = encoding.GetString(msgBytes);
Console.WriteLine(message);
channel.BasicAck(eventArgs.DeliveryTag, false);
}
}
//QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel);
//channel.BasicConsume("SISOqueue_fanout", false, consumer);
//while (true)
//{
// try
// {
// BasicDeliverEventArgs e = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
// IBasicProperties props = e.BasicProperties;
// byte[] body = e.Body;
// Console.WriteLine(System.Text.Encoding.UTF8.GetString(body));
// // channel.BasicAck(e.DeliveryTag, true);
// // ProcessRemainMessage();
// }
// catch (EndOfStreamException ex)
// {
// //The consumer was removed, either through channel or connection closure, or through the action of IModel.BasicCancel().
// Console.WriteLine(ex.ToString());
// break;
// }
// Console.ReadLine();
//}
}
}
}
}
<file_sep>/Subscriber/RecieveConsumer.cs
using EasyNetQ;
using Model;
using System;
using System.Collections.Generic;
using System.Text;
namespace Subscriber
{
public static class RecieveConsumer
{
public static void RecieveCon()
{
using (var bus = RabbitHutch.CreateBus("host=localhost"))
{
//sendrecieve
bus.Receive<TextMessage>("my.queue2", message => Console.WriteLine("MyMessage: {0}", message.Text));
Console.ReadLine();
}
}
}
}
<file_sep>/Subscriber/ComplexConsumer.cs
using System;
using System.Collections.Generic;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.IO;
using RabbitMQ.Client.MessagePatterns;
namespace Subscriber
{
public static class ComplexConsumer
{
public static string EXCHANGE_TYPE = "fanout";
public static string EXCHANGE_NAME = "exchange_famout1";
public static string CHANNEL_NAME = "chanel_fanout1";
public static string ROUTR_NAME = "route_fanout1";
public static void ComplexCon()
{
ConnectionFactory factory = new ConnectionFactory()
{
HostName="127.0.0.1",
Port=5672,
UserName="guest",
Password="<PASSWORD>",
Protocol = Protocols.DefaultProtocol,
AutomaticRecoveryEnabled = true, //自动重连
RequestedFrameMax = UInt32.MaxValue,
RequestedHeartbeat = UInt16.MaxValue //心跳超时时间
};
using (IConnection connection = factory.CreateConnection())
{
using (IModel channel = connection.CreateModel())
{
// 这指示通道不预取超过1个消息
channel.BasicQos(0, 1, false);
channel.ExchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, false, null);
channel.QueueDeclare(CHANNEL_NAME, true, false, false, null);
channel.QueueBind(CHANNEL_NAME, EXCHANGE_NAME, ROUTR_NAME);
using (var subscription = new Subscription(channel, CHANNEL_NAME, false))
{
Console.WriteLine("wait...");
var encoding = new UTF8Encoding();
while (channel.IsOpen)
{
BasicDeliverEventArgs eventArgs;
var success = subscription.Next(2000, out eventArgs);
if (success == false) continue;
var msgBytes = eventArgs.Body;
var message = encoding.GetString(msgBytes);
Console.WriteLine(message);
channel.BasicAck(eventArgs.DeliveryTag, false);
}
}
//QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel);
//channel.BasicConsume("CHANNEL_NAME", false, consumer);
//while (true)
//{
// try
// {
// BasicDeliverEventArgs e = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
// IBasicProperties props = e.BasicProperties;
// byte[] body = e.Body;
// Console.WriteLine(System.Text.Encoding.UTF8.GetString(body));
// // channel.BasicAck(e.DeliveryTag, true);
// // ProcessRemainMessage();
// }
// catch (EndOfStreamException ex)
// {
// //The consumer was removed, either through channel or connection closure, or through the action of IModel.BasicCancel().
// Console.WriteLine(ex.ToString());
// break;
// }
// Console.ReadLine();
//}
}
}
}
}
}
<file_sep>/NetMQ/ComplexProduct.cs
using System;
using System.Collections.Generic;
using System.Text;
using RabbitMQ.Client;
namespace NetMQ
{
public static class ComplexProduct
{
public static string EXCHANGE_TYPE = "fanout";
public static string EXCHANGE_NAME = "exchange_famout1";
public static string CHANNEL_NAME = "chanel_fanout1";
public static string ROUTR_NAME = "route_fanout1";
public static void ComplexPro()
{
ConnectionFactory Factory = new ConnectionFactory()
{
UserName="guest",
Password="<PASSWORD>",
Port=5672,
HostName="127.0.0.1",
Protocol = Protocols.DefaultProtocol,
AutomaticRecoveryEnabled = true, //自动重连
RequestedFrameMax = UInt32.MaxValue,
RequestedHeartbeat = UInt16.MaxValue //心跳超时时间
};
using (IConnection Connect = Factory.CreateConnection())
{
using (IModel channel = Connect.CreateModel())
{
channel.ExchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE, true, false, null);
channel.QueueDeclare(CHANNEL_NAME, true, false, false, null);
channel.QueueBind(CHANNEL_NAME, EXCHANGE_NAME, ROUTR_NAME);
// 设置消息属性
var properties = channel.CreateBasicProperties();
properties.DeliveryMode = 2; //消息是持久的,存在并不会受服务器重启影响
var input = "";
Console.WriteLine("start");
while((input= Console.ReadLine())!="quit")
{
var mess=Encoding.UTF8.GetBytes(input);
channel.BasicPublish(EXCHANGE_NAME, ROUTR_NAME, properties, mess);
}
}
}
}
}
}
<file_sep>/Subscriber/CustmerMq.cs
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Subscriber
{
public static class CustmerMq
{
public static void InitCustmerMq()
{
string exchange = "ex1";
string exchangeType = "direct";
string routingKey = "m1";
Uri uri = new Uri("amqp://127.0.0.1:5672/");
ConnectionFactory cf = new ConnectionFactory();
cf.Endpoint = new AmqpTcpEndpoint(uri);
cf.UserName = "guest";
cf.Password = "<PASSWORD>";
// cf.VirtualHost = "dnt_mq";
cf.RequestedHeartbeat = 0;
using (IConnection conn = cf.CreateConnection())
{
using (IModel ch = conn.CreateModel())
{
//普通使用方式BasicGet
//noAck = true,不需要回复,接收到消息后,queue上的消息就会清除
//noAck = false,需要回复,接收到消息后,queue上的消息不会被清除,直到调用channel.basicAck(deliveryTag, false); queue上的消息才会被清除 而且,在当前连接断开以前,其它客户端将不能收到此queue上的消息
//BasicGetResult res = ch.BasicGet("q1", false/*noAck*/);
//if (res != null)
//{
// bool t = res.Redelivered;
// t = true;
// Console.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(res.Body));
// ch.BasicAck(res.DeliveryTag, false);
//}
//else
//{
// Console.WriteLine("No message!");
//}
ch.ExchangeDeclare(exchange, exchangeType);//,true,true,false,false, true,null);
ch.QueueDeclare("q1", false, false, false, null);//true, true, true, false, false, null);
ch.QueueBind("q1", "ex1", "m1", null);
//while (true)
//{
// BasicGetResult res = ch.BasicGet("q1", false/*noAck*/);
// if (res != null)
// {
// try
// {
// bool t = res.Redelivered;
// t = true;
// Console.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(res.Body));
// ch.BasicAck(res.DeliveryTag, false);
// }
// catch { }
// }
// else
// break;
//}
QueueingBasicConsumer consumer = new QueueingBasicConsumer(ch);
ch.BasicConsume("q1", false, consumer);
while (true)
{
try
{
BasicDeliverEventArgs e = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
IBasicProperties props = e.BasicProperties;
byte[] body = e.Body;
Console.WriteLine(System.Text.Encoding.UTF8.GetString(body));
ch.BasicAck(e.DeliveryTag, true);
// ProcessRemainMessage();
}
catch (EndOfStreamException ex)
{
//The consumer was removed, either through channel or connection closure, or through the action of IModel.BasicCancel().
Console.WriteLine(ex.ToString());
break;
}
Console.ReadLine();
}
}
}
}
}
}
<file_sep>/NetMQ/Program.cs
using EasyNetQ;
using Model;
using RabbitMQ.Client;
using System;
using System.Text;
namespace NetMQ
{
class Program
{
private static string EXCHANGE_NAME = "exchangefanout";
private static string ROUTEKEY = "k1fanout";
private static string CHANCEL_NAME = "chanelfamout";
private static string EXCHANGE_TYPE = "fanout";
static void Main(string[] args)
{
//using (var bus = RabbitHutch.CreateBus("host=localhost"))
//{
// var input = "";
// Console.WriteLine("Enter a message. 'Quit' to quit.");
// while ((input = Console.ReadLine()) != "Quit")
// {
// //bus.Publish(new TextMessage
// //{
// // Text = input
// //});
// ////请求与响应
// //var myRequest = new TextMessage { Text = input };
// //var response = bus.Request<TextMessage, TextMessage>(myRequest);
// //Console.WriteLine(response.Text);
//Send Receive
// bus.Send("my.queue1", new TextMessage { Text = "Hello Widgets!" });
// }
//}
//ConnectionFactory factory = new ConnectionFactory() { HostName = "localhost" };
//using (IConnection connection = factory.CreateConnection())
//{
// using (IModel channel = connection.CreateModel())
// {
// channel.QueueDeclare("hello", false, false, false, null);
// var input = "";
// Console.WriteLine("Enter a message. 'Quit' to quit.");
// while ((input = Console.ReadLine()) != "Quit")
// {
// var message = GetMessage(args);
// var body = Encoding.UTF8.GetBytes(message);
// var properties = channel.CreateBasicProperties();
// properties.DeliveryMode = 2;//non-persistent (1) or persistent (2)
// //channel.TxSelect();
// channel.BasicPublish("", "hello", properties, body);
// //channel.TxCommit();
// }
// }
//}
////广播模式模式
//ConnectionFactory factory = new ConnectionFactory();
//using (IConnection connection = factory.CreateConnection())
//{
// using (IModel channel = connection.CreateModel())
// {
// channel.ExchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE);
// // channel.QueueDeclare(CHANCEL_NAME, false);//true, true, true, false, false, null);
// channel.QueueDeclare(CHANCEL_NAME, false, false, false, null);
// channel.QueueBind(CHANCEL_NAME, EXCHANGE_NAME, ROUTEKEY, null);
// var input = "";
// Console.WriteLine("Enter a message. 'Quit' to quit.");
// while ((input = Console.ReadLine()) != "Quit")
// {
// string msg = DateTime.Now + " have log sth...";
// var body = Encoding.UTF8.GetBytes(msg);
// channel.BasicPublish(EXCHANGE_NAME, "", null, body);
// }
// }
// }
// ProducerMQ.InitProducerMQ();
//广播模式 success
product.pro();
//最简单模式订阅发布
// Simproduct.sim();
//send recieve
// SendProduct.sendPro();
//复杂一点
// ComplexProduct.ComplexPro();
}
private static string GetMessage(string[] args)
{
return ((args.Length > 0) ? string.Join(" ", args) : "Hello World!");
}
}
} | ce3dddbae52f2da735275540822c4d2219bec31b | [
"C#"
] | 12 | C# | wenjunGG/NetMQ | d179c90b2a1d9ec0ce07b2f69f79076ac06f878f | b1ee35fbbfa10ce01b97e777556392030c92b964 |
refs/heads/master | <repo_name>AgnieszkaJarosik/markdown-previewer<file_sep>/src/Toolbar/Toolbar.js
import React from 'react';
import './Toolbar.css';
function Toolbar(props) {
return (
<div className="toolbar">
<i className="icon-leaf"></i>
{props.text}
</div>
);
}
export default Toolbar;<file_sep>/src/Converter.js
const marked = require('marked');
const options = {
baseUrl: null,
breaks: true,
gfm: true,
headerIds: true,
headerPrefix: "",
highlight: null,
langPrefix: "language-",
mangle: true,
pedantic: false,
sanitize: false,
sanitizer: null,
silent: false,
smartLists: false,
smartypants: false,
xhtml: false
};
const Converter = {
start (text) {
return marked(text, options);
}
}
export default Converter;<file_sep>/README.md
# Markdown previewer
A simple Markdown editor created with React.
## General info
This project is a Markdown parser, which allows you to convert Markdown into HTML. It uses **Marked** to convert text.
This project was created for a freeCodeCamp Front End Libraries Projects.
## Technologies
This project is created with **React.js** version: 16.9.0
## Usage
1. Type in some markdown on the left.
2. See the live updates on the right.
## Setup
Clone this repo to your desktop. After that go to it's root directory and run
`$ npm install`
to install its dependencies.
Once the dependencies are installed, you can run
`$ npm start`
to start the application. You will then be able to access it at localhost:3000<file_sep>/src/Textarea/Textarea.js
import React from 'react';
import Toolbar from '../Toolbar/Toolbar';
import './Textarea.css';
function Textarea(props) {
const handleTextareaChange = (e) => {
props.handleChange(e.target.value);
}
return (
<div className="editor-container">
<Toolbar text="Editor" />
<textarea id="editor" type="text" wrap="hard"
value={props.text}
onChange={handleTextareaChange} >
</textarea>
</div>
);
}
export default Textarea;<file_sep>/src/App.js
import React from 'react';
import Textarea from './Textarea/Textarea';
import Preview from './Preview/Preview';
import Converter from './Converter';
import text from './text';
import './App.css';
import './fontello/css/fontello.css';
class App extends React.Component {
constructor (props) {
super(props);
this.state = {
text: text,
html: {}
};
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
this.setState({ html: Converter.start(this.state.text) });
}
handleChange (value) {
this.setState({ text: value,
html: Converter.start(value) });
}
render() {
return (
<div className="App">
<Textarea text={this.state.text} handleChange={this.handleChange} />
<Preview html={this.state.html} />
</div>
);
}
}
export default App;
| 0ae44f9e6c1322ee00d01f69b11d6c20a43bddcf | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | AgnieszkaJarosik/markdown-previewer | 8c5dbcd1e526be2235afabb561f5324164afe0b3 | 45c997c57de507e1c06406a1bebb4c625488f088 |
refs/heads/master | <repo_name>solon4ak/jm_crud<file_sep>/src/main/java/ru/solon4ak/jm_crudapp/servlet/UpdateUserServlet.java
package ru.solon4ak.jm_crudapp.servlet;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ru.solon4ak.jm_crudapp.util.DBException;
import ru.solon4ak.jm_crudapp.model.User;
import ru.solon4ak.jm_crudapp.service.UserService;
import ru.solon4ak.jm_crudapp.service.UserServiceImpl;
/**
*
* @author solon4ak
*/
@WebServlet(name = "UpdateUserServlet", urlPatterns = {"/edit"})
public class UpdateUserServlet extends HttpServlet {
private final UserService userService = UserServiceImpl.getInstance();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
long id = Long.parseLong(req.getParameter("id"));
try {
User user = userService.getUserById(id);
user.setFirstName(req.getParameter("firstName"));
user.setLastName(req.getParameter("lastName"));
user.setEmail(req.getParameter("email"));
user.setAddress(req.getParameter("address"));
user.setPhoneNumber(req.getParameter("phoneNumber"));
user.setAge(Byte.valueOf(req.getParameter("age")));
userService.updateUser(user);
req.setAttribute("user", user);
resp.setStatus(200);
req.getRequestDispatcher("/WEB-INF/jsp/view/user/view.jsp").forward(req, resp);
} catch (DBException ex) {
resp.setStatus(400);
Logger.getLogger(UpdateUserServlet.class.getName())
.log(Level.SEVERE, "Exception while updating user.", ex);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String idString = req.getParameter("id");
long id = Long.parseLong(idString);
try {
User user = userService.getUserById(id);
req.setAttribute("user", user);
resp.setStatus(200);
req.getRequestDispatcher("/WEB-INF/jsp/view/user/edit.jsp").forward(req, resp);
} catch (DBException ex) {
resp.setStatus(400);
Logger.getLogger(UpdateUserServlet.class.getName())
.log(Level.SEVERE, "Exception while updating user.", ex);
}
}
}
<file_sep>/src/main/java/ru/solon4ak/jm_crudapp/util/DBHelper.java
package ru.solon4ak.jm_crudapp.util;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author solon4ak
*/
public class DBHelper {
private static Connection connection;
public static Connection getConnection() {
if (connection == null) {
connection = createConnection();
}
return connection;
}
private static Connection createConnection() {
try {
DriverManager.registerDriver(
(Driver) Class.forName("com.mysql.cj.jdbc.Driver").newInstance()
);
StringBuilder url = new StringBuilder();
url.
append("jdbc:mysql://"). //db type
append("localhost:"). //host name
append("3306/"). //port
append("db_example?"). //db name
append("user=root&"). //login
append("password=<PASSWORD>&"). //password
append("useLegacyDatetimeCode=false&").
append("serverTimezone=UTC");
Connection c = DriverManager.getConnection(url.toString());
return c;
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException | SQLException e) {
e.printStackTrace();
throw new IllegalStateException();
}
// Connection con = null;
// try {
// Context initContext = new InitialContext();
// Context envContext = (Context) initContext.lookup("java:/comp/env");
// DataSource ds = (DataSource) envContext.lookup("jdbc/db_example");
// con = ds.getConnection();
// } catch (NamingException | SQLException ex) {
// Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
// }
//
// return con;
}
}
<file_sep>/src/main/java/ru/solon4ak/jm_crudapp/servlet/ViewUserServlet.java
package ru.solon4ak.jm_crudapp.servlet;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ru.solon4ak.jm_crudapp.util.DBException;
import ru.solon4ak.jm_crudapp.model.User;
import ru.solon4ak.jm_crudapp.service.UserServiceImpl;
/**
*
* @author solon4ak
*/
@WebServlet(name = "ViewUserServlet", urlPatterns = {"/view"})
public class ViewUserServlet extends HttpServlet {
private UserServiceImpl userService = UserServiceImpl.getInstance();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String idString = req.getParameter("id");
long id = Long.parseLong(idString);
try {
User user = userService.getUserById(id);
req.setAttribute("user", user);
resp.setStatus(200);
req.getRequestDispatcher("/WEB-INF/jsp/view/user/view.jsp").forward(req, resp);
} catch (DBException ex) {
resp.setStatus(400);
Logger.getLogger(DeleteUserServlet.class.getName())
.log(Level.SEVERE, "Exception while retrieving user.", ex);
}
}
}
<file_sep>/src/main/java/ru/solon4ak/jm_crudapp/servlet/DeleteUserServlet.java
package ru.solon4ak.jm_crudapp.servlet;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ru.solon4ak.jm_crudapp.util.DBException;
import ru.solon4ak.jm_crudapp.model.User;
import ru.solon4ak.jm_crudapp.service.UserService;
import ru.solon4ak.jm_crudapp.service.UserServiceImpl;
/**
*
* @author solon4ak
*/
@WebServlet(name = "DeleteUserServlet", urlPatterns = {"/delete"})
public class DeleteUserServlet extends HttpServlet {
private final UserService userService = UserServiceImpl.getInstance();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String idString = req.getParameter("id");
long id = Long.parseLong(idString);
try {
userService.deleteUser(id);
resp.setStatus(200);
req.setAttribute("users", (List<User>) userService.getAllUsers());
req.getRequestDispatcher("/WEB-INF/jsp/view/user/list.jsp").forward(req, resp);
} catch (DBException ex) {
resp.setStatus(400);
Logger.getLogger(DeleteUserServlet.class.getName())
.log(Level.SEVERE, "Exception while deleting user.", ex);
}
}
}
<file_sep>/src/main/java/ru/solon4ak/jm_crudapp/dao/UserDaoImpl.java
package ru.solon4ak.jm_crudapp.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import ru.solon4ak.jm_crudapp.util.DBHelper;
import ru.solon4ak.jm_crudapp.model.User;
/**
*
* @author solon4ak
*/
public class UserDaoImpl implements UserDao {
private final Connection connection;
private static UserDaoImpl instance;
private UserDaoImpl() {
this.connection = DBHelper.getConnection();
}
public static UserDaoImpl getInstance() {
if (instance == null) {
instance = new UserDaoImpl();
}
return instance;
}
@Override
public User get(long id) throws SQLException {
String query = "select * from users where id='" + id + "'";
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery(query);
result.next();
return new User(
result.getLong("id"),
result.getString("first_name"),
result.getString("last_name"),
result.getString("email"),
result.getString("address"),
result.getString("phone_number"),
result.getByte("age")
);
}
@Override
public List<User> getAll() throws SQLException {
createTable();
List<User> users = new ArrayList<>();
String sql = "select * from users";
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery(sql);
User u;
while (result.next()) {
u = new User(
result.getLong("id"),
result.getString("first_name"),
result.getString("last_name"),
result.getString("email"),
result.getString("address"),
result.getString("phone_number"),
result.getByte("age")
);
users.add(u);
}
return users;
}
@Override
public int add(User user) throws SQLException {
int result = 0;
StringBuilder sb = new StringBuilder();
sb.append("insert into users (first_name, last_name, email, address, phone_number, age) ");
sb.append("values (?, ?, ?, ?, ?, ?)");
try {
connection.setAutoCommit(false);
PreparedStatement ps = connection.prepareStatement(sb.toString());
ps.setString(1, user.getFirstName());
ps.setString(2, user.getLastName());
ps.setString(3, user.getEmail());
ps.setString(4, user.getAddress());
ps.setString(5, user.getPhoneNumber());
ps.setByte(6, user.getAge());
result = ps.executeUpdate();
connection.commit();
} catch (SQLException e) {
connection.rollback();
} finally {
connection.setAutoCommit(true);
}
return result;
}
@Override
public int update(User user) throws SQLException {
int result = 0;
StringBuilder sb = new StringBuilder();
sb.append("update users set first_name=?, last_name=?, email=?, ");
sb.append("address=?, phone_number=?, age=? ");
sb.append("where id=?");
try {
connection.setAutoCommit(false);
PreparedStatement ps = connection.prepareStatement(sb.toString());
ps.setString(1, user.getFirstName());
ps.setString(2, user.getLastName());
ps.setString(3, user.getEmail());
ps.setString(4, user.getAddress());
ps.setString(5, user.getPhoneNumber());
ps.setByte(6, user.getAge());
ps.setLong(7, user.getId());
result = ps.executeUpdate();
connection.commit();
} catch (SQLException e) {
connection.rollback();
} finally {
connection.setAutoCommit(true);
}
return result;
}
@Override
public int delete(long id) throws SQLException {
int result = 0;
String query = "delete from users where id=?";
try {
connection.setAutoCommit(false);
PreparedStatement ps = connection.prepareStatement(query);
ps.setLong(1, id);
result = ps.executeUpdate();
connection.commit();
} catch (SQLException e) {
connection.rollback();
} finally {
connection.setAutoCommit(true);
}
return result;
}
public void createTable() throws SQLException {
StringBuilder sb = new StringBuilder();
sb.append("create table if not exists users ");
sb.append("(id bigint auto_increment, ");
sb.append("first_name varchar(256), ");
sb.append("last_name varchar(256), ");
sb.append("email varchar(256), ");
sb.append("address varchar(512), ");
sb.append("phone_number varchar(15), ");
sb.append("age TINYINT UNSIGNED, ");
sb.append("primary key (id))");
Statement stmt = connection.createStatement();
stmt.executeUpdate(sb.toString());
}
}
| 285fc78f8a0b13ee39ae30facb9ebec85dcb4b71 | [
"Java"
] | 5 | Java | solon4ak/jm_crud | 58f759b1a93e90d57eb8e7ea183a921d555e0491 | 7ff0014c93110b0156fa93c7e9486e227dd18d4a |
refs/heads/Arjun | <file_sep><!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Login</title>
<?php session_start();
session_destroy();
?>
<link rel="stylesheet" href="https://www.w3schools.com/lib/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway"><link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<style>
@import url(http://fonts.googleapis.com/css?family=Exo:100,200,400);
@import url(http://fonts.googleapis.com/css?family=Source+Sans+Pro:700,400,300);
body,h1,h2{font-family: "Pacifico",sans-serif}
body{
margin: 0;
padding: 0;
background: #fff;
color: #fff;
font-size: 12px;
}
.body{
position: absolute;
top: -20px;
left: -20px;
right: -40px;
bottom: -40px;
width: auto;
height: auto;
background-image: url(img/1.jpg);
background-size: cover;
-webkit-filter: blur(5px);
z-index: 0;
}
.grad{
position: absolute;
top: -20px;
left: -20px;
right: -40px;
bottom: -40px;
width: auto;
height: auto;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(0,0,0,0)), color-stop(100%,rgba(0,0,0,0.65))); /* Chrome,Safari4+ */
z-index: 1;
opacity: 0.7;
}
.header{
position: absolute;
top: calc(50% - 35px);
left: calc(50% - 255px);
z-index: 2;
}
.header div{
float: left;
color: #fff;
font-family: 'Exo', sans-serif;
font-size: 35px;
font-weight: 200;
}
.header div span{
color: #5379fa !important;
}
.login{
position: absolute;
top: calc(50% - 75px);
left: calc(50% - 50px);
height: 150px;
width: 350px;
padding: 10px;
z-index: 2;
}
.login input[type=text]{
width: 250px;
height: 30px;
background: transparent;
border: 1px solid rgba(255,255,255,0.6);
border-radius: 2px;
color: #fff;
font-family: 'Exo', sans-serif;
font-size: 16px;
font-weight: 400;
padding: 4px;
}
.login input[type=password]{
width: 250px;
height: 30px;
background: transparent;
border: 1px solid rgba(255,255,255,0.6);
border-radius: 2px;
color: #fff;
font-family: 'Exo', sans-serif;
font-size: 16px;
font-weight: 400;
padding: 4px;
margin-top: 10px;
}
.login input[type=button]{
width: 260px;
height: 35px;
background: #fff;
border: 1px solid #fff;
cursor: pointer;
border-radius: 2px;
color: #a18d6c;
font-family: 'Exo', sans-serif;
font-size: 16px;
font-weight: 400;
padding: 6px;
margin-top: 10px;
}
.login input[type=button]:hover{
opacity: 0.8;
}
.login input[type=button]:active{
opacity: 0.6;
}
.login input[type=text]:focus{
outline: none;
border: 1px solid rgba(255,255,255,0.9);
}
.login input[type=password]:focus{
outline: none;
border: 1px solid rgba(255,255,255,0.9);
}
.login input[type=button]:focus{
outline: none;
}
::-webkit-input-placeholder{
color: rgba(255,255,255,0.6);
}
::-moz-input-placeholder{
color: rgba(255,255,255,0.6);
}
</style>
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>-->
</head>
<body>
<div>
<div class="body"></div>
<div class="grad"></div>
<div class="header">
<div>Login<span>Here</span></div>
</div>
<br>
<div class="login">
<div class="login">
<form action="a.php" method="post">
<table>
<tr>
<td> Name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="<PASSWORD>" name="pass"></td>
</tr>
<tr>
<td><br></td>
<td><br></td>
</tr>
<tr>
<td></td>
<td > <center><button type="submit" style="color:black" class="btn btn-default btn-lg">Submit</button></td>
</tr>
</table>
</form>
</div>
<!--<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>-->
</div>
<div class="w3-bottom w3-hide-small">
<div class="w3-bar w3-white w3-center w3-padding-8 w3-opacity-min w3-hover-opacity-off">
<a href="/AHMS/index.html" style="width:100%" class="w3-bar-item w3-center w3-padding-8 w3-button">HOME</a>
</div>
</div>
</body>
</html>
<file_sep>This Repository is about Hostel Management System which is completely done on php , html and using bootstrap.
<file_sep><?php
$con = mysqli_connect('localhost', 'root', '', 'AHMS');
$name=$_POST["aname"];
$rno=$_POST["arno"];
$batch=$_POST["abatch"];
$gf=$_POST["agf"];
$campus=$_POST["campus"];
$time=$_POST["time"];
$dest=$_POST["adest"];
$rmno=$_POST["armno"];
$query=mysqli_query($con,"insert into leaves values ('$name','$rno','$batch','$gf','$campus','$time','$dest','$rmno',1)");
session_start();
$_SESSION['success']="Successfully Registered.. ! ";
header('location: /AHMS/student.html');
<file_sep><?php
$con = mysqli_connect('localhost', 'root', '', 'AHMS');
$rno=$_POST["arno"];
$query=mysqli_query($con,"delete from roomalloc where rollno='$rno'");
session_start();
$_SESSION['success']="Successfully Registered.. ! ";
header('location: /AHMS/warden.html');
?>
<file_sep><?php
$con = mysqli_connect('localhost', 'root', '', 'AHMS');
$name=$_POST["aname"];
$rno=$_POST["arno"];
$gender=$_POST["Gender"];
$cno=$_POST["apno"];
$pname=$_POST["apname"];
$pno=$_POST["aprno"];
$crno=$_POST["course"];
if($crno==1)
{
$course="Btech";
}
else if($crno==2)
{
$course="BBA";
}
else if($crno==3)
{
$course="BCA";
}
else if($crno==4)
{
$course="BCOM";
}
else if($crno==5)
{
$course="Int MA";
}
else if($crno==6)
{
$course="PG";
}
else {
$course="NONE";
}
$query=mysqli_query($con,"update student set rno='$rno',gender='$gender',pno='$cno',pname='$pname',prno='$pno',course='$course' where uname='$name'");
session_start();
$_SESSION['success']="Successfully Registered.. ! ";
header('location: /AHMS/student.html');
?>
<file_sep><?php
$con = mysqli_connect('localhost', 'root', '', 'AHMS');
$name=$_POST["aname"];
$rno=$_POST["arno"];
$rmno=$_POST["armno"];
$cmp=$_POST["cmp"];
$crno=$_POST["hostel"];
if($crno==1)
{
$course="Kailasam";
}
else if($crno==2)
{
$course="Shivam";
}
else if($crno==3)
{
$course="Ashokam";
}
else if($crno==4)
{
$course="Pranavam";
}
else if($crno==5)
{
$course="Prasadam";
}
else if($crno==6)
{
$course="Sanathanam";
}
else {
$course="NONE";
}
session_start();
$_SESSION['success']="Successfully Registered.. ! ";
$query=mysqli_query($con,"insert into complaint values ('$name','$rno','$rmno','$course','$cmp',0)");
header('location: /AHMS/student.html');
?>
<file_sep><?php
$con = mysqli_connect('localhost', 'root', '', 'AHMS');
$name=$_POST["aname"];
$rno=$_POST["arno"];
$rmno=$_POST["rmno"];
$query=mysqli_query($con,"insert into roomalloc values ('$name','$rmno','$rno')");
session_start();
$_SESSION['success']="Successfully Registered.. ! ";
header('location: /AHMS/warden.html');
?>
<file_sep><?php
session_start();
$con = mysqli_connect('localhost', 'root', '', 'AHMS');
/* if ($con) {
echo 'Success';
}
header('Location: '.'startbootstrap-sb-admin-2-gh-pages/index.html');
*/
$name=$_POST["name"];
$pass=$_POST["pass"];
if($name!=''&&$pass!='')
{
$query=mysqli_query($con,"select * from auth where uname='".$name."' and password='".$pass."'");
if(mysqli_num_rows($query) == 1)
{
$row = mysqli_fetch_assoc($query);
$rol=$row['role'];
$_SESSION['name']=$name;
if($rol==1)
{
header('location: /AHMS/student.html');
}
else if($rol==2)
{
header('location: /AHMS/warden.html');
}
else {
header('location: /AHMS/warden.html');
}
/* header('location: dash/dashboard.html');*/
}
else
{
header('Location: /AHMS/login.html');
}
}
else
{
header('Location: /AHMS/login.html');
}
/*
$result = mysql_query("SELECT * FROM auth");
while($row=mysql_fetch_array($result))
{
$user=$row['uname'];
$pwd=$row['<PASSWORD>'];
}*/
?>
<html>
<body>
</body>
</html>
<file_sep><?php
session_start();
$con = mysqli_connect('localhost', 'root', '', 'AHMS');
$name=$_POST["uname"];
$pass=$_POST["<PASSWORD>"];
$rno=$_POST["roll"];
$query=mysqli_query($con,"insert into auth values('".$name."','".$pass."',".$rno.")");
header("location: index.html");
?>
<file_sep><?php $con = mysqli_connect('localhost', 'root', '', 'AHMS');
$s=$_POST['status'];
$r=$_POST['h'];
$query=mysqli_query($con,"update leaves set status=$s where rno=$r");
header('location: leave.php');
?>
| e8d5347a6e6178e610a3ffed85a1771604245f04 | [
"Text",
"PHP"
] | 10 | PHP | ArjunNM/AHMS | 3655d3036fbe7071bd8ebcb03887002ed6c48a31 | 217fcd4996abe07bbbea21b8cf8d683becc5cd69 |
refs/heads/main | <file_sep>$(function () {
$('[data-toggle="tooltip"]').tooltip();
$('#enviarCorreo').click(function () {
alert('El correo fue enviado correctamente...');
});
$('#receipts > .row h5').on('dblclick', function () {
$(this).css('color', 'red');
});
$('#related > .row > div > .card img').click(function () {
$('#related > .row > div > .card .card-body').toggle();
});
});
| 3b96ba088b0ec2ad056ce2ab4c3864bda2a994c3 | [
"JavaScript"
] | 1 | JavaScript | EntwistleOx/ricomida | 884cb5fa9c8143a92b520aa599fdcbebfd18a828 | 2e37765c81ecca07848c0868b4a7979e51a95b2b |
refs/heads/main | <file_sep>import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { sequence, generate } from 'collatz-generator/lib';
export type resultType = 'nextNumber' | 'sequence' | 'detail' | 'explanation';
@Component({
selector: 'app-collatz',
templateUrl: './collatz.component.html',
styleUrls: ['./collatz.component.scss']
})
export class CollatzComponent {
form: FormGroup = new FormGroup({
value: new FormControl(null, [Validators.required, Validators.min(1)])
});
options: { [key in resultType]: string } = {
nextNumber: 'Next number',
sequence: 'Sequence',
detail: 'Detail',
explanation: 'Text'
};
option: resultType;
setOption(option: resultType): void {
this.option = option;
}
get value(): number {
return this.form.value.value;
}
get sequence(): number[] {
return sequence(this.value);
}
get next(): number {
const generator = generate(this.value);
return generator.next().value;
}
}
<file_sep>import { detail } from 'collatz-generator/lib';
import { CollatzComponent } from './collatz.component';
describe('CollatzComponent', () => {
let component: CollatzComponent;
beforeEach(() => {
component = new CollatzComponent();
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('setOption', () => {
it('should set an option', () => {
const option = 'detail';
component.setOption(option);
expect(component.option).toBe(option);
});
});
describe('next', () => {
it('should get next value', () => {
component.form.setValue({ value: 5 });
expect(component.next).toBe(16);
});
});
});
<file_sep>import { Component, Input, OnChanges } from '@angular/core';
import { detail, ICollatzDetail } from 'collatz-generator/lib';
@Component({
selector: 'app-explanation',
templateUrl: './explanation.component.html',
styleUrls: ['./explanation.component.scss']
})
export class ExplanationComponent implements OnChanges {
detail: ICollatzDetail;
@Input() value: number;
ngOnChanges() {
this.detail = detail(this.value);
}
}
<file_sep># collatz-app
Collatz conjecture numbers generator app.
The aim in the little project is learning about Github actions to deploy an Angular app using Collatz generator.
## Local development server
Run `npm start` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change
any of the source files.
## Running unit tests
Run `npm test` to execute the unit tests via [Karma](https://karma-runner.github.io).
<file_sep>import { ExplanationComponent } from './explanation.component';
describe('ExplanationComponent', () => {
let component: ExplanationComponent;
beforeEach(() => {
component = new ExplanationComponent();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Component, Input, OnChanges } from '@angular/core';
import { detail, ICollatzDetail } from 'collatz-generator/lib';
@Component({
selector: 'app-detail[value]',
templateUrl: './detail.component.html',
styleUrls: ['./detail.component.scss']
})
export class DetailComponent implements OnChanges {
@Input() value;
detail: ICollatzDetail;
ngOnChanges() {
this.detail = detail(this.value);
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { CollatzComponent } from './components/collatz/collatz.component';
import { DetailComponent } from './components/detail/detail.component';
import { YesNoPipe } from './pipes/yes-no.pipe';
import { ExplanationComponent } from './components/explanation/explanation.component';
@NgModule({
declarations: [AppComponent, CollatzComponent, DetailComponent, YesNoPipe, ExplanationComponent],
imports: [BrowserModule, ReactiveFormsModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
<file_sep>import { YesNoPipe } from './yes-no.pipe';
describe('YesNoPipe', () => {
let pipe: YesNoPipe;
beforeEach(() => {
pipe = new YesNoPipe();
});
it('create an instance', () => {
expect(pipe).toBeTruthy();
});
const falsy = [false, 0, '', null];
falsy.forEach((test) => {
it(`should get "no" with falsy values`, () => {
const result: string = pipe.transform(test);
expect(result).toEqual('no');
});
});
const truthy = [true, 1, {}, 'true'];
truthy.forEach((test) => {
it(`should get "yes" with truthy values`, () => {
const result: string = pipe.transform(test);
expect(result).toEqual('yes');
});
});
});
| b21492c460fc8abb1a30159e270daa79881952c3 | [
"Markdown",
"TypeScript"
] | 8 | TypeScript | emiliodeg/collatz-app | b50ff238017c079a7abda3579899156f82fc9fcb | 8a4bb6db175b0dc806bad2af0829e2d311e36f86 |
refs/heads/master | <repo_name>KTurnage/FriendFinder<file_sep>/README.md
# Friend Finder
Which one of Friend's friends is suited to be your best friend?
## Getting Started
Fill out our qick 10 question survey to find out who your best Friend friend is.
### Requirements
Use express and path npm packages in the server.js file
### Technologies Used
JavaScript
jQuery
node.js
Express.js
HTML
Bootstrap
## Authors
* KTurnage
<file_sep>/app/routing/apiRoutes.js
// Loading Data: linking to friends.js.
var friends = require("../data/friends");
// ROUTING
module.exports = function (app) {
app.get("/api/friends", function (req, res) {
res.json(friends);
});
// API POST Requests
// Below code handles when a user clicks submit button after answering all questions.
// The answers are added and totaled. (loop through)
// Compare user total to frieds array totals, and chose closest match. (loop through)
// After closest match is chosen, push the name and photo of friend to modal.
// In each of the below cases, when a user submits form data (a JSON object)
app.post("/api/friends", function (req, res) {
var userData = req.body;
var userScores = userData.score;
var userName = userData.name;
var userPhoto = userData.photo;
// variable for user score
// use this object to hold the best friend match. This will constantly update as it loops thru options
var bestFriendMatch = {
name: "",
photo: "",
friendDifference: Infinity
};
for (i = 0; i < friends.length; i++) {
var currentFriend = friends[i];
var difference = 0;
for (j = 0; j < currentFriend.scores.length; j++) {
var possibleFriendScore = currentFriend.scores[j];
var userScore = userScores[j];
difference += Math.abs(parseInt(userScore) - possibleFriendScore)
}
if (difference <= bestFriendMatch.friendDifference) {
bestFriendMatch.name = currentFriend.name;
bestFriendMatch.photo = currentFriend.photo;
bestFriendMatch.friendDifference = difference;
}
};
res.json(bestFriendMatch);
friends.push(userData);
});
}; | 7f029c12eee4e1f4a20813648a4ec21141f0c812 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | KTurnage/FriendFinder | 08fdca1c3783c552f68684dd52b19342f932ca09 | 5ac73b8e1f910cf340b6475eb5bfe5a6579b7ba6 |
refs/heads/master | <repo_name>piersonscarborough/Udemy<file_sep>/JS/function.js
// fucntion that checks if a number is even
function isEven(num){
if(num % 2 === 0){
console.log('true');
return true;
}
}
isEven(2);
// function that returns factorial of a number
function factorial(num){
var result = 1;
for(var i = 1; i <= num; i ++){
result = result * i;
}
return result;
}
factorial(3)
// function to rplace '-' with '_'
function kebabToSnake(str) {
var newStr = str.replace(/-/g, "_");
return newStr;
}
kebabToSnake('sup-bro');
console.log(kebabToSnake('sup-bro'))<file_sep>/React/section1/server.js
const express = require('express');
const app = express();
app.use(express.static(__dirname+'/'));
app.listen(3000);
console.log('server running')
// const express = require('express')
// const app = express()
// const port = 3000
// app.listen(3000, function(){
// console.log('server is running...')
// })
// app.get('/hello', (req, res) => res.send('Hello World!'))<file_sep>/Python/repeater.py
'''
user_input = input('How many times do I have to tell you? ')
user_input = int(user_input)
for num in range(user_input):
print('CLEAN UP YOUR ROOM!')
'''
for num in range(1,21) :
if num == 4 or num == 13:
print(f'{num} x is unlucky')
elif num % 2 == 0:
print(f'{num} x is even')
elif num % 2 != 0:
print(f'{num} is odd')
<file_sep>/node/mustache/routes/users.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
function authenticate(req,res,next){
if(req.session){
if(req.session.name){
next()
}else{
res.redirect('/add-user');
}
}else{
res.redirect('/add-user');
}
};
router.use(bodyParser.urlencoded({extended: false}));
router.get('/', (req,res) => {
let user = {
name: req.session.name,
age: req.session.age,
address: {
street: "789 St",
city: "Houston",
state: "Texas"
}
};
res.render('index', user);
});
router.get('/add-user', (req,res) => {
res.render('add-user');
});
router.get('/bank-accounts', authenticate, (req,res) => {
res.send('Bank Accounts');
});
router.post('/add-user', (req,res) =>{
let name = req.body.name;
let age = req.body.age;
if(req.session){
req.session.name = name;
req.session.age = age;
};
console.log(name);
console.log(age);
res.status(200).send();
});
router.get('/users', (req,res) => {
let users = [
{name: '<NAME>', age: 34},
{name: '<NAME>', age: 32}
]
res.render('users',{users: users});
});
module.exports = router<file_sep>/Python/while_loops.py
'''
for num in range(1,11):
print('*' * num)
'''
x = 1
while x <= 10:
print('*' * x)
x += 1<file_sep>/JS/arrays.js
// Reverse an array
function printReverse(arr){
for(var i = arr.length -1; i >= 0; i --){
console.log(arr[i]);
return (arr[i]);
}
}
printReverse([1,2,3,4]);
//Is an array uniform?
function isUniform(arr){
var first = arr[0];
for(var i = 1; i < arr.length-1; i ++){
if(arr[i] !== first){
return false;
}
}
return true;
}
isUniform([1,1,1]);
//Sum of the array
function sumArray(arr){
var total = 0;
arr.forEach(function(num){
total = total + num
});
return total;
console.log(total);
}
sumArray([1,2,3]);
function sumArray(arr){
var total = 0;
for(var i = 0; i < arr.length; i ++){
total += arr[i]
}
return total;
console.log(total);
}
sumArray([1,10,3]);
//Largest number in an array
function max(arr){
var highest = 0
arr.forEach(function(num){
if (num > highest){
highest = num
}
});
return highest;
console.log(highest);
}
max([0,3,5,4,5])
function max(arr){
var highest = 0
for(var i = 0; i < arr.length -1; i ++){
if(arr[i] > highest){
highest = arr[i]
}
}
return highest;
console.log(highest);
}
max([0,3,5,4,5])<file_sep>/node/route-basics/app.js
const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.listen(port, () => {
console.log(`server is running on port ${port}!`)
});
app.get('/', (req, res) => {
res.send('Hello Express!')
});
app.get('/movies/:genre/:year', (req, res) => {
console.log(req.params.genre);
console.log(req.params.year);
res.send('Movies Route');
});
// //get function
app.get('/movies', (req, res) => {
let movies = [
{title: "Lord of the Rings", year: 2001},
{title: "Spiderman", year: 2019},
{title: "Avengers", year: 2019}
];
// let movie = {title: "Lord of the Rings", year: 2001};
// res.json(movie);
res.json(movies);
});
// post function
app.post('/movies', (req, res) => {
let title = req.body.title;
let year = req.body.year;
console.log(title);
console.log(year);
res.send("OK");
});
<file_sep>/Python/rock_paper_scissors_AI.py
import random
print('...rock...')
print('...paper...')
print('...scissors...')
player_1 = input('Player 1, enter rock, paper or scissors. ')
rand_num = random.randint(0,2)
if rand_num == 0:
computer = 'rock'
elif rand_num == 1:
computer = 'paper'
else:
computer = 'scissors'
print(f'Computer chooses {computer}')
player_1 = player_1.lower()
if player_1 == computer:
print('Tie! Shoot again!')
elif player_1 == 'rock':
if computer == 'scissors':
print('Player 1 wins!')
elif computer == 'paper':
print('Computer wins!')
elif player_1 == 'paper':
if copmuter == 'rock':
print('Player 1 wins!')
elif computer == 'scissors':
print('Computer wins!')
elif player_1 == 'scissors':
if computer == 'paper':
print('Player 1 wins!')
elif computer == 'rock':
print('Computer wins!')
else:
print('Something went wrong, play again')<file_sep>/Python/rocker_paper_scissors.py
print('...rock...')
print('...paper...')
print('...scissors...')
player_1 = input('Player 1, enter rock, paper or scissors. ')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
print('***** No Cheating *****')
player_2 = input('Player 2, enter rock, paper or scissors. ')
player_1 = player_1.lower()
player_2 = player_2.lower()
if player_1 == 'rock' and player_2 == 'scissors':
print('Player 1 wins!')
elif player_1 == 'rock' and player_2 == 'paper':
print('Player 2 wins!')
elif player_1 == 'rock' and player_2 == 'rock':
print('Tie! Shoot again!')
elif player_1 == 'paper' and player_2 == 'scissors':
print('Player 2 wins!')
elif player_1 == 'paper' and player_2 == 'paper':
print('Tie! Shoot again!')
elif player_1 == 'paper' and player_2 == 'rock':
print('Player 1 wins!')
elif player_1 == 'scissors' and player_2 == 'rock':
print('Player 2 wins!')
elif player_1 == 'scissors' and player_2 == 'scissors':
print('Tie! Shoot again!')
elif player_1 == 'scissors' and player_2 == 'paper':
print('Player 1 wins!')
else:
print('Something went wrong, play again')
<file_sep>/React/section2/src/StatePractice.js
import React, { Component } from 'react';
class StatePractice extends Component {
constructor() {
super();
this.state = {
message: '',
imageWidth: ''
}
}
handleFocus = (event) => {
this.setState({
message: "you agree to terms of service"
})
}
handleMouseEnter = (event) => {
this.setState({
message: " "
})
}
handleImage = (event) => {
if (event.target.width > 100){
console.log('your image is large')
}
}
render() {
return (
<div>
<input onFocus={this.handleFocus} type="text" placeholder='Enter some text' />
<h3 onMouseEnter={this.handleMouseEnter}>{this.state.message}</h3>
<img onLoad={this.handleImage} src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQsAAAC9CAMAAACTb6i8AAAAYFBMVEX///9h2vtT2Pta2ftR1/v6/v9k2/u+7v3o+f7x+//7/v/W9P70/P+t6v3d9v7J8f2J4vya5vx/4Pxw3fvS8/6i6PzG8P2D4fyR5Pzr+v7h9/6q6f2g5/y27P2/7/3H8f3QEcouAAANwUlEQVR4nO1dCZejqhJuAZfEaNySGNOm//+/fFEpFgUhd7LIeXzn3LkzaUlDQe1V+PPj4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh8Xrsw38ZfU2S3atm8lVc+yJChKCoyNL906OTuI0IQoig+pa8YXafRFIgjIMRGCNU/D0zeJfVbPRjPKmcpkZG2FKm9SD8e7Ucm15mgx/UyN462<KEY>eHh4eHh4eHh4eHh4eHh4eHh4eHj8v+B/hEp+atJFmd0AAAAASUVORK5CYII=" alt=""/>
</div>
)
}
}
export default StatePractice;<file_sep>/JS/Objects.js
let movies = [
{
title: "Inception",
seen: "True",
rating: "5 Stars",
},
{
title: "Overlord",
seen: "True",
rating: "5 Stars",
},
{
title: "Avengers: Endgame",
seen: "False",
rating: "5 Stars",
}
]
/*
movies.forEach(function(mov){
if(mov.seen === "True"){
console.log(`You have watched "${mov.title}" - ${mov.rating}`);
} else{
console.log(`You have not watched "${mov.title}" - ${mov.rating}`);
}
});
*/
function getMovie(mov){
if(mov.seen === "True"){
console.log(`You have watched "${mov.title}" - ${mov.rating}`);
} else{
console.log(`You have not watched "${mov.title}" - ${mov.rating}`);
}
}
movies.forEach(function(mov){
getMovie(mov);
});
/*
for(let i=0; i<movies.length; i++){
if(movies[i].seen === "True"){
console.log(`You have watched "${movies[i].title}" - ${movies[i].rating}`);
} else{
console.log(`You have not watched "${movies[i].title}" - ${movies[i].rating}`);
}
}
*/
<file_sep>/node/newsApp/app.js
const express = require('express');
const app = express();
const PORT = 3000;
const mustacheExpress = require('mustache-express');
app.engine('mustache', mustacheExpress());
app.set('views', './views');
app.set('view engine', 'mustache');
app.get('/register', (req,res) => {
res.render('register');
});
app.listen(PORT, () => {
console.log(`Server has starrted on ${PORT}`)
});<file_sep>/Python/mileage.py
#print('How many kilometers did you cycle today?')
kms = input('How many kilometers did you cycle today? ')
miles = float(kms) / 1.60934
miles = round(miles, 2)
print(f'That is equal to {miles} miles')<file_sep>/node/hello-pg-promise/app.js
const pgp = require('pg-promise')();
const connectionString = "postgres://localhost:5432/firstdb";
const db = pgp(connectionString);
db.none('DELETE FROM dishes WHERE dishid = $1',[10])
.then(() => {
console.log('DELETED')
}).catch(error => console.log(error))
// db.none('UPDATE dishes SET price = $1, course = $2 WHERE dishid = $3',[10,'Entrees',10])
// .then(() => {
// console.log("UPDATED")
// }).catch(error => console.log(error))
// db.any('SELECT name,course,price,imageurl FROM dishes')
// .then((dishes) =>{
// console.log(dishes);
// }).catch(error => console.log(error));
// db.none('INSERT INTO dishes(name, course, price, imageURL) VALUES($1,$2,$3,$4)', ['Chicken Sandwich','Entrees', 6.50,'chickensandwich.png']
// ).then(()=>{
// console.log("SUCCESS");
// }).catch(error => console.log(error));
// db.one('INSERT INTO dishes(name, course, price, imageURL) VALUES($1,$2,$3,$4) RETURNING dishid', ['Chicken Sandwich','Entrees', 6.50,'chickensandwich.png'])
// .then((data)=>{
// console.log(data);
// }).catch(error => console.log(error));
| 9d43e7d9a43a062806d9d2fcc29ec0dd25fbdf87 | [
"JavaScript",
"Python"
] | 14 | JavaScript | piersonscarborough/Udemy | 40e0f614e247eca1f141d38e821008f5b2ecf572 | a4d4281e142859efc87ad18ea996460388c7a179 |
refs/heads/main | <file_sep>from django import forms
from .models import Category
class NewListing(forms.Form):
categories = list(Category.objects.values_list('id', 'name'))
title = forms.CharField(label = "Title", max_length = 100, required = True)
start_bid = forms.DecimalField(label = "Starting Bid", decimal_places = 2, required = True, widget = forms.NumberInput(attrs={'placeholder': '0.00'}))
category = forms.ChoiceField(widget = forms.Select, choices = categories, label = "Category")
description = forms.CharField(widget = forms.Textarea, label = "Description of the Item")
url = forms.URLField(required = False, label = "URL link to an image of the item")
class NewBid(forms.Form):
bid = forms.DecimalField(label = "Your Bid", decimal_places=2)
def __init__(self, *args, **kwargs):
try:
current_min = kwargs.pop('current_min')
except KeyError:
current_min = 0
super(NewBid, self).__init__(*args, **kwargs)
self.fields['bid'].widget.attrs['min'] = "{:.2f}".format(current_min)
self.fields['bid'].widget.attrs['placeholder'] = "{:.2f}".format(current_min)
class NewComment(forms.Form):
text = forms.CharField(label = "Your comment", widget = forms.Textarea(attrs={"rows":3, "cols":30, "placeholder": "Write your comment here."}), max_length = 200)
<file_sep># Generated by Django 3.1.6 on 2021-04-05 14:06
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auctions', '0005_auto_20210405_1005'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='time',
field=models.DateTimeField(default=datetime.datetime(2021, 4, 5, 10, 6, 35, 527557)),
),
]
<file_sep># Generated by Django 3.1.6 on 2021-04-05 14:05
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('auctions', '0004_auto_20210404_1132'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='time',
field=models.DateTimeField(default=datetime.datetime(2021, 4, 5, 10, 5, 42, 363326)),
),
migrations.AlterField(
model_name='listing',
name='owner',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owned', to=settings.AUTH_USER_MODEL),
),
]
<file_sep># Generated by Django 3.1.6 on 2021-04-07 02:22
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auctions', '0006_auto_20210405_1006'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='time',
field=models.DateTimeField(default=datetime.datetime(2021, 4, 6, 22, 22, 22, 993046)),
),
]
<file_sep># Generated by Django 3.1.6 on 2021-04-04 15:21
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auctions', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='time',
field=models.DateTimeField(default=datetime.datetime(2021, 4, 4, 11, 21, 41, 639494)),
),
]
<file_sep># Generated by Django 3.1.6 on 2021-04-04 15:31
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auctions', '0002_auto_20210404_1121'),
]
operations = [
migrations.AddField(
model_name='listing',
name='current_bid',
field=models.DecimalField(decimal_places=2, default=0.0, max_digits=100000),
),
migrations.AlterField(
model_name='comment',
name='time',
field=models.DateTimeField(default=datetime.datetime(2021, 4, 4, 11, 31, 46, 819307)),
),
]
<file_sep>from django.contrib.auth.models import AbstractUser
from django.db import models
from datetime import datetime
class Category(models.Model):
id = models.AutoField(primary_key = True)
url = models.CharField(default = "", max_length = 1000)
name = models.CharField(max_length = 50, default = "")
def __str__(self):
return self.name
class User(AbstractUser):
def __str__(self):
return self.username
pass
class Listing(models.Model):
status_choice = [('active','active'), ('inactive','inactive')]
winner = models.ForeignKey(User, on_delete = models.SET_DEFAULT, null = True, default = None, related_name = 'wonitems')
status = models.CharField(max_length = 10, choices = status_choice, default = 'active')
title = models.CharField(max_length = 100)
start_bid = models.DecimalField(decimal_places=2, max_digits = 1000000)
current_bid = models.DecimalField(default = 0.00, decimal_places = 2, max_digits=100000)
url = models.CharField(max_length = 200, blank = True)
description = models.CharField(max_length = 200, default = "")
category = models.ForeignKey(Category, on_delete = models.CASCADE, related_name = "category_listing", default = "")
watched = models.ManyToManyField(User, related_name = "watchedby", blank = True)
owner = models.ForeignKey(User, on_delete = models.CASCADE, null = True, blank = True, related_name = "owned")
def __str__(self):
return f"{self.title} starting at ${self.start_bid} posted by {self.owner}."
class Bid(models.Model):
listing = models.ForeignKey(Listing, on_delete = models.CASCADE, related_name = "same_start_bid", default = "")
current_bid = models.DecimalField(default = 0.00, decimal_places = 2, max_digits=100000)
bidder = models.ForeignKey(User, on_delete = models.SET_DEFAULT, null = True, default = None, blank = True, related_name = 'biddeditems')
def __str__(self):
return f"Current bid on {self.listing.title} is ${self.current_bid} by {self.bidder}"
pass
class Comment(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE, default = "")
listing = models.ForeignKey(Listing, on_delete = models.CASCADE, related_name = 'comments', default = "")
text = models.CharField(max_length=200, default = "")
time = models.DateTimeField(default = datetime.now())
def __str__(self):
return f"{self.user} commented {self.text} at {self.time} on {self.listing.title} listing"
pass <file_sep># Generated by Django 3.1.6 on 2021-04-07 03:10
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auctions', '0009_auto_20210406_2300'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='time',
field=models.DateTimeField(default=datetime.datetime(2021, 4, 6, 23, 10, 16, 4367)),
),
]
<file_sep>from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path("", views.index, name="index"),
path("accounts/login/", auth_views.LoginView.as_view()),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("newlisting", views.create_new, name = "newlisting"),
path("listing/<int:list_id>", views.listing, name = "listing"),
path("listing/<int:list_id>/add", views.add, name = "add"),
path("listing/<int:list_id>/remove", views.remove, name = "remove"),
path("listing/<int:list_id>/bid", views.bid, name = "bid"),
path("watchlist/", views.watchlist, name = "watchlist"),
path("categories/", views.categories, name = "categories"),
path("categories/<int:cat_id>", views.category_listing, name = "category_listing"),
path("wonauctions", views.won, name = "won_auctions"),
path("postedauctions", views.posted, name = "posted_auctions")
]
<file_sep># Generated by Django 3.1.6 on 2021-04-07 02:39
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auctions', '0007_auto_20210406_2222'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='time',
field=models.DateTimeField(default=datetime.datetime(2021, 4, 6, 22, 39, 33, 70916)),
),
]
<file_sep>from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse
from .models import User, Category, Listing, Bid, Comment
from datetime import datetime
from django.utils import timezone
from .forms import NewListing, NewBid, NewComment
def login_view(request):
if request.method == "POST":
# Attempt to sign user in
username = request.POST["username"]
password = request.POST["<PASSWORD>"]
user = authenticate(request, username=username, password=<PASSWORD>)
# Check if authentication successful
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "auctions/login.html", {
"message": "Invalid username and/or password."
})
else:
return render(request, "auctions/login.html")
def index(request):
if request.method == "POST":
list_id = request.POST.get("list_id")
listing_set = Listing.objects.filter(id = list_id)
listing = listing_set[0]
bid_set = Bid.objects.filter(listing = listing)
bid = bid_set[0]
bidder = bid.bidder
listing_set.update(status = 'inactive', winner = bidder)
return render(request, "auctions/index.html", {
"title": "Active Listings",
"listings": Listing.objects.filter(status = 'active')
})
else:
return render(request, "auctions/index.html", {
"title": 'Active Listings',
"listings": Listing.objects.filter(status = 'active')
})
@login_required
def create_new(request):
if request.method == "POST":
form = NewListing(request.POST)
if form.is_valid():
title = form.cleaned_data["title"]
start_bid = form.cleaned_data["start_bid"]
description = form.cleaned_data["description"]
category_id = form.cleaned_data["category"]
category = Category.objects.get(id = category_id)
url = form.cleaned_data["url"]
owner = User.objects.get(id = request.user.id)
listing = Listing(title = title, owner = owner, start_bid = start_bid, current_bid = start_bid, url = url, description = description, category = category)
listing.save()
bid = Bid(listing = listing, current_bid = start_bid)
bid.save()
return HttpResponseRedirect(reverse("listing", args = (listing.id, )))
else:
form = NewListing()
categories = Category.objects.all()
return render(request, "auctions/createlisting.html", {
"categories": categories,
"form": form
})
@login_required
def bid(request, list_id):
if request.method == "POST":
bidform = NewBid(request.POST)
if bidform.is_valid():
listing = Listing.objects.get(id = list_id)
bidded = bidform.cleaned_data['bid']
bid = Bid.objects.get(listing = listing)
current_bid = bid.current_bid
if bidded > current_bid:
user = User.objects.get(id = request.user.id)
Bid.objects.filter(listing = listing).update(current_bid = bidded, bidder = user)
Listing.objects.filter(id = list_id).update(current_bid = bidded)
watching_status = user.watchedby.filter(id = list_id).exists()
return HttpResponseRedirect(reverse('listing', args = (list_id, )))
return HttpResponseRedirect(reverse("listing", args = (list_id,)))
def listing(request, list_id):
if request.method == "POST":
comment_form = NewComment(request.POST)
if comment_form.is_valid():
text = comment_form.cleaned_data['text']
listing = Listing.objects.get(id = list_id)
user = User.objects.get(id = request.user.id)
time = datetime.now(tz=timezone.utc)
new_comment = Comment(text = text, listing = listing, user = user, time = time)
new_comment.save()
else:
return HttpResponse('oops')
return HttpResponseRedirect(reverse("listing", args = (list_id,) ))
else:
listing = Listing.objects.get(id = list_id)
bid = Bid.objects.get(listing = listing)
won = False
if request.user.id:
user = User.objects.get(id = request.user.id)
owner_status = listing.owner == user
watching_status = user.watchedby.filter(id = list_id).exists()
if listing.winner == user:
won = True
else:
owner_status = False
watching_status = False
form = NewBid(current_min = bid.current_bid)
comments = Comment.objects.filter(listing = listing)
comment_form = NewComment()
return render(request, "auctions/listing.html", {
"owner_status": str(owner_status).lower(),
"form": form,
"listing": listing,
"won": won,
"start_bid": "${:,.2f}".format(listing.start_bid),
"current_bid": "${:,.2f}".format(bid.current_bid),
"watching_status": str(watching_status).lower(),
"comments": comments,
"comment_form": comment_form,
"now": datetime.now()
})
@login_required
def add(request, list_id):
if request.method == "POST":
user = User.objects.get(id = request.user.id)
listing = Listing.objects.get(id = list_id)
listing.watched.add(user)
return HttpResponseRedirect(reverse("listing", args = (list_id,)))
else:
return HttpResponseRedirect(reverse("listing", args = (list_id,) ))
@login_required
def remove(request, list_id):
if request.method == "POST":
user = User.objects.get(id = request.user.id)
listing = Listing.objects.get(id = list_id)
listing.watched.remove(user)
return HttpResponseRedirect(reverse("listing", args = (list_id,)))
else:
return HttpResponseRedirect(reverse("listing", args = (list_id,)))
@login_required
def watchlist(request):
if request.method == "GET":
user = User.objects.get(id = request.user.id)
watchlist = user.watchedby.filter(status = 'active')
return render(request, "auctions/watchlist.html", {
"watchlist": watchlist
})
def categories(request):
if request.method == "GET":
categories = Category.objects.all()
return render(request, "auctions/categories.html", {
"categories": categories
})
def category_listing(request, cat_id):
if request.method == "GET":
category = Category.objects.get(id = cat_id)
listings = category.category_listing.filter(status = 'active')
return render(request, "auctions/index.html", {
"title": category.name,
"listings": listings
})
@login_required
def won(request):
user = User.objects.get(id = request.user.id)
listings = user.wonitems.all()
return render(request, "auctions/index.html", {
"title": "Won Auctions",
"listings": listings
})
@login_required
def posted(request):
user = User.objects.get(id = request.user.id)
listings = user.owned.all()
return render(request, "auctions/index.html", {
"title": "Posted Auctions",
"listings": listings
})
@login_required
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse("index"))
def register(request):
if request.method == "POST":
username = request.POST["username"]
email = request.POST["email"]
# Ensure password matches confirmation
password = request.POST["password"]
confirmation = request.POST["confirmation"]
if password != confirmation:
return render(request, "auctions/register.html", {
"message": "Passwords must match."
})
# Attempt to create new user
try:
user = User.objects.create_user(username, email, password)
user.save()
except IntegrityError:
return render(request, "auctions/register.html", {
"message": "Username already taken."
})
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "auctions/register.html")
| 51203e37f338a6d63e54f2fc4c85a76ee694cdae | [
"Python"
] | 11 | Python | zlatakp/Ecommerce-Auction-Site | 789b35f6c547a028ca5f8fee834436c046b5b4b4 | 0f23d24f2bbe7e08bf67c8a51242e15163d03e39 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.